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
34 changes: 28 additions & 6 deletions lib/services/html_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4609,6 +4609,26 @@ Technical details: $message''';
notifyListeners();
}

/// Scrolls the page to [y] CSS pixels and waits until the scroll settled.
/// The native scrollTo works in view pixels, which on phones
/// (devicePixelRatio > 1) are not CSS pixels — scrolling by viewportHeight
/// there would advance only a fraction of a screen — so scroll via
/// JavaScript in an isolated world, with instant behavior (pages may set
/// scroll-behavior: smooth).
Future<void> _scrollPageTo(InAppWebViewController c, int y) async {
final world = collectorWorld(defaultTargetPlatform);
await c.evaluateJavascript(
source: 'window.scrollTo({top: $y, left: 0, behavior: "instant"})',
contentWorld: world);
for (var i = 0; i < 10; i++) {
await Future<void>.delayed(const Duration(milliseconds: 60));
final cur = await c.evaluateJavascript(
source: 'window.scrollY', contentWorld: world);
final curY = double.tryParse(cur?.toString() ?? '') ?? 0;
if ((curY - y).abs() <= 1) return;
}
}

/// One scroll through the live page in viewport-sized steps: lazy content
/// (loading=lazy, IntersectionObserver) is fetched while each step is
/// screenshotted; the shots are stitched into one full-page image and the
Expand All @@ -4624,7 +4644,8 @@ Technical details: $message''';
source: '([Math.ceil(Math.max(document.scrollingElement ? '
'document.scrollingElement.scrollHeight : 0, document.body ? '
'document.body.scrollHeight : 0)), window.innerHeight, '
'window.innerWidth, Math.round(window.scrollY)]).join(",")');
'window.innerWidth, Math.round(window.scrollY)]).join(",")',
contentWorld: collectorWorld(defaultTargetPlatform));
final parts = (dims?.toString() ?? '').split(',');
if (parts.length < 4) return;
final pageH = double.tryParse(parts[0]) ?? 0;
Expand All @@ -4636,23 +4657,24 @@ Technical details: $message''';
final steps = (pageH / vh).ceil();
for (var i = 0; i < steps && i < _maxFullPageShots; i++) {
if (stale()) return;
await c.scrollTo(x: 0, y: (i * vh).round());
await _scrollPageTo(c, (i * vh).round());
// Let the new scroll position render and lazy content start.
await Future<void>.delayed(const Duration(milliseconds: 120));
await Future<void>.delayed(const Duration(milliseconds: 80));
// Where the browser actually scrolled to: rounding and clamping at
// the bottom make this differ from i*vh. The stitch places each shot
// at its real offset, so the image stays aligned with the page.
final pos = await c.evaluateJavascript(
source: 'Math.round(window.scrollY)');
source: 'Math.round(window.scrollY)',
contentWorld: collectorWorld(defaultTargetPlatform));
final y = double.tryParse(pos?.toString() ?? '') ?? i * vh;
final shot = await c.takeScreenshot(
screenshotConfiguration: _fullPageScreenshotCfg);
if (shot != null && shot.isNotEmpty) shots.add((shot, y));
}
await c.scrollTo(x: 0, y: oldY.round());
await _scrollPageTo(c, oldY.round());
if (stale() || shots.isEmpty) return;
final image = await stitchScreenshots(shots,
pageHeight: pageH, viewportWidth: iw);
pageHeight: pageH, viewportHeight: vh, viewportWidth: iw);
if (image == null) return;
final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
image.dispose();
Expand Down
20 changes: 12 additions & 8 deletions lib/services/screenshot_stitch.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@ import 'dart:ui'
/// offset (CSS px) it was taken at: the browser rounds and clamps scroll
/// positions (at the bottom the last shot starts at pageHeight - viewport,
/// not at steps*viewport), so shots are placed at their real offset to keep
/// the content aligned. [pageHeight] and [viewportWidth] are the page's CSS
/// dimensions at capture time; the result's width is the first shot's width
/// and its height the page height at that scale. Returns null when no shot
/// decodes.
/// the content aligned. Every shot is drawn into a slot of exactly one
/// viewport height at the shot scale, so a shot that decodes at an odd pixel
/// size cannot come out larger than the others. [pageHeight],
/// [viewportHeight] and [viewportWidth] are the page's CSS dimensions at
/// capture time; the result's width is the first shot's width and its height
/// the page height at that scale. Returns null when no shot decodes.
Future<Image?> stitchScreenshots(
List<(Uint8List shot, double offset)> shots, {
required double pageHeight,
required double viewportHeight,
required double viewportWidth,
}) async {
final images = <(Image img, double offset)>[];
Expand All @@ -28,19 +31,20 @@ Future<Image?> stitchScreenshots(
// Skip a shot that does not decode.
}
}
if (images.isEmpty || viewportWidth <= 0) return null;
if (images.isEmpty || viewportWidth <= 0 || viewportHeight <= 0) return null;
final w = images.first.$1.width.toDouble();
final scale = w / viewportWidth; // image px per CSS px
final slotH = viewportHeight * scale;
final targetH =
(pageHeight * w / viewportWidth).clamp(1.0, 100000.0).ceilToDouble();
(pageHeight * scale).clamp(1.0, 100000.0).ceilToDouble();
final recorder = PictureRecorder();
final canvas = Canvas(recorder);
canvas.clipRect(Rect.fromLTWH(0, 0, w, targetH));
final scale = w / viewportWidth; // image px per CSS px
for (final (img, offset) in images) {
canvas.drawImageRect(
img,
Rect.fromLTWH(0, 0, img.width.toDouble(), img.height.toDouble()),
Rect.fromLTWH(0, offset * scale, w, img.height.toDouble()),
Rect.fromLTWH(0, offset * scale, w, slotH),
Paint()..filterQuality = FilterQuality.low,
);
img.dispose();
Expand Down
29 changes: 28 additions & 1 deletion test/services/screenshot_stitch_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ void main() {
final img = await stitchScreenshots(
[(top, 0), (bottom, 50)],
pageHeight: 200,
viewportHeight: 100,
viewportWidth: 100);
expect(img, isNotNull);
expect(img!.width, 100);
Expand All @@ -48,6 +49,7 @@ void main() {
final img = await stitchScreenshots(
[(top, 0), (bottom, 50)],
pageHeight: 150,
viewportHeight: 100,
viewportWidth: 100);
expect(img, isNotNull);
expect(img!.width, 100);
Expand All @@ -68,21 +70,46 @@ void main() {
final img = await stitchScreenshots(
[(shot, 0), (shot, 400)],
pageHeight: 800,
viewportHeight: 400,
viewportWidth: 400);
expect(img, isNotNull);
expect(img!.width, 200);
expect(img.height, 400);
img.dispose();
});

test('a shot that decodes taller than one viewport is squeezed into its '
'slot, not drawn larger', () async {
// Phone quirk: the second shot comes back at an odd pixel size.
final tall = await solidPng(100, 150, const ui.Color(0xFF0000FF));
final bottom = await solidPng(100, 100, const ui.Color(0xFF00FF00));
final img = await stitchScreenshots(
[(tall, 0), (bottom, 100)],
pageHeight: 200,
viewportHeight: 100,
viewportWidth: 100);
expect(img, isNotNull);
// One viewport slot per shot: the image is the page height, not taller.
expect(img!.width, 100);
expect(img.height, 200);

final raw = await img.toByteData(format: ui.ImageByteFormat.rawStraightRgba);
final px = raw!.buffer.asUint8List();
int at(int x, int y) => (y * img.width + x) * 4;
expect(px[at(10, 50) + 2], 0xFF); // first slot: blue, squeezed to 100 px
expect(px[at(10, 150) + 1], 0xFF); // second slot: green
img.dispose();
});

test('stitchScreenshots returns null without decodable shots', () async {
expect(
await stitchScreenshots([], pageHeight: 100, viewportWidth: 100),
await stitchScreenshots([], pageHeight: 100, viewportHeight: 100, viewportWidth: 100),
isNull);
expect(
await stitchScreenshots(
[(Uint8List.fromList([1, 2, 3]), 0)],
pageHeight: 100,
viewportHeight: 100,
viewportWidth: 100),
isNull);
});
Expand Down
Loading