Skip to content

Truly independent web browser

LibWeb: Handle WebDriver screenshot allocation failure

Shannon Booth5f49da5631a2
diff --git a/Libraries/LibWeb/WebDriver/Screenshot.cpp b/Libraries/LibWeb/WebDriver/Screenshot.cpp
index 4012d469c6c..e0f832ba2d9 100644
--- a/Libraries/LibWeb/WebDriver/Screenshot.cpp
+++ b/Libraries/LibWeb/WebDriver/Screenshot.cpp
@@ -5,6 +5,7 @@
*/
#include <AK/Base64.h>
+#include <AK/Checked.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/ImageFormats/PNGWriter.h>
#include <LibWeb/DOM/Document.h>
@@ -27,7 +28,7 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_cont
{
HTML::TemporaryExecutionContext execution_context { element.document().relevant_settings_object() };
- // 1. If either the initial viewport's width or height is 0 CSS pixels, return error with error code unable to capture screen.
+ // 1. If either the visual viewport's width or height is 0 CSS pixels, return error with error code unable to capture screen.
// NB: Another process hosts the top-level traversable when the browsing context is in an isolated frame.
auto viewport_rect = browsing_context.active_document()->navigable()->local_root()->viewport_rect();
if (viewport_rect.is_empty()) {
@@ -36,20 +37,35 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_cont
}
auto viewport_device_rect = browsing_context.page().enclosing_device_rect(viewport_rect).to_type<int>();
+ auto rectangle = rect.to_type<i64>();
- // 2. Let paint width be the initial viewport's width – min(rectangle x coordinate, rectangle x coordinate + rectangle width dimension).
- auto paint_width = viewport_device_rect.width() - min(rect.x(), rect.x() + rect.width());
+ // 2. Let paint width be the visual viewport's width – min(rectangle x coordinate, rectangle x coordinate + rectangle width dimension).
+ auto paint_width = viewport_device_rect.width() - min(rectangle.x(), rectangle.x() + rectangle.width());
- // 3. Let paint height be the initial viewport's height – min(rectangle y coordinate, rectangle y coordinate + rectangle height dimension).
- auto paint_height = viewport_device_rect.height() - min(rect.y(), rect.y() + rect.height());
+ // 3. Let paint height be the visual viewport's height – min(rectangle y coordinate, rectangle y coordinate + rectangle height dimension).
+ auto paint_height = viewport_device_rect.height() - min(rectangle.y(), rectangle.y() + rectangle.height());
+
+ if (paint_width <= 0 || paint_height <= 0 || !AK::is_within_range<int>(paint_width) || !AK::is_within_range<int>(paint_height)) {
+ callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Invalid screenshot dimensions"sv));
+ return;
+ }
+
+ // NB: Validate the bitmap size before requesting canvas backing from the compositor.
+ 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);
+ if (bitmap_or_error.is_error()) {
+ callback(Error::from_code(ErrorCode::UnableToCaptureScreen, "Unable to allocate the screenshot"sv));
+ return;
+ }
+ auto bitmap = bitmap_or_error.release_value();
// 4. Let canvas be a new canvas element, and set its width and height to paint width and paint height, respectively.
auto canvas_element = DOM::create_element(element.document(), HTML::TagNames::canvas, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
auto& canvas = as<HTML::HTMLCanvasElement>(*canvas_element);
// FIXME: Handle DevicePixelRatio in HiDPI mode.
- MUST(canvas.set_width(paint_width));
- MUST(canvas.set_height(paint_height));
+ MUST(canvas.set_width(paint_size.width()));
+ MUST(canvas.set_height(paint_size.height()));
// FIXME: 5. Let context, a canvas context mode, be the result of invoking the 2D context creation algorithm given canvas as the target.
canvas.create_2d_context({});
@@ -64,9 +80,8 @@ void draw_bounding_box_from_the_framebuffer(HTML::BrowsingContext& browsing_cont
// - Y coordinate: rectangle y coordinate
// - Width: paint width
// - Height: paint height
- Gfx::IntRect paint_rect { rect.x(), rect.y(), paint_width, paint_height };
+ Gfx::IntRect paint_rect { rect.location(), paint_size };
- auto bitmap = MUST(Gfx::Bitmap::create_shareable(Gfx::BitmapFormat::BGRA8888, Gfx::AlphaType::Premultiplied, Gfx::IntSize { paint_width, paint_height }));
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 {
if (result == Compositor::ScreenshotResult::Failed) {
diff --git a/Tests/LibWebView/test-webdriver-error-keep-alive.py b/Tests/LibWebView/test-webdriver-error-keep-alive.py
index 0c22a755aed..abae2e71983 100755
--- a/Tests/LibWebView/test-webdriver-error-keep-alive.py
+++ b/Tests/LibWebView/test-webdriver-error-keep-alive.py
@@ -10,6 +10,8 @@ import importlib
import json
import subprocess
+from urllib.parse import quote
+
WEBDRIVER_REQUEST_TIMEOUT_SECONDS = 30
webdriver_helpers = importlib.import_module("test-webdriver-delete-session")
@@ -28,8 +30,36 @@ def request(connection, method, path, body=None):
return response.status, payload, response_body
+def check_screenshot_error_preserves_element(connection, session_id, left):
+ session_path = f"/session/{session_id}"
+ document = (
+ '<!doctype html><body style="margin:0">'
+ f'<div style="position:fixed;left:{left};top:0;width:1px;height:1px"></div>'
+ )
+ status, _, body = request(connection, "POST", f"{session_path}/url", {"url": f"data:text/html,{quote(document)}"})
+ assert status == 200, body
+
+ status, payload, body = request(
+ connection, "POST", f"{session_path}/element", {"using": "css selector", "value": "div"}
+ )
+ assert status == 200, body
+ element_id = payload["value"]["element-6066-11e4-a52e-4f735466cecf"]
+ element_path = f"{session_path}/element/{element_id}"
+
+ status, payload, body = request(connection, "GET", f"{element_path}/screenshot")
+ assert status == 500 and payload["value"]["error"] == "unable to capture screen", body
+
+ status, payload, body = request(connection, "GET", f"{element_path}/name")
+ assert status == 200 and payload["value"] == "div", body
+
+ status, _, body = request(connection, "GET", f"{session_path}/screenshot")
+ assert status == 200, body
+
+
def run_test(webdriver_binary):
- webdriver, webdriver_port = webdriver_helpers.launch_webdriver(webdriver_binary, "--headless")
+ webdriver, webdriver_port = webdriver_helpers.launch_webdriver(
+ webdriver_binary, "--headless", "--force-cpu-painting"
+ )
connection = None
try:
# Every request in this test is sent over the same keep-alive connection, matching how the
@@ -65,6 +95,10 @@ def run_test(webdriver_binary):
if status != 200:
raise AssertionError(f"Get Title after unknown command failed with HTTP {status}: {response_body}")
+ check_screenshot_error_preserves_element(connection, session_id, "-100000px")
+ # At the right edge of the viewport, the calculated screenshot width is zero.
+ check_screenshot_error_preserves_element(connection, session_id, "100vw")
+
status, payload, response_body = request(connection, "DELETE", f"/session/{session_id}")
if status != 200:
raise AssertionError(f"Delete Session failed with HTTP {status}: {response_body}")