Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/services/collectors/vsv_layout_js.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ const String vsvLayoutJs = r'''
return /^data:/i.test(s) ? '' : s.slice(0, 2000);
}

function clipsX(el) {
if (!el) return false;
var o = getComputedStyle(el).overflowX;
return o === 'hidden' || o === 'clip';
}

window.__vsv_layout = function() {
var body = document.body;
var se = document.scrollingElement || document.documentElement;
Expand All @@ -51,6 +57,14 @@ const String vsvLayoutJs = r'''
if (body.scrollWidth > docW) docW = body.scrollWidth;
if (body.scrollHeight > docH) docH = body.scrollHeight;
}
// Content sticking out to the right only widens the page when the reader
// can scroll there. With overflow-x hidden/clip on <html> or <body> it is
// cut off, and the page is as wide as the window (e.g. CNN: an off-screen
// menu makes scrollWidth twice the window width).
if (clipsX(document.documentElement) || clipsX(body)) {
var iw = window.innerWidth || 0;
if (iw > 0 && iw < docW) docW = iw;
}
if (!body || !docW || !docH) return JSON.stringify({v: 1, empty: true});
var sx = window.pageXOffset || window.scrollX || 0;
var sy = window.pageYOffset || window.scrollY || 0;
Expand Down
13 changes: 12 additions & 1 deletion lib/services/html_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4547,9 +4547,18 @@ Technical details: $message''';
/// platform gives none. Until then those tabs show the top-of-page shot.
Observed<Uint8List> get fullPageScreenshot => _fullPageShot;

PageShotTiles? _fullPageTiles;

/// The same capture as [fullPageScreenshot], as the separate shots: the
/// Structure tab draws these, sharp at any page length. Null until the
/// scroll-through capture is done.
PageShotTiles? get fullPageTiles => _fullPageTiles;

@visibleForTesting
void debugSetFullPageScreenshot(Observed<Uint8List> shot) {
void debugSetFullPageScreenshot(Observed<Uint8List> shot,
{PageShotTiles? tiles}) {
_fullPageShot = shot;
_fullPageTiles = tiles;
notifyListeners();
}

Expand Down Expand Up @@ -4683,6 +4692,7 @@ Technical details: $message''';
if (stale() || bytes == null) return;
_fullPageShot =
Present(bytes.buffer.asUint8List(), source: DataSource.browser);
_fullPageTiles = PageShotTiles(shots, cssWidth: iw);
notifyListeners();
} catch (e) {
debugPrint('Scroll-through screenshot unavailable: $e');
Expand Down Expand Up @@ -4997,6 +5007,7 @@ Technical details: $message''';
_cancelBrowserRefreshes();
final policy = _browserPoll;
_fullPageShot = kNoScreenshot;
_fullPageTiles = null;
// Screenshot of the top of the page right away, without scrolling; the
// Size and Structure tabs show it until the full-page capture is done.
_captureLiveScreenshot(gen).ignore();
Expand Down
11 changes: 11 additions & 0 deletions lib/services/screenshot_stitch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,17 @@ import 'dart:ui'
show Canvas, FilterQuality, Image, Paint, PictureRecorder, Rect,
instantiateImageCodec;

/// The scroll-through screenshots of a page, kept as separate tiles so the
/// Structure tab can draw them sharp: one stitched image of a long page has
/// to shrink to fit GPU limits (a 22000 px page ends up ~0.4 px per CSS px).
/// Each tile is [cssWidth] CSS px wide and starts at page offset `cssY`; its
/// height follows from its own aspect ratio.
class PageShotTiles {
final List<(Uint8List shot, double cssY)> tiles;
final double cssWidth;
const PageShotTiles(this.tiles, {required this.cssWidth});
}

/// Longest side of the stitched image in pixels (safe on mobile GPUs).
const double _maxSide = 8192;

Expand Down
65 changes: 32 additions & 33 deletions lib/widgets/structure_painter.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,43 +51,41 @@ class StructurePalette {
}

/// Draws the page's blocks in page proportions: [scale] logical px per CSS px.
/// When [background] is set (a screenshot of the page), it is drawn opaque
/// behind the blocks — stretched over the whole canvas when
/// [backgroundFullPage], else over the first screen only. The canvas is the
/// page at [model.layout]'s size, so a full-page background drawn at canvas
/// size always shares its coordinate space with the blocks, even when the
/// layout was measured at a different page height than the capture. The
/// blocks themselves are drawn 75% transparent so the screenshot shows
/// through.
/// Behind them, opaque, the page's screenshots: each of [background] is a
/// tile [backgroundCssWidth] CSS px wide (default: the viewport width) at
/// page offset `cssY`, drawn at the blocks' scale with its own aspect ratio,
/// so screenshot and blocks share one coordinate space. The top-of-page shot
/// is a single tile at 0; the scroll-through capture ([backgroundFullPage])
/// is one tile per screen. The blocks are drawn 75% transparent so the
/// screenshot shows through.
class StructurePainter extends CustomPainter {
final StructureModel model;
final double scale;
final StructureColoring coloring;
final ColorScheme scheme;
final ui.Image? background;
final List<(ui.Image image, double cssY)> background;
final double? backgroundCssWidth;
final bool backgroundFullPage;

StructurePainter({
required this.model,
required this.scale,
required this.coloring,
required this.scheme,
this.background,
this.background = const [],
this.backgroundCssWidth,
this.backgroundFullPage = false,
});

/// Where the screenshot goes on the canvas. The shot is as wide as the
/// viewport (not the document, which can overflow it, esp. on phones), so
/// it is drawn [layout.viewportWidth] * [scale] wide with its own aspect
/// ratio: one uniform scale, no stretching, so it lines up with the blocks
/// at the top and drifts only if the page height changed after capture.
/// Without a viewport width it falls back to the canvas width.
static Rect backgroundRect(
int imageWidth, int imageHeight, PageLayout layout, double scale) {
final w = (layout.viewportWidth > 0 ? layout.viewportWidth : layout.width) *
scale;
/// Where a screenshot tile goes on the canvas: [cssWidth] CSS px wide (the
/// viewport the shot covers, not the document, which can be wider) at page
/// offset [cssY], with the image's own aspect ratio, all at [scale] — no
/// stretching, so it lines up with the blocks.
static Rect tileRect(int imageWidth, int imageHeight, double cssWidth,
double cssY, double scale) {
final w = cssWidth * scale;
final h = imageWidth > 0 ? w * imageHeight / imageWidth : 0.0;
return Rect.fromLTWH(0, 0, w, h);
return Rect.fromLTWH(0, cssY * scale, w, h);
}

static const double minLabelWidth = 60;
Expand All @@ -104,18 +102,18 @@ class StructurePainter extends CustomPainter {
..style = PaintingStyle.stroke
..color = scheme.outlineVariant);

// The screenshot is the background, fully opaque: stretched over the
// whole canvas for a full-page capture (the canvas is the page, so the
// image and the blocks share coordinates), else over the first screen
// only.
if (background != null) {
// The screenshot tiles, fully opaque, in capture order (the last shot
// is clamped at the page bottom and overlaps the one before it).
final l = model.layout;
final cssWidth = backgroundCssWidth ??
(l.viewportWidth > 0 ? l.viewportWidth : l.width);
final tilePaint = Paint()..filterQuality = FilterQuality.medium;
for (final (image, cssY) in background) {
canvas.drawImageRect(
background!,
Rect.fromLTWH(
0, 0, background!.width.toDouble(), background!.height.toDouble()),
backgroundRect(
background!.width, background!.height, model.layout, scale),
Paint()..filterQuality = FilterQuality.medium,
image,
Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()),
tileRect(image.width, image.height, cssWidth, cssY, scale),
tilePaint,
);
}

Expand Down Expand Up @@ -192,6 +190,7 @@ class StructurePainter extends CustomPainter {
old.scale != scale ||
old.coloring != coloring ||
old.scheme != scheme ||
old.background != background ||
!identical(old.background, background) ||
old.backgroundCssWidth != backgroundCssWidth ||
old.backgroundFullPage != backgroundFullPage;
}
145 changes: 88 additions & 57 deletions lib/widgets/structure_view.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;

Expand All @@ -10,6 +11,7 @@ import 'package:view_source_vibe/services/derive/dom_tree.dart';
import 'package:view_source_vibe/services/derive/observed_text.dart';
import 'package:view_source_vibe/services/derive/structure_view.dart';
import 'package:view_source_vibe/services/html_service.dart';
import 'package:view_source_vibe/services/screenshot_stitch.dart';
import 'package:view_source_vibe/widgets/dom_tree_view.dart';
import 'package:view_source_vibe/widgets/structure_painter.dart';

Expand All @@ -26,44 +28,76 @@ class StructureView extends StatefulWidget {
class _StructureViewState extends State<StructureView> {
StructureColoring _coloring = StructureColoring.owner;

/// The live browser's screenshot, decoded, drawn behind the wireframe.
ui.Image? _background;
Uint8List? _backgroundBytes;
/// The page's screenshots, decoded, drawn behind the wireframe: one tile
/// per screen of the scroll-through capture, or the top-of-page shot as a
/// single tile at 0 until that capture is done.
List<(ui.Image, double)> _tiles = const [];

/// Whether the decoded [_background] covers the whole page (true) or only
/// the first screen (false). Swapped together with [_background], so the
/// painter never draws the old shot as full-page while the new one decodes.
bool _backgroundFullPage = false;
/// CSS width the decoded [_tiles] cover; null for the top-of-page shot
/// (the painter then uses the measured viewport width).
double? _tilesCssWidth;

/// What the tiles are (being) decoded from: the [PageShotTiles] or the
/// top-of-page shot's bytes. A newer source makes an older decode drop.
Object? _tilesSource;

/// Whether the selected source is the full-page capture. Each tile carries
/// its own page offset, so this only reports which one is shown.
bool _tilesFullPage = false;

/// Decoded pixels across all tiles, at most: a long page has up to 50
/// tiles, each decoded only as wide as this budget allows (~100 MB RGBA).
static const _tilePixelBudget = 24000000;

@override
void dispose() {
_background?.dispose();
_disposeTiles(_tiles);
super.dispose();
}

/// Decodes [bytes] into [_background]; a new screenshot replaces the old.
/// The bitmap is decoded downscaled to the wireframe's max width — the
/// wireframe never displays wider than [kMaxWireframeWidth], so a
/// full-resolution full-page shot would only waste memory.
Future<void> _loadBackground(Uint8List bytes, bool fullPage) async {
static void _disposeTiles(List<(ui.Image, double)> tiles) {
for (final (image, _) in tiles) {
image.dispose();
}
}

/// Decodes [shots] into [_tiles], replacing the old ones. Each is decoded
/// at most as wide as the wireframe can show it sharp (2x its max width)
/// and as the pixel budget across all tiles allows; never upscaled.
Future<void> _loadTiles(Object source, List<(Uint8List, double)> shots,
double? cssWidth) async {
final out = <(ui.Image, double)>[];
try {
final codec = await ui.instantiateImageCodec(bytes,
targetWidth: kMaxWireframeWidth.round(), allowUpscaling: false);
final frame = await codec.getNextFrame();
codec.dispose();
final image = frame.image;
if (!mounted || !identical(bytes, _backgroundBytes)) {
image.dispose();
return;
for (final (shot, cssY) in shots) {
final buffer = await ui.ImmutableBuffer.fromUint8List(shot);
final descriptor = await ui.ImageDescriptor.encoded(buffer);
final w = descriptor.width, h = descriptor.height;
final budgetWidth = w > 0 && h > 0
? math.sqrt(_tilePixelBudget * w / (shots.length * h))
: 0.0;
final maxWidth =
math.min(2 * kMaxWireframeWidth, budgetWidth).floor();
final codec = await descriptor.instantiateCodec(
targetWidth: maxWidth > 0 && w > maxWidth ? maxWidth : null);
final frame = await codec.getNextFrame();
codec.dispose();
descriptor.dispose();
buffer.dispose();
out.add((frame.image, cssY));
if (!mounted || !identical(source, _tilesSource)) break;
}
setState(() {
_background?.dispose();
_background = image;
_backgroundFullPage = fullPage;
});
} catch (_) {
// Not a decodable image: draw the wireframe without a background.
// A shot that does not decode: draw what did decode (or nothing).
}
if (!mounted || !identical(source, _tilesSource)) {
_disposeTiles(out);
return;
}
setState(() {
_disposeTiles(_tiles);
_tiles = out;
_tilesCssWidth = cssWidth;
});
}

@override
Expand All @@ -72,44 +106,40 @@ class _StructureViewState extends State<StructureView> {
.select<HtmlService, Observed<StructureModel>>((s) => s.structureView);
final hasBrowser = context
.select<HtmlService, bool>((s) => s.store.current.target is UrlTarget);
final fullShot = context.select<HtmlService, Observed<Uint8List>>(
(s) => s.fullPageScreenshot);
final fullTiles =
context.select<HtmlService, PageShotTiles?>((s) => s.fullPageTiles);
final liveShot = context.select<HtmlService, Observed<Uint8List>>(
(s) => s.store.current.liveScreenshot);
// Prefer the full-page screenshot; until the scroll-through capture is
// done, show the top-of-page shot taken without scrolling. When the
// larger one arrives, this rebuild swaps it in.
final useFull = fullShot is Present<Uint8List>;
final shot = useFull ? fullShot : liveShot;
final bytes = shot is Present<Uint8List> ? shot.value : null;
if (!identical(bytes, _backgroundBytes)) {
final wasFull = _backgroundFullPage;
_backgroundBytes = bytes;
_backgroundFullPage = useFull;
final b = bytes;
final full = useFull;
final liveBytes = liveShot is Present<Uint8List> ? liveShot.value : null;
// Prefer the full-page capture; until the scroll-through is done, show
// the top-of-page shot taken without scrolling. The old tiles stay on
// screen until the new ones are decoded (both are drawn at their own
// page offsets, so either lines up with the wireframe).
final Object? source = fullTiles ?? liveBytes;
if (!identical(source, _tilesSource)) {
_tilesSource = source;
_tilesFullPage = fullTiles != null;
final shots = fullTiles?.tiles ??
[if (liveBytes != null) (liveBytes, 0.0)];
final cssWidth = fullTiles?.cssWidth;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
if (b == null) {
if (_background != null) {
if (!mounted || !identical(source, _tilesSource)) return;
if (source == null) {
if (_tiles.isNotEmpty) {
setState(() {
_background?.dispose();
_background = null;
_disposeTiles(_tiles);
_tiles = const [];
});
}
} else {
// Drop a stale shot of the other kind right away, so it is not
// drawn with the new full-page flag while the new one decodes.
if (_background != null && wasFull != full) {
setState(() {
_background?.dispose();
_background = null;
});
}
_loadBackground(b, full);
_loadTiles(source, shots, cssWidth);
}
});
}
final bytes = liveBytes ??
(fullTiles != null && fullTiles.tiles.isNotEmpty
? fullTiles.tiles.first.$1
: null);
final body = switch (state) {
Pending<StructureModel>(:final detail) => Center(
child: Column(
Expand Down Expand Up @@ -248,8 +278,9 @@ class _StructureViewState extends State<StructureView> {
scale: scale,
coloring: _coloring,
scheme: scheme,
background: _background,
backgroundFullPage: _backgroundFullPage),
background: _tiles,
backgroundCssWidth: _tilesCssWidth,
backgroundFullPage: _tilesFullPage),
),
),
),
Expand Down
Loading
Loading