Skip to content

Lightpanda: the headless browser designed for AI and automation

convert rust panics into errors

Karl Seguin03b05e8ed239
diff --git a/src/browser/screenshot.zig b/src/browser/screenshot.zig
index 5ed53ddfc..25aea5ccb 100644
--- a/src/browser/screenshot.zig
+++ b/src/browser/screenshot.zig
@@ -110,6 +110,7 @@ pub const Prepared = struct {
RC_INVALID => "invalid options",
RC_NO_RASTER => "raster allocation failed",
RC_ENCODE_FAILED => "png encoding failed",
+ RC_PANIC => "renderer panicked",
else => "unknown",
}, .rc = rc });
return error.WriteFailed;
@@ -191,6 +192,7 @@ const RC_WRITE_REFUSED: i32 = 1;
const RC_INVALID: i32 = 2;
const RC_NO_RASTER: i32 = 3;
const RC_ENCODE_FAILED: i32 = 4;
+const RC_PANIC: i32 = 5;
const LINK_COLOR: u32 = 0x1a0dab;
const MUTED_COLOR: u32 = 0x6b6b6b;
diff --git a/src/rust/render/lib.rs b/src/rust/render/lib.rs
index d65cdaaf2..e802d900e 100644
--- a/src/rust/render/lib.rs
+++ b/src/rust/render/lib.rs
@@ -112,6 +112,7 @@ pub const RC_INVALID: i32 = 2;
/// The pixmap could not be allocated, even after the MAX_RASTER_* clamps.
pub const RC_NO_RASTER: i32 = 3;
pub const RC_ENCODE_FAILED: i32 = 4;
+pub const RC_PANIC: i32 = 5;
/// Renders `blocks` to PNG, streaming the encoded bytes to `write`.
/// `content_height` receives the full-page height in CSS px, and is filled in
@@ -124,6 +125,20 @@ pub unsafe extern "C" fn lp_render_png(
content_height: *mut u32,
ctx: *mut c_void,
write: LpWriteFn,
+) -> i32 {
+ let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ render_png(blocks, blocks_len, opts, content_height, ctx, write)
+ }));
+ caught.unwrap_or(RC_PANIC)
+}
+
+unsafe fn render_png(
+ blocks: *const LpBlock,
+ blocks_len: usize,
+ opts: LpRenderOpts,
+ content_height: *mut u32,
+ ctx: *mut c_void,
+ write: LpWriteFn,
) -> i32 {
if opts.width == 0 || !(opts.scale > 0.0) || opts.scale > 8.0 {
return RC_INVALID;