Truly independent web browser
LibWeb+WebContent: Screenshot an element from its own position
sideshowbarker59ded6071d7b
diff --git a/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Libraries/LibWeb/WebDriver/Screenshot.cppindex 4e1a5fb1917..47cb7ebbf90 100644--- a/Libraries/LibWeb/WebDriver/Screenshot.cpp+++ b/Libraries/LibWeb/WebDriver/Screenshot.cpp@@ -50,9 +50,10 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_contreturn;}- // NB: Validate the bitmap size before requesting canvas backing from the compositor.+ // NB: Validate the bitmap size before requesting canvas backing from the compositor. The framebuffer is captured+ // whole, so that step 6 can draw its region at the rectangle's coordinates.Gfx::IntSize paint_size { static_cast<int>(paint_width), static_cast<int>(paint_height) };- auto bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, paint_size);+ auto bitmap_or_error = Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, viewport_device_rect.size());if (bitmap_or_error.is_error()) {callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Unable to allocate the screenshot"sv));return;@@ -82,8 +83,8 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_cont// - Height: paint heightGfx::IntRect paint_rect { rect.location(), paint_size };- HTML::PaintConfig paint_config { .canvas_fill_rect = paint_rect };- browsing_context.active_document()->navigable()->render_screenshot(bitmap, paint_config, [bitmap, element = GC::make_root(element), canvas = GC::make_root(canvas), callback = move(callback)](auto result) mutable {+ HTML::PaintConfig paint_config { .canvas_fill_rect = Gfx::IntRect { {}, viewport_device_rect.size() } };+ browsing_context.active_document()->navigable()->render_screenshot(bitmap, paint_config, [bitmap, paint_rect, element = GC::make_root(element), canvas = GC::make_root(canvas), callback = move(callback)](auto result) mutable {if (result == Compositor::ScreenshotResult::Failed) {callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "The compositor did not take the screenshot"sv));return;@@ -91,7 +92,13 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_contHTML::TemporaryExecutionContext execution_context { element->document().relevant_settings_object() };- auto image_bitmap = HTML::ImageBitmap::create(bitmap);+ // A rectangle can start outside the framebuffer, where nothing is drawn.+ auto region = bitmap->cropped(paint_rect, Gfx::Color::Transparent);+ if (region.is_error()) {+ callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Unable to allocate the screenshot"sv));+ return;+ }+ auto image_bitmap = HTML::ImageBitmap::create(region.release_value());if (!canvas->canvas_rendering_context_2d()->draw_image(*image_bitmap, 0, 0)) {callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Failed to draw the screenshot to the canvas"sv));return;diff --git a/Services/WebContent/WebDriverConnection.cpp b/Services/WebContent/WebDriverConnection.cppindex bb757000a6e..4c3215a9039 100644--- a/Services/WebContent/WebDriverConnection.cpp+++ b/Services/WebContent/WebDriverConnection.cpp@@ -2638,7 +2638,15 @@ Web::WebDriver::Response WebDriverConnection::take_element_screenshot(String eleif (!connection)return;// a. Let element rect be element's rectangle.- auto element_rect = connection->calculate_absolute_rect_of_element(element);+ // NB: The framebuffer is the viewport, so the rectangle is the element's bounding client rect, which is+ // relative to the viewport rather than to the document.+ auto bounding_rect = element->get_bounding_client_rect();+ Gfx::IntRect element_rect {+ static_cast<int>(bounding_rect.x()),+ static_cast<int>(bounding_rect.y()),+ static_cast<int>(bounding_rect.width()),+ static_cast<int>(bounding_rect.height())+ };// b. Let screenshot result be the result of trying to call draw a bounding box from the framebuffer, given element rect as an argument.Web::WebDriver::draw_bounding_box_from_the_framebuffer(connection->current_browsing_context(), element, element_rect, [connection](auto canvas_or_error) mutable {diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 1b00fc0f924..cdd09a85304 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -26,6 +26,7 @@ if (BUILD_TESTING AND NOT WIN32)ladybird_python_test(test-webdriver-bidi.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-content-blockers.py ARGS $<TARGET_FILE:WebDriver> TIMEOUT 180)ladybird_python_test(test-webdriver-delete-session.py ARGS $<TARGET_FILE:WebDriver>)+ ladybird_python_test(test-webdriver-element-screenshot.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-error-keep-alive.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-force-dark.py ARGS $<TARGET_FILE:WebDriver>)ladybird_python_test(test-webdriver-permissions-settings.py ARGS $<TARGET_FILE:WebDriver>)diff --git a/Tests/LibWebView/test-webdriver-element-screenshot.py b/Tests/LibWebView/test-webdriver-element-screenshot.pynew file mode 100755index 00000000000..9ef1105f6fe--- /dev/null+++ b/Tests/LibWebView/test-webdriver-element-screenshot.py@@ -0,0 +1,148 @@+#!/usr/bin/env python3+#+# Copyright (c) 2026-present, the Ladybird developers.+#+# SPDX-License-Identifier: BSD-2-Clause++import http.server+import runpy+import subprocess+import sys+import tempfile+import threading+import time++from pathlib import Path++helpers = runpy.run_path(str(Path(__file__).with_name("test-webdriver-delete-session.py")))++PAGE = b"""<!doctype html>+<style>+html, body { margin: 0; background: white; }+#target { position: absolute; left: 300px; top: 200px; width: 100px; height: 50px; background: red; }+#offscreen { position: absolute; left: 0; top: -20px; width: 100px; height: 50px; background: red; }+#fixed { position: fixed; left: 500px; top: 0; width: 100px; height: 50px; background: red; }+#spacer { height: 3000px; }+</style>+<div id="target"></div>+<div id="offscreen"></div>+<div id="fixed"></div>+<div id="spacer"></div>+"""+++class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ if self.path == "/favicon.ico":+ self.send_error(404)+ return+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(PAGE)++ def log_message(self, format, *args):+ pass+++# The page decodes the screenshot itself, and reports its size and the colors of the pixels the test looks at.+DECODE_SCRIPT = """+const [data, points, done] = arguments;+const image = new Image();+image.onload = () => {+ const canvas = document.createElement("canvas");+ canvas.width = image.width;+ canvas.height = image.height;+ const context = canvas.getContext("2d");+ context.drawImage(image, 0, 0);+ const colors = points.map(([x, y]) => Array.from(context.getImageData(x, y, 1, 1).data));+ done({ width: image.width, height: image.height, colors });+};+image.onerror = () => done(null);+image.src = "data:image/png;base64," + data;+"""+++def main():+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ with tempfile.TemporaryDirectory() as directory:+ # The pixels are colors the display list carries, which take no GPU to draw.+ process, port = helpers["launch_webdriver"](+ sys.argv[1], "--headless", "--force-cpu-painting", "--profile-path", directory+ )+ session = None+ try:+ session = helpers["create_session"](port)++ def command(method, path, body=None):+ status, payload, raw = helpers["request"](port, method, f"/session/{session}/{path}", body)+ assert status == 200, raw+ return payload["value"]++ command("POST", "window/rect", {"width": 800, "height": 600})+ url = f"http://127.0.0.1:{server.server_port}/"+ command("POST", "url", {"url": url})+ deadline = time.monotonic() + 30+ while command("POST", "execute/sync", {"script": "return document.readyState", "args": []}) != "complete":+ assert time.monotonic() < deadline, "The page did not finish loading"+ time.sleep(0.01)++ element = command("POST", "element", {"using": "css selector", "value": "#target"})+ element_id = next(iter(element.values()))+ screenshot = command("GET", f"element/{element_id}/screenshot")++ # https://w3c.github.io/webdriver/#dfn-draw-a-bounding-box-from-the-framebuffer+ # The image starts at the element's position, so the element is at its top-left corner.+ result = command(+ "POST",+ "execute/async",+ {"script": DECODE_SCRIPT, "args": [screenshot, [[0, 0], [99, 49], [100, 50]]]},+ )+ assert result is not None, "The element screenshot isn't a decodable PNG"+ red, white = [255, 0, 0, 255], [255, 255, 255, 255]+ assert result["colors"][0] == red, f"Top-left pixel isn't the element: {result}"+ assert result["colors"][1] == red, f"The element's bottom-right pixel isn't red: {result}"+ assert result["colors"][2] == white, f"The pixel past the element isn't the page: {result}"+ print("PASS: the element screenshot starts at the element")++ # An element that starts above the viewport has nothing drawn for the rows above it.+ element = command("POST", "element", {"using": "css selector", "value": "#offscreen"})+ screenshot = command("GET", f"element/{next(iter(element.values()))}/screenshot")+ result = command(+ "POST", "execute/async", {"script": DECODE_SCRIPT, "args": [screenshot, [[0, 0], [0, 20]]]}+ )+ assert result is not None, "The offscreen element's screenshot isn't a decodable PNG"+ assert result["colors"][0][3] == 0, f"The rows above the viewport aren't transparent: {result}"+ assert result["colors"][1] == red, f"The element's first visible row isn't red: {result}"+ print("PASS: the part of an element outside the viewport is transparent")++ # On a scrolled page, an element is found where the viewport shows it.+ command("POST", "execute/sync", {"script": "window.scrollTo(0, 100)", "args": []})+ element = command("POST", "element", {"using": "css selector", "value": "#fixed"})+ screenshot = command("GET", f"element/{next(iter(element.values()))}/screenshot")+ result = command(+ "POST", "execute/async", {"script": DECODE_SCRIPT, "args": [screenshot, [[0, 0], [99, 49]]]}+ )+ assert result is not None, "The fixed element's screenshot isn't a decodable PNG"+ assert result["colors"] == [red, red], (+ f"The fixed element isn't at the top-left on a scrolled page: {result}"+ )+ print("PASS: the element screenshot of a scrolled page starts at the element")+ finally:+ try:+ if session is not None:+ helpers["request"](port, "DELETE", f"/session/{session}")+ finally:+ process.terminate()+ try:+ process.wait(timeout=5)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait()+ server.shutdown()+ server.server_close()+++main()