From 5b9610ad08d39d0b78e0435af76cec0456a7ebda Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Wed, 25 Nov 2026 20:23:42 +0100 Subject: [PATCH] Structure tab: sharp full-page screenshot; page width ignores clipped overflow Draw the scroll-through shots as separate tiles at their page offsets instead of one stitched image. A stitched image of a long page has to shrink to fit GPU limits (CNN: 22000 px tall -> 144x8192 px, ~0.4 px per CSS px), which looked blurry. Tiles are decoded within a pixel budget across all of them, so a long page stays sharp without using unbounded memory. The stitched image is still made for the Size tab thumbnail. The layout script took scrollWidth as the page width, but content that sticks out to the right is cut off when or has overflow-x hidden/clip (CNN: scrollWidth 760 in a 375 px window), so the wireframe and screenshot were drawn at half width. The page is then as wide as the window. Co-Authored-By: Claude Opus 5.5 --- lib/services/collectors/vsv_layout_js.dart | 14 ++ lib/services/html_service.dart | 13 +- lib/services/screenshot_stitch.dart | 11 ++ lib/widgets/structure_painter.dart | 65 +++++---- lib/widgets/structure_view.dart | 145 +++++++++++++-------- test/collectors/vsv_layout_js_test.dart | 35 ++++- test/widgets/structure_data_test.dart | 32 ++--- 7 files changed, 208 insertions(+), 107 deletions(-) diff --git a/lib/services/collectors/vsv_layout_js.dart b/lib/services/collectors/vsv_layout_js.dart index 491f8932..4e9fb940 100644 --- a/lib/services/collectors/vsv_layout_js.dart +++ b/lib/services/collectors/vsv_layout_js.dart @@ -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; @@ -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 or 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; diff --git a/lib/services/html_service.dart b/lib/services/html_service.dart index e540264f..1b0e52d6 100644 --- a/lib/services/html_service.dart +++ b/lib/services/html_service.dart @@ -4547,9 +4547,18 @@ Technical details: $message'''; /// platform gives none. Until then those tabs show the top-of-page shot. Observed 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 shot) { + void debugSetFullPageScreenshot(Observed shot, + {PageShotTiles? tiles}) { _fullPageShot = shot; + _fullPageTiles = tiles; notifyListeners(); } @@ -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'); @@ -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(); diff --git a/lib/services/screenshot_stitch.dart b/lib/services/screenshot_stitch.dart index 145707de..c5a62207 100644 --- a/lib/services/screenshot_stitch.dart +++ b/lib/services/screenshot_stitch.dart @@ -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; diff --git a/lib/widgets/structure_painter.dart b/lib/widgets/structure_painter.dart index 875cb843..f40efc91 100644 --- a/lib/widgets/structure_painter.dart +++ b/lib/widgets/structure_painter.dart @@ -51,20 +51,20 @@ 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({ @@ -72,22 +72,20 @@ class StructurePainter extends CustomPainter { 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; @@ -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, ); } @@ -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; } diff --git a/lib/widgets/structure_view.dart b/lib/widgets/structure_view.dart index ee1acc5c..c6017791 100644 --- a/lib/widgets/structure_view.dart +++ b/lib/widgets/structure_view.dart @@ -1,3 +1,4 @@ +import 'dart:math' as math; import 'dart:typed_data'; import 'dart:ui' as ui; @@ -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'; @@ -26,44 +28,76 @@ class StructureView extends StatefulWidget { class _StructureViewState extends State { 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 _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 _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 @@ -72,44 +106,40 @@ class _StructureViewState extends State { .select>((s) => s.structureView); final hasBrowser = context .select((s) => s.store.current.target is UrlTarget); - final fullShot = context.select>( - (s) => s.fullPageScreenshot); + final fullTiles = + context.select((s) => s.fullPageTiles); final liveShot = context.select>( (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; - final shot = useFull ? fullShot : liveShot; - final bytes = shot is Present ? 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 ? 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(:final detail) => Center( child: Column( @@ -248,8 +278,9 @@ class _StructureViewState extends State { scale: scale, coloring: _coloring, scheme: scheme, - background: _background, - backgroundFullPage: _backgroundFullPage), + background: _tiles, + backgroundCssWidth: _tilesCssWidth, + backgroundFullPage: _tilesFullPage), ), ), ), diff --git a/test/collectors/vsv_layout_js_test.dart b/test/collectors/vsv_layout_js_test.dart index 5449e7e9..944ae1ed 100644 --- a/test/collectors/vsv_layout_js_test.dart +++ b/test/collectors/vsv_layout_js_test.dart @@ -36,7 +36,9 @@ var document = { documentElement: { scrollWidth: 412, scrollHeight: 5210 } }; body.getElementsByTagName = function() { return __els; }; -function getComputedStyle(e) { return { position: e.pos, visibility: e.vis }; } +function getComputedStyle(e) { + return { position: e.pos, visibility: e.vis, overflowX: e.ox || 'visible' }; +} '''; Future?> layout(String dom) async { @@ -145,6 +147,37 @@ add(mk('section', {rect: [0, 100, 412, 300]})); expect([r['w'], r['h']], [500, 9000]); }); + test('overflow-x hidden on html caps the page width at the window', + () async { + final r = await layout(r''' +document.documentElement.ox = 'hidden'; +document.scrollingElement.scrollWidth = 760; +body.scrollWidth = 760; +add(mk('section', {rect: [0, 100, 412, 300]})); +'''); + if (r == null) return markTestSkipped('node not installed'); + expect(r['w'], 412); + }); + + test('overflow-x clip on body caps the page width at the window', () async { + final r = await layout(r''' +body.ox = 'clip'; +document.scrollingElement.scrollWidth = 760; +add(mk('section', {rect: [0, 100, 412, 300]})); +'''); + if (r == null) return markTestSkipped('node not installed'); + expect(r['w'], 412); + }); + + test('a page that really scrolls sideways keeps its width', () async { + final r = await layout(r''' +document.scrollingElement.scrollWidth = 760; +add(mk('section', {rect: [0, 100, 760, 300]})); +'''); + if (r == null) return markTestSkipped('node not installed'); + expect(r['w'], 760); + }); + test('scanCapped is set only when the element scan hit its limit', () async { final few = await layout(r''' add(mk('section', {rect: [0, 0, 100, 100]})); diff --git a/test/widgets/structure_data_test.dart b/test/widgets/structure_data_test.dart index 51008c4a..a74e28c3 100644 --- a/test/widgets/structure_data_test.dart +++ b/test/widgets/structure_data_test.dart @@ -7,6 +7,7 @@ import 'package:view_source_vibe/models/inspection/page_inspection.dart'; import 'package:view_source_vibe/models/inspection/page_layout.dart'; import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/services/inspection_store.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'; import 'package:view_source_vibe/widgets/structure_view.dart'; @@ -212,9 +213,10 @@ void main() { expect(wireframePainter(tester).backgroundFullPage, isFalse); // The scroll-through capture finishes: the larger screenshot replaces it. - service.debugSetFullPageScreenshot(Present( - Uint8List.fromList(pngBytes), - source: DataSource.browser)); + final shot = Uint8List.fromList(pngBytes); + service.debugSetFullPageScreenshot( + Present(shot, source: DataSource.browser), + tiles: PageShotTiles([(shot, 0), (shot, 800)], cssWidth: 1000)); await tester.pump(); await tester.pump(); expect(wireframePainter(tester).backgroundFullPage, isTrue); @@ -233,22 +235,22 @@ void main() { } void _backgroundRectTests() { - group('StructurePainter.backgroundRect', () { - const layout = PageLayout( - viewportWidth: 400, - viewportHeight: 800, - width: 600, // document overflows the viewport horizontally - height: 3000, - totalBlocks: 0, - blocks: []); - - test('draws the shot viewport-wide at its own aspect ratio', () { - // 480x2400 px shot of a 400x2000 CSS px page, at scale 0.5. - final r = StructurePainter.backgroundRect(480, 2400, layout, 0.5); + group('StructurePainter.tileRect', () { + test('draws a tile viewport-wide at its own aspect ratio', () { + // 480x2400 px shot of a 400 CSS px wide viewport, at scale 0.5. + final r = StructurePainter.tileRect(480, 2400, 400, 0, 0.5); expect(r.left, 0); expect(r.top, 0); expect(r.width, closeTo(200, 1e-9)); expect(r.height, closeTo(1000, 1e-9)); }); + + test('a tile starts at its page offset, scaled', () { + // 960x1100 px shot of a 400 CSS px wide viewport, 1300 CSS px down. + final r = StructurePainter.tileRect(960, 1100, 400, 1300, 0.5); + expect(r.top, closeTo(650, 1e-9)); + expect(r.width, closeTo(200, 1e-9)); + expect(r.height, closeTo(200 * 1100 / 960, 1e-9)); + }); }); }