const std = @import("std"); const nextPaintEpoch = @import("utils.zig").nextPaintEpoch; const api = @import("context_abi_c"); const handles = @import("context-handles.zig"); const grapheme = @import("grapheme.zig"); const link = @import("link.zig"); const highlight_layers = @import("highlight-layers.zig"); const yoga = @import("yoga.zig"); const renderer = @import("renderer.zig"); const session = @import("session.zig"); const stdout_writer = @import("stdout-writer.zig"); const input_parser = @import("input-parser.zig"); const scene = @import("scene.zig"); const native_span_feed = @import("native-span-feed.zig"); const buf = @import("buffer.zig"); const buffer_effects = @import("buffer-methods.zig"); const native_renderable = @import("native-renderable.zig"); const text_buffer = @import("text-buffer.zig"); const text_buffer_view = @import("text-buffer-view.zig"); const logger = @import("logger.zig"); const utf8 = @import("utf8.zig"); const syntax_style = @import("syntax-style.zig"); const text_work = @import("text-work.zig"); const edit_buffer = @import("edit-buffer.zig"); const editor_view = @import("editor-view.zig"); const ansi = @import("ansi.zig"); const image = @import("image.zig"); const audio = @import("audio.zig"); const video = @import("video.zig"); const clipboard = @import("clipboard/host.zig"); const encoded_unicode = @import("encoded-unicode.zig"); const markdown = @import("markdown.zig"); pub const embedded_terminal = if (@import("ghostty_vt_options").available) @import("embedded-terminal/main.zig") else @import("embedded-terminal/unavailable.zig"); pub const EncodedChar = encoded_unicode.EncodedChar; pub const EncodedUnicode = encoded_unicode.EncodedUnicode; pub const terminal_input_bytes_max: u32 = api.OT_EMBEDDED_TERMINAL_INPUT_BYTES_MAX; const terminal_mods: u32 = api.OT_EMBEDDED_TERMINAL_MOD_SHIFT | api.OT_EMBEDDED_TERMINAL_MOD_CTRL | api.OT_EMBEDDED_TERMINAL_MOD_ALT | api.OT_EMBEDDED_TERMINAL_MOD_SUPER | api.OT_EMBEDDED_TERMINAL_MOD_CAPS_LOCK | api.OT_EMBEDDED_TERMINAL_MOD_NUM_LOCK; /// Encode calls bit-cast the header's modifier bits to Ghostty's KeyMods. fn assertTerminalMods(comptime Mods: type) void { inline for (.{ .{ "shift", api.OT_EMBEDDED_TERMINAL_MOD_SHIFT }, .{ "ctrl", api.OT_EMBEDDED_TERMINAL_MOD_CTRL }, .{ "alt", api.OT_EMBEDDED_TERMINAL_MOD_ALT }, .{ "super", api.OT_EMBEDDED_TERMINAL_MOD_SUPER }, .{ "caps_lock", api.OT_EMBEDDED_TERMINAL_MOD_CAPS_LOCK }, .{ "num_lock", api.OT_EMBEDDED_TERMINAL_MOD_NUM_LOCK }, }) |pair| { var mods: Mods = .{}; @field(mods, pair[0]) = true; if (@as(u16, @bitCast(mods)) != pair[1]) @compileError("Embedded terminal modifier differs from Ghostty: " ++ pair[0]); } } pub const EmbeddedTerminalKey = struct { action: u32 = api.OT_EMBEDDED_TERMINAL_KEY_PRESS, composing: bool = false, mods: u32 = 0, consumed_mods: u32 = 0, unshifted_codepoint: u32 = 0, key: []const u8 = "", text: []const u8 = "", }; pub const EmbeddedTerminalMouse = struct { action: u32, button: i32 = api.OT_EMBEDDED_TERMINAL_BUTTON_NONE, mods: u32 = 0, any_button_pressed: bool = false, x: f32, y: f32, }; pub const Handle = handles.Handle; pub const Diagnostic = logger.Diagnostic; pub const Error = handles.Error || yoga.Error || session.Error || error{ InvalidOptions, InvalidDimensions, ContextClosed, ContextBusy, LeaseLimit, LeaseBytesLimit, StaleLease, UnsupportedResource, }; pub const RendererBuffer = enum { current, next }; const scene_style_enum_maxima = blk: { const names = @typeInfo(api).@"struct".decl_names; @setEvalBranchQuota(64 * names.len); var count = 0; for (names) |name| { if (std.mem.startsWith(u8, name, "OT_STYLE_ENUM_") and !std.mem.endsWith(u8, name, "_MAX")) count += 1; } var maxima: [count]u32 = undefined; var present: [count]bool = @splat(false); for (names) |name| { if (!std.mem.startsWith(u8, name, "OT_STYLE_ENUM_") or !std.mem.endsWith(u8, name, "_MAX")) continue; const kind = @field(api, name[0 .. name.len - "_MAX".len]); maxima[kind] = @field(api, name); present[kind] = true; } for (present) |found| if (!found) @compileError("Missing checked scene style enum constraint"); break :blk maxima; }; const FrameBufferLease = struct { frame: scene.FrameRequest, which: RendererBuffer, destination: scene.BufferIdentity, lease: buf.BufferLease, }; pub const BufferOptions = struct { respect_alpha: bool = false, width_method: utf8.WidthMethod = .unicode, }; pub const BufferCrop = struct { x: u32 = 0, y: u32 = 0, width: ?u32 = null, height: ?u32 = null }; pub const ImageDraw = struct { x: i32 = 0, y: i32 = 0, width: u32, height: u32, pixel_width: u32 = 0, pixel_height: u32 = 0, source_x: u32 = 0, source_y: u32 = 0, source_width: ?u32 = null, source_height: ?u32 = null, protocol: image.RenderProtocol = .auto, }; pub const BufferGrid = struct { border_chars: [11]u32, foreground: buf.RGBA, background: buf.RGBA, draw_inner: bool, draw_outer: bool, }; pub const BufferDraw = struct { pub const Operation = enum(u32) { clear = api.OT_BUFFER_DRAW_CLEAR, fill = api.OT_BUFFER_DRAW_FILL, text = api.OT_BUFFER_DRAW_TEXT, cell = api.OT_BUFFER_DRAW_CELL, cell_blend = api.OT_BUFFER_DRAW_CELL_BLEND, char = api.OT_BUFFER_DRAW_CHAR, box = api.OT_BUFFER_DRAW_BOX, compose = api.OT_BUFFER_DRAW_COMPOSE, respect_alpha = api.OT_BUFFER_DRAW_RESPECT_ALPHA, comptime { // Record decoders range-check the C value, then cast it with @fromBackingInt. for (0..api.OT_BUFFER_DRAW_RESPECT_ALPHA + 1) |value| std.debug.assert(std.enums.fromInt(Operation, value) != null); std.debug.assert(std.enums.values(Operation).len == api.OT_BUFFER_DRAW_RESPECT_ALPHA + 1); } }; operation: Operation, x: i32 = 0, y: i32 = 0, width: u32 = 0, height: u32 = 0, char: u32 = ' ', attributes: u32 = 0, foreground: buf.RGBA = .{ 0, 0, 0, 0 }, background: ?buf.RGBA = null, title_color: buf.RGBA = .{ 0, 0, 0, 0 }, packed_options: u32 = 0, border_chars: [11]u32 = @splat(0), source: ?Handle = null, crop: BufferCrop = .{}, fit: buf.TextFit = .{}, }; pub const BufferStack = struct { // Custom scopes are bounded independently of the scene's single inherited entry. pub const depth_max: u32 = api.OT_BUFFER_STACK_DEPTH_MAX; pub const Operation = enum(u32) { get_opacity = api.OT_BUFFER_STACK_GET_OPACITY, push_scissor = api.OT_BUFFER_STACK_PUSH_SCISSOR, pop_scissor = api.OT_BUFFER_STACK_POP_SCISSOR, clear_scissors = api.OT_BUFFER_STACK_CLEAR_SCISSORS, push_opacity = api.OT_BUFFER_STACK_PUSH_OPACITY, pop_opacity = api.OT_BUFFER_STACK_POP_OPACITY, clear_opacity = api.OT_BUFFER_STACK_CLEAR_OPACITY, }; operation: Operation, x: i32 = 0, y: i32 = 0, width: u32 = 0, height: u32 = 0, opacity: f32 = 1, }; pub const EditEvent = enum(u32) { cursor_changed = api.OT_EDIT_CURSOR_CHANGED, content_changed = api.OT_EDIT_CONTENT_CHANGED, history_cursor_changed = api.OT_EDIT_HISTORY_CURSOR_CHANGED, }; pub const EditEventCallback = *const fn (?*anyopaque, Handle, EditEvent) void; pub const Edit = struct { owner: *Context, handle: Handle, buffer: *edit_buffer.EditBuffer, views: ?*Editor = null, content_epoch: u64 = 0, input_mem_id: ?u8 = null, /// Measures with the width method of the session whose scene shows it. follow_width: bool = false, fn receive(data: *anyopaque, notification: edit_buffer.NativeEvent) void { const self: *Edit = @ptrCast(@alignCast(data)); const event: EditEvent = switch (notification) { inline else => |tag| @field(EditEvent, @tagName(tag)), }; const owner = self.owner; const epoch = self.buffer.tb.getContentEpoch(); const content_changed = epoch != self.content_epoch; if (content_changed) { self.content_epoch = epoch; } var next = self.views; while (next) |view| : (next = view.next) { if (content_changed) { view.invalidate(); } else { view.invalidatePreparation(); } } if (owner.edit_event_callback) |callback| callback(owner.edit_event_userdata, self.handle, event); } pub fn checkMutable(self: *Edit) !void { var next = self.views; while (next) |view| : (next = view.next) try view.checkMutable(); } pub fn invalidate(self: *Edit) void { var next = self.views; while (next) |view| : (next = view.next) view.invalidate(); } /// For changes that cannot change a size, such as highlights: views repaint, Yoga keeps the measure. pub fn invalidatePreparation(self: *Edit) void { var next = self.views; while (next) |view| : (next = view.next) view.invalidatePreparation(); } }; pub const Editor = struct { handle: Handle, edit: *Edit, view: *editor_view.EditorView, previous: ?*Editor = null, next: ?*Editor = null, node: ?*native_renderable.NativeRenderable = null, // Taken at creation and by every mutation gate, so retained paint repaints the bound node, // including when the editor is destroyed. paint_epoch: u64, pub fn checkMutable(self: *Editor) yoga.Error!void { self.paint_epoch = nextPaintEpoch(); if (self.node) |node| try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); var next = self.view.measure_dependents; while (next) |node| : (next = node.measure_next) try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); } pub fn invalidate(self: *Editor) void { var next = self.view.measure_dependents; while (next) |node| : (next = node.measure_next) yoga.yogaNodeInvalidateMeasure(node.yoga_node); if (self.node) |node| { yoga.yogaNodeInvalidateMeasure(node.yoga_node); node.scene_node.?.owner.invalidateObservation(node); } } pub fn invalidatePreparation(self: *Editor) void { if (self.node) |node| { // Idle frames reuse geometry but still prepare the view and follow its cursor. if (node.scene_node.?.owner.attempt == null) return scene.Scene.markObservationStale(node); node.scene_node.?.owner.invalidateObservation(node); } } pub fn prepareView(self: *Editor) !void { _ = self.view.text_buffer_view.getVirtualLines(); if (self.view.text_buffer_view.virtual_lines_dirty) return error.OutOfMemory; self.view.settle(); } }; pub const SharedText = struct { handle: Handle, buffer: *text_buffer.UnifiedTextBuffer, input_mem_id: u8, views: ?*TextView = null, pool_next: ?*SharedText = null, /// Measures with the width method of the session whose scene shows it. follow_width: bool = false, pub fn checkMutable(self: *SharedText) yoga.Error!void { var next = self.views; while (next) |view| : (next = view.next) try view.checkMutable(); } /// The Yoga measure depends on the bytes and layout options, never on styles or highlights. pub fn invalidate(self: *SharedText, measure: bool) void { var next = self.views; while (next) |view| : (next = view.next) if (measure) view.invalidate() else view.invalidatePreparation(); } /// Measures with `method` from now on; each view keeps its selection on its text. pub fn setWidthMethod(self: *SharedText, method: utf8.WidthMethod) yoga.Error!void { const old = self.buffer.widthMethod(); if (old == method) return; try self.checkMutable(); self.buffer.setWidthMethod(method); var next = self.views; while (next) |view| : (next = view.next) view.view.followWidthMethod(self.buffer, old); self.invalidate(true); } fn reclaimAppendBuffers(self: *SharedText) void { const registry = &self.buffer.mem_registry; // Shared text reserves slot zero for replacement; other slots only hold appends. std.debug.assert(self.input_mem_id == 0 and registry.free_slots.items.len == 0); for (registry.buffers.items[1..]) |memory| { std.debug.assert(memory.active and memory.owned); registry.allocator.free(memory.data); } registry.buffers.items.len = 1; } }; pub const TextView = struct { handle: Handle, text: *SharedText, view: *text_buffer_view.UnifiedTextBufferView, previous: ?*TextView = null, next: ?*TextView = null, node: ?*native_renderable.NativeRenderable = null, // Taken at creation and by every mutation gate, so retained paint repaints the bound node, // including when the view is destroyed. paint_epoch: u64, pub fn checkMutable(self: *TextView) yoga.Error!void { self.paint_epoch = nextPaintEpoch(); if (self.node) |node| try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); var next = self.view.measure_dependents; while (next) |node| : (next = node.measure_next) try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); } pub fn invalidate(self: *TextView) void { var next = self.view.measure_dependents; while (next) |node| : (next = node.measure_next) yoga.yogaNodeInvalidateMeasure(node.yoga_node); self.invalidatePreparation(); } pub fn invalidatePreparation(self: *TextView) void { if (self.node) |node| node.scene_node.?.owner.invalidateObservation(node); } pub fn prepareView(self: *TextView) !void { try self.view.prepare(); } }; pub const MarkdownOptions = struct { flags: u32 = api.OT_MD_CONCEAL | api.OT_MD_HYPERLINKS, /// 0: the 64 MiB ceiling. source_byte_limit: u32 = 0, syntax_style: ?Handle = null, hook_filter: []const u8 = "", const flags_all = api.OT_MD_CONCEAL | api.OT_MD_HYPERLINKS | api.OT_MD_MATH | api.OT_MD_HOOK; /// The engine's options; a flag outside OT_MD_* or a limit above the ceiling is rejected. pub fn engine(self: MarkdownOptions) !markdown.Options { if (self.flags & ~flags_all != 0 or self.source_byte_limit > markdown.source_byte_count_max) return error.InvalidOptions; return .{ .math = self.flags & api.OT_MD_MATH != 0, .hook = self.flags & api.OT_MD_HOOK != 0, .conceal = self.flags & api.OT_MD_CONCEAL != 0, .hyperlinks = self.flags & api.OT_MD_HYPERLINKS != 0, .hook_filter = self.hook_filter, .limits = .{ .source_byte_count = if (self.source_byte_limit == 0) markdown.source_byte_count_max else self.source_byte_limit }, }; } }; pub const MarkdownResult = struct { changed_block_count: u32, committed_top_level_count: u32, removed_from_index: u32 }; fn markdownError(err: markdown.Error) error{ OutOfMemory, TextLimit, ObjectLimit, InvalidOptions } { return switch (err) { error.OutOfMemory => error.OutOfMemory, error.SourceLimit => error.TextLimit, error.BlockLimit => error.ObjectLimit, error.InvalidOptions => error.InvalidOptions, }; } /// A Markdown document (`ot_markdown_*`): the engine, its options, and the scene text nodes of /// its bound leaves, which it writes while the live display is what read_leaf shows (conceal and /// hyperlinks on) and the leaf is not hooked; the host writes the others. pub const MarkdownDoc = struct { owner: *Context, doc: markdown.Doc, writer: markdown.Writer, syntax_style: ?Handle, /// Bound leaves and their nodes, sorted by block index. bindings: std.ArrayListUnmanaged(Binding) = .empty, /// The group set of each scope combination written so far (Context ids, never freed). scope_sets: std.AutoHashMapUnmanaged(u16, u32) = .empty, /// Bindings whose node a failed write left behind. stale_count: u32 = 0, /// The writes of the call in progress (`writeNode`), in the Markdown scratch. staged: std.ArrayListUnmanaged(markdown.NodeWrite) = .empty, /// `skipped`: a write to the node was skipped (hooked, or not live), or its text changed /// since the doc's last write (`epoch`, the buffer's content epoch then: the host wrote /// it), so it does not hold the live display's earlier bytes and takes only resync writes. /// `stale`: the node does not show the doc (a write failed); the next call writes it whole. /// `handoff`: the host wrote the node and the call would make the doc write it: the node is /// unbound and its leaf listed, so the host binds it again to hand it over (a doc never /// writes over a host's text, which it could not rebuild). pub const Binding = struct { block: u32, node: Handle, skipped: bool = false, epoch: u64 = 0, stale: bool = false, handoff: bool = false }; /// The Markdown layer of a bound node's buffer (its only layer). pub const layer_id: u32 = 2; fn deinit(self: *MarkdownDoc) void { const allocator = self.owner.allocator; self.doc.deinit(); self.bindings.deinit(allocator); self.scope_sets.deinit(allocator); allocator.destroy(self); } /// Where block `block`'s binding is or goes. fn bindingIndex(self: *const MarkdownDoc, block: u32) usize { var low: usize = 0; var high: usize = self.bindings.items.len; while (low < high) { const middle = low + (high - low) / 2; if (self.bindings.items[middle].block < block) low = middle + 1 else high = middle; } return low; } /// After a call: the nodes of removed blocks are unbound (they keep their text). fn unbindRemoved(self: *MarkdownDoc) void { const from = self.writer.unbound_from; self.writer.unbound_from = markdown.none; if (from == markdown.none) return; self.bindings.items.len = self.bindingIndex(from); } fn result(self: *const MarkdownDoc) MarkdownResult { return .{ .changed_block_count = self.doc.changeCount(), .committed_top_level_count = self.doc.committed_top_level_count, .removed_from_index = self.doc.removed_from_index, }; } fn setOptions(self: *MarkdownDoc, options: MarkdownOptions) !void { const engine = try options.engine(); const style = if (options.syntax_style) |handle| try self.owner.getSyntaxStyle(handle) else null; const old = self.doc.options; const same = engine.math == old.math and engine.hook == old.hook and engine.conceal == old.conceal and engine.hyperlinks == old.hyperlinks and engine.limits.source_byte_count == old.limits.source_byte_count and std.mem.eql(u8, engine.hook_filter, self.doc.filter()); if (!same) self.doc.setOptions(engine) catch |err| return markdownError(err); if (!std.meta.eql(options.syntax_style, self.syntax_style)) { // A style swap: the bound nodes draw with the new style, nothing is written again; // the leaves a host writes from read_leaf are listed. self.syntax_style = options.syntax_style; self.doc.relistHostWritten(); for (self.bindings.items) |binding| { const node = self.owner.sceneNode(binding.node) catch continue; const text = node.scene_node.?.text orelse continue; text.buffer.setSyntaxStyle(style); node.scene_node.?.paint_epoch = nextPaintEpoch(); } } } /// The group set of a scope combination: the names Core styles Markdown with, later names /// winning (null: no style, or the Context's group sets are full and it draws plain). fn scopeSet(self: *MarkdownDoc, scope: markdown.Scope) !?u32 { const key: u16 = @bitCast(scope); if (key == 0) return null; if (self.scope_sets.get(key)) |id| return id; var names: [highlight_layers.group_set_name_count_max][]const u8 = undefined; var count: usize = 0; const headings = [_][]const u8{ "markup.heading.1", "markup.heading.2", "markup.heading.3", "markup.heading.4", "markup.heading.5", "markup.heading.6" }; if (scope.heading_level != 0) { names[count] = headings[@min(scope.heading_level, 6) - 1]; count += 1; } const label = scope.link and !scope.link_gap and !scope.link_url; inline for (.{ .{ scope.strong, "markup.strong" }, .{ scope.italic, "markup.italic" }, .{ scope.strikethrough, "markup.strikethrough" }, .{ (scope.link or scope.link_gap) and !scope.link_url, "markup.link" }, .{ label, "markup.link.label" }, .{ scope.link_url, "markup.link.url" }, .{ scope.raw, "markup.raw" }, .{ scope.math, "markup.math" }, .{ scope.escape, "string.escape" }, }) |entry| { if (entry[0]) { names[count] = entry[1]; count += 1; } } if (count == 0) return null; const id = self.owner.group_sets.intern(names[0..count]) catch |err| switch (err) { error.GroupSetLimit => return null, error.OutOfMemory => return error.OutOfMemory, else => unreachable, }; try self.scope_sets.put(self.owner.allocator, key, id); return id; } /// A chunk's style resolved through the doc's style (read_leaf). pub fn resolve(self: *MarkdownDoc, scope: markdown.Scope) !syntax_style.StyleDefinition { const none_style: syntax_style.StyleDefinition = .{ .fg = null, .bg = null, .attributes = 0, .supplied_attributes = 0 }; const handle = self.syntax_style orelse return none_style; const style = self.owner.getSyntaxStyle(handle) catch return none_style; const id = (try self.scopeSet(scope)) orelse return none_style; return style.resolveGroupSet(&self.owner.group_sets, id); } /// The engine's write to a bound leaf, inside a call: kept (its slices are in the Markdown /// scratch, which the call resets after) until the call is accepted (`applyStaged`), so a /// rejected call writes no node. fn writeNode(context: *anyopaque, _: *const markdown.Doc, w: markdown.NodeWrite) markdown.Error!void { const self: *MarkdownDoc = @ptrCast(@alignCast(context)); try self.staged.append(self.owner.markdown_scratch.allocator(), w); } /// After an accepted call: its writes, in order. A write that fails leaves its node stale /// (the next accepted call writes it whole). fn applyStaged(self: *MarkdownDoc) void { for (self.staged.items) |w| { if (w.block < self.writer.unbound_from) self.write(w) catch {}; } self.staged = .empty; } /// Writes a bound leaf's node: its text tail and its Markdown runs. Leaves the host writes /// (hooked, or a doc whose read_leaf differs from the live display), unbound blocks and /// destroyed nodes are skipped. A node the host wrote is never written: a whole write the /// doc would make to it marks it `handoff` instead. fn write(self: *MarkdownDoc, w: markdown.NodeWrite) markdown.Error!void { const doc = &self.doc; if (w.block >= doc.blocks.items.len) return; const b = doc.blocks.items[w.block]; if (!markdown.Doc.isBound(b)) return; const at = self.bindingIndex(w.block); if (at == self.bindings.items.len or self.bindings.items[at].block != w.block) return; const binding = &self.bindings.items[at]; const node = self.owner.sceneMutableNode(binding.node) catch return; const text = node.scene_node.?.text orelse return; // A text change since the doc's last write is the host's (a hooked leaf's flag is off // while its pending line is parsed again, so a write may come for it). if (text.buffer.getContentEpoch() != binding.epoch) binding.skipped = true; const live = doc.options.liveShown() and !b.flags.hooked; if (!live or binding.skipped) { if (live and w.resync) binding.handoff = true; binding.skipped = true; self.clearStale(binding); return; } // A node a failed write left behind takes only a whole write. if (binding.stale and !w.resync) return; self.writeText(node, text, w) catch |err| { if (!binding.stale) self.stale_count += 1; binding.stale = true; return switch (err) { error.OutOfMemory => error.OutOfMemory, error.TextLimit => error.SourceLimit, error.LayerLimit => error.BlockLimit, else => error.InvalidOptions, }; }; binding.epoch = text.buffer.getContentEpoch(); self.clearStale(binding); } fn clearStale(self: *MarkdownDoc, binding: *Binding) void { if (!binding.stale) return; binding.stale = false; self.stale_count -= 1; } /// After an accepted call: the nodes the doc would take over from the host are unbound and /// their leaves listed, so the host binds them again to hand them over. fn finishHandoff(self: *MarkdownDoc) void { var kept: usize = 0; for (self.bindings.items) |binding| { if (binding.handoff) { if (binding.block < self.doc.blocks.items.len) self.doc.blocks.items[binding.block].flags.unreported = true; continue; } self.bindings.items[kept] = binding; kept += 1; } self.bindings.items.len = kept; } /// After an accepted call: the nodes a failed write left behind, written whole from the doc; /// one that fails again stays stale. fn resyncNodes(self: *MarkdownDoc) void { if (self.stale_count == 0) return; for (self.bindings.items) |binding| { if (!binding.stale or binding.block >= self.doc.blocks.items.len) continue; var whole = self.doc.wholeWrite(binding.block) catch continue; whole.resync = true; self.write(whole) catch {}; } } fn writeText(self: *MarkdownDoc, node: *native_renderable.NativeRenderable, text: *Text, w: markdown.NodeWrite) !void { const owner = self.owner; const buffer = text.buffer; try Context.validateTextBytes(buffer.tabWidth(), w.bytes, w.from); const arena = owner.markdown_scratch.allocator(); // The ranges' runs, one after another (`ends`), then storage for the layer sets: once the // text changes, nothing here may fail. var chunk_total: usize = 0; for (w.ranges) |range| chunk_total += range.chunks.len; const runs = try arena.alloc(highlight_layers.LayerRun, chunk_total); const ends = try arena.alloc(usize, w.ranges.len); var count: usize = 0; // Each run holds a link reference while it is set; the layer takes its own. defer for (runs[0..count]) |run| if (run.link_id != 0) owner.links.decref(run.link_id) catch unreachable; for (w.ranges, ends) |range, *range_end| { var at = range.from; for (range.chunks) |chunk| { defer at += chunk.byte_count; const url = range.urls[chunk.link_offset..][0..chunk.link_byte_count]; const link_id: u32 = if (url.len == 0 or !link.isWritableUrl(url)) 0 else owner.links.acquire(url) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => 0, }; // A linked chunk has the link scope, so only a full group-set table drops its run. const group_set = (try self.scopeSet(chunk.scope)) orelse { if (link_id != 0) owner.links.decref(link_id) catch unreachable; continue; }; runs[count] = .{ .start_byte = at, .end_byte = at + chunk.byte_count, .group_set = group_set, .link_id = link_id }; count += 1; } range_end.* = count; } // Two spares in turn: a set takes one and gives the layer's old storage back in it, so // after the first set the old storage is as large (each set may split one run). var spares: [2]std.ArrayListUnmanaged(highlight_layers.LayerRun) = .{ .empty, .empty }; defer for (&spares) |*spare| buffer.freeLayerSpare(spare); for (&spares) |*spare| spare.* = try buffer.reserveLayer(layer_id, count + 2 * w.ranges.len); const room = @min(spares[0].capacity, spares[1].capacity); const changed = w.bytes.len > 0 or w.from != buffer.getByteSize(); if (changed) try buffer.replaceTail(w.from, w.bytes); node.scene_node.?.paint_epoch = nextPaintEpoch(); const end = buffer.getByteSize(); var start: usize = 0; for (w.ranges, ends) |range, range_end| { defer start = range_end; const to = if (range.end == markdown.none) end else @min(range.end, end); const spare = if (spares[0].capacity >= room) &spares[0] else &spares[1]; buffer.setLayerWithSpare(layer_id, @min(range.from, to), to, runs[start..range_end], spare) catch |err| switch (err) { error.OutOfMemory => unreachable, else => return err, }; } if (changed) Context.textResourceChanged(text) else Context.textResent(node); node.scene_node.?.owner.clearPreparation(); } }; /// A `bool` payload applies the cursor rules around atomic marks. pub const EditCommand = union(enum) { delete_forward: bool, backspace: bool, new_line, delete_line, move_left: bool, move_right: bool, move_up, move_down, goto_line: u32, cursor_offset: u32, clear, clear_history, debug_rope, cursor_offset_atomic: u32, keep_outside: edit_buffer.EditBuffer.Toward, }; pub const EditorCommand = union(enum) { move_up: bool, move_down: bool, goto_line_end, delete_selection, cursor_offset: u32, wrap_mode: text_buffer_view.WrapMode, tab_indicator: ?u32, }; pub const TextViewCommand = union(enum) { wrap_width: ?u32, wrap_mode: text_buffer_view.WrapMode, first_line_offset: u32, tab_indicator: ?u32, truncate: bool, text_align: text_buffer_view.TextAlign, }; pub const TextDefaults = struct { pub const Fields = packed struct(u3) { foreground: bool = false, background: bool = false, attributes: bool = false, }; fields: Fields, foreground: ?buf.RGBA = null, background: ?buf.RGBA = null, attributes: ?u32 = null, }; pub const TextHighlight = union(enum) { pub const Range = struct { start: u32, end: u32, style_id: u32, priority: u8 = 0, ref: u16 = 0, }; add_line: struct { line: u32, range: Range }, add_range: Range, remove_ref: u16, clear_line: u32, clear_all, }; pub const EditMark = union(enum) { add: edit_buffer.EditBuffer.MarkOptions, remove: u32, clear, }; pub const LayerReplacement = struct { layer_id: u32, start_byte: u32, end_byte: u32, runs: []const highlight_layers.LayerRun, }; pub const TextSelection = struct { pub const Operation = enum { set, update, reset, local, local_update, local_reset, cell, occupancy, inclusive, colors }; operation: Operation, start: u32 = 0, end: u32 = 0, anchor_x: i32 = 0, anchor_y: i32 = 0, focus_x: i32 = 0, focus_y: i32 = 0, foreground: ?buf.RGBA = null, background: ?buf.RGBA = null, behavior: text_buffer_view.SelectionBehavior = .cell, occupancy: text_buffer_view.SelectionOccupancy = .cell, update_cursor: bool = false, follow_cursor: bool = false, }; pub const StyledTextChunk = struct { byte_count: u32, foreground: ?buf.RGBA = null, background: ?buf.RGBA = null, attributes: u32 = 0, link_url: ?[]const u8 = null, }; pub const SceneTextSelectionOptions = struct { operation: u32, behavior: u32 = 0, anchor_x: i32 = 0, anchor_y: i32 = 0, focus_x: i32 = 0, focus_y: i32 = 0, background: ?buf.RGBA = null, foreground: ?buf.RGBA = null, }; pub const Options = struct { /// Initial slots for all checked handles, including leases. See handles.Table.init. object_capacity: u32 = 4096, render_cells_max: u32 = 1_000_000, lease_count_max: u32 = buf.BufferLease.count_max_default, /// Distinct checked-leased storage, current or retired: headers, cell arrays, /// and reserved tracker/placement capacity. Shared resources are not storage allocations. lease_bytes_max: u64 = buf.BufferLease.bytes_max_default, /// Each entry holds at most Diagnostic.message_bytes_max bytes. Zero keeps /// only the cumulative drop count. Diagnostics are drained by the idle owner. diagnostic_capacity: u32 = api.OT_DIAGNOSTIC_QUEUE_MAX, yoga_callbacks: yoga.Callbacks = .{}, }; /// The view and its backing buffer share one lifetime. Measure borrowers are /// unlinked before either is freed, without scanning unrelated renderables. pub const Text = struct { buffer: *text_buffer.UnifiedTextBuffer, view: *text_buffer_view.UnifiedTextBufferView, input_mem_id: ?u8 = null, initial_viewport: ?text_buffer_view.Viewport = null, // Retain logical changes even when both positions truncate to the same cell. scroll_x: f64 = 0, scroll_y: f64 = 0, pool_next: ?*Text = null, /// How the view mapped cells to text when paint last drew it, and the frame that drew it. painted: ?Mapping = null, painted_frame: u64 = 0, /// What decides which grapheme a cell of the view shows, besides the node's place on screen. pub const Mapping = struct { content_epoch: u64, viewport: ?text_buffer_view.Viewport, wrap_width: ?u32, wrap_mode: text_buffer_view.WrapMode, text_align: text_buffer_view.TextAlign, truncate: bool, first_line_offset: u32, }; pub fn mapping(self: *const Text) Mapping { const view = self.view; return .{ .content_epoch = self.buffer.getContentEpoch(), .viewport = view.viewport, .wrap_width = view.wrap_width, .wrap_mode = view.wrap_mode, .text_align = view.text_align, .truncate = view.truncate, .first_line_offset = view.first_line_offset, }; } pub fn prepareView(self: *Text) !void { try self.view.prepare(); } }; pub const SceneMeasureCallback = *const fn (u64, u32, u32, f32, u32, f32, u32, *yoga.ExternalYogaSize) callconv(.c) void; const SceneMeasure = struct { owner: *Context, handle: Handle, callback: SceneMeasureCallback, fn measure(data: ?*anyopaque, width: f32, width_mode: u32, height: f32, height_mode: u32) callconv(.c) yoga.ExternalYogaSize { const self: *SceneMeasure = @ptrCast(@alignCast(data.?)); const node = (self.owner.sceneNode(self.handle) catch unreachable).scene_node.?; std.debug.assert(node.handle.generation == self.handle.generation); std.debug.assert(self.owner.mutating and !self.owner.scene_measuring); self.owner.scene_measuring = true; defer self.owner.scene_measuring = false; // Host exceptions leave unspecified dimensions and escape after the native // call. Unlike native measurement failures, they do not poison the tree. var result: yoga.ExternalYogaSize = .{ .width = std.math.nan(f32), .height = std.math.nan(f32) }; self.callback(self.handle.context_id, self.handle.slot, self.handle.generation, width, width_mode, height, height_mode, &result); // Yoga would warn and measure zero for NaN or negative sizes. A size beyond the // i32 cell range would fail the whole frame in layout validation. Yoga caches // the zero, so Scene.retryFailedMeasures handles the node before the next solve. const size: yoga.ExternalYogaSize = .{ .width = cellRangeOrZero(result.width), .height = cellRangeOrZero(result.height) }; if (size.width != result.width or size.height != result.height) { node.measure_failed = true; node.owner.measure_failed = true; } return size; } fn cellRangeOrZero(value: f32) f32 { return if (value >= 0 and @as(f64, value) <= std.math.maxInt(i32)) value else 0; } }; /// A context is single-owner and address-stable until deinit. Callers may move /// ownership between threads when idle, but must not enter one context concurrently. /// Returned pointers and pool IDs are borrowed for the owning object's lifetime. /// Pool IDs and render buffers must not cross contexts. Callbacks must not mutate /// borrowed objects; checked context mutations reject reentry during layout/render. /// raw() exposes borrowed implementation access, outside checked mutation/lease /// admission. Its getters do not register borrowers. Callers must release raw BufferLeases /// before context deinit; only checked lease handles prevent context teardown. /// Pending output and active terminal lifecycle block teardown until restored or cancelled. pub const Context = struct { allocator: std.mem.Allocator, io: std.Io, render_cells_max: u32, lease_count_max: u32, lease_bytes_max: u64, lease_count: u32 = 0, lease_bytes: u64 = 0, objects: handles.Table, last_image_id: u32 = 0, graphemes: grapheme.GraphemePool, links: link.LinkPool, /// Group sets that highlight layer runs name; every buffer of this Context borrows it. group_sets: highlight_layers.GroupSets, /// Per-call temporary memory of Markdown calls (one per Context; reset after each call). markdown_scratch: std.heap.ArenaAllocator, diagnostics: logger.Diagnostics, logger: logger.Logger, yoga_config: yoga.Config, edit_event_callback: ?EditEventCallback = null, edit_event_userdata: ?*anyopaque = null, /// Selection colors of views whose selection has none of its own, per color; neither inverts the cells. selection_default: text_buffer_view.SelectionStyle = .{}, /// Changes with `selection_default`, so retained paint repaints selections. selection_epoch: u64 = 0, closing: bool = false, mutating: bool = false, scene_measuring: bool = false, scene_measures: std.AutoHashMapUnmanaged(u32, *SceneMeasure) = .empty, // Idle storage only: live handles and scene hit tokens still retire normally. node_pool: []native_renderable.NodeStorage = &.{}, node_pool_count: u32 = 0, node_pool_bytes: usize = 0, text_pool: ?*Text = null, text_pool_count: u32 = 0, text_pool_bytes: usize = 0, // Idle standalone text buffers. Creating and freeing one maps and unmaps allocator pages, // which costs more than the buffer's own setup, so Markdown and Code blocks reuse them. shared_text_pool: ?*SharedText = null, shared_text_pool_count: u32 = 0, shared_text_pool_bytes: usize = 0, // Cover a rebuilt grid without retaining a Context's entire object capacity. pub const node_pool_count_max = 512; pub const node_pool_bytes_max = 2 * 1024 * 1024; pub const text_pool_count_max = 256; pub const text_pool_bytes_max = 4 * 1024 * 1024; pub const text_storage_bytes_max = 64 * 1024; /// Borrow implementation objects without retaining them. Raw access keeps /// handle-kind/generation checks, but calls on the returned pointers bypass /// Context mutation admission and frame authority. Never mutate them during /// callbacks or another checked operation. Checked destruction invalidates /// these pointers; use checked leases to pin buffer storage across calls. pub fn raw(self: *Context) RawAccess { return .{ .owner = self }; } pub const RawAccess = struct { owner: *Context, pub fn getSession(self: RawAccess, handle: Handle) Error!*session.Session { return self.owner.getSession(handle); } /// Draw only when no frame awaits completion. Route output, presentation, /// resize, terminal lifecycle, and destruction through checked Context methods. pub fn getSessionRenderer(self: RawAccess, handle: Handle) Error!*renderer.CliRenderer { return self.owner.getSessionRenderer(handle); } pub fn getUnicode(self: RawAccess, handle: Handle) Error!*EncodedUnicode { return self.owner.getUnicode(handle); } pub fn getEmbeddedTerminal(self: RawAccess, handle: Handle) Error!*embedded_terminal.EmbeddedTerminal { return self.owner.getEmbeddedTerminal(handle); } pub fn getImage(self: RawAccess, handle: Handle) Error!*image.Image { return self.owner.getImage(handle); } pub fn getAudioEngine(self: RawAccess, handle: Handle) Error!*audio.Engine { return self.owner.objects.get(handle, .audio_engine, audio.Engine); } pub fn getBuffer(self: RawAccess, handle: Handle) Error!*buf.OptimizedBuffer { return self.owner.getBuffer(handle); } pub fn getRenderable(self: RawAccess, handle: Handle) Error!*native_renderable.NativeRenderable { return self.owner.getRenderable(handle); } pub fn getTextBuffer(self: RawAccess, handle: Handle) Error!*SharedText { return self.owner.getTextBuffer(handle); } pub fn getTextBufferView(self: RawAccess, handle: Handle) Error!*TextView { return self.owner.getTextBufferView(handle); } pub fn getEditBuffer(self: RawAccess, handle: Handle) Error!*Edit { return self.owner.getEditBuffer(handle); } pub fn getEditorView(self: RawAccess, handle: Handle) Error!*Editor { return self.owner.getEditorView(handle); } pub fn getSyntaxStyle(self: RawAccess, handle: Handle) Error!*syntax_style.SyntaxStyle { return self.owner.getSyntaxStyle(handle); } }; pub fn init(allocator: std.mem.Allocator, io: std.Io, options: Options) Error!*Context { if (options.object_capacity == 0 or options.render_cells_max == 0) return error.InvalidOptions; const self = try allocator.create(Context); errdefer allocator.destroy(self); var objects = try handles.Table.init(allocator, options.object_capacity); errdefer objects.deinit(); var diagnostics = try logger.Diagnostics.init(allocator, options.diagnostic_capacity); errdefer diagnostics.deinit(); self.* = .{ .allocator = allocator, .io = io, .render_cells_max = options.render_cells_max, .lease_count_max = options.lease_count_max, .lease_bytes_max = options.lease_bytes_max, .objects = objects, .graphemes = grapheme.GraphemePool.init(allocator), .links = link.LinkPool.init(allocator), .group_sets = highlight_layers.GroupSets.init(allocator), .markdown_scratch = std.heap.ArenaAllocator.init(allocator), .diagnostics = diagnostics, .logger = .{ .diagnostics = &self.diagnostics }, .yoga_config = undefined, }; try self.yoga_config.init(allocator, options.yoga_callbacks); // Scene children must round inside their parents; public configs keep upstream rounding. yoga.configSetRoundsPositionsFromAbsoluteEdges(self.yoga_config.ref, 1); self.yoga_config.setLogger(&self.logger); return self; } const teardown_order = [_]handles.Kind{ .markdown_doc, .native_renderable, .text_buffer_view, .text_buffer, .editor_view, .edit_buffer, .syntax_style, .buffer, .session, .image, .encoded_unicode, .embedded_terminal, .audio_engine, .clipboard_service }; // A kind missing from teardown_order would trip Table.deinit's live_count assertion. // Leases cannot be live (deinit requires lease_count == 0), and services own their operations. comptime { for (std.enums.values(handles.Kind)) |kind| { const released_by_owner = switch (kind) { .buffer_lease, .frame_buffer_lease, .image_pixels_lease, .clipboard_operation => true, else => false, }; std.debug.assert(released_by_owner == (std.mem.findScalar(handles.Kind, &teardown_order, kind) == null)); } } pub fn deinit(self: *Context) error{ContextBusy}!void { if (self.closing or self.mutating or self.lease_count != 0) return error.ContextBusy; std.debug.assert(self.lease_bytes == 0); // Views only borrow scene nodes, and every scene node is in some Session's // node list, so this check also covers editor and text views. var session_cursor: usize = 0; while (self.objects.next(.session, &session_cursor)) |handle| { const value = self.objects.get(handle, .session, session.Session) catch unreachable; checkSessionTeardown(value) catch return error.ContextBusy; } var clipboard_cursor: usize = 0; var clipboard_ready = true; while (self.objects.next(.clipboard_service, &clipboard_cursor)) |handle| { const service = self.objects.get(handle, .clipboard_service, clipboard.Service) catch unreachable; service.beginShutdown(); if (service.pollShutdown() != .ready) clipboard_ready = false; } if (!clipboard_ready) return error.ContextBusy; self.closing = true; session_cursor = 0; while (self.objects.next(.session, &session_cursor)) |handle| { const value = self.objects.get(handle, .session, session.Session) catch unreachable; if (value.scene) |owned| owned.detachAll(); } // Walk the registry once per kind; borrowers release before their resources. for (teardown_order) |kind| { var cursor: usize = 0; while (self.objects.next(kind, &cursor)) |handle| { self.destroyToken(self.objects.beginDestroy(handle) catch unreachable); } } self.objects.deinit(); std.debug.assert(self.scene_measures.count() == 0); self.scene_measures.deinit(self.allocator); for (self.node_pool[0..self.node_pool_count]) |storage| { self.freeNodeStorage(storage); } self.allocator.free(self.node_pool); while (self.text_pool) |text| { self.text_pool = text.pool_next; self.freeTextStorage(text); } while (self.shared_text_pool) |text| { self.shared_text_pool = text.pool_next; self.freeSharedTextStorage(text); } self.yoga_config.deinit(); self.graphemes.deinit(); self.links.deinit(); self.group_sets.deinit(); self.markdown_scratch.deinit(); self.diagnostics.deinit(); self.allocator.destroy(self); } /// A size query returns the interned URL byte count. Copies require that /// bound. Link id 0 and unknown IDs fail. URLs fit in MAX_URL_LENGTH bytes. pub fn getLinkUrl(self: *Context, id: u32, out: []u8) Error!u32 { // The pool masks IDs to 24 bits and keeps released bytes until slot reuse. const id_max = (link.GEN_MASK << link.SLOT_BITS) | link.SLOT_MASK; if (id == 0 or id > id_max) return error.InvalidOptions; const refcount = self.links.getRefcount(id) catch return error.InvalidOptions; if (refcount == 0) return error.InvalidOptions; const url = self.links.get(id) catch unreachable; std.debug.assert(url.len <= link.MAX_URL_LENGTH); const count: u32 = @intCast(url.len); if (out.len == 0) return count; if (out.len < url.len) return error.InvalidOptions; @memcpy(out[0..url.len], url); return count; } fn checkSessionTeardown(value: *session.Session) Error!void { if (!value.canDestroy()) return error.ContextBusy; const owned = value.scene orelse return; var cursor = owned.head; while (cursor) |node| : (cursor = node.scene_node.?.next) { try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); } } pub fn createClipboardService(self: *Context, max_operations: u32, max_provider_transfers: u32, seat: ?[*]const u8, seat_length: u32) !Handle { try self.beginMutation(); defer self.mutating = false; return clipboard.createService(self.allocator, &self.objects, max_operations, max_provider_transfers, seat, seat_length); } pub fn createAudioEngine(self: *Context, options: ?*const audio.CreateOptions) Error!Handle { try self.beginMutation(); defer self.mutating = false; try self.objects.checkCapacity(); const engine = audio.create(self.allocator, options) orelse return error.InvalidOptions; errdefer audio.destroy(engine); return self.objects.insert(.audio_engine, engine); } pub fn createSession(self: *Context, options: session.Options) Error!Handle { try self.beginMutation(); defer self.mutating = false; if (options.chunk_size == 0 or options.chunk_count == 0 or options.span_capacity == 0) { return error.InvalidOptions; } if (options.control_capacity != 0) { const control_chunks = std.math.divCeil(u32, options.control_capacity, options.chunk_size) catch return error.InvalidOptions; if (control_chunks >= options.chunk_count or control_chunks >= options.span_capacity) { return error.InvalidOptions; } } try self.objects.checkCapacity(); const value = try self.allocator.create(session.Session); errdefer self.allocator.destroy(value); const output = try native_span_feed.Stream.create(self.allocator, .{ .chunk_size = options.chunk_size, .initial_chunks = options.chunk_count, .max_bytes = @as(u64, options.chunk_size) * options.chunk_count, .growth_policy = @backingInt(native_span_feed.GrowthPolicy.block), .auto_commit_on_full = 1, .span_queue_capacity = options.span_capacity, }); errdefer output.destroy(); if (options.control_capacity != 0) try output.reserveControlCapacity(options.control_capacity); const handle = try self.objects.insert(.session, value); value.* = .{ .handle = handle, .output = output }; return handle; } fn getSession(self: *Context, handle: Handle) Error!*session.Session { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .session, session.Session); } /// Attaches one renderer without terminal setup or output. Queued raw output /// stays in order. Failure preserves the Session and publishes no renderer. pub fn attachSessionRenderer( self: *Context, handle: Handle, width: u32, height: u32, options: session.RendererOptions, ) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); if (value.renderer != null) return error.RendererAlreadyAttached; const cells = std.math.mul(u32, width, height) catch return error.InvalidDimensions; if (width == 0 or height == 0 or cells > self.render_cells_max) return error.InvalidDimensions; var environment: ?std.process.Environ.Map = null; errdefer if (environment) |*map| map.deinit(); if (options.forwarded_env) |entries| { if (options.env_map != null or entries.len > session.environment_entries_max) return error.InvalidOptions; environment = std.process.Environ.Map.init(self.allocator); var remaining: usize = session.environment_bytes_max; for (entries) |entry| { if (remaining < 8) return error.InvalidOptions; remaining -= 8; if (entry.key.len == 0 or entry.key.len > remaining) return error.InvalidOptions; remaining -= entry.key.len; if (entry.value.len > remaining) return error.InvalidOptions; remaining -= entry.value.len; if (std.mem.findScalar(u8, entry.key, 0) != null or std.mem.findScalar(u8, entry.key, '=') != null or std.mem.findScalar(u8, entry.value, 0) != null or !std.unicode.utf8ValidateSlice(entry.key) or !std.unicode.utf8ValidateSlice(entry.value)) { return error.InvalidOptions; } try environment.?.put(entry.key, entry.value); } } const attached = try renderer.CliRenderer.createWithOptions(self.allocator, width, height, &self.graphemes, .{ .io = self.io, .host_driven_time = true, .logger = &self.logger, .remote_mode = options.remote_mode, .feed = value.output, .link_pool = &self.links, .env_map = options.env_map, }); attached.getCurrentBuffer().owner_context_id = self.objects.context_id; attached.getNextBuffer().owner_context_id = self.objects.context_id; attached.terminal.setCursorPosition(1, 1, false); if (environment) |map| { attached.terminal.adoptHostEnvironment(map); attached.syncWidthMethod(); } value.renderer = attached; } /// Borrows the Session's renderer for buffer drawing and queries, not ownership. fn getSessionRenderer(self: *Context, handle: Handle) Error!*renderer.CliRenderer { const value = try self.getSession(handle); return value.renderer orelse error.RendererNotAttached; } /// Reads one current-cell link id without retaining storage. Encode syncs /// those cells before presentation is pending, so this stays valid while /// output drains. Out-of-range coordinates are not a link. pub fn sessionGetLinkId(self: *Context, handle: Handle, x: i32, y: i32) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkRendering(); const attached = value.renderer orelse return error.RendererNotAttached; if (x < 0 or y < 0) return 0; const cell = attached.getCurrentBuffer().get(@intCast(x), @intCast(y)) orelse return 0; return ansi.TextAttributes.getLinkId(cell.attributes); } /// Retains mutable storage, not a frame. Finish drawing before submitting a /// frame; later rendering can change these cells without retiring storage. pub fn acquireSessionBufferLease(self: *Context, handle: Handle, which: RendererBuffer) Error!Handle { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkRendering(); try value.checkFrameIdle(); const attached = value.renderer orelse return error.RendererNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) { return error.PresentationPending; } // Raw cell access may write either buffer. if (which == .next) attached.leaveRetained() else attached.current_written = true; return self.acquireBufferLease(switch (which) { .current => attached.getCurrentBuffer(), .next => attached.getNextBuffer(), }); } /// Composites retained cells and image references into the next framebuffer. /// Rejection preserves cells and output, but can retain tracker capacity. pub fn drawSessionBuffer(self: *Context, handle: Handle, source_handle: Handle, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkRendering(); try value.checkFrameIdle(); const attached = value.renderer orelse return error.RendererNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) { return error.PresentationPending; } const source = try self.getBuffer(source_handle); attached.leaveRetained(); const target = attached.getNextBuffer(); try drawContextBuffer(target, source, x, y, .{}); } pub fn drawContextBuffer(target: *buf.OptimizedBuffer, source: *buf.OptimizedBuffer, x: i32, y: i32, crop: BufferCrop) !void { std.debug.assert(target.pool == source.pool and target.link_pool == source.link_pool); if (target == source) return error.InvalidOptions; try source.checkImageResources(); try target.checkImageResources(); if (crop.x >= source.width or crop.y >= source.height) return; const width = @min(crop.width orelse source.width, source.width - crop.x); const height = @min(crop.height orelse source.height, source.height - crop.y); if (width == 0 or height == 0) return; const end_x = @as(i64, x) + width; const end_y = @as(i64, y) + height; if (x >= target.width or y >= target.height or end_x <= 0 or end_y <= 0) return; // The compositor adds the exclusive endpoint before subtracting one. if (target.width > std.math.maxInt(i32) or target.height > std.math.maxInt(i32) or end_x > std.math.maxInt(i32) or end_y > std.math.maxInt(i32)) { return error.InvalidDimensions; } const entries = @as(u64, target.buffer.char.len) + 1; target.storage.ensureTrackerCapacity( if (source.grapheme_tracker.hasAny()) entries else 0, if (source.link_tracker.hasAny()) entries else 0, ) catch |err| return switch (err) { error.TrackerLimit => error.ObjectLimit, error.OutOfMemory => error.OutOfMemory, }; try target.drawFrameBufferChecked(x, y, source, crop.x, crop.y, width, height); } pub fn sessionSetDebugOverlay(self: *Context, handle: Handle, enabled: bool, corner: u32) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; if (corner > 3) return error.InvalidOptions; attached.setDebugOverlay(enabled, @fromBackingInt(@intCast(corner))); } pub fn sessionUpdateStats(self: *Context, handle: Handle, overall_ms: f64, fps: u32, callback_ms: f64) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; if (!std.math.isFinite(overall_ms) or overall_ms < 0 or !std.math.isFinite(callback_ms) or callback_ms < 0) return error.InvalidOptions; attached.updateStats(overall_ms, fps, callback_ms); } pub fn sessionUpdateMemoryStats(self: *Context, handle: Handle, heap_used: u32, heap_total: u32, array_buffers: u32) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; attached.updateMemoryStats(heap_used, heap_total, array_buffers); } pub fn sessionDumpHitGrid(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; const timestamp = std.Io.Clock.now(.real, self.io).toSeconds(); var filename_buf: [64]u8 = undefined; const filename = std.fmt.bufPrint(&filename_buf, "hitgrid_{d}.txt", .{timestamp}) catch return; const file = std.Io.Dir.cwd().createFile(self.io, filename, .{}) catch return; defer file.close(self.io); var file_buffer: [4096]u8 = undefined; var file_writer = file.writer(self.io, &file_buffer); const writer = &file_writer.interface; for (0..attached.height) |y| { for (0..attached.width) |x| { const token = if (value.scene) |owned| owned.hitToken(attached, @intCast(x), @intCast(y), 0) else 0; writer.writeByte(if (token == 0) '.' else '0' + @as(u8, @intCast(token % 10))) catch return; } writer.writeByte('\n') catch return; } writer.flush() catch {}; } pub fn renderSession(self: *Context, handle: Handle, force: bool) Error!session.RenderStatus { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).render(force); } /// Must precede accepted frames. Queued or copied raw middleware output is valid. pub fn setupSessionTerminal(self: *Context, handle: Handle, options: session.TerminalOptions) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).setupTerminal(options); } pub fn suspendSession(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).suspendTerminal(); } pub fn resumeSession(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).resumeTerminal(); } pub fn pumpSession(self: *Context, handle: Handle, now_ns: u64, work_budget: u32) Error!session.PumpResult { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).pump(now_ns, work_budget); } pub fn sessionInputFeed(self: *Context, handle: Handle, bytes: []const u8, now_ns: u64, sink: *input_parser.Sink) Error!session.InputFeed { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).feedInput(bytes, now_ns, sink); } pub fn sessionInputExpect(self: *Context, handle: Handle, expect: input_parser.Expectations) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).setInputExpectations(expect); } pub fn sessionInputReset(self: *Context, handle: Handle, keep_reply: bool) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).resetInput(keep_reply); } pub fn getSessionTerminalState(self: *Context, handle: Handle) Error!session.TerminalState { return (try self.getSession(handle)).getTerminalState(); } pub fn controlSession(self: *Context, handle: Handle, command: session.Control) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).control(command); } pub fn writeSessionClipboard(self: *Context, handle: Handle, target: @import("terminal.zig").ClipboardTarget, bytes: []const u8) Error!bool { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).writeClipboard(target, bytes); } pub fn resizeSessionRenderer(self: *Context, handle: Handle, width: u32, height: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkResizing(); try value.checkLayoutIdle(); const attached = value.renderer orelse return error.RendererNotAttached; const cells = std.math.mul(u32, width, height) catch return error.InvalidDimensions; if (width == 0 or height == 0 or cells > self.render_cells_max) return error.InvalidDimensions; // Only a pending frame depends on geometry; the renderer rejects it. std.debug.assert((value.frame_end_offset != null) == (attached.pendingPresentation != null)); try attached.resize(width, height); if (value.scene) |owned| owned.requalifyPainted(attached); } pub fn writeSession(self: *Context, handle: Handle, bytes: []const u8) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).write(bytes); } pub fn readOutput(self: *Context, handle: Handle, out: []u8) Error!?session.OutputTicket { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).readOutput(out); } /// The writer and its borrowed bytes live only for this checked call. /// Use an unbuffered writer that reports bytes delivered to its transport. pub fn drainOutput(self: *Context, handle: Handle, writer: anytype, max_bytes: u32) Error!u32 { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).drainOutput(writer, max_bytes); } pub fn drainStdout(self: *Context, handle: Handle, max_bytes: u32) Error!u32 { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).drainStdout(self.io, max_bytes); } /// Process stdout from a Session-owned native thread; see `Session.postStdout`. pub fn postStdout(self: *Context, handle: Handle, max_bytes: u32, wait: bool) Error!session.PostResult { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).postStdout(stdout_writer.StdoutWriter, StdoutCreate{}, max_bytes, wait); } const StdoutCreate = struct { pub fn create(_: StdoutCreate) error{UnsupportedResource}!*stdout_writer.StdoutWriter { if (comptime !stdout_writer.supported) return error.UnsupportedResource; if (!stdout_writer.stdoutSupported() or !stdout_writer.pinLibrary()) return error.UnsupportedResource; return stdout_writer.StdoutWriter.create(std.heap.c_allocator, .{ .fd = 1 }, .{}); } }; pub fn completeOutput( self: *Context, handle: Handle, ticket: session.OutputTicket, result: session.OutputResult, ) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).completeOutput(ticket, result); } pub fn beginSessionClose(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).beginClose(); } pub fn dropSessionOutput(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).dropOutput(); } pub fn cancelSession(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; (try self.getSession(handle)).cancel(); } pub fn createBuffer(self: *Context, width: u32, height: u32, options: BufferOptions) !Handle { try self.beginMutation(); defer self.mutating = false; try self.checkBufferDimensions(width, height); try self.objects.checkCapacity(); const value = try buf.OptimizedBuffer.init(self.allocator, width, height, .{ .pool = &self.graphemes, .link_pool = &self.links, .logger = &self.logger, .respectAlpha = options.respect_alpha, .width_method = options.width_method, }); errdefer value.deinit(); value.owner_context_id = self.objects.context_id; value.cells_max = self.render_cells_max; return self.objects.insert(.buffer, value); } pub fn importImage(self: *Context, source: *const image.Image) !Handle { try self.beginMutation(); defer self.mutating = false; try self.checkImageCapacity(); return self.insertImage(try source.cloneOwned(self.allocator)); } fn checkImageCapacity(self: *Context) !void { try self.objects.checkCapacity(); if (self.last_image_id == std.math.maxInt(u32)) return error.ObjectLimit; } fn insertImage(self: *Context, value: *image.Image) !Handle { errdefer value.deinit(); const handle = try self.objects.insert(.image, value); self.last_image_id += 1; value.render_id = self.last_image_id; value.owner_context_id = self.objects.context_id; return handle; } pub fn inspectImage(self: *Context, bytes: []const u8) !image.Info { try self.beginMutation(); defer self.mutating = false; return image.inspectOwned(self.allocator, bytes, .{}); } pub fn decodeImage(self: *Context, bytes: []const u8) !Handle { try self.beginMutation(); defer self.mutating = false; try self.checkImageCapacity(); return self.insertImage(try image.decode(self.allocator, bytes, .{})); } pub fn createImagePixels(self: *Context, pixels: []const u8, width: u32, height: u32, options: image.PixelImportOptions) !Handle { try self.beginMutation(); defer self.mutating = false; try self.checkImageCapacity(); return self.insertImage(try image.createFromPixels(self.allocator, pixels, width, height, options)); } pub fn cloneImageFrom(self: *Context, source_owner: *Context, handle: Handle) !Handle { try self.beginMutation(); defer self.mutating = false; if (source_owner != self) { try source_owner.beginMutation(); } defer if (source_owner != self) { source_owner.mutating = false; }; const source = try source_owner.getImage(handle); try self.checkImageCapacity(); return self.insertImage(try source.cloneOwned(self.allocator)); } pub fn retainImage(self: *Context, handle: Handle) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(handle); try self.objects.checkCapacity(); if (source.ref_count == std.math.maxInt(u32)) return error.MemoryLimit; const result = try self.objects.insert(.image, source); source.retain(); return result; } pub fn imageInfo(self: *Context, handle: Handle) !image.Info { try self.beginMutation(); defer self.mutating = false; return (try self.getImage(handle)).info(); } pub fn updateImagePixels(self: *Context, handle: Handle, pixels: []const u8, options: image.PixelImportOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getImage(handle); if (self.last_image_id == std.math.maxInt(u32)) return error.ObjectLimit; try image.updatePixels(value, pixels, options); // Cache identity belongs to pixel content, including pooled updates. self.last_image_id += 1; value.render_id = self.last_image_id; } pub fn resizeImage(self: *Context, handle: Handle, width: u32, height: u32, filter: image.ResizeFilter) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(handle); try self.checkImageCapacity(); return self.insertImage(try image.resize(self.allocator, source, width, height, filter)); } pub fn extractImage(self: *Context, handle: Handle, left: u32, top: u32, width: u32, height: u32) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(handle); try self.checkImageCapacity(); return self.insertImage(try image.extract(self.allocator, source, left, top, width, height)); } pub fn extendImage(self: *Context, handle: Handle, top: u32, right: u32, bottom: u32, left: u32, background: [4]u8) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(handle); try self.checkImageCapacity(); return self.insertImage(try image.extend(self.allocator, source, top, right, bottom, left, background)); } pub fn transformImage(self: *Context, handle: Handle, operation: image.Transform) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(handle); try self.checkImageCapacity(); return self.insertImage(try image.transform(self.allocator, source, operation)); } pub fn compositeImage(self: *Context, base: Handle, overlay: Handle, left: i32, top: i32, blend: image.Blend, opacity: u8) !Handle { try self.beginMutation(); defer self.mutating = false; const source = try self.getImage(base); const layer = try self.getImage(overlay); try self.checkImageCapacity(); return self.insertImage(try image.composite(self.allocator, source, layer, left, top, blend, opacity)); } pub fn copyImagePixels(self: *Context, handle: Handle, destination: []u8, stride: u32, format: image.PixelFormat) !void { try self.beginMutation(); defer self.mutating = false; try image.errorFromStatus(image.copyPixels(try self.getImage(handle), destination, stride, format == .bgra8)); } /// Zero capacity returns the exact encoded byte count. A short output writes nothing. pub fn copyImagePng(self: *Context, handle: Handle, destination: []u8) !usize { try self.beginMutation(); defer self.mutating = false; const bytes = try (try self.getImage(handle)).ensureEncodedPng(); if (destination.len != 0) { if (destination.len < bytes.len) return error.OutputTooSmall; @memcpy(destination[0..bytes.len], bytes); } return bytes.len; } /// Consumes the exclusive image handle; the lease prevents Context teardown. pub fn takeImagePixels(self: *Context, handle: Handle) !Handle { try self.beginMutation(); defer self.mutating = false; const value = try self.getImage(handle); if (value.ref_count != 1) return error.Busy; try self.objects.checkCapacity(); if (self.lease_count == self.lease_count_max) return error.LeaseLimit; const size_bytes = @sizeOf(image.Image) + @as(u64, value.width()) * value.height() * 4; if (size_bytes > self.lease_bytes_max - self.lease_bytes) return error.LeaseBytesLimit; _ = try value.ensurePixels(); const result = try self.objects.insert(.image_pixels_lease, value); value.discardEncoded(); value.metadata.has_alpha = 1; self.lease_count += 1; self.lease_bytes += size_bytes; // Transfer the reference instead of retaining it: no image handle may alias mutable pixels. self.objects.finishDestroy(self.objects.beginDestroy(handle) catch unreachable); return result; } pub fn imagePixelsSnapshot(self: *Context, handle: Handle) ![]u8 { try self.beginMutation(); defer self.mutating = false; return (try self.objects.get(handle, .image_pixels_lease, image.Image)).pixels; } pub fn releaseImagePixels(self: *Context, handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; _ = try self.objects.get(handle, .image_pixels_lease, image.Image); self.destroyToken(try self.objects.beginDestroy(handle)); } pub fn createUnicode(self: *Context, text: []const u8, width_method: utf8.WidthMethod) !Handle { try self.beginMutation(); defer self.mutating = false; try self.objects.checkCapacity(); const value = try EncodedUnicode.init(self.allocator, &self.graphemes, text, width_method); errdefer value.deinit(self.allocator, &self.graphemes); return self.objects.insert(.encoded_unicode, value); } fn getUnicode(self: *Context, handle: Handle) Error!*EncodedUnicode { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .encoded_unicode, EncodedUnicode); } pub fn drawBufferUnicode(self: *Context, handle: Handle, frame: ?scene.FrameRequest, source_handle: Handle, index: u32, x: i32, y: i32, foreground: buf.RGBA, background: buf.RGBA, attributes: u32) !void { try self.beginMutation(); defer self.mutating = false; try self.drawUnicodeOn(try self.bufferDrawTarget(handle, frame), source_handle, index, x, y, foreground, background, attributes); } pub fn drawUnicodeOn(self: *Context, target: *buf.OptimizedBuffer, source_handle: Handle, index: u32, x: i32, y: i32, foreground: buf.RGBA, background: buf.RGBA, attributes: u32) !void { const source = try self.getUnicode(source_handle); if (index >= source.chars.len) return error.InvalidOptions; try buf.validateColor(foreground); try buf.validateColor(background); if (attributes & ~ansi.TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; try target.checkImageResources(); if (x < 0 or y < 0 or x >= target.width or y >= target.height) return; const char = source.chars[index].char; const width: u32 = source.chars[index].width; if (width > target.width - @as(u32, @intCast(x))) return; for (0..width) |offset| { if (!target.isPointInScissor(x + @as(i32, @intCast(offset)), y)) return; } if (grapheme.isGraphemeChar(char)) { const id = grapheme.graphemeIdFromChar(char); if ((try self.graphemes.getRefcount(id)) == std.math.maxInt(u32)) return error.TrackerLimit; try target.storage.ensureTrackerCapacity( @min(@as(u64, target.grapheme_tracker.getGraphemeCount()) + 1, @as(u64, target.buffer.char.len) + 1), target.link_tracker.getLinkCount(), ); } target.drawChar(char, @intCast(x), @intCast(y), foreground, background, attributes); } pub fn createEmbeddedTerminal(self: *Context, cols: u32, rows: u32, max_scrollback: u32) !Handle { try self.beginMutation(); defer self.mutating = false; try self.checkBufferDimensions(cols, rows); if (cols > std.math.maxInt(u16) or rows > std.math.maxInt(u16)) return error.InvalidDimensions; try self.objects.checkCapacity(); if (comptime !@import("ghostty_vt_options").available) return error.Unsupported; const value = try embedded_terminal.EmbeddedTerminal.init(self.io, self.allocator, .{ .cols = @intCast(cols), .rows = @intCast(rows), .max_scrollback = max_scrollback, .logger = &self.logger, }); errdefer value.deinit(); return self.objects.insert(.embedded_terminal, value); } fn getEmbeddedTerminal(self: *Context, handle: Handle) Error!*embedded_terminal.EmbeddedTerminal { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .embedded_terminal, embedded_terminal.EmbeddedTerminal); } pub fn embeddedTerminalWrite(self: *Context, handle: Handle, bytes: []const u8) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); if (bytes.len > terminal_input_bytes_max) return error.TextLimit; try value.write(bytes); } pub fn embeddedTerminalResize(self: *Context, handle: Handle, cols: u32, rows: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); try self.checkBufferDimensions(cols, rows); if (cols > std.math.maxInt(u16) or rows > std.math.maxInt(u16)) return error.InvalidDimensions; try value.resize(@intCast(cols), @intCast(rows)); } pub fn embeddedTerminalCommand(self: *Context, handle: Handle, command: u32, argument: i32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); switch (command) { api.OT_EMBEDDED_TERMINAL_INVALIDATE => { if (argument != 0) return error.InvalidOptions; value.invalidate(); }, api.OT_EMBEDDED_TERMINAL_SCROLL => value.scroll(argument), api.OT_EMBEDDED_TERMINAL_CLEAR_SELECTION => { if (argument != 0) return error.InvalidOptions; value.clearSelection(); }, api.OT_EMBEDDED_TERMINAL_SET_TRANSPARENT_BACKGROUND => { if (argument != 0 and argument != 1) return error.InvalidOptions; value.setTransparentBackground(argument == 1); }, else => return error.InvalidOptions, } } pub fn embeddedTerminalSetSelection(self: *Context, handle: Handle, start_x: u32, start_y: u32, end_x: u32, end_y: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); if (comptime !@import("ghostty_vt_options").available) return error.Unsupported; if (start_x >= value.cols or end_x >= value.cols or start_y >= value.rows or end_y >= value.rows) return error.InvalidOptions; try value.setSelection(.{ .x = @intCast(start_x), .y = @intCast(start_y) }, .{ .x = @intCast(end_x), .y = @intCast(end_y) }); } pub fn embeddedTerminalGetSelectedText(self: *Context, handle: Handle, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); const text = try value.selectedText(); defer value.freeSelectedText(text); return copyTerminalOutput(output, text); } pub fn embeddedTerminalCompose(self: *Context, source_handle: Handle, handle: Handle, frame: ?scene.FrameRequest, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; const target = try self.bufferDrawTarget(handle, frame); const source = try self.getEmbeddedTerminal(source_handle); // Session drafts are cleared between frames; only retained buffers keep clean rows. if (frame != null) source.invalidate(); try source.composeChecked(target, x, y, self.render_cells_max); } pub fn embeddedTerminalCursor(self: *Context, handle: Handle) !embedded_terminal.Cursor { try self.checkSceneRead(); return (try self.getEmbeddedTerminal(handle)).cursor(); } pub fn embeddedTerminalScrollbar(self: *Context, handle: Handle) !embedded_terminal.Scrollbar { try self.checkSceneRead(); return (try self.getEmbeddedTerminal(handle)).scrollbar(); } pub fn embeddedTerminalEncodeKey(self: *Context, handle: Handle, options: EmbeddedTerminalKey, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); if (comptime !@import("ghostty_vt_options").available) return error.Unsupported; if (options.action > api.OT_EMBEDDED_TERMINAL_KEY_REPEAT or options.mods & ~terminal_mods != 0 or options.consumed_mods & ~terminal_mods != 0 or !utf8.isScalar(options.unshifted_codepoint)) return error.InvalidOptions; if (options.key.len > terminal_input_bytes_max or options.text.len > terminal_input_bytes_max) return error.TextLimit; if (!std.unicode.utf8ValidateSlice(options.text)) return error.InvalidUnicode; const vt = @import("ghostty-vt.zig").vt; comptime assertTerminalMods(vt.input.KeyMods); const encoded = try value.encodeKey(.{ .action = switch (options.action) { api.OT_EMBEDDED_TERMINAL_KEY_RELEASE => .release, api.OT_EMBEDDED_TERMINAL_KEY_PRESS => .press, api.OT_EMBEDDED_TERMINAL_KEY_REPEAT => .repeat, else => unreachable, }, .key = vt.input.Key.fromW3C(options.key) orelse .unidentified, .mods = @bitCast(@as(u16, @intCast(options.mods))), .consumed_mods = @bitCast(@as(u16, @intCast(options.consumed_mods))), .composing = options.composing, .utf8 = options.text, .unshifted_codepoint = @intCast(options.unshifted_codepoint), }); defer value.freeEncoded(encoded); return copyTerminalOutput(output, encoded); } pub fn embeddedTerminalEncodeMouse(self: *Context, handle: Handle, options: EmbeddedTerminalMouse, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); if (comptime !@import("ghostty_vt_options").available) return error.Unsupported; if (options.action > api.OT_EMBEDDED_TERMINAL_MOUSE_MOTION or options.button < api.OT_EMBEDDED_TERMINAL_BUTTON_NONE or options.button > api.OT_EMBEDDED_TERMINAL_BUTTON_SEVEN or options.mods & ~terminal_mods != 0) return error.InvalidOptions; const previous = value.mouse_last_cell; errdefer value.mouse_last_cell = previous; const encoded = try value.encodeMouse(.{ .action = switch (options.action) { api.OT_EMBEDDED_TERMINAL_MOUSE_PRESS => .press, api.OT_EMBEDDED_TERMINAL_MOUSE_RELEASE => .release, api.OT_EMBEDDED_TERMINAL_MOUSE_MOTION => .motion, else => unreachable, }, .button = switch (options.button) { api.OT_EMBEDDED_TERMINAL_BUTTON_NONE => null, api.OT_EMBEDDED_TERMINAL_BUTTON_UNKNOWN => .unknown, api.OT_EMBEDDED_TERMINAL_BUTTON_LEFT => .left, api.OT_EMBEDDED_TERMINAL_BUTTON_RIGHT => .right, api.OT_EMBEDDED_TERMINAL_BUTTON_MIDDLE => .middle, api.OT_EMBEDDED_TERMINAL_BUTTON_FOUR => .four, api.OT_EMBEDDED_TERMINAL_BUTTON_FIVE => .five, api.OT_EMBEDDED_TERMINAL_BUTTON_SIX => .six, api.OT_EMBEDDED_TERMINAL_BUTTON_SEVEN => .seven, else => unreachable, }, .mods = @bitCast(@as(u16, @intCast(options.mods))), .x = options.x, .y = options.y, .any_button_pressed = options.any_button_pressed, }); defer value.freeEncoded(encoded); // Sizing and rejected output must not suppress the caller's retry as duplicate motion. if (output.len == 0) value.mouse_last_cell = previous; return copyTerminalOutput(output, encoded); } pub fn embeddedTerminalEncodePaste(self: *Context, handle: Handle, input: []const u8, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); if (input.len > terminal_input_bytes_max) return error.TextLimit; const encoded = try value.encodePaste(input); defer value.freeEncoded(encoded); return copyTerminalOutput(output, encoded); } pub fn embeddedTerminalEncodeFocus(self: *Context, handle: Handle, focused: bool, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getEmbeddedTerminal(handle); const encoded = try value.encodeFocus(focused); defer value.freeEncoded(encoded); return copyTerminalOutput(output, encoded); } pub fn embeddedTerminalDrainResponses(self: *Context, handle: Handle, output: []u8) !u32 { try self.beginMutation(); defer self.mutating = false; return @intCast(try (try self.getEmbeddedTerminal(handle)).drainResponses(output)); } fn copyTerminalOutput(output: []u8, bytes: []const u8) !u32 { if (bytes.len > std.math.maxInt(u32)) return error.TextLimit; if (output.len != 0) { if (bytes.len > output.len) return error.BufferTooSmall; @memcpy(output[0..bytes.len], bytes); } return @intCast(bytes.len); } fn getImage(self: *Context, handle: Handle) Error!*image.Image { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .image, image.Image); } pub fn drawBufferImage(self: *Context, handle: Handle, frame: ?scene.FrameRequest, source_handle: Handle, options: ImageDraw) !bool { try self.beginMutation(); defer self.mutating = false; return self.drawImageOn(try self.bufferDrawTarget(handle, frame), source_handle, options); } pub fn drawImageOn(self: *Context, target: *buf.OptimizedBuffer, source_handle: Handle, options: ImageDraw) !bool { const source = try self.getImage(source_handle); try target.checkImageResources(); if (options.source_x > source.width() or options.source_y > source.height()) return error.InvalidOptions; const width = options.source_width orelse source.width() - options.source_x; const height = options.source_height orelse source.height() - options.source_y; if (width > source.width() - options.source_x or height > source.height() - options.source_y) return error.InvalidOptions; if (source.ref_count == std.math.maxInt(u32)) return error.ObjectLimit; return target.drawImage(source, source.render_id, options.x, options.y, options.width, options.height, options.pixel_width, options.pixel_height, options.source_x, options.source_y, width, height, options.protocol); } pub fn sessionSetImageResolution(self: *Context, handle: Handle, terminal_width: u32, terminal_height: u32, pixel_width: u32, pixel_height: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; const cleared = terminal_width == 0 and terminal_height == 0 and pixel_width == 0 and pixel_height == 0; if (!cleared and (terminal_width == 0 or terminal_height == 0 or pixel_width == 0 or pixel_height == 0)) return error.InvalidOptions; attached.image_resolution = .{ .terminal_width = terminal_width, .terminal_height = terminal_height, .pixel_width = pixel_width, .pixel_height = pixel_height, }; } pub fn sessionSetKittyImageTransport(self: *Context, handle: Handle, mode: u32) !void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).setKittyImageTransport(mode); } pub fn sessionKittyImageTransportStatus(self: *Context, handle: Handle) ![6]u32 { return (try self.getSession(handle)).kittyImageTransportStatus(); } pub fn sessionPollKittyImageTransport(self: *Context, handle: Handle, now_ns: u64) !bool { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).pollKittyImageTransport(now_ns); } pub fn sessionCancelKittyImageTransport(self: *Context, handle: Handle, failed: bool) !void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).cancelKittyImageTransport(failed); } pub fn sessionProcessKittyImageReply(self: *Context, handle: Handle, response: []const u8) !u32 { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(handle)).processKittyImageReply(response); } pub fn sessionStartKittyFileProbe(self: *Context, handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; try (try self.getSession(handle)).startKittyFileProbe(); } fn getBuffer(self: *Context, handle: Handle) Error!*buf.OptimizedBuffer { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .buffer, buf.OptimizedBuffer); } pub fn resizeBuffer(self: *Context, handle: Handle, width: u32, height: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getBuffer(handle); try self.checkBufferDimensions(width, height); try value.resize(width, height); } pub fn clearBuffer(self: *Context, handle: Handle, background: buf.RGBA) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getBuffer(handle); try buf.validateColor(background); value.clear(background, null); } pub fn drawBufferText( self: *Context, handle: Handle, text: []const u8, x: i32, y: i32, foreground: buf.RGBA, background: ?buf.RGBA, attributes: u32, ) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getBuffer(handle); try value.drawTextChecked(text, x, y, foreground, background, attributes); } pub fn fillBufferRect(self: *Context, handle: Handle, x: u32, y: u32, width: u32, height: u32, background: buf.RGBA) Error!void { try self.beginMutation(); defer self.mutating = false; const value = try self.getBuffer(handle); try buf.validateColor(background); if (x >= value.width or y >= value.height) return; // Clip before the native fill's signed scissor and unsigned endpoint arithmetic. value.fillRect(x, y, @min(width, value.width - x), @min(height, value.height - y), background); } /// A Session target requires the exact active prefix or painted-frame ticket. /// No handle or raw address can grant access to a Session's framebuffer alone. pub fn drawBuffer(self: *Context, handle: Handle, frame: ?scene.FrameRequest, options: *const BufferDraw, text: []const u8, bottom_title: []const u8) !void { try self.beginMutation(); defer self.mutating = false; try self.drawBufferOn(try self.bufferDrawTarget(handle, frame), frame != null, options, text, bottom_title); } /// Frame targets keep their scene-owned alpha mode. The options stay behind a pointer: copying /// the record on every primitive draw costs more than drawing a small primitive. pub fn drawBufferOn(self: *Context, target: *buf.OptimizedBuffer, frame_target: bool, options: *const BufferDraw, text: []const u8, bottom_title: []const u8) !void { const background = options.background orelse ansi.rgbColor(0, 0, 0, 0); for ([_]buf.RGBA{ options.foreground, background, options.title_color }) |color| try buf.validateColor(color); if (options.attributes & ~ansi.TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; try target.checkImageResources(); switch (options.operation) { .clear => target.clear(background, null), .respect_alpha => { if (frame_target or options.packed_options > api.OT_BUFFER_RESPECT_ALPHA) return error.InvalidOptions; target.respectAlpha = options.packed_options == api.OT_BUFFER_RESPECT_ALPHA; }, .compose => try drawContextBuffer(target, try self.getBuffer(options.source orelse return error.InvalidOptions), options.x, options.y, options.crop), .box => { if (options.packed_options & ~@as(u32, 0x1ff) != 0 or (options.packed_options >> 5) & 3 > 2 or (options.packed_options >> 7) & 3 > 2) return error.InvalidOptions; if (options.width == 0 or options.height == 0) return; // Zero keeps the default border character. for (options.border_chars) |char| { if (!utf8.isScalar(char) or (char != 0 and utf8.isControl(char))) return error.InvalidOptions; } try buf.validateTextInput(text); try buf.validateTextInput(bottom_title); try target.drawBoxChecked(options.x, options.y, options.width, options.height, &options.border_chars, .{ .top = options.packed_options & api.OT_BORDER_TOP != 0, .right = options.packed_options & api.OT_BORDER_RIGHT != 0, .bottom = options.packed_options & api.OT_BORDER_BOTTOM != 0, .left = options.packed_options & api.OT_BORDER_LEFT != 0, }, options.foreground, background, options.title_color, options.packed_options & 16 != 0, if (text.len == 0) null else text, @intCast((options.packed_options >> 5) & 3), if (bottom_title.len == 0) null else bottom_title, @intCast((options.packed_options >> 7) & 3)); }, // Text and fills draw their part inside the target. A cell outside it draws nothing. .text => try target.drawTextFitted(text, options.x, options.y, options.foreground, options.background, options.attributes, options.fit), .fill => target.fillRectClipped(options.x, options.y, options.width, options.height, background), .cell, .cell_blend, .char => { if (!utf8.isScalar(options.char)) return error.InvalidOptions; const char = if (utf8.isControl(options.char)) buf.DEFAULT_SPACE_CHAR else options.char; if (options.x < 0 or options.y < 0) return; const x: u32 = @intCast(options.x); const y: u32 = @intCast(options.y); if (x >= target.width or y >= target.height) return; switch (options.operation) { .cell => target.set(x, y, .{ .char = char, .fg = options.foreground, .bg = background, .attributes = options.attributes }), .cell_blend => target.setCellWithAlphaBlending(x, y, char, options.foreground, background, options.attributes), .char => target.drawChar(char, x, y, options.foreground, background, options.attributes), else => unreachable, } }, } } pub fn bufferStack(self: *Context, handle: Handle, frame: ?scene.FrameRequest, options: BufferStack) !f32 { try self.beginMutation(); defer self.mutating = false; return bufferStackOn(try self.bufferDrawTarget(handle, frame), 0, options); } /// Entries below floor belong to the scene; recorded paint starts with one clip and opacity. pub fn bufferStackOn(target: *buf.OptimizedBuffer, floor: usize, options: BufferStack) !f32 { std.debug.assert(target.scissor_stack.items.len >= floor); std.debug.assert(target.opacity_stack.items.len >= floor); switch (options.operation) { .get_opacity => {}, .push_scissor => { if (options.width > std.math.maxInt(i32) or options.height > std.math.maxInt(i32) or @as(i64, options.x) + options.width > std.math.maxInt(i32) or @as(i64, options.y) + options.height > std.math.maxInt(i32)) return error.InvalidDimensions; if (target.scissor_stack.items.len - floor >= BufferStack.depth_max) return error.ObjectLimit; try target.pushScissorRect(options.x, options.y, options.width, options.height); }, .pop_scissor => if (target.scissor_stack.items.len > floor) { target.popScissorRect(); }, .clear_scissors => target.scissor_stack.shrinkRetainingCapacity(floor), .push_opacity => { if (!std.math.isFinite(options.opacity)) return error.InvalidOptions; if (target.opacity_stack.items.len - floor >= BufferStack.depth_max) return error.ObjectLimit; try target.pushOpacity(options.opacity); }, .pop_opacity => if (target.opacity_stack.items.len > floor) { target.popOpacity(); }, .clear_opacity => target.opacity_stack.shrinkRetainingCapacity(floor), } return target.getCurrentOpacity(); } pub fn drawGrid(self: *Context, handle: Handle, frame: ?scene.FrameRequest, options: BufferGrid, columns: []const i32, rows: []const i32) !void { try self.beginMutation(); defer self.mutating = false; try self.drawGridOn(try self.bufferDrawTarget(handle, frame), options, columns, rows); } pub fn drawGridOn(self: *Context, target: *buf.OptimizedBuffer, options: BufferGrid, columns: []const i32, rows: []const i32) !void { try target.checkImageResources(); try buf.validateColor(options.foreground); try buf.validateColor(options.background); for (options.border_chars) |char| { if (!utf8.isScalar(char) or (char != 0 and utf8.eastAsianWidth(@intCast(char)) != 1)) return error.InvalidOptions; } for ([_][]const i32{ columns, rows }) |offsets| { if (offsets.len > @as(u64, self.render_cells_max) + 1) return error.InvalidOptions; for (offsets, 0..) |offset, index| { if (index != 0 and offset <= offsets[index - 1]) return error.InvalidOptions; } } if (columns.len < 2 or rows.len < 2) return; target.drawGrid(&options.border_chars, options.foreground, options.background, columns.ptr, @intCast(columns.len - 1), rows.ptr, @intCast(rows.len - 1), options.draw_inner, options.draw_outer); } pub fn drawPackedBuffer(self: *Context, handle: Handle, frame: ?scene.FrameRequest, data: []const u8, x: i32, y: i32, width: u32, height: u32) !void { try self.beginMutation(); defer self.mutating = false; const target = try self.bufferDrawTarget(handle, frame); try target.drawPackedBufferChecked(data, x, y, width, height); } pub fn drawSuperSampleBuffer(self: *Context, handle: Handle, frame: ?scene.FrameRequest, data: []const u8, x: i32, y: i32, format: u32, stride: u32) !void { try self.beginMutation(); defer self.mutating = false; try drawSuperSampleOn(try self.bufferDrawTarget(handle, frame), data, x, y, format, stride); } pub fn drawSuperSampleOn(target: *buf.OptimizedBuffer, data: []const u8, x: i32, y: i32, format: u32, stride: u32) !void { if (format > 1) return error.InvalidOptions; try target.drawSuperSampleBufferChecked(x, y, data, @intCast(format), stride); } pub fn drawGrayscaleBuffer(self: *Context, handle: Handle, frame: ?scene.FrameRequest, data: []align(1) const f32, x: i32, y: i32, width: u32, height: u32, foreground: ?buf.RGBA, background: ?buf.RGBA, supersampled: bool) !void { try self.beginMutation(); defer self.mutating = false; const target = try self.bufferDrawTarget(handle, frame); try target.drawGrayscaleBufferChecked(x, y, data, width, height, foreground, background, supersampled); } pub fn colorMatrixBuffer(self: *Context, handle: Handle, frame: ?scene.FrameRequest, matrix: []align(1) const f32, mask: ?[]align(1) const f32, strength: f32, channel: u32) !void { try self.beginMutation(); defer self.mutating = false; try self.colorMatrixOn(try self.bufferDrawTarget(handle, frame), matrix, mask, strength, channel); } pub fn colorMatrixOn(self: *Context, target: *buf.OptimizedBuffer, matrix: []align(1) const f32, mask: ?[]align(1) const f32, strength: f32, channel: u32) !void { if (matrix.len != 16 or !std.math.isFinite(strength) or channel < 1 or channel > 3) return error.InvalidOptions; for (matrix) |value| if (!std.math.isFinite(value)) return error.InvalidOptions; if (mask) |cells| { if (cells.len / 3 > self.render_cells_max) return error.InvalidOptions; } try target.checkImageResources(); const channels: buffer_effects.ColorTarget = @fromBackingInt(@intCast(channel)); if (mask) |cells| { buffer_effects.colorMatrix(target, matrix, cells, strength, channels); } else { buffer_effects.colorMatrixUniform(target, matrix, strength, channels); } } pub fn checkBufferDimensions(self: *const Context, width: u32, height: u32) Error!void { const cells = std.math.mul(u32, width, height) catch return error.InvalidDimensions; if (width == 0 or height == 0 or cells > self.render_cells_max or width > std.math.maxInt(i32) or height > std.math.maxInt(i32)) { return error.InvalidDimensions; } } pub fn drawTextBufferView(self: *Context, handle: Handle, frame: ?scene.FrameRequest, view_handle: Handle, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; try self.drawTextViewOn(try self.bufferDrawTarget(handle, frame), view_handle, x, y); } pub fn drawTextViewOn(self: *Context, target: *buf.OptimizedBuffer, view_handle: Handle, x: i32, y: i32) !void { const view = try self.getTextBufferView(view_handle); if (x >= target.width or y >= target.height) return; try view.prepareView(); try target.drawTextBufferChecked(view.view, x, y, self.selection_default); } pub fn drawEditorView(self: *Context, handle: Handle, frame: ?scene.FrameRequest, view_handle: Handle, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; try self.drawEditorViewOn(try self.bufferDrawTarget(handle, frame), view_handle, x, y); } pub fn drawEditorViewOn(self: *Context, target: *buf.OptimizedBuffer, view_handle: Handle, x: i32, y: i32) !void { const editor = try self.getEditorView(view_handle); if (x >= target.width or y >= target.height) return; try target.drawEditorViewChecked(editor.view, x, y, self.selection_default); } pub fn drawSceneBody(self: *Context, handle: Handle, frame: ?scene.FrameRequest, node_handle: Handle, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; try self.drawSceneBodyOn(try self.bufferDrawTarget(handle, frame), node_handle, x, y); } pub fn drawSceneBodyOn(self: *Context, target: *buf.OptimizedBuffer, node_handle: Handle, x: i32, y: i32) !void { const node = try self.sceneNode(node_handle); const owned = node.scene_node.?; try owned.owner.prepareOmitted(&self.objects, node); if (owned.text == null and owned.kind != api.OT_SCENE_BOX and owned.kind != api.OT_SCENE_SLIDER and owned.kind != api.OT_SCENE_ARROW) return error.WrongKind; if (x >= target.width or y >= target.height) return; const text = owned.text orelse return owned.owner.paintBody(&self.objects, target, node, x, y); // A prepared text that Yoga sizes to zero paints nothing; an unprepared one draws its text. const content = scene.contentLayout(owned.layout); if (owned.geometry_epoch != std.math.maxInt(u64) and (content.width == 0 or content.height == 0)) return; try text.prepareView(); const offset = scene.contentOffset(owned.layout); try target.drawTextBufferChecked(text.view, x +| offset[0], y +| offset[1], self.selection_default); } pub fn acquireOwnedBufferLease(self: *Context, handle: Handle) Error!Handle { try self.beginMutation(); defer self.mutating = false; return self.acquireBufferLease(try self.getBuffer(handle)); } fn acquireBufferLease(self: *Context, target: *buf.OptimizedBuffer) Error!Handle { std.debug.assert(self.mutating); if (self.lease_count >= self.lease_count_max) return error.LeaseLimit; try self.objects.checkCapacity(); var lease = try buf.BufferLease.acquireChecked( target, &self.lease_count, self.lease_count_max, &self.lease_bytes, &self.lease_bytes_max, ); errdefer lease.releaseChecked(&self.lease_count, &self.lease_bytes, &self.lease_bytes_max); const result = try self.objects.insert(.buffer_lease, lease.storage.?); lease.storage = null; return result; } /// Resize/destroy makes the snapshot stale without freeing its storage. /// Saved aliases remain allocated until release, but must not be used after /// release or to change tagged IDs without maintaining the buffer trackers. pub fn bufferLeaseSnapshot(self: *Context, handle: Handle) Error!buf.BufferSnapshot { if (self.closing) return error.ContextClosed; if (self.mutating) return error.ContextBusy; const lease: buf.BufferLease = switch (try self.objects.getKind(handle)) { .buffer_lease => .{ .storage = try self.objects.get(handle, .buffer_lease, buf.BufferStorage) }, .frame_buffer_lease => qualified: { const access = try self.objects.get(handle, .frame_buffer_lease, FrameBufferLease); const value = self.getSession(access.frame.session) catch return error.StaleLease; const owned = value.scene orelse return error.StaleLease; const painted = owned.checkPainted(access.frame) catch return error.StaleLease; const attached = value.renderer orelse return error.StaleLease; if (!painted.destination.matches(attached.getNextBuffer())) return error.StaleLease; const target = switch (access.which) { .current => attached.getCurrentBuffer(), .next => attached.getNextBuffer(), }; if (!access.destination.matches(target) or access.lease.storage != target.storage) return error.StaleLease; break :qualified access.lease; }, else => return error.WrongKind, }; return lease.snapshot() catch |err| switch (err) { error.StaleLease => error.StaleLease, error.LeaseReleased => unreachable, }; } pub fn releaseBufferLease(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; switch (try self.objects.getKind(handle)) { .buffer_lease, .frame_buffer_lease => {}, else => return error.WrongKind, } self.destroyToken(try self.objects.beginDestroy(handle)); } pub fn sceneCreateNode(self: *Context, session_handle: Handle, kind: u32, num: u32) !Handle { try self.beginMutation(); defer self.mutating = false; if (kind > api.OT_SCENE_VIDEO or num == 0) return error.InvalidOptions; const value = try self.getSession(session_handle); try value.checkOpen(); const attached = value.renderer orelse return error.RendererNotAttached; try self.objects.checkCapacity(); const owned = value.scene orelse blk: { if (kind != api.OT_SCENE_ROOT) return error.SceneNotAttached; if (value.frame_end_offset != null or attached.renderStats.frameCount != 0) return error.InvalidTerminalState; break :blk try scene.Scene.init(self.allocator, &self.yoga_config, session_handle); }; errdefer if (value.scene == null) owned.deinit(); try owned.prepareInsert(kind, num); const storage = try self.createNodeStorage(); const node = storage.node; errdefer { node.detachMeasure(); self.releaseNodeStorage(storage); } try yoga.check(yoga.yogaNodeStyleSetFloatChecked(node.yoga_node, api.OT_STYLE_FLOAT_FLEX_SHRINK, 1)); for (api.OT_EDGE_LEFT..api.OT_EDGE_START) |edge| try yoga.check(yoga.yogaNodeStyleSetBorderChecked(node.yoga_node, @intCast(edge), 0)); const text = if (kind == api.OT_SCENE_TEXT) try self.createTextResource(attached.getNextBuffer().width_method) else null; errdefer if (text) |resource| self.destroyTextResource(resource); if (text) |resource| { resource.view.setWrapMode(.word); try node.setMeasureTarget(.{ .text_buffer_view = resource.view }); } const handle = try self.objects.insert(.native_renderable, node); owned.insert(storage, handle, kind, num); node.scene_node.?.text = text; value.scene = owned; return handle; } fn createNodeStorage(self: *Context) !native_renderable.NodeStorage { if (self.node_pool_count != 0) { self.node_pool_count -= 1; const storage = self.node_pool[self.node_pool_count]; self.node_pool[self.node_pool_count] = undefined; self.node_pool_bytes -= storage.retainedBytes(); errdefer self.freeNodeStorage(storage); // Only useWebDefaults affects Yoga's initial style; other config fields are read live. if (storage.reuse_web_defaults != yoga.yogaConfigGetUseWebDefaults(self.yoga_config.ref)) { try yoga.check(yoga.yogaNodeResetChecked(storage.node.yoga_node)); } return storage; } // Reserve idle entries during construction; retirement must never allocate. const capacity_max = @min(self.objects.slots.len, node_pool_count_max); if (self.node_pool.len < @min(self.objects.live_count + 1, capacity_max)) { const capacity = @min(capacity_max, @max(8, self.node_pool.len * 2)); self.node_pool = try self.allocator.realloc(self.node_pool, capacity); } const node = try self.allocator.create(native_renderable.NativeRenderable); errdefer self.allocator.destroy(node); const scene_node = try self.allocator.create(scene.Node); errdefer self.allocator.destroy(scene_node); node.* = try native_renderable.NativeRenderable.initWithConfig(&self.yoga_config); node.context_owned = true; return .{ .node = node, .scene_node = scene_node }; } fn releaseNodeStorage(self: *Context, storage: native_renderable.NodeStorage) void { const node = storage.node; // Destruction and constructor rollback detach measurement before releasing storage. if (!self.closing and self.node_pool_count < self.node_pool.len and node.resetForReuse()) { const bytes = storage.retainedBytes(); const entries_bytes = self.node_pool.len * @sizeOf(native_renderable.NodeStorage); if (bytes <= node_pool_bytes_max - entries_bytes - self.node_pool_bytes) { self.node_pool[self.node_pool_count] = storage; self.node_pool[self.node_pool_count].reuse_web_defaults = yoga.yogaConfigGetUseWebDefaults(self.yoga_config.ref); self.node_pool_count += 1; self.node_pool_bytes += bytes; return; } } self.freeNodeStorage(storage); } fn freeNodeStorage(self: *Context, storage: native_renderable.NodeStorage) void { var children = storage.children; var paint_children = storage.paint_children; var attention = storage.attention; children.deinit(self.allocator); paint_children.deinit(self.allocator); attention.deinit(self.allocator); self.allocator.destroy(storage.scene_node); storage.node.deinit(); self.allocator.destroy(storage.node); } fn sceneNode(self: *Context, handle: Handle) !*native_renderable.NativeRenderable { const node = try self.getRenderable(handle); std.debug.assert(node.scene_node != null); return node; } fn sceneMutableNode(self: *Context, handle: Handle) !*native_renderable.NativeRenderable { const node = try self.sceneNode(handle); try (try self.getSession(node.scene_node.?.owner.session)).checkOpen(); try node.scene_node.?.owner.prepareOmitted(&self.objects, node); return node; } /// For setters of what a node paints; a rejected change only repaints the node. fn scenePaintNode(self: *Context, handle: Handle) !*native_renderable.NativeRenderable { const node = try self.sceneMutableNode(handle); node.scene_node.?.paint_epoch = nextPaintEpoch(); return node; } pub fn sceneDestroyNode(self: *Context, handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneNode(handle); try node.scene_node.?.owner.prepareOmitted(&self.objects, node); try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); self.destroyToken(try self.objects.beginDestroy(handle)); } pub fn sceneSetMeasure(self: *Context, handle: Handle, callback: ?SceneMeasureCallback) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); if (callback) |function| { if (self.scene_measures.get(handle.slot)) |registration| { try yoga.check(yoga.yogaNodeSetNativeMeasureFunc(node.yoga_node, registration, &SceneMeasure.measure, false)); registration.callback = function; } else { try self.scene_measures.ensureUnusedCapacity(self.allocator, 1); const registration = try self.allocator.create(SceneMeasure); errdefer self.allocator.destroy(registration); registration.* = .{ .owner = self, .handle = handle, .callback = function }; try yoga.check(yoga.yogaNodeSetNativeMeasureFunc(node.yoga_node, registration, &SceneMeasure.measure, false)); self.scene_measures.putAssumeCapacity(handle.slot, registration); } } else { try yoga.check(yoga.yogaNodeSetNativeMeasureFunc(node.yoga_node, null, null, false)); if (self.scene_measures.fetchRemove(handle.slot)) |entry| self.allocator.destroy(entry.value); } yoga.yogaNodeInvalidateMeasure(node.yoga_node); node.scene_node.?.measure_overridden = true; } pub fn sceneSetBoxDetails(self: *Context, handle: Handle, details: scene.BoxDetails) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); try value.scene_node.?.owner.setBoxDetails(value, details); } pub fn sceneSetImage(self: *Context, handle: Handle, source_handle: ?Handle, fit: image.Fit, protocol: image.RenderProtocol, buffer_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.scenePaintNode(handle); if (node.scene_node.?.kind != api.OT_SCENE_IMAGE) return error.WrongKind; try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); const source = if (source_handle) |id| try self.getImage(id) else null; const target = if (buffer_handle) |id| try self.getBuffer(id) else null; if (source) |value| { if (value.ref_count == std.math.maxInt(u32)) return error.ObjectLimit; } if (target) |value| try value.retain(); if (source) |value| value.retain(); const state = &node.scene_node.?.control.image; const crop = state.crop; state.deinit(); state.* = .{ .source = source, .fit = fit, .protocol = protocol, .buffer = target, .crop = crop }; } /// Sets the source region an IMAGE or VIDEO node shows; null shows the whole source. pub fn sceneSetCrop(self: *Context, handle: Handle, crop: ?image.Region) !void { if (crop) |region| std.debug.assert(region.width > 0 and region.height > 0); try self.beginMutation(); defer self.mutating = false; const node = (try self.scenePaintNode(handle)).scene_node.?; switch (node.kind) { api.OT_SCENE_IMAGE => node.control.image.crop = crop, api.OT_SCENE_VIDEO => node.control.video.image.crop = crop, else => return error.WrongKind, } } fn videoState(self: *Context, handle: Handle) !*scene.VideoState { const node = try self.sceneMutableNode(handle); if (node.scene_node.?.kind != api.OT_SCENE_VIDEO) return error.WrongKind; return &node.scene_node.?.control.video; } fn videoPlayer(self: *Context, handle: Handle) !*video.Player { return (try self.videoState(handle)).player orelse error.NoPlayer; } pub fn sceneSetVideo(self: *Context, handle: Handle, fit: image.Fit, buffer_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); if (node.scene_node.?.kind != api.OT_SCENE_VIDEO) return error.WrongKind; try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); const target = if (buffer_handle) |id| try self.getBuffer(id) else null; if (target) |value| try value.retain(); const state = &node.scene_node.?.control.video; const crop = state.image.crop; state.image.deinit(); state.image = .{ .fit = fit, .buffer = target, .crop = crop }; } /// Replaces the node's player. An empty path closes it. A failed open keeps no player. pub fn videoOpen(self: *Context, handle: Handle, path: []const u8, audio_enabled: bool) !video.Info { try self.beginMutation(); defer self.mutating = false; const state = try self.videoState(handle); if (state.player) |player| player.deinit(); state.player = null; state.painted = 0; self.allocator.free(state.open_error); state.open_error = &.{}; if (path.len == 0) return .{}; var detail: [256]u8 = undefined; state.player = video.Player.open(self.allocator, path, audio_enabled, &detail) catch |err| { state.open_error = self.allocator.dupe(u8, std.mem.sliceTo(&detail, 0)) catch &.{}; return err; }; return state.player.?.video.info; } pub fn videoControl(self: *Context, handle: Handle, comptime operation: anytype, args: anytype) !void { try self.beginMutation(); defer self.mutating = false; const player = try self.videoPlayer(handle); try @call(.auto, operation, .{player} ++ args); } pub fn videoGetState(self: *Context, handle: Handle) !video.PlayerState { try self.beginMutation(); defer self.mutating = false; return (try self.videoPlayer(handle)).snapshot(); } /// Returns the detail of the last open, seek, or decode failure, or of a non-fatal audio failure. pub fn videoGetError(self: *Context, handle: Handle) ![]const u8 { try self.beginMutation(); defer self.mutating = false; const state = try self.videoState(handle); const player = state.player orelse return state.open_error; return player.lastError(); } pub fn sceneSetSurface(self: *Context, handle: Handle, buffer_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.scenePaintNode(handle); if (node.scene_node.?.kind != api.OT_SCENE_CUSTOM) return error.WrongKind; try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); const source = if (buffer_handle) |id| try self.getBuffer(id) else null; if (source) |value| try value.retain(); if (node.surface) |previous| previous.deinit(); node.surface = source; } pub fn sceneSetEditorView(self: *Context, handle: Handle, view_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_EDITOR) return error.WrongKind; const editor = if (view_handle) |id| try self.getEditorView(id) else null; if (editor) |view| { if (view.edit.follow_width) try checkFollowOwner(Editor, view.edit.views, node.owner); if (view.node != null and view.node != value) return error.ContextBusy; } try value.setMeasureTargetPreservingProvider(if (editor) |view| .{ .editor_view = view.view } else .none, node.measure_overridden); if (node.editor) |previous| previous.node = null; node.editor = editor; if (editor) |view| view.node = value; node.owner.invalidateObservation(value); self.followSessionWidth(value); } pub fn sceneSetEditorOptions(self: *Context, handle: Handle, options: scene.EditorOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_EDITOR) return error.WrongKind; if (options.style > api.OT_CURSOR_STYLE_DEFAULT or (options.mouse_pointer > api.OT_MOUSE_POINTER_MAX and options.mouse_pointer != api.OT_MOUSE_POINTER_UNCHANGED)) return error.InvalidOptions; try buf.validateColor(options.color); node.control = .{ .editor = options }; } pub fn sceneSetTextView(self: *Context, handle: Handle, view_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_TEXT_VIEW) return error.WrongKind; const text_view = if (view_handle) |id| try self.getTextBufferView(id) else null; if (text_view) |view| { if (view.text.follow_width) try checkFollowOwner(TextView, view.text.views, node.owner); if (view.node != null and view.node != value) return error.ContextBusy; } try value.setMeasureTargetPreservingProvider(if (text_view) |view| .{ .text_buffer_view = view.view } else .none, node.measure_overridden); if (node.control.text_view.view) |previous| previous.node = null; node.control.text_view.view = text_view; if (text_view) |view| view.node = value; node.owner.invalidateObservation(value); self.followSessionWidth(value); } pub fn sceneSetTextViewPaint(self: *Context, handle: Handle, enabled: bool) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_TEXT_VIEW) return error.WrongKind; node.control.text_view.paint = enabled; } pub fn sceneHasMeasure(self: *Context, handle: Handle) !bool { try self.checkSceneRead(); return yoga.yogaNodeHasMeasureFunc((try self.sceneNode(handle)).yoga_node); } pub fn sceneReachesHooks(self: *Context, handle: Handle) !bool { try self.checkSceneRead(); const node = try self.sceneNode(handle); return node.scene_node.?.owner.reaches(&self.objects, node); } pub fn scenePainted(self: *Context, handle: Handle) !bool { try self.checkSceneRead(); const node = try self.sceneNode(handle); return node.scene_node.?.owner.paintedLatest(node); } pub fn sceneMarkDirty(self: *Context, handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); try yoga.check(yoga.yogaNodeMarkDirtyChecked(node.yoga_node)); } pub fn checkSceneRead(self: *Context) Error!void { if (self.closing or (self.mutating and !self.scene_measuring)) return error.ContextBusy; } pub fn sceneMoveNode(self: *Context, handle: Handle, parent_handle: ?Handle, index: u32) !void { try self.beginMutation(); defer self.mutating = false; // Detachment is also used by child-first wrapper cleanup after cancellation. const node = if (parent_handle == null) try self.sceneNode(handle) else try self.sceneMutableNode(handle); if (parent_handle == null) try node.scene_node.?.owner.prepareOmitted(&self.objects, node); const parent = if (parent_handle) |id| try self.sceneMutableNode(id) else null; try node.scene_node.?.owner.move(node, parent, index); } pub fn sceneClearChildren(self: *Context, handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneNode(handle); const owner = node.scene_node.?.owner; for (node.scene_node.?.children.items) |child| try owner.prepareOmitted(&self.objects, child); owner.clearChildren(node); } pub fn sceneSetStyle(self: *Context, handle: Handle, group: u32, kind: u32, edge: u32, unit: u32, value: f32, flags: u32) !void { try self.beginMutation(); defer self.mutating = false; return self.sceneSetStyleLocked(handle, group, kind, edge, unit, value, flags); } /// Caller holds the mutation admission; used by ot_scene_flush to admit once per batch. pub fn sceneSetStyleLocked( self: *Context, handle: Handle, group: u32, kind: u32, edge: u32, unit: u32, value: f32, flags: u32, ) !void { std.debug.assert(self.mutating); const content = flags & api.OT_STYLE_CONTENT != 0; const yoga_flags = flags & ~@as(u32, api.OT_STYLE_CONTENT); if (group > api.OT_STYLE_DIMENSION or group == api.OT_STYLE_BORDER or (group != api.OT_STYLE_DIMENSION and yoga_flags != api.OT_STYLE_FLAGS_NONE) or yoga_flags > api.OT_STYLE_DISABLE_FLEX_SHRINK or (content and group == api.OT_STYLE_ENUM and kind == api.OT_STYLE_ENUM_DISPLAY)) { return error.InvalidOptions; } if ((group == api.OT_STYLE_ENUM or group == api.OT_STYLE_FLOAT) and (edge != api.OT_EDGE_NONE or unit != api.OT_UNIT_UNDEFINED)) { return error.InvalidOptions; } if (group == api.OT_STYLE_DIMENSION and edge != api.OT_EDGE_NONE) return error.InvalidOptions; if (group == api.OT_STYLE_ENUM and (!std.math.isFinite(value) or value < 0 or @as(f64, value) > std.math.maxInt(u32) or @trunc(value) != value)) { return error.InvalidOptions; } if (group == api.OT_STYLE_ENUM and (kind >= scene_style_enum_maxima.len or value > @as(f32, @floatFromInt(scene_style_enum_maxima[kind])))) return error.InvalidOptions; const node = try self.sceneMutableNode(handle); const scroll = node.scene_node.?.scroll; if (content and scroll == null) return error.WrongKind; // A scroll node's own padding holds its bar gutters. if (!content and scroll != null and group == api.OT_STYLE_VALUE and kind == api.OT_STYLE_VALUE_PADDING) return error.InvalidOptions; const target = if (content) scroll.?.content_node else node.yoga_node; const display = group == api.OT_STYLE_ENUM and kind == api.OT_STYLE_ENUM_DISPLAY; // A read that fails returns 0, and then the write below fails too. const shown = if (display) yoga.yogaNodeStyleGetEnum(target, kind) else 0; try yoga.check(switch (group) { api.OT_STYLE_ENUM => yoga.yogaNodeStyleSetEnumChecked(target, kind, @intFromFloat(value)), api.OT_STYLE_FLOAT => yoga.yogaNodeStyleSetFloatChecked(target, kind, value), // Finite summed edges and gaps saturate so Yoga's f32 sums stay finite; NaN still unsets. api.OT_STYLE_VALUE => yoga.yogaNodeStyleSetValueChecked(target, kind, edge, unit, if (kind >= api.OT_STYLE_VALUE_MARGIN and std.math.isFinite(value) and @abs(value) > 1e30) std.math.copysign(@as(f32, 1e30), value) else value), api.OT_STYLE_DIMENSION => yoga.yogaNodeStyleSetDimensionChecked(target, kind, unit, value, yoga_flags), else => unreachable, }); if (display and shown != @as(u32, @intFromFloat(value))) { node.scene_node.?.owner.visibility_epoch +%= 1; // A shown child's refresh prepares its view although its layout did not change. scene.Scene.markObservationStale(node); } // A culling parent's main axis decides which children it selects. if (group == api.OT_STYLE_ENUM and kind == api.OT_STYLE_ENUM_FLEX_DIRECTION) node.scene_node.?.owner.selection_epoch +%= 1; } pub fn sceneGetStyle(self: *Context, handle: Handle, group: u32, kind: u32, edge: u32) !scene.StyleValue { try self.checkSceneRead(); if (group > api.OT_STYLE_DIMENSION) return error.InvalidOptions; if ((group == api.OT_STYLE_ENUM or group == api.OT_STYLE_FLOAT or group == api.OT_STYLE_DIMENSION) and edge != api.OT_EDGE_NONE) { return error.InvalidOptions; } const node = try self.sceneNode(handle); var result: scene.StyleValue = .{ .unit = api.OT_UNIT_UNDEFINED, .value = 0 }; switch (group) { api.OT_STYLE_ENUM => { var value: u32 = 0; try yoga.check(yoga.yogaNodeStyleGetEnumChecked(node.yoga_node, kind, &value)); result.value = @floatFromInt(value); }, api.OT_STYLE_FLOAT => try yoga.check(yoga.yogaNodeStyleGetFloatChecked(node.yoga_node, kind, &result.value)), api.OT_STYLE_VALUE, api.OT_STYLE_DIMENSION => { if (group == api.OT_STYLE_DIMENSION and kind > api.OT_DIMENSION_HEIGHT) return error.InvalidOptions; var encoded: u64 = 0; try yoga.check(yoga.yogaNodeStyleGetValueChecked(node.yoga_node, kind, edge, &encoded)); result.unit = @truncate(encoded); result.value = @bitCast(@as(u32, @truncate(encoded >> 32))); }, api.OT_STYLE_BORDER => { if (kind != api.OT_STYLE_BORDER_WIDTH) return error.InvalidOptions; result.unit = api.OT_UNIT_POINT; try yoga.check(yoga.yogaNodeStyleGetBorderChecked(node.yoga_node, edge, &result.value)); }, else => unreachable, } return result; } pub fn sceneSetPositions(self: *Context, handle: Handle, mask: u32, units: [4]u32, values: [4]f32) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); try yoga.check(yoga.yogaNodeStyleSetPositionsChecked(node.yoga_node, mask, &units, &values)); } pub fn sceneSetPaint(self: *Context, handle: Handle, paint: scene.Paint) !void { return self.scenePatchPaint(handle, scene.paint_fields_all, paint); } /// Unselected fields retain accepted native state; reset-border-characters requires border style. pub fn scenePatchPaint(self: *Context, handle: Handle, fields: u32, paint: scene.Paint) !void { try self.beginMutation(); defer self.mutating = false; return self.scenePatchPaintLocked(handle, fields, paint); } pub fn scenePatchPaintLocked(self: *Context, handle: Handle, fields: u32, paint: scene.Paint) !void { std.debug.assert(self.mutating); const value = try self.sceneMutableNode(handle); const node = value.scene_node.?; const reset = fields & api.OT_SCENE_PROPERTY_RESET_BORDER_CHARACTERS != 0; if (reset and node.kind != api.OT_SCENE_BOX) return error.WrongKind; if (reset and fields & api.OT_SCENE_PROPERTY_BORDER_STYLE == 0) return error.InvalidOptions; const paint_fields = fields & ~@as(u32, api.OT_SCENE_PROPERTY_RESET_BORDER_CHARACTERS); try node.owner.setPaintPartial(value, paint_fields, paint); if (reset) { if (node.control.box) |details| details.custom_border_chars = null; } } pub fn sceneSetViewport(self: *Context, handle: Handle, viewport_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.sceneMutableNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_BOX) return error.WrongKind; if (node.scroll != null) return error.InvalidOptions; if (viewport_handle) |id| { const viewport = try self.sceneNode(id); if (viewport.scene_node.?.owner != node.owner) return error.WrongSession; if (viewport.scene_node.?.kind > api.OT_SCENE_BOX) return error.WrongKind; } try scene.Scene.checkWritable(value); node.owner.setViewport(value, viewport_handle); } pub fn sceneSetScroll(self: *Context, handle: Handle, options: scene.ScrollOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); try value.scene_node.?.owner.setScroll(&self.yoga_config, value, options); } pub fn sceneSetScrollArrow(self: *Context, handle: Handle, axis: u32, end: u32, options: scene.ArrowOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); if (options.attributes & ~@import("ansi.zig").TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; try buf.validateColor(options.foreground); try buf.validateColor(options.background); if (options.text) |text| try buf.validateTextInput(text); try value.scene_node.?.owner.setScrollArrow(value, axis, end, options); } /// An explicit scroll; returns the state after it. pub fn sceneScrollTo(self: *Context, handle: Handle, target: [2]f64, relative: [2]bool, reapply: bool) !api.ot_scene_scroll_state { try self.beginMutation(); defer self.mutating = false; const value = try self.sceneMutableNode(handle); try value.scene_node.?.owner.scrollTo(value, target, relative, reapply); return scene.scrollReport(value); } /// An INTO_VIEW, ANCHOR, or LAYOUT request; returns the state after it. pub fn sceneScrollRequest(self: *Context, handle: Handle, kind: u32, target_handle: ?Handle, alignment: u32, inset: u32) !api.ot_scene_scroll_state { try self.beginMutation(); defer self.mutating = false; const value = try self.sceneMutableNode(handle); const target = if (target_handle) |id| try self.sceneNode(id) else null; if (target) |node| if (node.scene_node.?.owner != value.scene_node.?.owner) return error.WrongSession; try value.scene_node.?.owner.requestScroll(&self.objects, value, kind, target, alignment, inset); return scene.scrollReport(value); } pub fn sceneGetScroll(self: *Context, handle: Handle) !api.ot_scene_scroll_state { try self.checkSceneRead(); return scene.scrollReport(try self.sceneNode(handle)); } pub fn sceneSetFocus(self: *Context, handle: Handle, focused: bool) !void { try self.beginMutation(); defer self.mutating = false; // Blur also participates in wrapper cleanup after Session cancellation. const value = if (focused) try self.sceneMutableNode(handle) else try self.sceneNode(handle); const owned = value.scene_node.?.owner; if (focused) { try scene.Scene.checkWritable(value); owned.focus = handle; } else if (owned.focus) |accepted| { if (std.meta.eql(accepted, handle)) owned.focus = null; } owned.clearPreparation(); } pub fn sceneSetHooks(self: *Context, handle: Handle, flags: u32, generation: u64, initial_width: f64, initial_height: f64) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); try node.scene_node.?.owner.setHooks(node, flags, generation, initial_width, initial_height); } pub fn sceneSetSlider(self: *Context, handle: Handle, options: scene.SliderOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_SLIDER) return error.WrongKind; try buf.validateColor(options.foreground); try buf.validateColor(options.background); try scene.Scene.checkWritable(value); _ = try scene.sliderThumb(options, node.resize_width, node.resize_height); _ = try scene.sliderThumb(options, node.layout.width, node.layout.height); node.control = .{ .slider = options }; node.owner.clearPreparation(); } pub fn sceneGetSliderThumb(self: *Context, handle: Handle) !scene.SliderThumb { try self.beginMutation(); defer self.mutating = false; const node = (try self.sceneNode(handle)).scene_node.?; if (node.kind != api.OT_SCENE_SLIDER) return error.WrongKind; return scene.sliderThumb(node.control.slider, node.resize_width, node.resize_height); } pub fn sceneSetArrow(self: *Context, handle: Handle, options: scene.ArrowOptions) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.scenePaintNode(handle); const node = value.scene_node.?; if (node.kind != api.OT_SCENE_ARROW) return error.WrongKind; if (options.direction > 3 or options.attributes & ~@import("ansi.zig").TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; try buf.validateColor(options.foreground); try buf.validateColor(options.background); if (options.text) |text| try buf.validateTextInput(text); try scene.Scene.checkWritable(value); var replacement = options; if (options.text) |text| replacement.text = try self.allocator.dupe(u8, text); node.control.arrow.deinit(self.allocator); node.control = .{ .arrow = replacement }; node.owner.clearPreparation(); } pub fn sceneSetText(self: *Context, handle: Handle, bytes: []const u8) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.sceneMutableNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; var dirty: u32 = 0; try yoga.check(yoga.yogaNodeIsDirtyChecked(node.yoga_node, &dirty)); // The same bytes without styles to drop: a replacement would rebuild what is there. // They passed validation when they were set, and scene text keeps its tab width. if (text.buffer.internal_highlight_count == 0 and holdsBytes(text, bytes)) return; try validateTextBytes(text.buffer.tabWidth(), bytes, 0); node.scene_node.?.paint_epoch = nextPaintEpoch(); if (try self.replaceTextContent(text, bytes)) textResourceChanged(text) else textResent(node); node.scene_node.?.owner.clearPreparation(); } pub fn validateTextBytes(tab_width: u8, bytes: []const u8, retained_bytes: u32) !void { // Rope columns and line counts are u32. Tabs and control notation (two cells per byte) // are the largest cell/byte expansion; reserve one count for the trailing logical line. const bytes_max = (std.math.maxInt(u32) - 1) / @as(u32, @max(tab_width, 2)); if (retained_bytes > bytes_max or bytes.len > bytes_max - retained_bytes) return error.TextLimit; if (!std.unicode.utf8ValidateSlice(bytes)) return error.InvalidUnicode; } pub fn sceneSetStyledText(self: *Context, handle: Handle, bytes: []const u8, chunks: []const StyledTextChunk) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.scenePaintNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; var dirty: u32 = 0; try yoga.check(yoga.yogaNodeIsDirtyChecked(node.yoga_node, &dirty)); if (try self.replaceStyledTextResource(text, bytes, chunks)) textResourceChanged(text) else textResent(node); node.scene_node.?.owner.clearPreparation(); } /// Returns whether the bytes changed. fn replaceStyledTextResource(self: *Context, text: anytype, bytes: []const u8, chunks: []const StyledTextChunk) !bool { var prepared: PreparedStyledTextResource = undefined; try self.prepareStyledTextResource(&prepared, text, bytes, chunks); defer prepared.deinit(self.allocator); return self.commitStyledTextResource(&prepared, text); } const PreparedStyledTextResource = struct { buffer: text_buffer.UnifiedTextBuffer.PreparedOwnedStyledText = undefined, buffer_ready: bool = false, bytes: ?[]const u8 = null, links: link.LinkTracker, fn deinit(prepared: *PreparedStyledTextResource, allocator: std.mem.Allocator) void { if (prepared.buffer_ready) prepared.buffer.deinit(); if (prepared.bytes) |bytes| allocator.free(bytes); prepared.links.deinit(); } }; fn prepareStyledTextResource(self: *Context, prepared: *PreparedStyledTextResource, text: anytype, bytes: []const u8, chunks: []const StyledTextChunk) !void { try validateTextBytes(text.buffer.tabWidth(), bytes, 0); var offset: usize = 0; for (chunks) |chunk| { if ((chunk.byte_count == 0 and @TypeOf(text) != *SharedText) or chunk.byte_count > bytes.len - offset or chunk.attributes & ~@import("ansi.zig").TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; for ([_]?buf.RGBA{ chunk.foreground, chunk.background }) |color| { if (color) |rgba| try buf.validateColor(rgba); } _ = std.unicode.Utf8View.init(bytes[offset..][0..chunk.byte_count]) catch return error.InvalidUnicode; offset += chunk.byte_count; } if (offset != bytes.len) return error.InvalidOptions; prepared.* = .{ .links = link.LinkTracker.init(self.allocator, &self.links) }; errdefer prepared.deinit(self.allocator); const ranges = try self.allocator.alloc(text_buffer.OwnedStyledChunk, chunks.len); defer self.allocator.free(ranges); offset = 0; var range_count: usize = 0; for (chunks) |chunk| { if (chunk.byte_count == 0) continue; var attributes = chunk.attributes; if (chunk.link_url) |url| { // Legacy styled text omits unwritable URLs and zero-width chunks; their text stays. if (link.isWritableUrl(url) and text.buffer.measureText(bytes[offset..][0..chunk.byte_count]) > 0) { const id = try prepared.links.trackUrl(url); attributes = @import("ansi.zig").TextAttributes.setLinkId(attributes, id); } } offset += chunk.byte_count; ranges[range_count] = .{ .byte_count = chunk.byte_count, .style = .{ .fg = chunk.foreground, .bg = chunk.background, .attributes = attributes }, }; range_count += 1; } const copy = try self.allocator.dupe(u8, bytes); prepared.bytes = copy; text_work.add(.styled_text_sets, 1); text_work.add(.styled_text_bytes, copy.len); try text.buffer.prepareOwnedStyledText(&prepared.buffer, copy, text.input_mem_id, ranges[0..range_count], &prepared.links); prepared.buffer_ready = true; } fn commitStyledTextResource(_: *Context, prepared: *PreparedStyledTextResource, text: anytype) bool { const changed = !holdsBytes(text, prepared.bytes.?); text.input_mem_id = prepared.buffer.commit(); prepared.bytes = null; return changed; } pub fn sceneSetTextOptions(self: *Context, handle: Handle, options: scene.TextOptions) !void { try self.beginMutation(); defer self.mutating = false; const node = try self.scenePaintNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; if (options.attributes & ~@import("ansi.zig").TextAttributes.ATTRIBUTE_BASE_MASK != 0 or options.first_line_offset > std.math.maxInt(i32) or !std.math.isFinite(options.scroll_x) or options.scroll_x < 0 or options.scroll_x > std.math.maxInt(i32) or !std.math.isFinite(options.scroll_y) or options.scroll_y < 0 or options.scroll_y > std.math.maxInt(i32)) { return error.InvalidOptions; } try buf.validateColor(options.foreground); try buf.validateColor(options.background); if (options.tab_color) |rgba| try buf.validateColor(rgba); try validateTabIndicator(options.tab_indicator); var dirty: u32 = 0; try yoga.check(yoga.yogaNodeIsDirtyChecked(node.yoga_node, &dirty)); const previous_viewport = text.view.getViewport(); var has_viewport = previous_viewport != null; var viewport = previous_viewport orelse text.initial_viewport orelse viewport: { var initial: text_buffer_view.Viewport = .{ .x = 0, .y = 0, .width = 0, .height = 0 }; has_viewport = true; // Match constructor geometry before the first completed layout. Later // style changes keep this viewport until native layout resizes it. for ([_]*u32{ &initial.width, &initial.height }, 0..) |dimension, kind| { var encoded: u64 = 0; try yoga.check(yoga.yogaNodeStyleGetValueChecked(node.yoga_node, @intCast(kind), api.OT_EDGE_NONE, &encoded)); const unit: u32 = @truncate(encoded); const value: f32 = @bitCast(@as(u32, @truncate(encoded >> 32))); if (unit == api.OT_UNIT_POINT and value >= 0) { if (!std.math.isFinite(value) or @as(f64, value) > std.math.maxInt(i32)) return error.InvalidDimensions; dimension.* = @intFromFloat(value); if (value == 0) has_viewport = false; } else { has_viewport = false; } } break :viewport initial; }; const wrap_changed = text.view.wrap_mode != options.wrap_mode; const scroll_changed = text.scroll_x != options.scroll_x or text.scroll_y != options.scroll_y; const measure_changed = wrap_changed or text.view.first_line_offset != options.first_line_offset; const prepare_changed = measure_changed or scroll_changed or text.view.truncate != options.truncate; text.buffer.setDefaultFg(options.foreground); text.buffer.setDefaultBg(options.background); text.buffer.setDefaultAttributes(options.attributes); text.view.setWrapMode(options.wrap_mode); text.view.setTextAlign(options.text_align); text.view.setTruncate(options.truncate); text.view.setFirstLineOffset(options.first_line_offset); text.view.setTabIndicator(options.tab_indicator); text.view.setTabIndicatorColor(options.tab_color); text.scroll_x = options.scroll_x; text.scroll_y = options.scroll_y; viewport.x = @intFromFloat(options.scroll_x); viewport.y = @intFromFloat(options.scroll_y); if (has_viewport) { if (previous_viewport != null and wrap_changed and options.wrap_mode != .none) { text.view.setWrapWidth(if (viewport.width > 0) viewport.width else null); } if (previous_viewport == null or scroll_changed) { text.view.setViewport(viewport); } } else { // Unresolved constructor dimensions do not yet define a viewport. // Retain accepted offsets for the first layout without forcing wrap. text.initial_viewport = viewport; text.view.setWrapWidth(if (viewport.width > 0) viewport.width else null); } if (measure_changed) yoga.yogaNodeMarkDirty(node.yoga_node); if (prepare_changed) node.scene_node.?.owner.invalidateObservation(node); node.scene_node.?.owner.clearPreparation(); } pub fn sceneSetTextSelection(self: *Context, handle: Handle, options: SceneTextSelectionOptions) !bool { try self.beginMutation(); defer self.mutating = false; if (options.operation > api.OT_SCENE_TEXT_SELECTION_COLORS or options.behavior > api.OT_SCENE_TEXT_SELECTION_LINE) return error.InvalidOptions; for ([_]?buf.RGBA{ options.background, options.foreground }) |color| { if (color) |rgba| try buf.validateColor(rgba); } // Reset participates in wrapper cleanup after Session cancellation and // must not depend on Yoga health or allocate view caches. const node = if (options.operation == api.OT_SCENE_TEXT_SELECTION_RESET) try self.sceneNode(handle) else try self.sceneMutableNode(handle); node.scene_node.?.paint_epoch = nextPaintEpoch(); const text = node.scene_node.?.text orelse return error.WrongKind; if (options.operation == api.OT_SCENE_TEXT_SELECTION_COLORS) { text.view.setSelectionColors(options.background, options.foreground); return false; } const changed = if (options.operation == api.OT_SCENE_TEXT_SELECTION_RESET) reset: { const had_selection = text.view.getSelection() != null; text.view.resetLocalSelection(); break :reset had_selection; } else selection: { var dirty: u32 = 0; try yoga.check(yoga.yogaNodeIsDirtyChecked(node.yoga_node, &dirty)); // Hosts pass cells local to the node; the view starts at its content and clamps cells off its edges. const offset = scene.contentOffset(node.scene_node.?.layout); var local = options; for ([_]*i32{ &local.anchor_x, &local.anchor_y, &local.focus_x, &local.focus_y }, [_]i32{ offset[0], offset[1], offset[0], offset[1] }) |point, by| point.* -|= by; if (text.view.getViewport()) |viewport| { const x_offset: i32 = if (text.view.wrap_mode == .none) @intCast(viewport.x) else 0; const y_offset: i32 = @intCast(viewport.y); _ = std.math.add(i32, local.anchor_x, x_offset) catch return error.InvalidOptions; _ = std.math.add(i32, local.focus_x, x_offset) catch return error.InvalidOptions; _ = std.math.add(i32, local.anchor_y, y_offset) catch return error.InvalidOptions; _ = std.math.add(i32, local.focus_y, y_offset) catch return error.InvalidOptions; } if (text.buffer.lineWidthColsMax() > std.math.maxInt(i32)) return error.InvalidOptions; // The legacy view methods cannot report allocation failures. Prepare // their caches first so no failing work follows selection publication. try text.prepareView(); if (text.view.virtual_lines.items.len > std.math.maxInt(i32)) return error.InvalidOptions; const behavior: text_buffer_view.SelectionBehavior = @fromBackingInt(@intCast(options.behavior)); break :selection if (options.operation == api.OT_SCENE_TEXT_SELECTION_SET) text.view.setLocalSelectionBehavior(local.anchor_x, local.anchor_y, local.focus_x, local.focus_y, options.background, options.foreground, behavior) else text.view.updateLocalSelectionBehavior(local.anchor_x, local.anchor_y, local.focus_x, local.focus_y, options.background, options.foreground, behavior); }; node.scene_node.?.owner.clearPreparation(); return changed; } pub fn sceneGetTextSelection(self: *Context, handle: Handle) !u64 { try self.checkSceneRead(); const node = try self.sceneNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; return text.view.packSelectionInfo(); } /// Zero capacity queries exact selected UTF-8 bytes. Short copies preserve output. pub fn sceneGetSelectedText(self: *Context, handle: Handle, out: []u8) !u32 { try self.checkSceneRead(); const was_mutating = self.mutating; self.mutating = true; defer self.mutating = was_mutating; const node = try self.sceneNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; return text.view.copySelectedText(out); } pub fn textBufferGetRange(self: *Context, handle: Handle, start: u32, end: u32, out: []u8) !u32 { try self.checkSceneRead(); const text = try self.getTextBuffer(handle); return text.buffer.copyTextRange(start, end, out); } pub const TextRange = union(enum) { offsets: struct { start: u32, end: u32 }, coords: struct { start_row: u32, start_col: u32, end_row: u32, end_col: u32 }, }; pub fn editBufferGetRange(self: *Context, handle: Handle, range: TextRange, out: []u8) !u32 { try self.checkSceneRead(); const was_mutating = self.mutating; self.mutating = true; defer self.mutating = was_mutating; const edit = try self.getEditBuffer(handle); const buffer = edit.buffer.tb; const offsets: @FieldType(TextRange, "offsets") = switch (range) { .offsets => |offsets| offsets, .coords => |coords| result: { const iter = @import("text-buffer-iterators.zig"); break :result .{ .start = iter.coordsToOffset(buffer.rope(), coords.start_row, coords.start_col) orelse return 0, .end = iter.coordsToOffset(buffer.rope(), coords.end_row, coords.end_col) orelse return 0, }; }, }; return buffer.copyTextRange(offsets.start, offsets.end, out); } /// Lays `bytes` out as setText would, without storing them, and returns the cursor offset at their end. pub fn editMeasureText(self: *Context, handle: Handle, bytes: []const u8) !u32 { try self.checkSceneRead(); const buffer = (try self.getEditBuffer(handle)).buffer.tb; return measureEditText(bytes, buffer.tabWidth(), buffer.controlDisplay(), buffer.widthMethod()); } /// Returns the cursor offset at the end of `bytes` after setText on an edit buffer with these /// settings: the cells of each line plus one per line break. pub fn measureEditText(bytes: []const u8, tab_width: u8, control_display: utf8.ControlDisplay, width_method: utf8.WidthMethod) !u32 { // The byte limit keeps the widths and line breaks within u32. try validateTextBytes(tab_width, bytes, 0); var offset: u32 = 0; var rest = bytes; while (true) { const end = std.mem.indexOfAny(u8, rest, "\r\n") orelse rest.len; const line = rest[0..end]; offset += utf8.calculateTextWidth(line, tab_width, control_display, utf8.isAsciiOnly(line), width_method); if (end == rest.len) return offset; // Lines end at LF, CR, or CRLF, as textToSegments splits them. const crlf = std.mem.startsWith(u8, rest[end..], "\r\n"); offset += 1; rest = rest[end + 1 + @intFromBool(crlf) ..]; } } pub fn textViewGetSelectedText(self: *Context, handle: Handle, out: []u8) !u32 { try self.checkSceneRead(); const view = try self.getTextBufferView(handle); return view.view.copySelectedText(out); } pub fn editorGetSelectedText(self: *Context, handle: Handle, out: []u8) !u32 { try self.checkSceneRead(); const view = try self.getEditorView(handle); return view.view.text_buffer_view.copySelectedText(out); } pub fn sceneGetText(self: *Context, handle: Handle, out: []u8) !u32 { try self.checkSceneRead(); const was_mutating = self.mutating; self.mutating = true; defer self.mutating = was_mutating; const node = try self.sceneNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; const count = text.buffer.getByteSize(); if (out.len == 0) return count; if (out.len < count) return error.InvalidOptions; const written = text.buffer.getPlainTextIntoBuffer(out); std.debug.assert(written == count); return count; } pub fn sceneGetTextInfo(self: *Context, handle: Handle) !scene.TextInfo { try self.checkSceneRead(); const was_mutating = self.mutating; self.mutating = true; defer self.mutating = was_mutating; const node = try self.sceneNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; try text.prepareView(); return .{ .byte_count = text.buffer.getByteSize(), .text_length = text.buffer.getLength(), .line_count = text.buffer.lineCount(), .virtual_line_count = @intCast(text.view.virtual_lines.items.len), .width_cols_max = text.buffer.lineWidthColsMax(), }; } pub fn sceneGetTextLines(self: *Context, handle: Handle, first_line: u32, out: []scene.TextLine) !u32 { try self.checkSceneRead(); const was_mutating = self.mutating; self.mutating = true; defer self.mutating = was_mutating; const node = try self.sceneNode(handle); const text = node.scene_node.?.text orelse return error.WrongKind; try text.prepareView(); const lines = text.view.getLogicalLineInfo(); const count: u32 = @intCast(lines.line_start_cols.len); // Copy only the requested window, so a viewport read does not scale with the document. const start = @min(first_line, count); for (out[0..@min(out.len, count - start)], start..) |*line, index| { line.* = .{ .start_cols = lines.line_start_cols[index], .width_cols = lines.line_width_cols[index], .source_line = lines.line_sources[index], .wrap_index = lines.line_wraps[index], }; } return count; } pub fn sceneGetTextByteAt(self: *Context, handle: Handle, x: i32, y: i32) !?u32 { try self.checkSceneRead(); const node = (try self.sceneNode(handle)).scene_node.?; const text = node.text orelse return error.WrongKind; // Only what the latest frame painted: the node's cells in that frame, and its view as drawn then. const area = node.owner.paintedArea(node) orelse return null; // A stamp from an attempt that did not finish describes cells that frame never showed. if (text.painted_frame > area.frame or !std.meta.eql(text.painted, text.mapping())) return null; const clip = area.clip; if (x < clip.x or y < clip.y or x - @as(i64, clip.x) >= clip.width or y - @as(i64, clip.y) >= clip.height) return null; const hit = text.view.graphemeAtCell(@intCast(@as(i64, x) - area.x), @intCast(@as(i64, y) - area.y)) orelse return null; // An edge that cuts a wide grapheme leaves its cells blank. const left = area.x + hit.x; if (left < clip.x or left + hit.width > @as(i64, clip.x) + clip.width) return null; return hit.byte; } pub fn sceneGetLayout(self: *Context, handle: Handle, raw_yoga: bool) !scene.Layout { try self.checkSceneRead(); const node = try self.sceneNode(handle); if (!raw_yoga) return scene.getLayout(node); var layout: yoga.ExternalYogaLayout = undefined; try yoga.check(yoga.yogaNodeGetComputedLayoutChecked(node.yoga_node, &layout)); return .{ .left = layout.left, .top = layout.top, .right = layout.right, .bottom = layout.bottom, .width = layout.width, .height = layout.height, }; } pub fn sceneGetPaintLayout(self: *Context, handle: Handle, content: bool) !scene.Layout { try self.checkSceneRead(); const node = try self.sceneNode(handle); try node.scene_node.?.owner.prepareOmitted(&self.objects, node); return scene.getPaintLayout(node, content); } /// Solve the Session root without painting or publishing output. Measurement /// callbacks may use checked scene queries; mutations reject until this returns. pub fn sceneMeasureLayout(self: *Context, session_handle: Handle, root: Handle) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); try value.checkRendering(); try value.checkFrameIdle(); const attached = value.renderer orelse return error.RendererNotAttached; const owned = value.scene orelse return error.SceneNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) return error.PresentationPending; if (attached.width > std.math.maxInt(i32) or attached.height > std.math.maxInt(i32)) return error.InvalidDimensions; try owned.measureLayout(&self.objects, attached, root); } /// Paints a hook-free scene and retains its DONE draft. Commit or cancel the /// returned request before painting again; frame-qualified effects may run first. pub fn scenePaint(self: *Context, session_handle: Handle, background: buf.RGBA, use_mouse: bool, excluded_hit_num: u32) !scene.FrameRequest { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); try value.checkRendering(); try value.checkFrameIdle(); const attached = value.renderer orelse return error.RendererNotAttached; const owned = value.scene orelse return error.SceneNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) return error.PresentationPending; if (attached.width > std.math.maxInt(i32) or attached.height > std.math.maxInt(i32)) return error.InvalidDimensions; errdefer attached.clearSkippedFrameState(); const result = try owned.frameStep(self, attached, null, .{ .background = background, .use_mouse = use_mouse, .excluded_hit_num = excluded_hit_num, .max_layout_rounds = 8, .max_host_requests = 65536, }, false, null); std.debug.assert(result.kind == api.OT_SCENE_FRAME_DONE); return result; } pub fn sceneFrameStep(self: *Context, session_handle: Handle, previous: ?scene.FrameRequest, options: scene.FrameOptions) !scene.FrameRequest { return self.sceneFrameStepWithRecording(session_handle, previous, options, null); } pub fn sceneFrameStepWithRecording(self: *Context, session_handle: Handle, previous: ?scene.FrameRequest, options: scene.FrameOptions, recording: ?[]const u8) !scene.FrameRequest { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); try value.checkRendering(); if (value.frame_lease_count != 0) return error.FrameBusy; const attached = value.renderer orelse return error.RendererNotAttached; const owned = value.scene orelse return error.SceneNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) return error.PresentationPending; if (attached.width > std.math.maxInt(i32) or attached.height > std.math.maxInt(i32)) return error.InvalidDimensions; return owned.frameStep(self, attached, previous, options, true, recording); } pub fn sceneFramePaintSlots(self: *Context, session_handle: Handle, frame: scene.FrameRequest) ![]const scene.PaintSlot { try self.checkSceneRead(); const owned = (try self.getSession(session_handle)).scene orelse return error.SceneNotAttached; return owned.paintSlots(frame); } pub fn sceneFrameAcquireBufferLease(self: *Context, session_handle: Handle, frame: scene.FrameRequest, which: RendererBuffer) !Handle { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); try value.checkRendering(); const owned = value.scene orelse return error.SceneNotAttached; const painted = try owned.checkPainted(frame); const attached = value.renderer orelse return error.RendererNotAttached; if (!painted.destination.matches(attached.getNextBuffer())) return error.StaleFrame; if (self.lease_count >= self.lease_count_max) return error.LeaseLimit; try self.objects.checkCapacity(); attached.taint(renderer.FrameWork.full_path_tainted); const access = try self.allocator.create(FrameBufferLease); errdefer self.allocator.destroy(access); const target = switch (which) { .current => attached.getCurrentBuffer(), .next => attached.getNextBuffer(), }; access.* = .{ .frame = frame, .which = which, .destination = scene.BufferIdentity.init(target), .lease = try buf.BufferLease.acquireChecked(target, &self.lease_count, self.lease_count_max, &self.lease_bytes, &self.lease_bytes_max), }; errdefer access.lease.releaseChecked(&self.lease_count, &self.lease_bytes, &self.lease_bytes_max); const handle = try self.objects.insert(.frame_buffer_lease, access); value.frame_lease_count += 1; return handle; } pub fn sceneFrameDrawBuffer(self: *Context, session_handle: Handle, frame: scene.FrameRequest, source_handle: Handle, x: i32, y: i32) !void { try self.beginMutation(); defer self.mutating = false; const target = try self.frameDrawTarget(session_handle, frame); const source = try self.getBuffer(source_handle); try drawContextBuffer(target, source, x, y, .{}); } fn bufferDrawTarget(self: *Context, handle: Handle, frame: ?scene.FrameRequest) !*buf.OptimizedBuffer { std.debug.assert(self.mutating); return if (frame) |ticket| self.frameDrawTarget(handle, ticket) else self.getBuffer(handle); } fn frameDrawTarget(self: *Context, session_handle: Handle, frame: scene.FrameRequest) !*buf.OptimizedBuffer { const value = try self.getSession(session_handle); try value.checkRendering(); const attached = value.renderer orelse return error.RendererNotAttached; if (value.frame_end_offset != null or attached.pendingPresentation != null) return error.PresentationPending; const owned = value.scene orelse return error.SceneNotAttached; const access = try owned.checkPainted(frame); const target = attached.getNextBuffer(); if (!access.destination.matches(target)) return error.StaleFrame; attached.taint(renderer.FrameWork.full_path_tainted); return target; } pub fn sceneFrameCommit(self: *Context, session_handle: Handle, frame: scene.FrameRequest, force: bool) Error!session.RenderStatus { try self.beginMutation(); defer self.mutating = false; return (try self.getSession(session_handle)).commitSceneFrame(frame, force); } pub fn sceneFrameCancel(self: *Context, session_handle: Handle, frame_id: u64) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); const owned = value.scene orelse return error.SceneNotAttached; const active_id = if (owned.attempt) |active| active.frame_id else if (owned.painted) |painted| painted.ticket.frame_id else return error.StaleFrame; if (active_id != frame_id) return error.StaleFrame; value.cancelSceneFrame(); } pub fn sceneHitTest(self: *Context, session_handle: Handle, x: i32, y: i32) !u32 { return self.sceneHitTestExcluding(session_handle, x, y, 0); } pub fn sceneHitTestExcluding(self: *Context, session_handle: Handle, x: i32, y: i32, excluded: u32) !u32 { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); const attached = value.renderer orelse return error.RendererNotAttached; const owned = value.scene orelse return error.SceneNotAttached; if (x < 0 or y < 0) return 0; const token = owned.hitToken(attached, @intCast(x), @intCast(y), excluded); const handle = owned.tokens.get(token) orelse return 0; const node = self.objects.get(handle, .native_renderable, native_renderable.NativeRenderable) catch return 0; const state = node.scene_node orelse return 0; if (state.owner != owned or state.token != token) return 0; return state.num; } pub fn sceneSetDebugFlags(self: *Context, session_handle: Handle, flags: u32) !void { try self.beginMutation(); defer self.mutating = false; const value = try self.getSession(session_handle); try value.checkOpen(); const owned = value.scene orelse return error.SceneNotAttached; if (flags & ~@as(u32, api.OT_SCENE_DEBUG_FULL_FRAME | api.OT_SCENE_DEBUG_VERIFY) != 0) return error.InvalidOptions; try value.checkFrameIdle(); owned.debug_flags = flags; } pub fn sceneGetStats(self: *Context, session_handle: Handle) !renderer.RenderStatsSnapshot { try self.beginMutation(); defer self.mutating = false; return (try self.getSessionRenderer(session_handle)).getRenderStats(); } pub fn sceneGetCursorState(self: *Context, session_handle: Handle) !scene.CursorState { try self.beginMutation(); defer self.mutating = false; const terminal = &(try self.getSessionRenderer(session_handle)).terminal; const position = terminal.getCursorPosition(); const style = terminal.getCursorStyle(); const color = terminal.getCursorColor(); return .{ .x = position.x, .y = position.y, .visible = position.visible, .blinking = style.blinking, .style = switch (style.style) { .block => 0, .line => 1, .underline => 2, .default => 3, }, .color = .{ ansi.redF(color), ansi.greenF(color), ansi.blueF(color), ansi.alphaF(color) }, }; } fn getRenderable(self: *Context, handle: Handle) Error!*native_renderable.NativeRenderable { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .native_renderable, native_renderable.NativeRenderable); } fn createTextResource(self: *Context, width_method: utf8.WidthMethod) !*Text { // First sceneSetText registers the real bytes; an empty slot would be replaced. if (self.text_pool) |value| { self.text_pool = value.pool_next; self.text_pool_count -= 1; self.text_pool_bytes -= @sizeOf(Text) + value.buffer.retainedStorageBytes() + value.view.retainedStorageBytes(); errdefer self.freeTextStorage(value); try value.buffer.reinitStorage(width_method); try value.view.reinitStorage(); value.* = .{ .buffer = value.buffer, .view = value.view }; return value; } const value = try self.allocator.create(Text); errdefer self.allocator.destroy(value); const buffer = try text_buffer.UnifiedTextBuffer.initWithOptions(self.allocator, &self.graphemes, &self.links, width_method, .{ .io = self.io, .logger = &self.logger, .group_sets = &self.group_sets, }); errdefer buffer.deinit(); const view = try text_buffer_view.UnifiedTextBufferView.init(self.allocator, buffer); errdefer view.deinit(); value.* = .{ .buffer = buffer, .view = view }; return value; } pub fn createTextBuffer(self: *Context, width_method: utf8.WidthMethod) !Handle { try self.beginMutation(); defer self.mutating = false; try self.objects.checkCapacity(); const value = try self.takeSharedTextStorage(width_method); errdefer self.freeSharedTextStorage(value); const input_mem_id = try value.buffer.registerMemBuffer("", false); const handle = try self.objects.insert(.text_buffer, value); value.* = .{ .handle = handle, .buffer = value.buffer, .input_mem_id = input_mem_id }; return handle; } fn takeSharedTextStorage(self: *Context, width_method: utf8.WidthMethod) !*SharedText { if (self.shared_text_pool) |value| { self.shared_text_pool = value.pool_next; self.shared_text_pool_count -= 1; self.shared_text_pool_bytes -= @sizeOf(SharedText) + value.buffer.retainedStorageBytes(); errdefer self.freeSharedTextStorage(value); try value.buffer.reinitStorage(width_method); return value; } const value = try self.allocator.create(SharedText); errdefer self.allocator.destroy(value); const buffer = try text_buffer.UnifiedTextBuffer.initWithOptions(self.allocator, &self.graphemes, &self.links, width_method, .{ .io = self.io, .logger = &self.logger, .group_sets = &self.group_sets, }); value.* = .{ .handle = undefined, .buffer = buffer, .input_mem_id = 0 }; return value; } /// The caller has destroyed every view. fn releaseSharedTextStorage(self: *Context, value: *SharedText) void { std.debug.assert(value.views == null); if (!self.closing and self.shared_text_pool_count < @min(self.objects.slots.len, text_pool_count_max)) { value.buffer.retireStorage(); const bytes = @sizeOf(SharedText) + value.buffer.retainedStorageBytes(); if (bytes <= text_storage_bytes_max and bytes <= text_pool_bytes_max - self.shared_text_pool_bytes) { value.pool_next = self.shared_text_pool; self.shared_text_pool = value; self.shared_text_pool_count += 1; self.shared_text_pool_bytes += bytes; return; } } self.freeSharedTextStorage(value); } fn freeSharedTextStorage(self: *Context, value: *SharedText) void { value.buffer.deinit(); self.allocator.destroy(value); } fn getTextBuffer(self: *Context, handle: Handle) Error!*SharedText { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .text_buffer, SharedText); } pub fn createTextBufferView(self: *Context, text_handle: Handle) !Handle { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(text_handle); try self.objects.checkCapacity(); const value = try self.allocator.create(TextView); errdefer self.allocator.destroy(value); const view = try text_buffer_view.UnifiedTextBufferView.init(self.allocator, text.buffer); errdefer view.deinit(); const handle = try self.objects.insert(.text_buffer_view, value); value.* = .{ .handle = handle, .text = text, .view = view, .next = text.views, .paint_epoch = nextPaintEpoch() }; if (text.views) |next| next.previous = value; text.views = value; return handle; } fn getTextBufferView(self: *Context, handle: Handle) Error!*TextView { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .text_buffer_view, TextView); } pub fn textBufferSetText(self: *Context, handle: Handle, bytes: []const u8) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try validateTextBytes(text.buffer.tabWidth(), bytes, 0); const changed = try self.replaceTextContent(text, bytes); text.reclaimAppendBuffers(); text.invalidate(changed); } pub fn textBufferSetStyledText(self: *Context, handle: Handle, bytes: []const u8, chunks: []const StyledTextChunk) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); const changed = try self.replaceStyledTextResource(text, bytes, chunks); text.reclaimAppendBuffers(); text.invalidate(changed); } pub const text_replacement_count_max = 256; pub const text_replacement_chunks_max = 4096; pub const text_replacement_bytes_max = 4 * 1024 * 1024; pub const text_replacement_url_bytes_max = 1024 * 1024; pub const TextReplacement = struct { buffer: Handle, view: Handle, bytes: []const u8, chunks: []const StyledTextChunk, }; pub const TextReplacementInfo = extern struct { text_length: u32, byte_count: u32 }; pub fn textBufferReplaceStyledBatch(self: *Context, replacements: []const TextReplacement, output: []TextReplacementInfo) !void { try self.beginMutation(); defer self.mutating = false; if (replacements.len > text_replacement_count_max or output.len != replacements.len) return error.InvalidOptions; var views: [text_replacement_count_max]*TextView = undefined; var bytes_left: usize = text_replacement_bytes_max; var chunks_left: usize = text_replacement_chunks_max; var urls_left: usize = text_replacement_url_bytes_max; for (replacements, 0..) |replacement, index| { if (replacement.bytes.len > bytes_left or replacement.chunks.len > chunks_left) return error.InvalidOptions; bytes_left -= replacement.bytes.len; chunks_left -= replacement.chunks.len; for (replacement.chunks) |chunk| if (chunk.link_url) |url| { if (url.len > urls_left) return error.InvalidOptions; urls_left -= url.len; }; const text = try self.getTextBuffer(replacement.buffer); const dependent = try self.getTextBufferView(replacement.view); if (dependent.text != text) return error.InvalidOptions; for (views[0..index]) |previous| if (previous.text == text) return error.InvalidOptions; try text.checkMutable(); views[index] = dependent; } // Allocate once: moving a prepared arena would invalidate its allocator pointers. const prepared = try self.allocator.alloc(PreparedStyledTextResource, replacements.len); defer self.allocator.free(prepared); var ready: usize = 0; defer for (prepared[0..ready]) |*candidate| candidate.deinit(self.allocator); for (replacements, 0..) |replacement, index| { try self.prepareStyledTextResource(&prepared[index], views[index].text, replacement.bytes, replacement.chunks); ready += 1; } for (prepared, 0..) |*candidate, index| { const text = views[index].text; const changed = self.commitStyledTextResource(candidate, text); text.reclaimAppendBuffers(); views[index].view.resetLocalSelection(); text.invalidate(changed); output[index] = .{ .text_length = text.buffer.getLength(), .byte_count = text.buffer.getByteSize() }; } } pub fn textBufferAppend(self: *Context, handle: Handle, bytes: []const u8) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try validateTextBytes(text.buffer.tabWidth(), bytes, text.buffer.getByteSize()); if (bytes.len == 0) return; // Each append takes a registry slot. When none is left, one owned copy of the whole // document replaces them all, so a long append stream copies O(n^2) bytes in total. if (text.buffer.mem_registry.getFreeSlots() == 0) try text.buffer.flattenMemRegistry(); try text.buffer.appendCopy(bytes); text.invalidate(true); } pub fn textBufferClear(self: *Context, handle: Handle, reset: bool) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); if (reset) { try text.buffer.reset(); // Reset retains registry capacity, including the reserved replacement slot. std.debug.assert(text.buffer.mem_registry.buffers.capacity > 0); text.input_mem_id = text.buffer.registerMemBuffer("", false) catch unreachable; } else { try text.buffer.clear(); } text.invalidate(true); } pub fn textBufferSetSyntaxStyle(self: *Context, handle: Handle, style_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); const style = if (style_handle) |id| try self.getSyntaxStyle(id) else null; text.buffer.style_binding.dependent = .{ .text = text }; text.buffer.setSyntaxStyle(style); text.invalidate(false); } pub fn textBufferSetDefaults(self: *Context, handle: Handle, options: TextDefaults) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try setBufferDefaults(text.buffer, options); text.invalidate(false); } pub fn editBufferSetTabWidth(self: *Context, handle: Handle, width: u8) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try edit.buffer.tb.checkTabWidth(width); edit.buffer.setTabWidth(width); edit.invalidate(); } pub fn textBufferSetTabWidth(self: *Context, handle: Handle, width: u8) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try text.buffer.checkTabWidth(width); text.buffer.setTabWidth(width); text.invalidate(true); } pub fn textBufferSetWidthMethod(self: *Context, handle: Handle, method: utf8.WidthMethod) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); // NO_ZWJ breaks graphemes at joiners: chunks made under it or for it can't be re-measured in place. if (text.follow_width or method == .no_zwj or text.buffer.widthMethod() == .no_zwj) return error.InvalidOptions; try text.setWidthMethod(method); } pub fn textBufferHighlight(self: *Context, handle: Handle, operation: TextHighlight) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try highlightBuffer(text.buffer, operation); text.invalidate(false); } pub fn textBufferSetLayer(self: *Context, handle: Handle, layer: LayerReplacement) !void { try self.beginMutation(); defer self.mutating = false; const text = try self.getTextBuffer(handle); try text.checkMutable(); try text.buffer.setLayer(layer.layer_id, layer.start_byte, layer.end_byte, layer.runs); text.invalidate(false); } /// Group set ids are Context-wide: a buffer composes them against whatever style it binds. pub fn groupSet(self: *Context, names: []const []const u8) !u32 { try self.beginMutation(); defer self.mutating = false; return self.group_sets.intern(names); } pub fn textViewSetViewport(self: *Context, handle: Handle, viewport: text_buffer_view.Viewport, size_only: bool) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getTextBufferView(handle); try view.checkMutable(); try validateViewport(viewport); if (size_only) { if (view.view.getViewport()) |previous| try validateViewport(.{ .x = previous.x, .y = previous.y, .width = viewport.width, .height = viewport.height, }); view.view.setViewportSize(viewport.width, viewport.height); } else view.view.setViewport(viewport); view.invalidatePreparation(); } pub fn textViewCommand(self: *Context, handle: Handle, command: TextViewCommand) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getTextBufferView(handle); try view.checkMutable(); switch (command) { .wrap_width => |width| { if (width) |value| if (value > std.math.maxInt(i32)) return error.InvalidOptions; view.view.setWrapWidth(width); }, .wrap_mode => |mode| view.view.setWrapMode(mode), .first_line_offset => |offset| { if (offset > std.math.maxInt(i32)) return error.InvalidOptions; view.view.setFirstLineOffset(offset); }, .tab_indicator => |indicator| { try validateTabIndicator(indicator); view.view.setTabIndicator(indicator); }, .truncate => |enabled| view.view.setTruncate(enabled), .text_align => |alignment| view.view.setTextAlign(alignment), } switch (command) { .wrap_width, .wrap_mode, .first_line_offset => view.invalidate(), .tab_indicator, .truncate, .text_align => view.invalidatePreparation(), } } pub fn textViewSetTabColor(self: *Context, handle: Handle, color: ?buf.RGBA) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getTextBufferView(handle); try view.checkMutable(); if (color) |rgba| try buf.validateColor(rgba); view.view.setTabIndicatorColor(color); view.invalidatePreparation(); } /// Paint takes the default at draw time, so every view's current selection follows it. pub fn setSelectionColors(self: *Context, bg: ?buf.RGBA, fg: ?buf.RGBA) !void { try self.beginMutation(); defer self.mutating = false; for ([_]?buf.RGBA{ bg, fg }) |color| if (color) |rgba| try buf.validateColor(rgba); self.selection_default = .{ .bgColor = bg, .fgColor = fg }; self.selection_epoch = nextPaintEpoch(); } pub fn textViewSelect(self: *Context, handle: Handle, options: TextSelection) !bool { try self.beginMutation(); defer self.mutating = false; const view = try self.getTextBufferView(handle); try view.checkMutable(); if (options.update_cursor or options.follow_cursor) return error.InvalidOptions; return selectView(view, options); } pub fn createEditBuffer(self: *Context, width_method: utf8.WidthMethod) !Handle { try self.beginMutation(); defer self.mutating = false; try self.objects.checkCapacity(); const value = try self.allocator.create(Edit); errdefer self.allocator.destroy(value); value.* = .{ .owner = self, .handle = undefined, .buffer = undefined, }; value.buffer = try edit_buffer.EditBuffer.initWithOptions(self.allocator, &self.graphemes, &self.links, width_method, .{ .userdata = value, .callback = Edit.receive, }, .{ .io = self.io, .logger = &self.logger, .group_sets = &self.group_sets, }); errdefer value.buffer.deinit(); value.handle = try self.objects.insert(.edit_buffer, value); value.content_epoch = value.buffer.tb.getContentEpoch(); return value.handle; } fn getEditBuffer(self: *Context, handle: Handle) Error!*Edit { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .edit_buffer, Edit); } pub fn createEditorView(self: *Context, edit_handle: Handle, width: u32, height: u32) !Handle { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(edit_handle); try self.objects.checkCapacity(); const value = try self.allocator.create(Editor); errdefer self.allocator.destroy(value); const view = try editor_view.EditorView.init(self.allocator, edit.buffer, width, height); errdefer view.deinit(); const handle = try self.objects.insert(.editor_view, value); value.* = .{ .handle = handle, .edit = edit, .view = view, .next = edit.views, .paint_epoch = nextPaintEpoch() }; if (edit.views) |next| next.previous = value; edit.views = value; return handle; } fn getEditorView(self: *Context, handle: Handle) Error!*Editor { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .editor_view, Editor); } pub fn createSyntaxStyle(self: *Context) !Handle { try self.beginMutation(); defer self.mutating = false; try self.objects.checkCapacity(); const style = try syntax_style.SyntaxStyle.init(self.allocator); errdefer style.deinit(); return self.objects.insert(.syntax_style, style); } fn getSyntaxStyle(self: *Context, handle: Handle) Error!*syntax_style.SyntaxStyle { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .syntax_style, syntax_style.SyntaxStyle); } pub fn syntaxStyleRegister(self: *Context, handle: Handle, name: []const u8, definition: syntax_style.StyleDefinition) !u32 { try self.beginMutation(); defer self.mutating = false; if (!std.unicode.utf8ValidateSlice(name)) return error.InvalidUnicode; if (definition.attributes & ~@as(u32, definition.supplied_attributes) != 0) return error.InvalidOptions; if (definition.fg) |color| try buf.validateColor(color); if (definition.bg) |color| try buf.validateColor(color); const style = try self.getSyntaxStyle(handle); // Paint resolves styles from the table every frame, so borrowers need no invalidation; // retained paint repaints them by their paint epochs. try checkStyleDependents(style); return style.registerStyleDefinition(name, definition); } fn checkStyleDependents(style: *const syntax_style.SyntaxStyle) !void { var next = style.borrowers; while (next) |borrower| : (next = borrower.next) { if (borrower.dependent != .none) text_work.add(.style_dependent_visits, 1); switch (borrower.dependent) { .none => {}, .text => |text| try @as(*SharedText, @ptrCast(@alignCast(text))).checkMutable(), .edit => |edit| try @as(*Edit, @ptrCast(@alignCast(edit))).checkMutable(), .scene_text => |node| { const value: *native_renderable.NativeRenderable = @ptrCast(@alignCast(node)); try yoga.check(yoga.nodeTeardownStatus(value.yoga_node)); value.scene_node.?.paint_epoch = nextPaintEpoch(); }, } } } // ---- Markdown documents (ot_markdown_*) ---- pub fn createMarkdown(self: *Context, options: MarkdownOptions) !Handle { try self.beginMutation(); defer self.mutating = false; defer self.resetMarkdownScratch(); try self.objects.checkCapacity(); if (options.syntax_style) |handle| _ = try self.getSyntaxStyle(handle); const value = try self.allocator.create(MarkdownDoc); errdefer self.allocator.destroy(value); value.* = .{ .owner = self, .doc = markdown.Doc.init(self.allocator, &self.markdown_scratch, try options.engine()) catch |err| return markdownError(err), .writer = .{ .context = value, .write_fn = MarkdownDoc.writeNode }, .syntax_style = options.syntax_style, }; value.doc.writer = &value.writer; errdefer value.doc.deinit(); return self.objects.insert(.markdown_doc, value); } fn getMarkdown(self: *Context, handle: Handle) Error!*MarkdownDoc { if (self.closing) return error.ContextClosed; return self.objects.get(handle, .markdown_doc, MarkdownDoc); } fn resetMarkdownScratch(self: *Context) void { _ = self.markdown_scratch.reset(.{ .retain_with_limit = markdown.scratch_retained_byte_count_max }); } pub const MarkdownCall = union(enum) { append: []const u8, set: []const u8, finish, options: MarkdownOptions }; /// One mutating call on a doc. A rejected call publishes nothing; a removal unbinds the /// nodes of the removed blocks. pub fn markdownCall(self: *Context, handle: Handle, call: MarkdownCall) !MarkdownResult { try self.beginMutation(); defer self.mutating = false; defer self.resetMarkdownScratch(); const value = try self.getMarkdown(handle); switch (call) { .append, .set => |bytes| if (!std.unicode.utf8ValidateSlice(bytes)) return error.InvalidUnicode, else => {}, } // The doc's writes wait for the call to be accepted: a rejected one writes no node. errdefer value.writer.unbound_from = markdown.none; errdefer value.staged = .empty; switch (call) { .append => |bytes| value.doc.append(bytes) catch |err| return markdownError(err), .set => |bytes| value.doc.set(bytes) catch |err| return markdownError(err), .finish => value.doc.finish() catch |err| return markdownError(err), .options => |options| try value.setOptions(options), } value.applyStaged(); value.unbindRemoved(); value.resyncNodes(); value.finishHandoff(); return value.result(); } pub fn markdownSource(self: *Context, handle: Handle) ![]const u8 { if (self.mutating) return error.ContextBusy; return (try self.getMarkdown(handle)).doc.source.items; } /// The changed blocks, in document order, when `capacity` holds them all (then /// acknowledged); otherwise only their count. pub fn markdownReadChanges(self: *Context, handle: Handle, capacity: u32) !struct { count: u32, changes: []const markdown.Doc.Change } { try self.beginMutation(); defer self.mutating = false; const value = try self.getMarkdown(handle); const count = value.doc.changeCount(); if (capacity == 0 or capacity < count) return .{ .count = count, .changes = &.{} }; _ = self.markdown_scratch.reset(.{ .retain_with_limit = markdown.scratch_retained_byte_count_max }); const changes = try self.markdown_scratch.allocator().alloc(markdown.Doc.Change, count); _ = value.doc.readChanges(changes); return .{ .count = count, .changes = changes }; } /// Leaf `index`'s parser output (in the Markdown scratch, valid until the next Markdown /// call), and the doc that resolves its styles. pub fn markdownReadLeaf(self: *Context, handle: Handle, index: u32) !struct { leaf: markdown.Leaf, doc: *MarkdownDoc } { if (self.mutating) return error.ContextBusy; const value = try self.getMarkdown(handle); if (index >= value.doc.blocks.items.len) return error.InvalidIndex; switch (value.doc.blocks.items[index].kind) { .paragraph, .heading, .code, .html, .table_cell => {}, else => return error.InvalidIndex, } self.resetMarkdownScratch(); const leaf = value.doc.readLeaf(self.markdown_scratch.allocator(), index) catch |err| return markdownError(err); return .{ .leaf = leaf, .doc = value }; } /// Inline leaf `index`'s source (in the Markdown scratch, valid until the next Markdown call). pub fn markdownReadSource(self: *Context, handle: Handle, index: u32) ![]const u8 { if (self.mutating) return error.ContextBusy; const value = try self.getMarkdown(handle); if (index >= value.doc.blocks.items.len or !markdown.Doc.isInlineLeaf(value.doc.blocks.items[index])) return error.InvalidIndex; self.resetMarkdownScratch(); return value.doc.leafSubject(self.markdown_scratch.allocator(), index) catch |err| return markdownError(err); } pub fn markdownBind(self: *Context, handle: Handle, index: u32, node_handle: Handle) !void { try self.beginMutation(); defer self.mutating = false; defer self.resetMarkdownScratch(); const value = try self.getMarkdown(handle); if (index >= value.doc.blocks.items.len or !markdown.Doc.isBound(value.doc.blocks.items[index])) return error.InvalidIndex; const node = try self.sceneMutableNode(node_handle); const text = node.scene_node.?.text orelse return error.WrongKind; const style = if (value.syntax_style) |id| try self.getSyntaxStyle(id) else null; try value.bindings.ensureUnusedCapacity(self.allocator, 1); const at = value.bindingIndex(index); const rebind = at < value.bindings.items.len and value.bindings.items[at].block == index; const previous = if (rebind) value.bindings.items[at] else undefined; if (rebind and previous.stale) value.stale_count -= 1; // The node's text as it is now is what the bind hands over. const binding: MarkdownDoc.Binding = .{ .block = index, .node = node_handle, .epoch = text.buffer.getContentEpoch() }; if (rebind) { value.bindings.items[at] = binding; } else { value.bindings.insertAssumeCapacity(at, binding); } // A rejected bind leaves the bindings as they were. errdefer { if (value.bindings.items[at].stale) value.stale_count -= 1; if (rebind) { value.bindings.items[at] = previous; if (previous.stale) value.stale_count += 1; } else _ = value.bindings.orderedRemove(at); } // The node shows the leaf now, if the doc writes it; then the doc's style (a rejected // bind leaves both as they were). var whole = value.doc.wholeWrite(index) catch |err| return markdownError(err); whole.resync = true; value.write(whole) catch |err| return markdownError(err); text.buffer.style_binding.dependent = .{ .scene_text = node }; text.buffer.setSyntaxStyle(style); node.scene_node.?.paint_epoch = nextPaintEpoch(); } pub fn editSetSyntaxStyle(self: *Context, handle: Handle, style_handle: ?Handle) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); const style = if (style_handle) |id| try self.getSyntaxStyle(id) else null; edit.buffer.tb.style_binding.dependent = .{ .edit = edit }; edit.buffer.tb.setSyntaxStyle(style); edit.invalidate(); } pub fn editSetText(self: *Context, handle: Handle, bytes: []const u8, preserve_history: bool) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try validateTextBytes(edit.buffer.tb.tabWidth(), bytes, 0); if (preserve_history) { try edit.buffer.replaceText(bytes); } else { edit.input_mem_id = try edit.buffer.setTextOwned(bytes, edit.input_mem_id); } } pub fn editInsertText(self: *Context, handle: Handle, bytes: []const u8) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try validateTextBytes(edit.buffer.tb.tabWidth(), bytes, edit.buffer.tb.getByteSize()); try edit.buffer.insertText(bytes); } pub fn editDeleteRange(self: *Context, handle: Handle, start: edit_buffer.Cursor, end: edit_buffer.Cursor) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try edit.buffer.deleteRange(start, end); } pub fn editSetCursor(self: *Context, handle: Handle, row: u32, col: u32) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try edit.buffer.setCursor(row, col); } pub fn editHistory(self: *Context, handle: Handle, redo: bool) ![]const u8 { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); if (!if (redo) edit.buffer.canRedo() else edit.buffer.canUndo()) return &.{}; return if (redo) edit.buffer.redo() else edit.buffer.undo(); } pub fn editCommand(self: *Context, handle: Handle, command: EditCommand) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); switch (command) { .delete_forward => |atomic| if (atomic) try edit.buffer.deleteAtomic(true) else try edit.buffer.deleteForward(), .backspace => |atomic| if (atomic) try edit.buffer.deleteAtomic(false) else try edit.buffer.backspace(), .new_line => { try validateTextBytes(edit.buffer.tb.tabWidth(), "\n", edit.buffer.tb.getByteSize()); try edit.buffer.insertText("\n"); }, .delete_line => try edit.buffer.deleteLine(), .move_left => |atomic| if (atomic) try edit.buffer.moveAtomic(false) else edit.buffer.moveLeft(), .move_right => |atomic| if (atomic) try edit.buffer.moveAtomic(true) else edit.buffer.moveRight(), .move_up => edit.buffer.moveUp(), .move_down => edit.buffer.moveDown(), .goto_line => |line| try edit.buffer.gotoLine(line), .cursor_offset => |offset| try edit.buffer.setCursorByOffset(offset), .clear => try edit.buffer.clear(), .clear_history => edit.buffer.clearHistory(), .debug_rope => edit.buffer.debugLogRope(), .cursor_offset_atomic => |offset| try edit.buffer.setCursorByOffsetAtomic(offset), .keep_outside => |toward| try edit.buffer.keepOutside(toward), } } pub fn editSetDefaults(self: *Context, handle: Handle, options: TextDefaults) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try setBufferDefaults(edit.buffer.tb, options); edit.invalidate(); } pub fn editHighlight(self: *Context, handle: Handle, operation: TextHighlight) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try highlightBuffer(edit.buffer.tb, operation); edit.invalidatePreparation(); } pub fn editSetLayer(self: *Context, handle: Handle, layer: LayerReplacement) !void { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); try edit.buffer.tb.setLayer(layer.layer_id, layer.start_byte, layer.end_byte, layer.runs); edit.invalidatePreparation(); } /// Returns the added id, the removed id or 0, or 0 for clear. pub fn editMark(self: *Context, handle: Handle, operation: EditMark) !u32 { try self.beginMutation(); defer self.mutating = false; const edit = try self.getEditBuffer(handle); try edit.checkMutable(); const result = switch (operation) { .add => |options| try edit.buffer.addMark(options), .remove => |id| if (try edit.buffer.removeMark(id)) id else 0, .clear => clear: { edit.buffer.clearMarks(); break :clear 0; }, }; edit.invalidatePreparation(); return result; } pub fn editorSetViewport(self: *Context, handle: Handle, viewport: text_buffer_view.Viewport, size_only: bool, move_cursor: bool) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); try view.edit.checkMutable(); try validateViewport(viewport); try view.prepareView(); if (size_only) view.view.setViewportSize(viewport.width, viewport.height) else view.view.setViewport(viewport, move_cursor); view.invalidatePreparation(); } pub fn editorSetScrollMargin(self: *Context, handle: Handle, margin: f32) !void { try self.beginMutation(); defer self.mutating = false; if (!std.math.isFinite(margin)) return error.InvalidOptions; const view = try self.getEditorView(handle); try view.edit.checkMutable(); if (view.view.follow_pending) try view.prepareView(); view.view.setScrollMargin(margin); view.invalidatePreparation(); } pub fn editorCommand(self: *Context, handle: Handle, command: EditorCommand) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); // Cursor commands synchronously update every view of the edit buffer. try view.edit.checkMutable(); if (command == .tab_indicator) try validateTabIndicator(command.tab_indicator); // Cursor and text changes only make a scroll due; visual moves need the layout. switch (command) { .move_up, .move_down, .goto_line_end => try view.prepareView(), .wrap_mode => if (view.view.follow_pending) try view.prepareView(), .delete_selection, .cursor_offset, .tab_indicator => {}, } const from = view.edit.buffer.getPrimaryCursor().offset; switch (command) { .move_up => |atomic| { view.view.moveUpVisual(); if (atomic) try view.edit.buffer.leaveAtomic(from, false); }, .move_down => |atomic| { view.view.moveDownVisual(); if (atomic) try view.edit.buffer.leaveAtomic(from, true); }, .goto_line_end => view.view.gotoVisualLineEnd(), .delete_selection => try view.view.deleteSelectedText(), .cursor_offset => |offset| try view.view.setCursorByOffset(offset), .wrap_mode => |mode| view.view.setWrapMode(mode), .tab_indicator => |indicator| view.view.setTabIndicator(indicator), } switch (command) { .wrap_mode => view.invalidate(), else => view.invalidatePreparation(), } } pub fn editorSetTabColor(self: *Context, handle: Handle, color: ?buf.RGBA) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); try view.edit.checkMutable(); if (color) |rgba| try buf.validateColor(rgba); view.view.setTabIndicatorColor(color); view.invalidatePreparation(); } pub fn editorSelect(self: *Context, handle: Handle, options: TextSelection) !bool { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); try view.edit.checkMutable(); return selectView(view, options); } pub fn editorPrepareView(self: *Context, handle: Handle, follow_cursor: bool) !*Editor { try self.checkSceneRead(); const view = try self.getEditorView(handle); if (follow_cursor) _ = view.view.updateCursorBeforeRender(); try view.prepareView(); return view; } pub fn editorReplaceSelection(self: *Context, handle: Handle, bytes: []const u8) !u32 { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); try view.edit.checkMutable(); try validateTextBytes(view.edit.buffer.tb.tabWidth(), bytes, view.edit.buffer.tb.getByteSize()); const steps = try view.view.replaceSelectedText(bytes); view.invalidate(); return steps; } pub fn editorSetPlaceholder(self: *Context, handle: Handle, bytes: []const u8, chunks: []const StyledTextChunk) !void { try self.beginMutation(); defer self.mutating = false; const view = try self.getEditorView(handle); try view.edit.checkMutable(); try validateTextBytes(view.edit.buffer.tb.tabWidth(), bytes, 0); var offset: usize = 0; for (chunks) |chunk| { if (chunk.byte_count == 0 or chunk.byte_count > bytes.len - offset or chunk.attributes & ~ansi.TextAttributes.ATTRIBUTE_BASE_MASK != 0 or chunk.link_url != null) return error.InvalidOptions; if (chunk.foreground) |color| try buf.validateColor(color); if (chunk.background) |color| try buf.validateColor(color); if (!std.unicode.utf8ValidateSlice(bytes[offset..][0..chunk.byte_count])) return error.InvalidUnicode; offset += chunk.byte_count; } if (offset != bytes.len) return error.InvalidOptions; if (chunks.len == 0) { view.view.clearPlaceholder(); view.invalidate(); return; } const ranges = try self.allocator.alloc(text_buffer.OwnedStyledChunk, chunks.len); defer self.allocator.free(ranges); for (chunks, ranges) |chunk, *range| { range.* = .{ .byte_count = chunk.byte_count, .style = .{ .fg = chunk.foreground, .bg = chunk.background, .attributes = chunk.attributes } }; } const copy = try self.allocator.dupe(u8, bytes); errdefer self.allocator.free(copy); try view.view.setPlaceholderOwnedStyledText(copy, ranges, null); view.invalidate(); } fn setBufferDefaults(buffer: *text_buffer.UnifiedTextBuffer, options: TextDefaults) !void { if (@as(u3, @bitCast(options.fields)) == 0) return error.InvalidOptions; if (options.foreground) |color| try buf.validateColor(color); if (options.background) |color| try buf.validateColor(color); if (options.attributes) |attributes| if (attributes & ~ansi.TextAttributes.ATTRIBUTE_BASE_MASK != 0) return error.InvalidOptions; if (options.fields.foreground) buffer.setDefaultFg(options.foreground); if (options.fields.background) buffer.setDefaultBg(options.background); if (options.fields.attributes) buffer.setDefaultAttributes(options.attributes); } fn highlightBuffer(buffer: *text_buffer.UnifiedTextBuffer, operation: TextHighlight) !void { switch (operation) { .add_line => |line| { const h = line.range; try buffer.addHighlight(line.line, h.start, h.end, h.style_id, h.priority, h.ref); }, .add_range => |h| try buffer.addHighlightByCharRange(h.start, h.end, h.style_id, h.priority, h.ref), .remove_ref => |ref| try buffer.removeHighlightsByRefChecked(ref), .clear_line => |line| buffer.clearLineHighlights(line), .clear_all => buffer.clearAllHighlights(), } } fn validateViewport(viewport: text_buffer_view.Viewport) !void { if (@as(u64, viewport.x) + viewport.width > std.math.maxInt(i32) or @as(u64, viewport.y) + viewport.height > std.math.maxInt(i32)) return error.InvalidOptions; } fn validateTabIndicator(indicator: ?u32) !void { if (indicator) |value| { if (utf8.isControl(value) or !utf8.isScalar(value)) return error.InvalidOptions; } } fn selectView(value: anytype, options: TextSelection) !bool { const is_editor = @TypeOf(value) == *Editor; const view = if (is_editor) value.view.text_buffer_view else value.view; const buffer = if (is_editor) value.edit.buffer.tb else value.text.buffer; const local = options.operation == .local or options.operation == .local_update; if (options.foreground) |color| try buf.validateColor(color); if (options.background) |color| try buf.validateColor(color); if (local) { if (is_editor and value.view.follow_pending) try value.prepareView(); if (view.getViewport()) |viewport| { const x = if (view.wrap_mode == .none) std.math.cast(i32, viewport.x) orelse return error.InvalidOptions else 0; const y = std.math.cast(i32, viewport.y) orelse return error.InvalidOptions; _ = std.math.add(i32, options.anchor_x, x) catch return error.InvalidOptions; _ = std.math.add(i32, options.focus_x, x) catch return error.InvalidOptions; _ = std.math.add(i32, options.anchor_y, y) catch return error.InvalidOptions; _ = std.math.add(i32, options.focus_y, y) catch return error.InvalidOptions; } if (buffer.lineWidthColsMax() > std.math.maxInt(i32)) return error.InvalidOptions; } if (options.operation != .reset and options.operation != .local_reset) { try value.prepareView(); } const fg = options.foreground; const bg = options.background; if (is_editor and local) value.view.setSelectionFollowCursor(options.follow_cursor); var changed = false; switch (options.operation) { .set => value.view.setSelection(options.start, options.end, bg, fg), .update => value.view.updateSelection(options.end, bg, fg), .reset => value.view.resetSelection(), .local => changed = if (is_editor) value.view.setLocalSelectionBehavior(options.anchor_x, options.anchor_y, options.focus_x, options.focus_y, bg, fg, options.update_cursor, options.behavior) else value.view.setLocalSelectionBehavior(options.anchor_x, options.anchor_y, options.focus_x, options.focus_y, bg, fg, options.behavior), .local_update => changed = if (is_editor) value.view.updateLocalSelectionBehavior(options.anchor_x, options.anchor_y, options.focus_x, options.focus_y, bg, fg, options.update_cursor, options.behavior) else value.view.updateLocalSelectionBehavior(options.anchor_x, options.anchor_y, options.focus_x, options.focus_y, bg, fg, options.behavior), .local_reset => value.view.resetLocalSelection(), .cell => changed = value.view.convertSelectionToCell(), .occupancy => value.view.setSelectionOccupancy(options.occupancy), .inclusive => if (is_editor) value.view.setSelectionInclusive(options.start, options.end, bg, fg) else view.setSelectionInclusiveStyle(options.start, options.end, .{ .bgColor = bg, .fgColor = fg }), .colors => view.setSelectionColors(bg, fg), } value.invalidatePreparation(); return changed; } /// During checked edits, the observer runs without admitting Context mutation. /// Hosts retaining legacy event order enqueue each notification before returning. pub fn setEditEventCallback(self: *Context, callback: ?EditEventCallback, userdata: ?*anyopaque) Error!void { try self.beginMutation(); defer self.mutating = false; self.edit_event_callback = callback; self.edit_event_userdata = userdata; } /// Returns whether the bytes changed. fn replaceTextContent(self: *Context, text: anytype, bytes: []const u8) !bool { const changed = !holdsBytes(text, bytes); const copy = try self.allocator.dupe(u8, bytes); errdefer self.allocator.free(copy); // Owned scene/shared text excludes registrations borrowed from the rope arena. text.input_mem_id = try text.buffer.replaceOwnedText(copy, text.input_mem_id); return changed; } /// Replacements put the whole text in the `input_mem_id` slot. The rope holds exactly those /// bytes when it has no other slot and the byte counts agree. An append adds a slot. A clear /// leaves a stale slot and a flatten drops the slot's line breaks; both make the counts /// differ whenever the slot is not the text. The rope counts a CRLF break as one byte. fn holdsBytes(text: anytype, bytes: []const u8) bool { const registry = &text.buffer.mem_registry; const current = registry.get(@as(?u8, text.input_mem_id) orelse return false).?; return registry.buffers.items.len == 1 and text.buffer.getByteSize() == bytes.len - std.mem.count(u8, bytes, "\r\n") and std.mem.eql(u8, current, bytes); } fn textResourceChanged(text: *Text) void { var next = text.view.measure_dependents; while (next) |dependent| { // A dependent without a Yoga measure function does not solve, so mark its refresh stale. yoga.yogaNodeMarkDirty(dependent.yoga_node); scene.Scene.markObservationStale(dependent); next = dependent.measure_next; } } /// Brings what a session's scene shows to the session's new width method: its scene text and /// the bound buffers created to follow their session. Other buffers keep their own method. pub fn followWidthMethod(owned: *scene.Scene, method: utf8.WidthMethod) void { var next = owned.head; while (next) |node| : (next = node.scene_node.?.next) followNodeWidth(node, method); owned.clearPreparation(); } fn followNodeWidth(node: *native_renderable.NativeRenderable, method: utf8.WidthMethod) void { const value = node.scene_node.?; // Selections are cell offsets: each view moves its own back onto its text. if (value.text) |text| { const old = text.buffer.widthMethod(); if (old == method) return; value.paint_epoch = nextPaintEpoch(); text.buffer.setWidthMethod(method); text.view.followWidthMethod(text.buffer, old); textResourceChanged(text); } else if (value.kind == api.OT_SCENE_TEXT_VIEW) { const text = (value.control.text_view.view orelse return).text; if (text.follow_width) text.setWidthMethod(method) catch {}; } else if (value.kind == api.OT_SCENE_EDITOR) { const edit = (value.editor orelse return).edit; if (!edit.follow_width or edit.buffer.tb.widthMethod() == method) return; edit.checkMutable() catch return; // The cursor event invalidates the editors' measures (content epoch). const old = edit.buffer.remeasure(method); var next = edit.views; while (next) |view| : (next = view.next) view.view.followWidthMethod(old.width_method); edit.buffer.remapCursor(old); } } /// A following buffer measures with one session's method, so only one session's scene may show its views, /// the view being bound included. fn checkFollowOwner(comptime View: type, first: ?*View, owner: *const scene.Scene) error{WrongSession}!void { var next = first; while (next) |view| : (next = view.next) { const bound = view.node orelse continue; if (bound.scene_node.?.owner != owner) return error.WrongSession; } } /// A buffer made to follow its session takes the session's method when a scene node shows it. fn followSessionWidth(self: *Context, node: *native_renderable.NativeRenderable) void { const attached = (self.getSession(node.scene_node.?.owner.session) catch return).renderer orelse return; followNodeWidth(node, attached.getNextBuffer().width_method); } /// Equal bytes still rebuild the rope, so the view prepares again; the size does not change. fn textResent(node: *native_renderable.NativeRenderable) void { scene.Scene.markObservationStale(node); } fn destroyTextResource(self: *Context, text: *Text) void { text.view.retireStorage(); text.buffer.retireStorage(); if (!self.closing and self.text_pool_count < @min(self.objects.slots.len, text_pool_count_max)) { const bytes = @sizeOf(Text) + text.buffer.retainedStorageBytes() + text.view.retainedStorageBytes(); if (bytes <= text_storage_bytes_max and bytes <= text_pool_bytes_max - self.text_pool_bytes) { text.pool_next = self.text_pool; self.text_pool = text; self.text_pool_count += 1; self.text_pool_bytes += bytes; return; } } self.freeTextStorage(text); } fn freeTextStorage(self: *Context, text: *Text) void { text.view.deinit(); text.buffer.deinit(); self.allocator.destroy(text); } /// Destroys one object, not a subtree. An attached renderable detaches from /// its Yoga parent and invalidates that parent's layout. pub fn destroy(self: *Context, handle: Handle) Error!void { try self.beginMutation(); defer self.mutating = false; switch (try self.objects.getKind(handle)) { .session => try checkSessionTeardown(try self.getSession(handle)), .native_renderable => { const node = try self.getRenderable(handle); if (node.scene_node != null) try yoga.check(yoga.nodeTeardownStatus(node.yoga_node)); }, .edit_buffer => try (try self.getEditBuffer(handle)).checkMutable(), .clipboard_service => { const service = try self.objects.get(handle, .clipboard_service, clipboard.Service); service.beginShutdown(); if (service.pollShutdown() != .ready) return error.ContextBusy; }, .clipboard_operation => { const operation = try self.objects.get(handle, .clipboard_operation, clipboard.Operation); if (!operation.isReadyToDestroy()) return error.ContextBusy; }, .editor_view => try (try self.getEditorView(handle)).checkMutable(), .text_buffer => try (try self.getTextBuffer(handle)).checkMutable(), .text_buffer_view => try (try self.getTextBufferView(handle)).checkMutable(), else => {}, } const token = try self.objects.beginDestroy(handle); self.destroyToken(token); } pub fn beginMutation(self: *Context) Error!void { if (self.closing) return error.ContextClosed; if (self.mutating) return error.ContextBusy; self.mutating = true; } fn destroyToken(self: *Context, token: handles.DestroyToken) void { defer self.objects.finishDestroy(token); switch (token.kind) { .audio_engine => audio.destroy(@ptrCast(@alignCast(token.ptr))), .clipboard_service => { const service: *clipboard.Service = @ptrCast(@alignCast(token.ptr)); service.deinit(); }, .clipboard_operation => { const operation: *clipboard.Operation = @ptrCast(@alignCast(token.ptr)); operation.destroyStorage(); }, .image_pixels_lease => { const value: *image.Image = @ptrCast(@alignCast(token.ptr)); self.lease_count -= 1; self.lease_bytes -= @sizeOf(image.Image) + value.pixels.len; value.deinit(); }, .encoded_unicode => { const value: *EncodedUnicode = @ptrCast(@alignCast(token.ptr)); value.deinit(self.allocator, &self.graphemes); }, .embedded_terminal => { const value: *embedded_terminal.EmbeddedTerminal = @ptrCast(@alignCast(token.ptr)); value.deinit(); }, .image => { const value: *image.Image = @ptrCast(@alignCast(token.ptr)); value.deinit(); }, .text_buffer => { const value: *SharedText = @ptrCast(@alignCast(token.ptr)); while (value.views) |view| self.destroyToken(self.objects.beginDestroy(view.handle) catch unreachable); // Detach the buffer from its style before the style goes away. value.buffer.setSyntaxStyle(null); self.releaseSharedTextStorage(value); }, .text_buffer_view => { const value: *TextView = @ptrCast(@alignCast(token.ptr)); if (value.node) |node| { node.setMeasureTargetPreservingProvider(.none, node.scene_node.?.measure_overridden) catch unreachable; node.scene_node.?.control.text_view.view = null; node.scene_node.?.owner.invalidateObservation(node); } if (value.previous) |previous| previous.next = value.next else value.text.views = value.next; if (value.next) |next| next.previous = value.previous; value.view.deinit(); self.allocator.destroy(value); }, .edit_buffer => { const value: *Edit = @ptrCast(@alignCast(token.ptr)); while (value.views) |view| self.destroyToken(self.objects.beginDestroy(view.handle) catch unreachable); value.buffer.deinit(); self.allocator.destroy(value); }, .editor_view => { const value: *Editor = @ptrCast(@alignCast(token.ptr)); if (value.node) |node| { node.setMeasureTargetPreservingProvider(.none, node.scene_node.?.measure_overridden) catch unreachable; node.scene_node.?.editor = null; node.scene_node.?.owner.invalidateObservation(node); } if (value.previous) |previous| previous.next = value.next else value.edit.views = value.next; if (value.next) |next| next.previous = value.previous; value.view.deinit(); self.allocator.destroy(value); }, .syntax_style => { const value: *syntax_style.SyntaxStyle = @ptrCast(@alignCast(token.ptr)); value.deinit(); }, .markdown_doc => { const value: *MarkdownDoc = @ptrCast(@alignCast(token.ptr)); value.deinit(); }, .session => { const value: *session.Session = @ptrCast(@alignCast(token.ptr)); if (value.scene) |owned| { owned.detachAll(); while (owned.head) |node| self.destroyToken(self.objects.beginDestroy(node.scene_node.?.handle) catch unreachable); } value.deinit() catch unreachable; self.allocator.destroy(value); }, .buffer_lease => { const storage: *buf.BufferStorage = @ptrCast(@alignCast(token.ptr)); var lease: buf.BufferLease = .{ .storage = storage }; lease.releaseChecked(&self.lease_count, &self.lease_bytes, &self.lease_bytes_max); }, .frame_buffer_lease => { const access: *FrameBufferLease = @ptrCast(@alignCast(token.ptr)); const value = self.objects.get(access.frame.session, .session, session.Session) catch unreachable; std.debug.assert(value.frame_lease_count > 0); access.lease.releaseChecked(&self.lease_count, &self.lease_bytes, &self.lease_bytes_max); value.frame_lease_count -= 1; self.allocator.destroy(access); }, .buffer => { const value: *buf.OptimizedBuffer = @ptrCast(@alignCast(token.ptr)); value.deinit(); }, .native_renderable => { const value: *native_renderable.NativeRenderable = @ptrCast(@alignCast(token.ptr)); const state = value.scene_node.?; const text = state.text; if (state.editor) |editor| editor.node = null; if (state.kind == api.OT_SCENE_TEXT_VIEW) { if (state.control.text_view.view) |view| view.node = null; } const storage = state.owner.remove(value); if (value.surface) |surface| surface.deinit(); value.surface = null; value.detachMeasure(); if (self.scene_measures.fetchRemove(token.handle.slot)) |entry| self.allocator.destroy(entry.value); if (text) |resource| self.destroyTextResource(resource); self.releaseNodeStorage(storage); }, } } };