Lightpanda: the headless browser designed for AI and automation
Add buffers to Context2D state to minimize allocations
Karl Seguin195e240c9daa
diff --git a/src/browser/tests/canvas/canvas_rendering_context_2d.html b/src/browser/tests/canvas/canvas_rendering_context_2d.htmlindex f48d98586..ff06264db 100644--- a/src/browser/tests/canvas/canvas_rendering_context_2d.html+++ b/src/browser/tests/canvas/canvas_rendering_context_2d.html@@ -195,6 +195,14 @@testing.expectEqual("bold 20px Arial", ctx.font);ctx.font = "12pt serif";testing.expectEqual(16 * 0.6 * 3, ctx.measureText("abc").width);++ // Longer than the inline buffer.+ const long = "8px " + Array.from({length: 40}, (_, i) => "'Family Number " + i + "'").join(", ");+ ctx.font = long;+ testing.expectEqual(long, ctx.font);+ testing.expectEqual(8 * 0.6, ctx.measureText("a").width);+ ctx.font = "10px serif";+ testing.expectEqual("10px serif", ctx.font);}</script>@@ -209,6 +217,11 @@testing.expectEqual("3,3", ctx.getLineDash().join());ctx.setLineDash([]);testing.expectEqual(0, ctx.getLineDash().length);+ // Longer than the inline buffer once doubled.+ ctx.setLineDash([1, 2, 3, 4, 5]);+ testing.expectEqual("1,2,3,4,5,1,2,3,4,5", ctx.getLineDash().join());+ ctx.setLineDash([6, 7]);+ testing.expectEqual("6,7", ctx.getLineDash().join());ctx.lineDashOffset = 2;testing.expectEqual(2, ctx.lineDashOffset);@@ -226,12 +239,22 @@testing.expectEqual(true, ctx.createRadialGradient(0, 0, 1, 0, 0, 5) instanceof CanvasGradient);testing.expectEqual(true, ctx.createConicGradient(0, 5, 5) instanceof CanvasGradient);ctx.fillStyle = gradient;+ testing.expectEqual(true, ctx.fillStyle === gradient);ctx.strokeStyle = gradient;+ testing.expectEqual(true, ctx.strokeStyle === gradient);ctx.fillRect(0, 0, 10, 10);+ ctx.fillStyle = "red";+ testing.expectEqual("#ff0000", ctx.fillStyle);+ ctx.strokeStyle = "not a color";+ testing.expectEqual(true, ctx.strokeStyle === gradient);+ ctx.strokeStyle = "blue";+ testing.expectEqual("#0000ff", ctx.strokeStyle);const pattern = ctx.createPattern(document.createElement("canvas"), "repeat");testing.expectEqual(true, pattern instanceof CanvasPattern);pattern.setTransform();+ ctx.fillStyle = pattern;+ testing.expectEqual(true, ctx.fillStyle === pattern);testing.expectError("SyntaxError", () => ctx.createPattern(document.createElement("canvas"), "sideways"));testing.expectEqual(0, ctx.shadowBlur);diff --git a/src/browser/webapi/canvas/CanvasGradient.zig b/src/browser/webapi/canvas/CanvasGradient.zigindex 2f68e075d..aab62ca10 100644--- a/src/browser/webapi/canvas/CanvasGradient.zig+++ b/src/browser/webapi/canvas/CanvasGradient.zig@@ -1,4 +1,4 @@-// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)//// Francis Bouvier <[email protected]>// Pierre Tachoire <[email protected]>diff --git a/src/browser/webapi/canvas/CanvasPattern.zig b/src/browser/webapi/canvas/CanvasPattern.zigindex 79664c720..7003aef92 100644--- a/src/browser/webapi/canvas/CanvasPattern.zig+++ b/src/browser/webapi/canvas/CanvasPattern.zig@@ -1,4 +1,4 @@-// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)//// Francis Bouvier <[email protected]>// Pierre Tachoire <[email protected]>diff --git a/src/browser/webapi/canvas/CanvasRenderingContext2D.zig b/src/browser/webapi/canvas/CanvasRenderingContext2D.zigindex ef9329e9c..29cfc13cd 100644--- a/src/browser/webapi/canvas/CanvasRenderingContext2D.zig+++ b/src/browser/webapi/canvas/CanvasRenderingContext2D.zig@@ -20,8 +20,6 @@ const std = @import("std");const js = @import("../../js/js.zig");-const color = @import("../../color.zig");-const Canvas = @import("../element/html/Canvas.zig");const ImageData = @import("../ImageData.zig");const context2d = @import("context2d.zig");@@ -38,27 +36,26 @@ const CanvasRenderingContext2D = @This();/// Reference to the parent canvas element./// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/canvas_canvas: *Canvas,-/// Fill color.-/// TODO: Add support for `CanvasGradient` and `CanvasPattern`.-_fill_style: color.RGBA = color.RGBA.Named.black,_state: context2d.State = .{},pub fn getCanvas(self: *const CanvasRenderingContext2D) *Canvas {return self._canvas;}-pub fn getFillStyle(self: *const CanvasRenderingContext2D, exec: *Execution) ![]const u8 {- var w = std.Io.Writer.Allocating.init(exec.local_arena);- try self._fill_style.format(&w.writer);- return w.written();+pub fn getFillStyle(self: *const CanvasRenderingContext2D, exec: *const Execution) !context2d.StyleOutput {+ return self._state.getStyle(.fill, exec);+}++pub fn setFillStyle(self: *CanvasRenderingContext2D, value: context2d.StyleInput) void {+ self._state.setStyle(.fill, value);+}++pub fn getStrokeStyle(self: *const CanvasRenderingContext2D, exec: *const Execution) !context2d.StyleOutput {+ return self._state.getStyle(.stroke, exec);}-pub fn setFillStyle(- self: *CanvasRenderingContext2D,- value: []const u8,-) !void {- // Prefer the same fill_style if fails.- self._fill_style = color.RGBA.parse(value) catch self._fill_style;+pub fn setStrokeStyle(self: *CanvasRenderingContext2D, value: context2d.StyleInput) void {+ self._state.setStyle(.stroke, value);}const WidthOrImageData = union(enum) {@@ -107,7 +104,7 @@ pub fn getImageData(}pub fn getFont(self: *const CanvasRenderingContext2D) []const u8 {- return self._state.font;+ return self._state.font();}pub fn setFont(self: *CanvasRenderingContext2D, value: []const u8, exec: *const Execution) !void {@@ -123,7 +120,7 @@ pub fn setLineDash(self: *CanvasRenderingContext2D, segments: []const f64, exec:}pub fn getLineDash(self: *const CanvasRenderingContext2D) []const f64 {- return self._state.line_dash;+ return self._state.lineDash();}pub fn roundRect(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: ?js.Value) void {}@@ -164,7 +161,6 @@ pub fn translate(_: *CanvasRenderingContext2D, _: f64, _: f64) void {}pub fn transform(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64) void {}pub fn setTransform(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64) void {}pub fn resetTransform(_: *CanvasRenderingContext2D) void {}-pub fn setStrokeStyle(_: *CanvasRenderingContext2D, _: []const u8) void {}pub fn clearRect(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}pub fn fillRect(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}pub fn strokeRect(_: *CanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}@@ -220,7 +216,7 @@ pub const JsApi = struct {pub const fontKerning = bridge.property("auto", .{ .template = false, .readonly = false });pub const globalAlpha = bridge.property(1.0, .{ .template = false, .readonly = false });pub const globalCompositeOperation = bridge.property("source-over", .{ .template = false, .readonly = false });- pub const strokeStyle = bridge.property("#000000", .{ .template = false, .readonly = false });+ pub const strokeStyle = bridge.accessor(CanvasRenderingContext2D.getStrokeStyle, CanvasRenderingContext2D.setStrokeStyle, .{});pub const lineWidth = bridge.property(1.0, .{ .template = false, .readonly = false });pub const lineCap = bridge.property("butt", .{ .template = false, .readonly = false });pub const lineJoin = bridge.property("miter", .{ .template = false, .readonly = false });diff --git a/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig b/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zigindex 2048fdd27..53af9e984 100644--- a/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig+++ b/src/browser/webapi/canvas/OffscreenCanvasRenderingContext2D.zig@@ -19,7 +19,6 @@const std = @import("std");const js = @import("../../js/js.zig");-const color = @import("../../color.zig");const ImageData = @import("../ImageData.zig");const context2d = @import("context2d.zig");@@ -33,23 +32,22 @@ const Execution = js.Execution;/// It can be obtained with a call to `OffscreenCanvas#getContext`./// https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCanvasRenderingContext2Dconst OffscreenCanvasRenderingContext2D = @This();-/// Fill color.-/// TODO: Add support for `CanvasGradient` and `CanvasPattern`.-_fill_style: color.RGBA = color.RGBA.Named.black,_state: context2d.State = .{},-pub fn getFillStyle(self: *const OffscreenCanvasRenderingContext2D, exec: *Execution) ![]const u8 {- var w = std.Io.Writer.Allocating.init(exec.local_arena);- try self._fill_style.format(&w.writer);- return w.written();+pub fn getFillStyle(self: *const OffscreenCanvasRenderingContext2D, exec: *const Execution) !context2d.StyleOutput {+ return self._state.getStyle(.fill, exec);}-pub fn setFillStyle(- self: *OffscreenCanvasRenderingContext2D,- value: []const u8,-) !void {- // Prefer the same fill_style if fails.- self._fill_style = color.RGBA.parse(value) catch self._fill_style;+pub fn setFillStyle(self: *OffscreenCanvasRenderingContext2D, value: context2d.StyleInput) void {+ self._state.setStyle(.fill, value);+}++pub fn getStrokeStyle(self: *const OffscreenCanvasRenderingContext2D, exec: *const Execution) !context2d.StyleOutput {+ return self._state.getStyle(.stroke, exec);+}++pub fn setStrokeStyle(self: *OffscreenCanvasRenderingContext2D, value: context2d.StyleInput) void {+ self._state.setStyle(.stroke, value);}const WidthOrImageData = union(enum) {@@ -94,7 +92,7 @@ pub fn getImageData(}pub fn getFont(self: *const OffscreenCanvasRenderingContext2D) []const u8 {- return self._state.font;+ return self._state.font();}pub fn setFont(self: *OffscreenCanvasRenderingContext2D, value: []const u8, exec: *const Execution) !void {@@ -110,7 +108,7 @@ pub fn setLineDash(self: *OffscreenCanvasRenderingContext2D, segments: []const f}pub fn getLineDash(self: *const OffscreenCanvasRenderingContext2D) []const f64 {- return self._state.line_dash;+ return self._state.lineDash();}pub fn roundRect(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: ?js.Value) void {}@@ -151,7 +149,6 @@ pub fn translate(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64) void {}pub fn transform(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64) void {}pub fn setTransform(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64, _: f64, _: f64) void {}pub fn resetTransform(_: *OffscreenCanvasRenderingContext2D) void {}-pub fn setStrokeStyle(_: *OffscreenCanvasRenderingContext2D, _: []const u8) void {}pub fn clearRect(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}pub fn fillRect(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}pub fn strokeRect(_: *OffscreenCanvasRenderingContext2D, _: f64, _: f64, _: f64, _: f64) void {}@@ -206,7 +203,7 @@ pub const JsApi = struct {pub const fontKerning = bridge.property("auto", .{ .template = false, .readonly = false });pub const globalAlpha = bridge.property(1.0, .{ .template = false, .readonly = false });pub const globalCompositeOperation = bridge.property("source-over", .{ .template = false, .readonly = false });- pub const strokeStyle = bridge.property("#000000", .{ .template = false, .readonly = false });+ pub const strokeStyle = bridge.accessor(OffscreenCanvasRenderingContext2D.getStrokeStyle, OffscreenCanvasRenderingContext2D.setStrokeStyle, .{});pub const lineWidth = bridge.property(1.0, .{ .template = false, .readonly = false });pub const lineCap = bridge.property("butt", .{ .template = false, .readonly = false });pub const lineJoin = bridge.property("miter", .{ .template = false, .readonly = false });diff --git a/src/browser/webapi/canvas/TextMetrics.zig b/src/browser/webapi/canvas/TextMetrics.zigindex 9538a8510..c418cec4e 100644--- a/src/browser/webapi/canvas/TextMetrics.zig+++ b/src/browser/webapi/canvas/TextMetrics.zig@@ -1,4 +1,4 @@-// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)//// Francis Bouvier <[email protected]>// Pierre Tachoire <[email protected]>@@ -16,7 +16,10 @@// You should have received a copy of the GNU Affero General Public License// along with this program. If not, see <https://www.gnu.org/licenses/>.+const lp = @import("lightpanda");+const js = @import("../../js/js.zig");+const Page = @import("../../Page.zig");const Execution = js.Execution;@@ -24,6 +27,7 @@ const Execution = js.Execution;/// 0.8em and descent 0.2em, as in a generic sans-serif face.const TextMetrics = @This();+_rc: lp.RC = .{},_width: f64,_ascent: f64,_descent: f64,@@ -36,6 +40,18 @@ pub fn init(width: f64, font_size: f64, exec: *const Execution) !*TextMetrics {});}+pub fn deinit(self: *TextMetrics, page: *Page) void {+ page.factory.destroy(self);+}++pub fn acquireRef(self: *TextMetrics) void {+ self._rc.acquire();+}++pub fn releaseRef(self: *TextMetrics, page: *Page) void {+ self._rc.release(self, page);+}+pub fn getWidth(self: *const TextMetrics) f64 {return self._width;}diff --git a/src/browser/webapi/canvas/context2d.zig b/src/browser/webapi/canvas/context2d.zigindex 02e06b787..e0a269a1b 100644--- a/src/browser/webapi/canvas/context2d.zig+++ b/src/browser/webapi/canvas/context2d.zig@@ -1,4 +1,4 @@-// Copyright (C) 2023-2025 Lightpanda (Selecy SAS)+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)//// Francis Bouvier <[email protected]>// Pierre Tachoire <[email protected]>@@ -21,23 +21,74 @@const std = @import("std");const js = @import("../../js/js.zig");+const color = @import("../../color.zig");const text_measure = @import("../../text_measure.zig");const TextMetrics = @import("TextMetrics.zig");+const CanvasGradient = @import("CanvasGradient.zig");+const CanvasPattern = @import("CanvasPattern.zig");const Execution = js.Execution;pub const default_font = "10px sans-serif";+// Chart libraries flip font and dash per label per animation frame, so these+// are stored inline: a page-arena copy per change never comes back. Only a+// value that doesn't fit falls back to the arena. 256 covers the long+// framework font stacks (Bootstrap's is ~200 bytes); 8 covers any real dash+// pattern after the odd-count doubling.+const font_capacity = 256;+const dash_capacity = 8;++/// What fillStyle/strokeStyle hold. Gradients and patterns are never painted,+/// but they round-trip so a script that assigns one reads it back.+pub const Style = union(enum) {+ color: color.RGBA,+ gradient: *CanvasGradient,+ pattern: *CanvasPattern,+};++/// Pointer fields first: the bridge probes them for an exact match before+/// falling back to string coercion.+pub const StyleInput = union(enum) {+ gradient: *CanvasGradient,+ pattern: *CanvasPattern,+ color: []const u8,+};++pub const StyleOutput = union(enum) {+ color: []const u8,+ gradient: *CanvasGradient,+ pattern: *CanvasPattern,+};+pub const State = struct {- font: []const u8 = default_font,+ fill_style: Style = .{ .color = color.RGBA.Named.black },+ stroke_style: Style = .{ .color = color.RGBA.Named.black },+font_size: f64 = 10,- line_dash: []const f64 = &.{},+ font_buf: [font_capacity]u8 = default_font.* ++ [_]u8{0} ** (font_capacity - default_font.len),+ font_len: u16 = default_font.len,+ font_overflow: ?[]const u8 = null,++ dash_buf: [dash_capacity]f64 = undefined,+ dash_len: u8 = 0,+ dash_overflow: ?[]const f64 = null,++ pub fn font(self: *const State) []const u8 {+ return self.font_overflow orelse self.font_buf[0..self.font_len];+ }/// Invalid font strings are ignored, per the spec.pub fn setFont(self: *State, value: []const u8, exec: *const Execution) !void {- if (std.mem.eql(u8, value, self.font)) return;+ if (std.mem.eql(u8, value, self.font())) return;const size = parseFontSize(value) orelse return;- self.font = try exec.arena.dupe(u8, value);+ if (value.len <= font_capacity) {+ @memcpy(self.font_buf[0..value.len], value);+ self.font_len = @intCast(value.len);+ self.font_overflow = null;+ } else {+ self.font_overflow = try exec.arena.dupe(u8, value);+ }self.font_size = size;}@@ -45,21 +96,58 @@ pub const State = struct {return TextMetrics.init(text_measure.width(text, self.font_size), self.font_size, exec);}+ pub fn lineDash(self: *const State) []const f64 {+ return self.dash_overflow orelse self.dash_buf[0..self.dash_len];+ }+/// Negative or non-finite segments leave the list unchanged; an odd count/// is repeated, per the spec.pub fn setLineDash(self: *State, segments: []const f64, exec: *const Execution) !void {for (segments) |s| {if (!(s >= 0) or std.math.isInf(s)) return;}- if (std.mem.eql(f64, segments, self.line_dash)) return;- if (segments.len % 2 == 0) {- self.line_dash = try exec.arena.dupe(f64, segments);+ if (std.mem.eql(f64, segments, self.lineDash())) return;+ const repeat: usize = if (segments.len % 2 == 0) 1 else 2;+ const len = segments.len * repeat;+ if (len <= dash_capacity) {+ for (0..repeat) |i| @memcpy(self.dash_buf[i * segments.len ..][0..segments.len], segments);+ self.dash_len = @intCast(len);+ self.dash_overflow = null;return;}- const doubled = try exec.arena.alloc(f64, segments.len * 2);- @memcpy(doubled[0..segments.len], segments);- @memcpy(doubled[segments.len..], segments);- self.line_dash = doubled;+ const dash = try exec.arena.alloc(f64, len);+ for (0..repeat) |i| @memcpy(dash[i * segments.len ..][0..segments.len], segments);+ self.dash_overflow = dash;+ }++ pub fn setStyle(self: *State, comptime field: enum { fill, stroke }, value: StyleInput) void {+ const style: *Style = if (field == .fill) &self.fill_style else &self.stroke_style;+ switch (value) {+ .gradient => |g| style.* = .{ .gradient = g },+ .pattern => |p| style.* = .{ .pattern = p },+ .color => |c| {+ // An unparseable color keeps the current style, per the spec.+ // Parsed into a local on purpose: assigning the literal+ // straight through `style` writes the tag before the payload,+ // so an early return from inside it leaves a `.color` with+ // no colour.+ const parsed = color.RGBA.parse(c) catch return;+ style.* = .{ .color = parsed };+ },+ }+ }++ pub fn getStyle(self: *const State, comptime field: enum { fill, stroke }, exec: *const Execution) !StyleOutput {+ const style = if (field == .fill) self.fill_style else self.stroke_style;+ switch (style) {+ .gradient => |g| return .{ .gradient = g },+ .pattern => |p| return .{ .pattern = p },+ .color => |c| {+ var w = std.Io.Writer.Allocating.init(exec.local_arena);+ try c.format(&w.writer);+ return .{ .color = w.written() };+ },+ }}};