RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
editor: open, scroll and edit very large files
oxydizer34e6fdf1cafc
diff --git a/AGENTS.md b/AGENTS.mdindex 2e1175e..cdafe40 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -402,6 +402,37 @@ calling a failure a regression.stays listed dimmed, a file pin opens like a double click (a chooser browsesits folder).+## Text editor++* **Never give Pango more than a few lines.** One layout of 1 MiB took 46 s+ (cost grows faster than the line count); `view.zig` lays out one *segment*+ (`lines.zig`: a logical line, or a piece of one folded at `fold` = 16 KiB,+ cut after a nearby space) at a time in a content-keyed cache (`Layouts`), so+ edits need no invalidation. Pieces are a function of the line start alone, so+ walking up or down finds the same ones; keep `lines.zig`'s property test+ green when touching it.+* **Scroll is `Document.top` (a byte offset) plus `Tab.dy` pixels into that+ line**, never a pixel count from the file start (needs every line's height).+ `Document.replace` shifts `top` and the line waypoints (`retarget`) so edits+ above the view do not move it. `Port.clamp` after any change; `locate`+ returns null for a position more than three viewports away, so jump+ (`jumpTo`) instead of walking.+* **Scrollbar units:** pixels (exact) up to `exact_limit`, bytes above it,+ because a drag in progress must not see its units shift as the height+ estimate improves. Line numbers come from sparse waypoints (`linesBefore`).+* **Large saves are written in place** (`Operation.startSave` `borrow`, above+ `copy_limit`) and `Document.locked` refuses edits meanwhile; smaller ones are+ copied. Anything that frees or reallocates the text during a save is a+ use-after-free. Loads read straight into one buffer sized from `fstat`, sniff+ the first 64 KiB for binary data and refuse files that will not fit in+ `MemAvailable` (`ensureMemory`).+* **Benchmark in ReleaseSafe.** Debug makes the vector scans ~50x slower and+ fakes a regression. Editing near the start of a huge file memmoves the tail+ (about 100 ms per keystroke at 2 GB); a gap buffer would fix it but every+ `text.items` reader (segmenter, find, IME, clipboard) would need to learn it.+* A selected line break is not in the segment layout, so `paintLine` draws the+ highlight out to the margin itself (wrapped mode only, as Pango did).+## Shared UI* Widget callbacks carry `owner` and `id`; pass a stable host or sectiondiff --git a/docs/wiki/Apps-and-Services.md b/docs/wiki/Apps-and-Services.mdindex 42a104c..8aac251 100644--- a/docs/wiki/Apps-and-Services.md+++ b/docs/wiki/Apps-and-Services.md@@ -27,8 +27,12 @@ The file manager. Space opens images, PDFs and text files.## Text editor (`rediwm-editor [FILE ...]`)-Tabs, one window per display. UTF-8 up to 16 MiB, keeps BOM and line endings,-asks before discarding changes.+Tabs, one window per display. UTF-8 files up to 4 GiB (they must fit in free+memory), keeps BOM and line endings, asks before discarding changes. Only the+lines on screen are ever laid out, so opening, scrolling and Find stay fast on+huge files, and a single line of many megabytes is folded onto several rows.+Editing near the start of a very large file moves the rest of the text, which+costs a few milliseconds per 100 MB per keystroke.| Keys | Action || --- | --- |diff --git a/src/editor/app.zig b/src/editor/app.zigindex e0df2d5..e1393e6 100644--- a/src/editor/app.zig+++ b/src/editor/app.zig@@ -9,11 +9,21 @@ const dialog = @import("ui").widgets.dialog;const menu = @import("ui").context_menu;const p = @import("pango.zig");const Document = @import("document.zig").Document;+const view = @import("view.zig");+const lines = @import("lines.zig");const op = @import("operation.zig");const a = std.heap.c_allocator;const top: f64 = 40;const status_h: f64 = 26;const tab_w: f64 = 176;+const Status = struct {+ revision: usize = std.math.maxInt(usize),+ cursor: usize = 0,+ line: usize = 0,+ column: usize = 0,+};+/// Stand-in for the position of a cursor too far from the view to measure.+const far: c_int = 1_000_000 * 1024;const Action = enum { new, open, save, save_as, find, wrap };const labels = [_][]const u8{ "New", "Open", "Save", "Save As", "Find", "Word Wrap" };const Tab = struct {@@ -21,18 +31,15 @@ const Tab = struct {doc: Document = .{},path: ?[:0]u8 = null,stamp: ?op.Stamp = null,- scroll: f64 = 0,+ /// Pixels of the first visible line (`doc.top`) scrolled out of view.+ dy: f64 = 0,scroll_x: f64 = 0,- layout: ?*p.Layout = null,- layout_revision: usize = std.math.maxInt(usize),- layout_width: i32 = 0,- layout_scale: i32 = 0,- height: i32 = 0,- width: i32 = 0,+ measure: view.Measure = .{},+ /// The status bar's line and column, recomputed only when the cursor or text moves.+ status: Status = .{},fn deinit(t: *Tab) void {t.doc.deinit();if (t.path) |path| a.free(path);- if (t.layout) |layout| p.g_object_unref(layout);a.destroy(t);}fn name(t: *Tab) []const u8 {@@ -86,6 +93,8 @@ pub const App = struct {clipboard_revision: usize = 0,paste_requested: bool = false,preedit: std.ArrayList(u8) = .empty,+ layouts: view.Layouts = .{},+ rows: std.ArrayList(view.Row) = .empty,pub fn init(io: std.Io) !App {var self: App = .{ .io = io };@@ -101,6 +110,8 @@ pub const App = struct {self.query.deinit(a);self.clipboard.deinit(a);self.preedit.deinit(a);+ self.rows.deinit(a);+ self.layouts.deinit();}fn current(self: *App) *Tab {return self.tabs.items[self.selected];@@ -193,7 +204,9 @@ pub const App = struct {error.FileChanged => "File changed on disk. Use Save As to keep your edits in another file.",error.BinaryFile => "This file contains binary data and cannot be edited as text.",error.UnsupportedEncoding => "This file is not valid UTF-8 text.",- error.FileTooLarge => "Text files are limited to 16 MiB.",+ error.FileTooLarge => "Text files are limited to 4 GiB.",+ error.OutOfMemory => "Not enough free memory to hold this file.",+ error.Busy => "Saving a large file. Editing resumes when it is written.",error.PermissionDenied => "Permission denied. Try Save As in a writable folder.",error.HardLinkedFile => "This file has multiple hard links. Use Save As to create a separate copy.",else => @errorName(err),@@ -219,6 +232,9 @@ pub const App = struct {self.operation = null;defer job.deinit();self.dirty = true;+ if (job.kind == .save) if (self.findTab(job.tab_id)) |i| {+ self.tabs.items[i].doc.locked = false;+ };if (job.err) |err| {self.close_all = false;self.failure(err);@@ -243,7 +259,9 @@ pub const App = struct {job.document = null;t.path = path;t.stamp = job.stamp;- t.layout_revision = std.math.maxInt(usize);+ t.dy = 0;+ t.scroll_x = 0;+ t.measure = .{};self.notice_len = 0;self.changed();},@@ -287,15 +305,16 @@ pub const App = struct {};}fn startSave(self: *App, t: *Tab, path: []const u8, stamp: ?op.Stamp) void {- var bytes: std.ArrayList(u8) = .empty;- defer bytes.deinit(a);- if (t.doc.bom) bytes.appendSlice(a, "\xef\xbb\xbf") catch return;- bytes.appendSlice(a, t.doc.text.items) catch return;- self.operation = op.Operation.start(.save, self.io, t.id, path, bytes.items, stamp) catch |err| {+ // A small document is copied so typing can continue while it is+ // written. A large one is written where it is, which needs the text to+ // stay put until the save finishes (see `Document.locked`).+ const borrow = t.doc.text.items.len > op.copy_limit;+ self.operation = op.Operation.startSave(self.io, t.id, path, t.doc.bom, t.doc.text.items, borrow, stamp) catch |err| {self.failure(err);return;};self.operation.?.revision = t.doc.revision;+ t.doc.locked = borrow;self.message("Saving…");}fn save(self: *App, as: bool) void {@@ -343,6 +362,7 @@ pub const App = struct {.wrap => {self.wrap = !self.wrap;self.current().scroll_x = 0;+ self.port().clamp();},}self.dirty = true;@@ -370,10 +390,23 @@ pub const App = struct {/// while the document fits.fn scrollbarGeometry(self: *App) ?scrollbar.Geometry {if (self.tabs.items.len == 0) return null;- const tab = self.current();const strip = scrollbar.gutter(theme.global.scrollbar_width);const track: scrollbar.Rect = .{ .x = @as(f32, @floatFromInt(self.w)) - strip, .y = @floatCast(self.viewTop()), .w = strip, .h = @floatCast(self.viewHeight()) };- return scrollbar.Geometry.compute(.vertical, track, track.h, @floatFromInt(tab.height), @floatCast(tab.scroll));+ const e = self.port().extent(&self.current().measure);+ return scrollbar.Geometry.compute(.vertical, track, @floatCast(e.viewport), @floatCast(e.content), @floatCast(e.offset));+ }+ /// The current tab's scroll offset in the scrollbar's units.+ fn scrollOffset(self: *App) f32 {+ return @floatCast(self.port().extent(&self.current().measure).offset);+ }+ fn seekScroll(self: *App, offset: f32) void {+ self.port().seek(&self.current().measure, offset);+ }+ /// The current tab as something to scroll, lay out and hit-test.+ fn port(self: *App) view.Port {+ const t = self.current();+ self.layouts.configure(theme.global.mono_font, ui.textSize(), if (self.wrap) self.w - 40 else null, self.scale);+ return .{ .doc = &t.doc, .layouts = &self.layouts, .height = self.viewHeight(), .dy = &t.dy };}/// Advances the scrollbar's hover and scroll feedback.@@ -381,13 +414,14 @@ pub const App = struct {if (self.tabs.items.len == 0) return;const tab = self.current();const bar = self.scrollbarGeometry();+ const position = @as(f64, @floatFromInt(tab.doc.top)) * 1024 + tab.dy;if (self.bar_tab != tab) {self.bar_tab = tab;- self.bar_observed = tab.scroll;+ self.bar_observed = position;}const hovered = !self.menu_open and self.close_tab == null and if (bar) |b| b.overThumb(@floatCast(self.px), @floatCast(self.py)) else false;- if (self.bar_appearance.step(now, tab.scroll != self.bar_observed, hovered, self.scroll_drag.active, bar != null)) self.dirty = true;- self.bar_observed = tab.scroll;+ if (self.bar_appearance.step(now, position != self.bar_observed, hovered, self.scroll_drag.active, bar != null)) self.dirty = true;+ self.bar_observed = position;}/// How long the event loop may sleep before the scrollbar needs a frame.@@ -397,10 +431,6 @@ pub const App = struct {return null;}- fn clampScroll(self: *App) void {- const t = self.current();- t.scroll = std.math.clamp(t.scroll, 0, @max(0, @as(f64, @floatFromInt(t.height)) - self.viewHeight()));- }pub fn handleScroll(self: *App, amount: f64) void {if (self.close_tab != null or self.menu_open) return;if (self.py >= 0 and self.py < top) {@@ -408,75 +438,50 @@ pub const App = struct {} else if (self.shift and !self.wrap) {self.current().scroll_x = @max(0, self.current().scroll_x + amount * 3);} else {- self.current().scroll += amount * 3;- self.clampScroll();+ self.port().scrollBy(amount * 3);}self.dirty = true;}- fn layout(self: *App, cr: *c.cairo_t) void {- const t = self.current();- if (t.layout == null) t.layout = p.pango_cairo_create_layout(cr) orelse return;- const width: i32 = if (self.wrap) @max(1, self.w - 40) * 1024 else -1;- if (t.layout_revision != t.doc.revision or t.layout_width != width or t.layout_scale != self.scale) {- const family = a.dupeZ(u8, theme.global.mono_font) catch return;- defer a.free(family);- const font = p.pango_font_description_from_string(family) orelse return;- defer p.pango_font_description_free(font);- p.pango_font_description_set_absolute_size(font, ui.textSize() * 1024);- p.pango_layout_set_font_description(t.layout.?, font);- p.pango_layout_set_text(t.layout.?, t.doc.text.items.ptr, @intCast(t.doc.text.items.len));- p.pango_layout_set_width(t.layout.?, width);- p.pango_layout_set_wrap(t.layout.?, 2);- p.pango_cairo_update_layout(cr, t.layout.?);- p.pango_layout_get_pixel_size(t.layout.?, &t.width, &t.height);- t.layout_revision = t.doc.revision;- t.layout_width = width;- t.layout_scale = self.scale;- self.clampScroll();- }- }- fn ensureLayout(self: *App) void {- const surface = c.cairo_image_surface_create(c.CAIRO_FORMAT_ARGB32, 1, 1);- defer c.cairo_surface_destroy(surface);- const cr = c.cairo_create(surface);- defer c.cairo_destroy(cr);- c.cairo_scale(cr, @floatFromInt(self.scale), @floatFromInt(self.scale));- self.layout(cr.?);- }+ /// The cursor's rectangle in Pango units, with `y` measured from the top+ /// of the text view. A cursor too far away to measure without scrolling+ /// is reported well outside the view, above or below it.pub fn caretRect(self: *App) p.Rectangle {- self.ensureLayout();- var r: p.Rectangle = .{ .x = 0, .y = 0, .width = 0, .height = 18 * 1024 };- if (self.current().layout) |l| p.pango_layout_get_cursor_pos(l, @intCast(self.document().cursor), &r, null);+ const d = self.document();+ const row = self.port().locate(d.cursor) orelse return .{ .x = 0, .y = if (d.cursor < d.top) -far else far, .width = 0, .height = 18 * 1024 };+ var r: p.Rectangle = undefined;+ p.pango_layout_get_cursor_pos(row.line.layout, row.line.index(d.cursor), &r, null);+ r.y += @intFromFloat(row.y * 1024);+ return r;+ }+ /// Like `caretRect`, but first scrolls to a cursor that is far away.+ fn caretRectNear(self: *App) p.Rectangle {+ var r = self.caretRect();+ if (r.y <= -far / 2 or r.y >= far / 2) {+ self.port().jumpTo(self.document().cursor);+ r = self.caretRect();+ }return r;}pub fn inputRectangle(self: *App) p.Rectangle {const r = self.caretRect();- return .{ .x = @intFromFloat(@as(f64, @floatFromInt(r.x)) / 1024 + 16 - self.current().scroll_x), .y = @intFromFloat(@as(f64, @floatFromInt(r.y)) / 1024 + self.viewTop() - self.current().scroll), .width = 2, .height = @max(1, @divTrunc(r.height, 1024)) };+ return .{ .x = @intFromFloat(@as(f64, @floatFromInt(r.x)) / 1024 + 16 - self.current().scroll_x), .y = @intFromFloat(@as(f64, @floatFromInt(r.y)) / 1024 + self.viewTop()), .width = 2, .height = @max(1, @divTrunc(r.height, 1024)) };}fn reveal(self: *App) void {- const r = self.caretRect();+ const r = self.caretRectNear();const t = self.current();const y = @as(f64, @floatFromInt(r.y)) / 1024;const h = @as(f64, @floatFromInt(r.height)) / 1024;- t.scroll = @max(0, @min(t.scroll, y));- t.scroll = @max(t.scroll, y + h - self.viewHeight());- self.clampScroll();+ const pt = self.port();+ if (y < 0) pt.scrollBy(y) else if (y + h > pt.height) pt.scrollBy(y + h - pt.height);if (!self.wrap) {const x = @as(f64, @floatFromInt(r.x)) / 1024;t.scroll_x = @max(0, @max(x - @as(f64, @floatFromInt(self.w)) + 48, @min(t.scroll_x, x)));}self.changed();}+ /// The byte offset nearest a point given relative to the text origin.fn indexAt(self: *App, x: f64, y: f64) usize {- self.ensureLayout();- const t = self.current();- const l = t.layout orelse return 0;- var idx: c_int = 0;- var trailing: c_int = 0;- _ = p.pango_layout_xy_to_index(l, @intFromFloat(std.math.clamp(x * 1024, -1e9, 1e9)), @intFromFloat(std.math.clamp(y * 1024, -1e9, 1e9)), &idx, &trailing);- var offset: usize = @intCast(@max(0, idx));- while (trailing > 0 and offset < t.doc.text.items.len) : (trailing -= 1) offset += std.unicode.utf8ByteSequenceLength(t.doc.text.items[offset]) catch 1;- return @min(offset, t.doc.text.items.len);+ return self.port().indexAt(x, y);}pub fn handleMotion(self: *App, x: f64, y: f64) void {const changed_hover = ((self.py < top or y < top) and @divFloor(self.px, 76) != @divFloor(x, 76)) or (self.py < top) != (y < top);@@ -492,16 +497,12 @@ pub const App = struct {}if (self.dragging) {const t = self.current();- if (y < self.viewTop()) t.scroll -= 18 else if (y > self.viewTop() + self.viewHeight()) t.scroll += 18;- self.clampScroll();- t.doc.move(self.indexAt(x - 16 + t.scroll_x, y - self.viewTop() + t.scroll), true);+ if (y < self.viewTop()) self.port().scrollBy(-18) else if (y > self.viewTop() + self.viewHeight()) self.port().scrollBy(18);+ t.doc.move(self.indexAt(x - 16 + t.scroll_x, y - self.viewTop()), true);self.changed();}if (self.scroll_drag.active) {- if (self.scrollbarGeometry()) |bar| {- self.current().scroll = self.scroll_drag.offsetAt(bar, @floatCast(x), @floatCast(y));- self.clampScroll();- }+ if (self.scrollbarGeometry()) |bar| self.seekScroll(self.scroll_drag.offsetAt(bar, @floatCast(x), @floatCast(y)));self.dirty = true;}if (changed_hover) self.dirty = true;@@ -552,14 +553,11 @@ pub const App = struct {} else if (self.py < @as(f64, @floatFromInt(self.h)) - status_h) {if (self.px > @as(f64, @floatFromInt(self.w)) - scrollbar.gutter(theme.global.scrollbar_width)) {if (self.scrollbarGeometry()) |bar| {- const scroll: f32 = @floatCast(self.current().scroll);+ const scroll = self.scrollOffset();if (scrollbar.press(bar, @floatCast(self.px), @floatCast(self.py), scroll)) |action| {switch (action) {.grab => self.scroll_drag.begin(bar, @floatCast(self.px), @floatCast(self.py), scroll),- .page => |offset| {- self.current().scroll = offset;- self.clampScroll();- },+ .page => |offset| self.seekScroll(offset),}self.dirty = true;}@@ -568,7 +566,7 @@ pub const App = struct {}self.find_open = false;const t = self.current();- t.doc.move(self.indexAt(self.px - 16 + t.scroll_x, self.py - self.viewTop() + t.scroll), self.shift);+ t.doc.move(self.indexAt(self.px - 16 + t.scroll_x, self.py - self.viewTop()), self.shift);self.dragging = true;self.changed();}@@ -741,7 +739,7 @@ pub const App = struct {c.XKB_KEY_Home => d.move(if (self.ctrl) 0 else d.lineStart(d.cursor), self.shift),c.XKB_KEY_End => d.move(if (self.ctrl) d.text.items.len else d.lineEnd(d.cursor), self.shift),c.XKB_KEY_Up, c.XKB_KEY_Down, c.XKB_KEY_Page_Up, c.XKB_KEY_Page_Down => {- const r = self.caretRect();+ const r = self.caretRectNear();const down = sym == c.XKB_KEY_Down or sym == c.XKB_KEY_Page_Down;const distance = if (sym == c.XKB_KEY_Page_Up or sym == c.XKB_KEY_Page_Down) self.viewHeight() else @as(f64, @floatFromInt(r.height)) / 1024;d.move(self.indexAt(@as(f64, @floatFromInt(r.x)) / 1024, @as(f64, @floatFromInt(r.y)) / 1024 + @as(f64, @floatFromInt(r.height)) / 2048 + (if (down) distance else -distance)), self.shift);@@ -866,79 +864,105 @@ pub const App = struct {c.cairo_restore(cr);self.paintButton(cr, .{ .x = @floatFromInt(self.w - 90), .y = 43, .w = 78, .h = 30 }, "Next", false);}- self.layout(cr);+ self.layouts.beginFrame();+ const pt = self.port();+ pt.clamp();+ pt.visible(&self.rows);const tab = self.current();const sel = tab.doc.selection();c.cairo_save(cr);c.cairo_rectangle(cr, 12, self.viewTop(), @floatFromInt(self.w - 30), self.viewHeight());c.cairo_clip(cr);- c.cairo_translate(cr, 16 - tab.scroll_x, self.viewTop() - tab.scroll);- if (tab.layout) |layout_ptr| {- if (p.pango_layout_get_iter(layout_ptr)) |iter| {- defer p.pango_layout_iter_free(iter);- var line_index: c_int = 0;- while (true) : (line_index += 1) {- var rect: p.Rectangle = undefined;- p.pango_layout_iter_get_line_extents(iter, null, &rect);- const y = @as(f64, @floatFromInt(rect.y)) / 1024;- const h = @as(f64, @floatFromInt(rect.height)) / 1024;- if (y > tab.scroll + self.viewHeight()) break;- if (y + h >= tab.scroll) {- const line = p.pango_layout_iter_get_line_readonly(iter);- const line_start: usize = @intCast(p.pango_layout_line_get_start_index(line));- const line_end: usize = if (p.pango_layout_get_line_readonly(layout_ptr, line_index + 1)) |next|- @intCast(p.pango_layout_line_get_start_index(next))- else- tab.doc.text.items.len;- // Pango extends ranges to the right margin even for- // lines entirely before the selection. Only ask for- // intersecting lines, including a selected line break.- if (sel[0] != sel[1] and sel[0] < line_end and sel[1] > line_start) {- var ranges: ?[*]c_int = null;- var count: c_int = 0;- p.pango_layout_line_get_x_ranges(line, @intCast(sel[0]), @intCast(sel[1]), &ranges, &count);- if (ranges) |r| {- defer p.g_free(r);- var n: usize = 0;- while (n < @as(usize, @intCast(count))) : (n += 1) {- var accent = theme.shellPalette().accent;- accent[3] = 0.35;- fill(cr, @as(f64, @floatFromInt(r[n * 2])) / 1024, y, @as(f64, @floatFromInt(r[n * 2 + 1] - r[n * 2])) / 1024, h, accent);- }- }- }- ui.setSource(cr, t.window_fg);- c.cairo_move_to(cr, @as(f64, @floatFromInt(rect.x)) / 1024, @as(f64, @floatFromInt(p.pango_layout_iter_get_baseline(iter))) / 1024);- p.pango_cairo_show_layout_line(cr, line);- }- if (p.pango_layout_iter_next_line(iter) == 0) break;- }- }- if (self.focused and !self.find_open and self.close_tab == null) {- var r: p.Rectangle = undefined;- p.pango_layout_get_cursor_pos(layout_ptr, @intCast(tab.doc.cursor), &r, null);- if (self.caret_visible) fill(cr, @as(f64, @floatFromInt(r.x)) / 1024, @as(f64, @floatFromInt(r.y)) / 1024, 1.5, @as(f64, @floatFromInt(r.height)) / 1024, t.window_fg);- if (self.preedit.items.len > 0) {- const x = @as(f64, @floatFromInt(r.x)) / 1024;- const y = @as(f64, @floatFromInt(r.y + r.height)) / 1024;- ui.setSource(cr, t.window_fg);- ui.drawText(cr, self.preedit.items, x, y, ui.textSize(), false);- fill(cr, x, y + 2, ui.measureText(cr, self.preedit.items, ui.textSize(), false), 1, theme.shellPalette().accent);- }- }- }+ for (self.rows.items) |row| self.paintLine(cr, tab, row, sel);c.cairo_restore(cr);if (self.scrollbarGeometry()) |bar| ui.drawScrollbar(cr, scrollbar.look(bar, self.bar_appearance, theme.global.scrollbar_width, theme.shellPalette()));fill(cr, 0, @as(f64, @floatFromInt(self.h)) - status_h, @floatFromInt(self.w), status_h, t.app_bar);var info: [256]u8 = undefined;- const line = std.mem.count(u8, tab.doc.text.items[0..tab.doc.cursor], "\n") + 1;- const column = (std.unicode.utf8CountCodepoints(tab.doc.text.items[tab.doc.lineStart(tab.doc.cursor)..tab.doc.cursor]) catch 0) + 1;- const text = if (self.notice_len > 0) self.notice[0..self.notice_len] else std.fmt.bufPrint(&info, "Line {d}, Column {d} · UTF-8{s} · {s}", .{ line, column, if (tab.doc.bom) " BOM" else "", if (tab.doc.crlf) "CRLF" else "LF" }) catch "";+ if (tab.status.revision != tab.doc.revision or tab.status.cursor != tab.doc.cursor) {+ const d = &tab.doc;+ tab.status = .{+ .revision = d.revision,+ .cursor = d.cursor,+ .line = d.linesBefore(d.cursor) + 1,+ .column = (std.unicode.utf8CountCodepoints(d.text.items[d.lineStart(d.cursor)..d.cursor]) catch 0) + 1,+ };+ }+ const text = if (self.notice_len > 0) self.notice[0..self.notice_len] else std.fmt.bufPrint(&info, "Line {d}, Column {d} · UTF-8{s} · {s}", .{ tab.status.line, tab.status.column, if (tab.doc.bom) " BOM" else "", if (tab.doc.crlf) "CRLF" else "LF" }) catch "";ui.setSource(cr, t.window_fg);ui.drawText(cr, text, 12, @floatFromInt(self.h - 8), ui.statusSize(), false);if (self.menu_open) self.paintMenu(cr);if (self.close_tab != null) self.paintClose(cr);}+ /// Draws one segment: its selection, text and, if the cursor is in it, the caret.+ fn paintLine(self: *App, cr: *c.cairo_t, tab: *Tab, row: view.Row, sel: [2]usize) void {+ const t = theme.global;+ const l = row.line;+ const seg = l.seg;+ const iter = p.pango_layout_get_iter(l.layout) orelse return;+ defer p.pango_layout_iter_free(iter);+ c.cairo_save(cr);+ defer c.cairo_restore(cr);+ c.cairo_translate(cr, 16 - tab.scroll_x, self.viewTop() + row.y);+ const text_len = l.textLen();+ // The selection as indices into this layout, which holds the text+ // without its line break. With wrapping, a selected break is drawn as+ // highlight out to the right margin, as Pango does when the break is+ // in the layout; without it Pango stops at the end of the text.+ const margin: f64 = @floatFromInt(self.w - 40);+ const s0 = sel[0] -| seg.start;+ const s1 = @min(sel[1] -| seg.start, text_len);+ const covers_break = seg.terminated() and sel[0] <= seg.text_end and sel[1] > seg.text_end;+ var accent = theme.shellPalette().accent;+ accent[3] = 0.35;+ var line_index: c_int = 0;+ while (true) : (line_index += 1) {+ var rect: p.Rectangle = undefined;+ p.pango_layout_iter_get_line_extents(iter, null, &rect);+ const y = @as(f64, @floatFromInt(rect.y)) / 1024;+ const h = @as(f64, @floatFromInt(rect.height)) / 1024;+ if (row.y + y > self.viewHeight()) break;+ if (row.y + y + h >= 0) {+ const line = p.pango_layout_iter_get_line_readonly(iter);+ const first: usize = @intCast(p.pango_layout_line_get_start_index(line));+ const next = p.pango_layout_get_line_readonly(l.layout, line_index + 1);+ const end: usize = if (next) |n| @intCast(p.pango_layout_line_get_start_index(n)) else text_len;+ // Pango extends ranges to the right margin even for lines+ // entirely before the selection, so only ask for lines it intersects.+ if (sel[0] != sel[1] and s0 < s1 and s0 < end and s1 > first) {+ var ranges: ?[*]c_int = null;+ var count: c_int = 0;+ p.pango_layout_line_get_x_ranges(line, @intCast(s0), @intCast(s1), &ranges, &count);+ if (ranges) |r| {+ defer p.g_free(r);+ var n: usize = 0;+ while (n < @as(usize, @intCast(count))) : (n += 1) {+ fill(cr, @as(f64, @floatFromInt(r[n * 2])) / 1024, y, @as(f64, @floatFromInt(r[n * 2 + 1] - r[n * 2])) / 1024, h, accent);+ }+ }+ }+ if (covers_break and next == null and self.wrap) {+ const x = @as(f64, @floatFromInt(rect.x + rect.width)) / 1024;+ if (margin > x) fill(cr, x, y, margin - x, h, accent);+ }+ ui.setSource(cr, t.window_fg);+ c.cairo_move_to(cr, @as(f64, @floatFromInt(rect.x)) / 1024, @as(f64, @floatFromInt(p.pango_layout_iter_get_baseline(iter))) / 1024);+ p.pango_cairo_show_layout_line(cr, line);+ }+ if (p.pango_layout_iter_next_line(iter) == 0) break;+ }+ if (self.focused and !self.find_open and self.close_tab == null and lines.holds(seg, tab.doc.cursor, tab.doc.text.items.len)) {+ var r: p.Rectangle = undefined;+ p.pango_layout_get_cursor_pos(l.layout, l.index(tab.doc.cursor), &r, null);+ if (self.caret_visible) fill(cr, @as(f64, @floatFromInt(r.x)) / 1024, @as(f64, @floatFromInt(r.y)) / 1024, 1.5, @as(f64, @floatFromInt(r.height)) / 1024, t.window_fg);+ if (self.preedit.items.len > 0) {+ const x = @as(f64, @floatFromInt(r.x)) / 1024;+ const py = @as(f64, @floatFromInt(r.y + r.height)) / 1024;+ ui.setSource(cr, t.window_fg);+ ui.drawText(cr, self.preedit.items, x, py, ui.textSize(), false);+ fill(cr, x, py + 2, ui.measureText(cr, self.preedit.items, ui.textSize(), false), 1, theme.shellPalette().accent);+ }+ }+ }fn paintClose(self: *App, cr: *c.cairo_t) void {fill(cr, 0, 0, @floatFromInt(self.w), @floatFromInt(self.h), .{ 0, 0, 0, 0.45 });const x: f32 = @as(f32, @floatFromInt(self.w - 420)) / 2;diff --git a/src/editor/document.zig b/src/editor/document.zigindex f60b2ef..a13f423 100644--- a/src/editor/document.zig+++ b/src/editor/document.zig@@ -2,7 +2,15 @@const std = @import("std");const a = std.heap.c_allocator;const pango = @import("pango.zig");-pub const limit = 16 * 1024 * 1024;+const lines = @import("lines.zig");+/// Largest document, in bytes. The text lives in one contiguous buffer.+pub const limit: usize = 4 * 1024 * 1024 * 1024;+/// A line-number waypoint is kept about this often, so locating a line scans+/// at most this much text and edits only have to adjust a short list.+const waypoint_span: usize = 1024 * 1024;+/// How far either side of the cursor character and word movement look.+const boundary_reach: usize = 2048;+const Waypoint = struct { offset: usize, line: usize };const Edit = struct {at: usize,before: []u8,@@ -25,9 +33,19 @@ pub const Document = struct {revision: usize = 0,bom: bool = false,crlf: bool = false,+ /// Byte offset of the first line on screen. Edits keep it in step, so+ /// changing text above the view does not move what is shown.+ top: usize = 0,+ /// While a save reads the text in place, edits are refused instead of copied.+ locked: bool = false,+ waypoints: std.ArrayList(Waypoint) = .empty,+ /// Bounds of the line most recently asked about, so repeated queries in+ /// one enormous line do not each scan back to its start.+ line_memo: struct { revision: usize = std.math.maxInt(usize), start: usize = 0, end: usize = 0 } = .{},pub fn deinit(d: *Document) void {d.text.deinit(a);+ d.waypoints.deinit(a);for (d.history.items) |e| e.deinit();d.history.deinit(a);}@@ -35,14 +53,49 @@ pub const Document = struct {if (bytes.len > limit) return error.FileTooLarge;const bom = std.mem.startsWith(u8, bytes, "\xef\xbb\xbf");const value = bytes[if (bom) @as(usize, 3) else 0..];- try validate(value);- var d: Document = .{ .bom = bom, .crlf = std.mem.indexOf(u8, value, "\r\n") != null };- try d.text.appendSlice(a, value);- return d;+ var text: std.ArrayList(u8) = .empty;+ errdefer text.deinit(a);+ try text.appendSlice(a, value);+ return adopt(text, bom);+ }+ /// Takes the already-read `text` (without its BOM) as the document. On+ /// error the caller still owns the buffer.+ pub fn adopt(text: std.ArrayList(u8), bom: bool) !Document {+ if (text.items.len > limit) return error.FileTooLarge;+ try validate(text.items);+ return .{ .text = text, .bom = bom, .crlf = hasCrlf(text.items) };}pub fn validate(value: []const u8) !void {if (!std.unicode.utf8ValidateSlice(value)) return error.UnsupportedEncoding;- for (value) |b| if (b < 32 and b != '\n' and b != '\r' and b != '\t') return error.BinaryFile;+ if (hasControl(value)) return error.BinaryFile;+ }+ /// Rejects a binary or non-UTF-8 file from its first bytes, before the rest+ /// of a huge file is read. A multi-byte character cut by the end of+ /// `prefix` is not an error.+ pub fn sniff(prefix: []const u8) !void {+ var end = prefix.len;+ while (end > 0 and prefix.len - end < 4 and !std.unicode.utf8ValidateSlice(prefix[0..end])) end -= 1;+ try validate(prefix[0..end]);+ }+ /// Any control character other than tab and line breaks.+ fn hasControl(value: []const u8) bool {+ const V = @Vector(32, u8);+ var i: usize = 0;+ while (i + 32 <= value.len) : (i += 32) {+ const v: V = value[i..][0..32].*;+ const low = v < @as(V, @splat(32));+ const allowed = (v == @as(V, @splat('\t'))) | (v == @as(V, @splat('\n'))) | (v == @as(V, @splat('\r')));+ if (@reduce(.Or, low & ~allowed)) return true;+ }+ for (value[i..]) |b| if (b < 32 and b != '\n' and b != '\r' and b != '\t') return true;+ return false;+ }+ fn hasCrlf(value: []const u8) bool {+ var at: usize = 0;+ while (std.mem.indexOfScalarPos(u8, value, at, '\r')) |r| : (at = r + 1) {+ if (r + 1 < value.len and value[r + 1] == '\n') return true;+ }+ return false;}pub fn modified(d: *const Document) bool {return d.saved == null or d.saved.? != d.position;@@ -58,18 +111,58 @@ pub const Document = struct {const size = d.text.items.len - len + bytes.len;if (size > limit) return error.FileTooLarge;try d.text.ensureTotalCapacity(a, size);+ d.retarget(at, len, bytes);const old = d.text.items.len;- if (size > old) {- d.text.items.len = size;- std.mem.copyBackwards(u8, d.text.items[at + bytes.len ..], d.text.items[at + len .. old]);- } else {- std.mem.copyForwards(u8, d.text.items[at + bytes.len .. size], d.text.items[at + len ..]);- d.text.items.len = size;- }+ if (size > old) d.text.items.len = size;+ @memmove(d.text.items[at + bytes.len .. size], d.text.items[at + len .. old]);+ if (size < old) d.text.items.len = size;@memcpy(d.text.items[at..][0..bytes.len], bytes);d.revision +%= 1;}+ /// Keeps the view anchor and line waypoints valid across replacing+ /// `len` bytes at `at` with `bytes`. Call before the text changes.+ fn retarget(d: *Document, at: usize, len: usize, bytes: []const u8) void {+ const removed = std.mem.count(u8, d.text.items[at..][0..len], "\n");+ const added = std.mem.count(u8, bytes, "\n");+ var kept: usize = 0;+ for (d.waypoints.items) |w| {+ var next = w;+ if (w.offset > at) {+ if (w.offset < at + len) continue;+ next = .{ .offset = w.offset - len + bytes.len, .line = w.line - removed + added };+ }+ d.waypoints.items[kept] = next;+ kept += 1;+ }+ d.waypoints.shrinkRetainingCapacity(kept);+ if (d.top > at) d.top = if (d.top >= at + len) d.top - len + bytes.len else at;+ }+ /// How many line breaks precede `pos`, i.e. its zero-based line number.+ pub fn linesBefore(d: *Document, pos: usize) usize {+ const text = d.text.items;+ const end = @min(pos, text.len);+ var index = std.sort.upperBound(Waypoint, d.waypoints.items, end, struct {+ fn order(key: usize, w: Waypoint) std.math.Order {+ return std.math.order(key, w.offset);+ }+ }.order);+ var offset: usize = 0;+ var line: usize = 0;+ if (index > 0) {+ offset = d.waypoints.items[index - 1].offset;+ line = d.waypoints.items[index - 1].line;+ }+ while (end - offset > waypoint_span) {+ offset += waypoint_span;+ line += std.mem.count(u8, text[offset - waypoint_span .. offset], "\n");+ // A far jump leaves a trail of waypoints, so the next one is cheap.+ d.waypoints.insert(a, index, .{ .offset = offset, .line = line }) catch continue;+ index += 1;+ }+ return line + std.mem.count(u8, text[offset..end], "\n");+ }pub fn insert(d: *Document, bytes: []const u8) !void {+ if (d.locked) return error.Busy;try validate(bytes);const sel = d.selection();if (std.mem.eql(u8, d.text.items[sel[0]..sel[1]], bytes)) {@@ -105,6 +198,7 @@ pub const Document = struct {}}pub fn undo(d: *Document, redo: bool) !void {+ if (d.locked) return error.Busy;if (redo) {if (d.position == d.history.items.len) return;const e = d.history.items[d.position];@@ -120,8 +214,18 @@ pub const Document = struct {d.position -= 1;}}+ /// The display segment containing `pos` (see lines.zig).+ pub fn segmentAt(d: *Document, pos: usize) lines.Segment {+ const text = d.text.items;+ const p = @min(pos, text.len);+ const memo = &d.line_memo;+ if (memo.revision != d.revision or p < memo.start or p > memo.end) {+ memo.* = .{ .revision = d.revision, .start = lines.lineStart(text, p), .end = std.mem.indexOfScalarPos(u8, text, p, '\n') orelse text.len };+ }+ return lines.atLine(text, p, memo.start, lines.fold);+ }pub fn lineStart(d: *const Document, pos: usize) usize {- return if (std.mem.lastIndexOfScalar(u8, d.text.items[0..pos], '\n')) |n| n + 1 else 0;+ return lines.lineStart(d.text.items, pos);}pub fn lineEnd(d: *const Document, pos: usize) usize {const end = if (std.mem.indexOfScalarPos(u8, d.text.items, pos, '\n')) |n| n else d.text.items.len;@@ -129,10 +233,17 @@ pub const Document = struct {}pub fn boundary(d: *const Document, right: bool, word: bool) usize {const pos = d.cursor;- if (right and pos == d.text.items.len or !right and pos == 0) return pos;- const start = d.lineStart(if (!right and pos > 0) pos - 1 else pos);- const end = if (std.mem.indexOfScalarPos(u8, d.text.items, pos, '\n')) |n| n + 1 else d.text.items.len;- const slice = d.text.items[start..end];+ const text = d.text.items;+ if (right and pos == text.len or !right and pos == 0) return pos;+ // Only the text near the cursor is analysed, so moving along a single+ // enormous line costs the same as along a short one.+ const from = if (!right and pos > 0) pos - 1 else pos;+ const floor = from -| boundary_reach;+ var start = if (std.mem.lastIndexOfScalar(u8, text[floor..from], '\n')) |n| floor + n + 1 else floor;+ while (start < pos and text[start] & 0xc0 == 0x80) start += 1;+ var end = if (std.mem.indexOfScalarPos(u8, text[0..@min(text.len, pos +| boundary_reach)], pos, '\n')) |n| n + 1 else @min(text.len, pos +| boundary_reach);+ while (end > pos and end < text.len and text[end] & 0xc0 == 0x80) end -= 1;+ const slice = text[start..end];const count = std.unicode.utf8CountCodepoints(slice) catch return pos;const attrs = a.alloc(u32, count + 1) catch return pos;defer a.free(attrs);@@ -146,7 +257,7 @@ pub const Document = struct {if (!right and byte >= pos) return previous;previous = byte;}- if (i < count) byte += std.unicode.utf8ByteSequenceLength(d.text.items[byte]) catch 1;+ if (i < count) byte += std.unicode.utf8ByteSequenceLength(text[byte]) catch 1;}return if (right) end else previous;}@@ -187,3 +298,79 @@ test "cursor treats combining characters, emoji and CRLF as clusters" {try std.testing.expectError(error.BinaryFile, Document.init("abc\x00"));try std.testing.expectError(error.UnsupportedEncoding, Document.init("\xff"));}++fn naiveLines(text: []const u8, pos: usize) usize {+ return std.mem.count(u8, text[0..pos], "\n");+}++test "line numbers and the view anchor survive edits across waypoints" {+ const gpa = std.testing.allocator;+ var source: std.ArrayList(u8) = .empty;+ defer source.deinit(gpa);+ var i: usize = 0;+ while (source.items.len < 3 * waypoint_span + 1000) : (i += 1) try source.print(gpa, "line {d} of the document\n", .{i});+ var d = try Document.init(source.items);+ defer d.deinit();+ const len = d.text.items.len;+ // A far query leaves waypoints behind, and they agree with a plain count.+ try std.testing.expectEqual(naiveLines(d.text.items, len), d.linesBefore(len));+ try std.testing.expect(d.waypoints.items.len >= 2);+ for ([_]usize{ 0, 17, waypoint_span - 1, waypoint_span, waypoint_span + 5, 2 * waypoint_span + 99, len }) |pos| {+ try std.testing.expectEqual(naiveLines(d.text.items, pos), d.linesBefore(pos));+ }+ d.top = 2 * waypoint_span;+ // Inserting lines before the view moves the anchor by the inserted bytes.+ d.move(100, false);+ try d.insert("a\nb\nc\n");+ try std.testing.expectEqual(2 * waypoint_span + 6, d.top);+ // Replacing text that spans the anchor pulls it back to the edit.+ d.move(d.top - 50, false);+ d.move(d.top + 50, true);+ try d.insert("x");+ try std.testing.expectEqual(2 * waypoint_span + 6 - 50, d.top);+ // After every edit the waypoints still describe the new text.+ d.move(waypoint_span + 3, false);+ d.move(waypoint_span + 3000, true);+ try d.insert("replaced\nwith\nthree lines\n");+ try d.undo(false);+ try d.undo(false);+ try d.undo(false);+ const total = d.text.items.len;+ for ([_]usize{ 0, 100, waypoint_span, waypoint_span + 3000, 2 * waypoint_span, 3 * waypoint_span, total }) |pos| {+ try std.testing.expectEqual(naiveLines(d.text.items, pos), d.linesBefore(pos));+ }+ try std.testing.expectEqualStrings(source.items, d.text.items);+}++test "a binary or non-UTF-8 file is refused from its first bytes" {+ try Document.sniff("plain text, even cut mid-character: \xc3");+ try Document.sniff("日本語".*[0..4]);+ try std.testing.expectError(error.BinaryFile, Document.sniff("ok\x00binary"));+ try std.testing.expectError(error.UnsupportedEncoding, Document.sniff("bad \xff byte"));+}++test "documents refuse edits while a save reads them in place" {+ var d = try Document.init("abc");+ defer d.deinit();+ d.locked = true;+ try std.testing.expectError(error.Busy, d.insert("x"));+ try std.testing.expectError(error.Busy, d.undo(false));+ d.locked = false;+ try d.insert("x");+ try std.testing.expectEqualStrings("xabc", d.text.items);+}++test "moving by character or word inside an enormous line looks only nearby" {+ const gpa = std.testing.allocator;+ const line = try gpa.alloc(u8, 4 * 1024 * 1024);+ defer gpa.free(line);+ for (line, 0..) |*b, n| b.* = if (n % 8 == 7) ' ' else 'a';+ var d = try Document.init(line);+ defer d.deinit();+ d.move(2 * 1024 * 1024 + 3, false);+ try std.testing.expectEqual(d.cursor + 1, d.boundary(true, false));+ try std.testing.expectEqual(d.cursor - 1, d.boundary(false, false));+ // The next word boundary is found without scanning the line.+ const word = d.boundary(true, true);+ try std.testing.expect(word > d.cursor and word - d.cursor < 16);+}diff --git a/src/editor/lines.zig b/src/editor/lines.zignew file mode 100644index 0000000..80bb707--- /dev/null+++ b/src/editor/lines.zig@@ -0,0 +1,244 @@+//! Splits a document into display segments, the unit the view lays out.+//! A segment is one logical line; a line longer than `fold` bytes is cut into+//! pieces so that no single Pango layout is ever large (layout cost grows+//! faster than linearly with the text it is given). Cut points depend only on+//! the line's start, so walking in either direction finds the same pieces.+//! Pieces end after a space or tab when one is near the nominal cut, so a+//! folded paragraph still breaks between words.+const std = @import("std");++/// Longest piece of one line, in bytes, before it is folded onto another row.+/// Laying out one paragraph this long costs a few milliseconds.+pub const fold: usize = 16 * 1024;+/// How far before the nominal cut a space may be looked for.+const soft_limit: usize = 256;++fn soft(cut: usize) usize {+ return @min(soft_limit, cut / 8);+}++pub const Segment = struct {+ /// Start of the logical line this piece belongs to.+ line: usize,+ start: usize,+ /// The text to lay out is `text[start..text_end]`; `[text_end..next)` is+ /// the terminator ("\n" or "\r\n"), empty for a cut piece or the last line.+ text_end: usize,+ next: usize,++ pub fn len(s: Segment) usize {+ return s.next - s.start;+ }+ pub fn terminated(s: Segment) bool {+ return s.text_end < s.next;+ }+};++fn continuation(byte: u8) bool {+ return byte & 0xc0 == 0x80;+}++/// Start of the line containing `pos`: just after the last line break before it.+/// Scans backwards 32 bytes at a time, as a line can be megabytes long.+pub fn lineStart(text: []const u8, pos: usize) usize {+ const V = @Vector(32, u8);+ const newline: V = @splat('\n');+ var end = @min(pos, text.len);+ while (end >= 32) : (end -= 32) {+ const hit = text[end - 32 ..][0..32].* == newline;+ if (@reduce(.Or, hit)) return end - 32 + (31 - @clz(@as(u32, @bitCast(hit)))) + 1;+ }+ while (end > 0) {+ end -= 1;+ if (text[end] == '\n') return end + 1;+ }+ return 0;+}++/// Whether the cursor position `pos` lies in `s`: before its end, or at the+/// very end of the text when `s` is the last segment.+pub fn holds(s: Segment, pos: usize, len: usize) bool {+ return s.start <= pos and (pos < s.next or (pos == len and s.next == len and !s.terminated()));+}++/// Start of piece `k` of the line starting at `line`: `cut` bytes apart, moved+/// back to just after a nearby space or tab, or else forward onto a character+/// boundary. It depends on nothing but the line, so any piece can be found+/// without visiting the ones before it.+fn pieceStart(text: []const u8, line: usize, k: usize, cut: usize) usize {+ if (k == 0) return line;+ const nominal = std.math.add(usize, line, std.math.mul(usize, k, cut) catch return text.len) catch return text.len;+ if (nominal >= text.len) return text.len;+ var back = nominal;+ const floor = nominal - soft(cut);+ while (back > floor) {+ back -= 1;+ if (text[back] == ' ' or text[back] == '\t') return back + 1;+ }+ var pos = nominal;+ while (pos < text.len and continuation(text[pos])) pos += 1;+ return pos;+}++/// The index of the piece starting at `start`, in a line starting at `line`.+fn pieceIndex(start: usize, line: usize, cut: usize) usize {+ return (start - line + soft(cut)) / cut;+}++fn atTerminator(text: []const u8, pos: usize) bool {+ if (pos >= text.len) return true;+ return text[pos] == '\n' or (text[pos] == '\r' and pos + 1 < text.len and text[pos + 1] == '\n');+}++/// The piece that starts at `start`, `k` pieces into the line starting at `line`.+fn piece(text: []const u8, line: usize, start: usize, k: usize, cut: usize) Segment {+ const limit = pieceStart(text, line, k + 1, cut);+ // A terminator that ends exactly at the limit still belongs to this piece,+ // so a line of exactly `cut` bytes does not grow an empty second row.+ const window = text[start..@min(text.len, limit +| 2)];+ if (std.mem.indexOfScalar(u8, window, '\n')) |rel| {+ const nl = start + rel;+ if (nl <= limit or (nl == limit + 1 and text[limit] == '\r')) {+ const end = if (nl > start and text[nl - 1] == '\r') nl - 1 else nl;+ return .{ .line = line, .start = start, .text_end = end, .next = nl + 1 };+ }+ }+ const end = @min(limit, text.len);+ return .{ .line = line, .start = start, .text_end = end, .next = end };+}++/// The segment containing byte offset `pos` (`text.len` is the end of the last line).+pub fn at(text: []const u8, pos: usize, cut: usize) Segment {+ const p = @min(pos, text.len);+ return atLine(text, p, lineStart(text, p), cut);+}++/// `at`, for a caller that already knows where `pos`'s line starts.+pub fn atLine(text: []const u8, pos: usize, line: usize, cut: usize) Segment {+ const p = @min(pos, text.len);+ var k = pieceIndex(p, line, cut);+ var start = pieceStart(text, line, k, cut);+ // A boundary after `p` means `p` is in an earlier piece. So is a position+ // at or inside a terminator that follows a full piece.+ while (k > 0 and (start > p or atTerminator(text, start))) {+ k -= 1;+ start = pieceStart(text, line, k, cut);+ }+ return piece(text, line, start, k, cut);+}++/// The segment after `s`, or null if `s` is the last.+pub fn after(text: []const u8, s: Segment, cut: usize) ?Segment {+ if (s.next >= text.len and !s.terminated()) return null;+ if (s.terminated()) return piece(text, s.next, s.next, 0, cut);+ return piece(text, s.line, s.next, pieceIndex(s.next, s.line, cut), cut);+}++/// The segment before `s`, or null if `s` is the first.+pub fn before(text: []const u8, s: Segment, cut: usize) ?Segment {+ if (s.start == 0) return null;+ if (s.start > s.line) {+ const k = pieceIndex(s.start, s.line, cut) - 1;+ return piece(text, s.line, pieceStart(text, s.line, k, cut), k, cut);+ }+ return at(text, s.start - 1, cut);+}++fn expectCovers(text: []const u8, cut: usize) !void {+ var list: std.ArrayList(Segment) = .empty;+ defer list.deinit(std.testing.allocator);+ var seg = at(text, 0, cut);+ try std.testing.expectEqual(@as(usize, 0), seg.start);+ while (true) {+ try list.append(std.testing.allocator, seg);+ seg = after(text, seg, cut) orelse break;+ try std.testing.expectEqual(list.items[list.items.len - 1].next, seg.start);+ try std.testing.expect(list.items.len <= text.len + 2);+ }+ const last = list.items[list.items.len - 1];+ try std.testing.expectEqual(text.len, last.next);+ try std.testing.expect(!last.terminated());+ for (list.items, 0..) |s, i| {+ try std.testing.expect(s.start <= s.text_end and s.text_end <= s.next);+ try std.testing.expect(s.len() <= cut + soft(cut) + 5);+ // No piece cuts a character, and none is an empty cut piece.+ if (s.start < text.len) try std.testing.expect(!continuation(text[s.start]));+ if (!s.terminated() and s.next < text.len) try std.testing.expect(s.next > s.start);+ if (i > 0) {+ const back = before(text, s, cut).?;+ try std.testing.expectEqual(list.items[i - 1], back);+ } else try std.testing.expectEqual(@as(?Segment, null), before(text, s, cut));+ }+ var i: usize = 0;+ var pos: usize = 0;+ while (pos <= text.len) : (pos += 1) {+ if (pos < text.len and continuation(text[pos])) continue;+ while (i + 1 < list.items.len and list.items[i].next <= pos) i += 1;+ const s = list.items[i];+ try std.testing.expect(s.start <= pos and (pos < s.next or pos == text.len));+ try std.testing.expectEqual(s, at(text, pos, cut));+ try std.testing.expect(holds(s, pos, text.len));+ if (i > 0) try std.testing.expect(!holds(list.items[i - 1], pos, text.len));+ }+ // The vectorized scan agrees with a plain one at every position.+ for (0..text.len + 1) |p| {+ const expected = if (std.mem.lastIndexOfScalar(u8, text[0..p], '\n')) |n| n + 1 else 0;+ try std.testing.expectEqual(expected, lineStart(text, p));+ }+}++test "segments partition any text identically in both directions" {+ try expectCovers("", 4);+ try expectCovers("\n", 4);+ try expectCovers("a", 4);+ try expectCovers("abcd", 4);+ try expectCovers("abcd\n", 4);+ try expectCovers("abcd\r\n", 4);+ try expectCovers("abcde\r\nfg\n\n\nhijklmnopq", 4);+ try expectCovers("abcdefgh\nabcdefgh\r\n", 4);+ try expectCovers("é雪👩é雪👩é雪👩é雪👩\nx", 4);+ var prng = std.Random.DefaultPrng.init(0x5eed);+ const random = prng.random();+ const alphabet = [_][]const u8{ "a", "b", " ", "\n", "\r\n", "\r", "é", "雪", "👩", "\t" };+ for (0..2000) |_| {+ var buf: std.ArrayList(u8) = .empty;+ defer buf.deinit(std.testing.allocator);+ const n = random.uintLessThan(usize, 120);+ for (0..n) |_| try buf.appendSlice(std.testing.allocator, alphabet[random.uintLessThan(usize, alphabet.len)]);+ // Small cuts exercise folding hard; 16 and 40 also let a space be preferred.+ try expectCovers(buf.items, switch (random.uintLessThan(usize, 4)) {+ 0 => 16,+ 1 => 40,+ else => 4 + random.uintLessThan(usize, 9),+ });+ }+}++test "a huge single line folds into bounded pieces without scanning it all" {+ const a = std.testing.allocator;+ const text = try a.alloc(u8, 3 * 1024 * 1024);+ defer a.free(text);+ @memset(text, 'x');+ var seg = at(text, text.len / 2, fold);+ try std.testing.expect(seg.len() <= fold);+ try std.testing.expectEqual(@as(usize, 0), seg.line);+ var count: usize = 0;+ seg = at(text, 0, fold);+ while (after(text, seg, fold)) |n| : (seg = n) count += 1;+ try std.testing.expectEqual(text.len / fold - 1, count);+}++test "a folded paragraph breaks after a space when one is near" {+ // No word is longer than the 8 bytes looked back at this cut, so every+ // piece can end after a space.+ const text = "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron pi rho sigma tau " ** 3;+ var seg = at(text, 0, 64);+ var pieces: usize = 0;+ while (true) : (pieces += 1) {+ if (after(text, seg, 64)) |n| {+ try std.testing.expectEqual(@as(u8, ' '), text[seg.next - 1]);+ seg = n;+ } else break;+ }+ try std.testing.expect(pieces >= 4);+}diff --git a/src/editor/operation.zig b/src/editor/operation.zigindex ecfde44..dea75ea 100644--- a/src/editor/operation.zig+++ b/src/editor/operation.zig@@ -1,8 +1,17 @@//! Immutable file/chooser jobs. The UI only consumes results after the eventfd wakes it.const std = @import("std");const c = @import("../files/c.zig").api;-const Document = @import("document.zig").Document;+const document = @import("document.zig");+const Document = document.Document;const a = std.heap.c_allocator;+/// Saves of documents up to this size are copied, so editing can continue+/// while they are written; larger ones are written in place and editing waits.+pub const copy_limit: usize = 32 * 1024 * 1024;+/// Files smaller than this are not checked against free memory.+const memory_check_floor: usize = 64 * 1024 * 1024;+/// A binary or non-UTF-8 file is refused after this many bytes, before the rest is read.+const sniff_len: usize = 64 * 1024;+const bom_bytes = "\xef\xbb\xbf";extern fn flistxattr(c_int, ?[*]u8, usize) isize;extern fn fgetxattr(c_int, [*:0]const u8, ?[*]u8, usize) isize;extern fn fsetxattr(c_int, [*:0]const u8, [*]const u8, usize, c_int) c_int;@@ -68,6 +77,54 @@ fn readAll(fd: c_int, limit: usize) ![]u8 {}return bytes.toOwnedSlice(a);}+/// Reads the whole file into one buffer sized from `hint`, so a huge file is+/// neither grown by doubling nor copied afterwards.+fn readInto(fd: c_int, text: *std.ArrayList(u8), hint: usize, max: usize) !void {+ try text.ensureTotalCapacityPrecise(a, hint + 1);+ var sniffed = false;+ while (true) {+ if (text.unusedCapacitySlice().len == 0) {+ // The file grew while it was read.+ if (text.items.len >= max) return error.FileTooLarge;+ try text.ensureTotalCapacity(a, @min(max, text.items.len + text.items.len / 2 + 1024 * 1024));+ }+ const room = text.unusedCapacitySlice();+ const n = c.read(fd, room.ptr, room.len);+ if (n == 0) break;+ if (n < 0) {+ if (std.posix.errno(n) == .INTR) continue;+ return error.ReadFailed;+ }+ text.items.len += @intCast(n);+ if (!sniffed and text.items.len >= sniff_len) {+ sniffed = true;+ try Document.sniff(text.items[0..sniff_len]);+ }+ }+}+/// Memory the kernel could give a new allocation without swapping, in bytes.+fn availableMemory() ?usize {+ const fd = c.open("/proc/meminfo", c.O_RDONLY | c.O_CLOEXEC);+ if (fd < 0) return null;+ defer _ = c.close(fd);+ var buf: [4096]u8 = undefined;+ const n = c.read(fd, &buf, buf.len);+ if (n <= 0) return null;+ const info = buf[0..@intCast(n)];+ const key = "MemAvailable:";+ const at = std.mem.indexOf(u8, info, key) orelse return null;+ var rest = std.mem.trimStart(u8, info[at + key.len ..], " ");+ rest = rest[0 .. std.mem.indexOfAny(u8, rest, " \n") orelse rest.len];+ const kib = std.fmt.parseInt(usize, rest, 10) catch return null;+ return std.math.mul(usize, kib, 1024) catch null;+}+/// Opening must not push the machine into swap or the OOM killer: refuse a+/// file that, with room to edit it, would not fit in free memory.+fn ensureMemory(size: usize) !void {+ if (size < memory_check_floor) return;+ const available = availableMemory() orelse return;+ if (size + size / 8 > available) return error.OutOfMemory;+}pub fn executable(buf: []u8, name: []const u8) []const u8 {var path: [4096]u8 = undefined;const n = c.readlink("/proc/self/exe", &path, path.len);@@ -85,7 +142,10 @@ pub const Operation = struct {tab_id: usize,revision: usize = 0,path: [:0]u8,- bytes: []u8,+ /// What a save writes after the optional BOM; owned unless `owns_bytes` is false.+ bytes: []const u8,+ owns_bytes: bool = true,+ bom: bool = false,expected: ?Stamp,stamp: ?Stamp = null,io: std.Io,@@ -97,16 +157,24 @@ pub const Operation = struct {document: ?Document = null,pub fn start(kind: Kind, io: std.Io, tab_id: usize, path: []const u8, bytes: []const u8, expected: ?Stamp) !*Operation {+ return create(kind, io, tab_id, path, try a.dupe(u8, bytes), true, false, expected);+ }+ /// Writes `text` (after a BOM if `bom`). With `borrow` the caller keeps+ /// `text` alive and unchanged until the operation finishes, which spares+ /// a copy of a very large document.+ pub fn startSave(io: std.Io, tab_id: usize, path: []const u8, bom: bool, text: []const u8, borrow: bool, expected: ?Stamp) !*Operation {+ return create(.save, io, tab_id, path, if (borrow) text else try a.dupe(u8, text), !borrow, bom, expected);+ }+ fn create(kind: Kind, io: std.Io, tab_id: usize, path: []const u8, data: []const u8, owns: bool, bom: bool, expected: ?Stamp) !*Operation {+ errdefer if (owns) a.free(data);const self = try a.create(Operation);errdefer a.destroy(self);const owned = try a.dupeZ(u8, path);errdefer a.free(owned);- const data = try a.dupe(u8, bytes);- errdefer a.free(data);const fd = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);if (fd < 0) return error.EventFailed;errdefer _ = c.close(fd);- self.* = .{ .kind = kind, .io = io, .tab_id = tab_id, .path = owned, .bytes = data, .expected = expected, .fd = fd };+ self.* = .{ .kind = kind, .io = io, .tab_id = tab_id, .path = owned, .bytes = data, .owns_bytes = owns, .bom = bom, .expected = expected, .fd = fd };self.thread = try std.Thread.spawn(.{}, run, .{self});return self;}@@ -114,7 +182,7 @@ pub const Operation = struct {self.thread.?.join();if (self.document) |*d| d.deinit();a.free(self.path);- a.free(self.bytes);+ if (self.owns_bytes) a.free(self.bytes);_ = c.close(self.fd);a.destroy(self);}@@ -143,10 +211,19 @@ pub const Operation = struct {var st: c.struct_stat = undefined;if (c.fstat(fd, &st) != 0 or st.st_mode & c.S_IFMT != c.S_IFREG) return error.NotRegularFile;self.stamp = Stamp.of(st);- const bytes = try readAll(fd, @import("document.zig").limit);- defer a.free(bytes);- self.document = try Document.init(bytes);+ const size: usize = @intCast(@max(0, st.st_size));+ if (size > document.limit) return error.FileTooLarge;+ try ensureMemory(size);+ var text: std.ArrayList(u8) = .empty;+ errdefer text.deinit(a);+ try readInto(fd, &text, size, document.limit);if (c.fstat(fd, &st) != 0 or !self.stamp.?.eql(Stamp.of(st))) return error.FileChanged;+ const bom = std.mem.startsWith(u8, text.items, bom_bytes);+ if (bom) {+ @memmove(text.items[0 .. text.items.len - bom_bytes.len], text.items[bom_bytes.len..]);+ text.items.len -= bom_bytes.len;+ }+ self.document = try Document.adopt(text, bom);},.save => try self.save(),.open_dialog, .save_dialog => try self.choose(),@@ -186,6 +263,7 @@ pub const Operation = struct {if (c.fstat(source, &source_stat) != 0 or !before.?.eql(Stamp.of(source_stat))) return error.FileChanged;try copyAttributes(source, fd);}+ if (self.bom) try writeAll(fd, bom_bytes);try writeAll(fd, self.bytes);if (c.fsync(fd) != 0) return error.WriteFailed;if (before) |stamp| {@@ -293,3 +371,49 @@ test "atomic saves preserve permissions, reject stale files and follow symlink tjob.expected = null;try std.testing.expectError(error.FileChanged, job.work());}++test "loading reads one buffer, keeps the BOM aside and refuses binary data early" {+ var template: [64:0]u8 = @splat(0);+ _ = try std.fmt.bufPrintZ(&template, "/tmp/rediwm-editor-XXXXXX", .{});+ const dir = c.mkdtemp(&template) orelse return error.CreateFailed;+ defer _ = c.rmdir(dir);+ const path = try std.fmt.allocPrintSentinel(a, "{s}/big.txt", .{std.mem.span(dir)}, 0);+ defer a.free(path);+ defer _ = c.unlink(path);+ var body: std.ArrayList(u8) = .empty;+ defer body.deinit(a);+ try body.appendSlice(a, bom_bytes);+ for (0..5000) |n| try body.print(a, "line {d}\r\n", .{n});+ const fd = c.open(path, c.O_WRONLY | c.O_CREAT | c.O_CLOEXEC, @as(c_uint, 0o600));+ try std.testing.expect(fd >= 0);+ try writeAll(fd, body.items);+ _ = c.close(fd);+ var job: Operation = .{ .kind = .load, .tab_id = 1, .path = try a.dupeZ(u8, path), .bytes = "", .owns_bytes = false, .expected = null, .io = undefined, .fd = -1 };+ defer a.free(job.path);+ defer if (job.document) |*d| d.deinit();+ try job.work();+ const d = job.document.?;+ try std.testing.expect(d.bom and d.crlf);+ try std.testing.expectEqualSlices(u8, body.items[bom_bytes.len..], d.text.items);+ // A NUL past the sniffed prefix is still caught, by the full validation.+ job.document.?.deinit();+ job.document = null;+ try body.append(a, 0);+ const fd2 = c.open(path, c.O_WRONLY | c.O_TRUNC | c.O_CLOEXEC);+ try writeAll(fd2, body.items);+ _ = c.close(fd2);+ try std.testing.expectError(error.BinaryFile, job.work());+ // One inside it is refused before the rest of the file is read.+ body.items[1000] = 0;+ const fd3 = c.open(path, c.O_WRONLY | c.O_TRUNC | c.O_CLOEXEC);+ try writeAll(fd3, body.items);+ _ = c.close(fd3);+ try std.testing.expectError(error.BinaryFile, job.work());+}++test "free memory is read from the kernel" {+ const available = availableMemory() orelse return;+ try std.testing.expect(available > 1024 * 1024);+ try ensureMemory(1024);+ try std.testing.expectError(error.OutOfMemory, ensureMemory(available + memory_check_floor));+}diff --git a/src/editor/pango.zig b/src/editor/pango.zigindex bd0749c..fd2be54 100644--- a/src/editor/pango.zig+++ b/src/editor/pango.zig@@ -15,6 +15,8 @@ pub extern fn pango_font_description_from_string([*:0]const u8) ?*Font;pub extern fn pango_font_description_set_absolute_size(*Font, f64) void;pub extern fn pango_font_description_free(*Font) void;pub extern fn pango_layout_get_pixel_size(*Layout, *c_int, *c_int) void;+pub extern fn pango_layout_get_extents(*Layout, ?*Rectangle, *Rectangle) void;+pub extern fn pango_layout_get_text(*Layout) [*:0]const u8;pub extern fn pango_layout_get_cursor_pos(*Layout, c_int, *Rectangle, ?*Rectangle) void;pub extern fn pango_layout_xy_to_index(*Layout, c_int, c_int, *c_int, *c_int) c_int;pub extern fn pango_layout_get_iter(*Layout) ?*Iter;diff --git a/src/editor/view.zig b/src/editor/view.zignew file mode 100644index 0000000..bc210ec--- /dev/null+++ b/src/editor/view.zig@@ -0,0 +1,492 @@+//! What is on screen. Text reaches Pango one display segment at a time (see+//! lines.zig) and layouts are cached by content, so opening, scrolling and+//! editing cost the same for a megabyte as for a gigabyte: only the lines+//! near the viewport are ever laid out. The scroll position is a byte offset+//! (`Document.top`) plus a pixel offset into that line, never a pixel count+//! from the start of the file, which would need every line's height.+const std = @import("std");+const c = @import("../files/c.zig").api;+const p = @import("pango.zig");+const Document = @import("document.zig").Document;+const lines = @import("lines.zig");+const a = std.heap.c_allocator;++/// Documents up to this size are measured exactly, so their scrollbar and+/// scrolling behave as if the whole text were one layout. Larger ones+/// estimate their height from the lines seen so far.+const exact_limit: usize = 32 * 1024;+/// How far from the view, in viewports, a position is still looked up by+/// walking lines rather than by jumping the view to it.+const reach_views = 3;++pub const Line = struct {+ seg: lines.Segment,+ layout: *p.Layout,+ height: f64,++ /// The text laid out, for translating Pango indices.+ pub fn textLen(l: Line) usize {+ return l.seg.text_end - l.seg.start;+ }+ pub fn index(l: Line, pos: usize) c_int {+ return @intCast(@min(pos -| l.seg.start, l.textLen()));+ }+};++/// Layouts of recently shown segments, keyed by their text, so editing one+/// line or scrolling by one line lays out one line. Nothing here depends on+/// where in the document a segment is, only on its bytes, the width and the font.+pub const Layouts = struct {+ const Entry = struct { layout: *p.Layout, height: f64, used: u64, len: usize };+ const max_entries = 2048;+ const max_bytes = 1024 * 1024;+ map: std.AutoHashMapUnmanaged(u64, Entry) = .empty,+ surface: ?*c.cairo_surface_t = null,+ cr: ?*c.cairo_t = null,+ font: ?*p.Font = null,+ family: u64 = 0,+ size: f64 = 0,+ width: i32 = 0,+ scale: i32 = 0,+ /// Advanced once per painted frame; entries used this frame or the last survive a sweep.+ frame: u64 = 2,+ bytes: usize = 0,+ /// Sizes at which the cache next drops what the last frames did not use;+ /// doubled when that frees nothing, so one long walk is not swept per line.+ trim_count: usize = max_entries,+ trim_bytes: usize = max_bytes,+ sampled_bytes: f64 = 0,+ sampled_height: f64 = 0,+ /// Changes whenever cached heights stop being valid.+ epoch: usize = 1,++ pub fn deinit(l: *Layouts) void {+ l.flush();+ l.map.deinit(a);+ if (l.font) |f| p.pango_font_description_free(f);+ if (l.cr) |cr| c.cairo_destroy(cr);+ if (l.surface) |s| c.cairo_surface_destroy(s);+ }++ fn flush(l: *Layouts) void {+ var it = l.map.valueIterator();+ while (it.next()) |e| p.g_object_unref(e.layout);+ l.map.clearRetainingCapacity();+ l.bytes = 0;+ l.sampled_bytes = 0;+ l.sampled_height = 0;+ l.epoch +%= 1;+ }++ /// Sets how text is laid out; a change drops every cached layout.+ /// `wrap_width` is in logical pixels, null for no wrapping.+ pub fn configure(l: *Layouts, family: []const u8, size: f64, wrap_width: ?i32, scale: i32) void {+ const hash = std.hash.Wyhash.hash(0, family);+ const width: i32 = if (wrap_width) |w| @max(1, w) * 1024 else -1;+ if (l.font != null and l.family == hash and l.size == size and l.width == width and l.scale == scale) return;+ l.flush();+ l.family = hash;+ l.size = size;+ l.width = width;+ l.scale = scale;+ var buf: [256:0]u8 = undefined;+ const name = std.fmt.bufPrintZ(&buf, "{s}", .{family}) catch "monospace";+ if (l.font) |f| p.pango_font_description_free(f);+ l.font = p.pango_font_description_from_string(name);+ if (l.font) |f| p.pango_font_description_set_absolute_size(f, size * 1024);+ if (l.cr) |cr| c.cairo_destroy(cr);+ if (l.surface) |s| c.cairo_surface_destroy(s);+ l.surface = c.cairo_image_surface_create(c.CAIRO_FORMAT_ARGB32, 1, 1);+ l.cr = c.cairo_create(l.surface);+ c.cairo_scale(l.cr, @floatFromInt(scale), @floatFromInt(scale));+ }++ pub fn beginFrame(l: *Layouts) void {+ l.frame += 1;+ }++ fn sweep(l: *Layouts) void {+ var doomed: std.ArrayList(u64) = .empty;+ defer doomed.deinit(a);+ var it = l.map.iterator();+ while (it.next()) |kv| {+ if (kv.value_ptr.used + 1 < l.frame) doomed.append(a, kv.key_ptr.*) catch return;+ }+ for (doomed.items) |key| l.drop(key);+ }++ fn drop(l: *Layouts, key: u64) void {+ const e = (l.map.fetchRemove(key) orelse return).value;+ l.bytes -= e.len;+ p.g_object_unref(e.layout);+ }++ /// The layout of one segment of `text`, or null if memory ran out.+ pub fn line(l: *Layouts, text: []const u8, seg: lines.Segment) ?Line {+ const content = text[seg.start..seg.text_end];+ const key = std.hash.Wyhash.hash(0, content);+ if (l.map.getPtr(key)) |e| {+ if (e.len == content.len and std.mem.eql(u8, std.mem.span(p.pango_layout_get_text(e.layout)), content)) {+ e.used = l.frame;+ return .{ .seg = seg, .layout = e.layout, .height = e.height };+ }+ l.drop(key);+ }+ const cr = l.cr orelse return null;+ const font = l.font orelse return null;+ if (l.map.count() >= l.trim_count or l.bytes >= l.trim_bytes) {+ l.sweep();+ l.trim_count = @max(max_entries, l.map.count() * 2);+ l.trim_bytes = @max(max_bytes, l.bytes * 2);+ }+ const layout = p.pango_cairo_create_layout(cr) orelse return null;+ p.pango_layout_set_font_description(layout, font);+ p.pango_layout_set_width(layout, l.width);+ p.pango_layout_set_wrap(layout, 2);+ p.pango_layout_set_text(layout, content.ptr, @intCast(content.len));+ p.pango_cairo_update_layout(cr, layout);+ var extents: p.Rectangle = undefined;+ p.pango_layout_get_extents(layout, null, &extents);+ const height = @max(1, @as(f64, @floatFromInt(extents.height)) / 1024);+ l.map.put(a, key, .{ .layout = layout, .height = height, .used = l.frame, .len = content.len }) catch {+ p.g_object_unref(layout);+ return null;+ };+ l.bytes += content.len;+ l.sampled_bytes += @floatFromInt(content.len + 1);+ l.sampled_height += height;+ return .{ .seg = seg, .layout = layout, .height = height };+ }++ /// Average height per byte of the text laid out so far.+ pub fn heightPerByte(l: *const Layouts) f64 {+ return if (l.sampled_bytes > 0) l.sampled_height / l.sampled_bytes else 0.25;+ }+};++pub const Row = struct { line: Line, y: f64 };++/// Remembers the exact height of a small document so the scrollbar does not+/// re-measure it on every query.+pub const Measure = struct {+ revision: usize = std.math.maxInt(usize),+ epoch: usize = 0,+ total: f64 = 0,+ top: usize = std.math.maxInt(usize),+ before: f64 = 0,+};++/// Scrollbar geometry in one unit: pixels for a small document, bytes for a+/// large one (whose pixel height is only an estimate that keeps improving, and+/// a drag in progress must not see its units change under it).+pub const Extent = struct { content: f64, viewport: f64, offset: f64 };++/// The view of one document: where it is scrolled to and how tall it is.+pub const Port = struct {+ doc: *Document,+ layouts: *Layouts,+ /// Height of the text area in logical pixels.+ height: f64,+ /// Pixels of the top line scrolled out of view.+ dy: *f64,++ fn text(s: Port) []const u8 {+ return s.doc.text.items;+ }+ fn lineAt(s: Port, pos: usize) ?Line {+ return s.layouts.line(s.text(), s.doc.segmentAt(pos));+ }+ fn nextLine(s: Port, l: Line) ?Line {+ return s.layouts.line(s.text(), lines.after(s.text(), l.seg, lines.fold) orelse return null);+ }+ fn prevLine(s: Port, l: Line) ?Line {+ return s.layouts.line(s.text(), lines.before(s.text(), l.seg, lines.fold) orelse return null);+ }+ /// The first visible line, snapping `doc.top` onto a segment start.+ fn topLine(s: Port) ?Line {+ const l = s.lineAt(s.doc.top) orelse return null;+ s.doc.top = l.seg.start;+ return l;+ }++ /// Keeps `dy` inside the top line by moving the top line itself.+ fn normalize(s: Port) void {+ var cur = s.topLine() orelse return;+ var guard: usize = 0;+ while (guard < 100_000) : (guard += 1) {+ if (s.dy.* < 0) {+ const prev = s.prevLine(cur) orelse {+ s.dy.* = 0;+ break;+ };+ cur = prev;+ s.dy.* += prev.height;+ } else if (s.dy.* >= cur.height) {+ const next = s.nextLine(cur) orelse break;+ s.dy.* -= cur.height;+ cur = next;+ } else break;+ }+ s.doc.top = cur.seg.start;+ }++ /// Scrolls so the end of the text sits at the bottom of the view (or the+ /// start at the top, if everything fits).+ pub fn scrollToEnd(s: Port) void {+ var cur = s.lineAt(s.text().len) orelse return;+ var acc = cur.height;+ while (acc < s.height) {+ cur = s.prevLine(cur) orelse {+ s.doc.top = 0;+ s.dy.* = 0;+ return;+ };+ acc += cur.height;+ }+ s.doc.top = cur.seg.start;+ s.dy.* = acc - s.height;+ }++ /// Normalizes the position and pulls it back if it shows space past the end.+ pub fn clamp(s: Port) void {+ s.normalize();+ var cur = s.topLine() orelse return;+ var y = -s.dy.*;+ while (true) {+ y += cur.height;+ if (y >= s.height) return;+ cur = s.nextLine(cur) orelse break;+ }+ s.scrollToEnd();+ }++ pub fn scrollBy(s: Port, pixels: f64) void {+ s.dy.* += pixels;+ s.clamp();+ }++ /// The lines intersecting the view, with their top edges relative to it.+ pub fn visible(s: Port, rows: *std.ArrayList(Row)) void {+ rows.clearRetainingCapacity();+ var cur = s.topLine() orelse return;+ var y = -s.dy.*;+ while (true) {+ rows.append(a, .{ .line = cur, .y = y }) catch return;+ y += cur.height;+ if (y >= s.height) return;+ cur = s.nextLine(cur) orelse return;+ }+ }++ /// The line containing `pos` and its top edge relative to the view, or+ /// null if it is more than a few viewports away.+ pub fn locate(s: Port, pos: usize) ?Row {+ const target = s.doc.segmentAt(pos).start;+ var cur = s.topLine() orelse return null;+ var y = -s.dy.*;+ const reach = s.height * reach_views;+ if (target >= cur.seg.start) {+ while (y <= reach) {+ if (cur.seg.start == target) return .{ .line = cur, .y = y };+ y += cur.height;+ cur = s.nextLine(cur) orelse return null;+ }+ } else {+ while (y >= -reach) {+ cur = s.prevLine(cur) orelse return null;+ y -= cur.height;+ if (cur.seg.start == target) return .{ .line = cur, .y = y };+ }+ }+ return null;+ }++ /// Scrolls so the line holding `pos` is about a third of the way down.+ pub fn jumpTo(s: Port, pos: usize) void {+ var cur = s.lineAt(pos) orelse return;+ const want = s.height / 3;+ var above: f64 = 0;+ while (above < want) {+ cur = s.prevLine(cur) orelse break;+ above += cur.height;+ }+ s.doc.top = cur.seg.start;+ s.dy.* = @max(0, above - want);+ s.clamp();+ }++ /// The byte offset nearest (x, y), both relative to the view's text origin.+ pub fn indexAt(s: Port, x: f64, y: f64) usize {+ var cur = s.topLine() orelse return 0;+ var top = -s.dy.*;+ var guard: usize = 0;+ while (y < top and guard < 10_000) : (guard += 1) {+ cur = s.prevLine(cur) orelse break;+ top -= cur.height;+ }+ while (y >= top + cur.height and guard < 10_000) : (guard += 1) {+ const next = s.nextLine(cur) orelse break;+ top += cur.height;+ cur = next;+ }+ const local = std.math.clamp(y - top, 0, cur.height - 0.01);+ var idx: c_int = 0;+ var trailing: c_int = 0;+ _ = p.pango_layout_xy_to_index(cur.layout, @intFromFloat(std.math.clamp(x * 1024, -1e9, 1e9)), @intFromFloat(local * 1024), &idx, &trailing);+ var offset = cur.seg.start + @as(usize, @intCast(@max(0, idx)));+ while (trailing > 0 and offset < cur.seg.text_end) : (trailing -= 1) offset += std.unicode.utf8ByteSequenceLength(s.text()[offset]) catch 1;+ return @min(offset, cur.seg.text_end);+ }++ /// The scrollable length and the current offset in the same units.+ pub fn extent(s: Port, memo: *Measure) Extent {+ const len = s.text().len;+ if (len <= exact_limit) {+ if (memo.revision != s.doc.revision or memo.epoch != s.layouts.epoch) {+ memo.* = .{ .revision = s.doc.revision, .epoch = s.layouts.epoch };+ var total: f64 = 0;+ var cur = s.lineAt(0);+ while (cur) |l| : (cur = s.nextLine(l)) total += l.height;+ memo.total = total;+ }+ if (memo.top != s.doc.top) {+ var before: f64 = 0;+ var cur = s.lineAt(0);+ while (cur) |l| : (cur = s.nextLine(l)) {+ if (l.seg.start >= s.doc.top) break;+ before += l.height;+ }+ memo.top = s.doc.top;+ memo.before = before;+ }+ return .{ .content = memo.total, .viewport = s.height, .offset = memo.before + s.dy.* };+ }+ const cur = s.lineAt(s.doc.top) orelse return .{ .content = 0, .viewport = 0, .offset = 0 };+ const fraction = std.math.clamp(s.dy.* / cur.height, 0, 1);+ const at = @as(f64, @floatFromInt(cur.seg.start)) + fraction * @as(f64, @floatFromInt(cur.seg.len()));+ return .{ .content = @floatFromInt(len + 1), .viewport = s.height / s.layouts.heightPerByte(), .offset = at };+ }++ /// Scrolls to `offset`, which is in the units `extent` reports.+ pub fn seek(s: Port, memo: *Measure, offset: f64) void {+ const e = s.extent(memo);+ if (offset >= e.content - e.viewport - 0.5) return s.scrollToEnd();+ if (s.text().len <= exact_limit) {+ var acc: f64 = 0;+ var cur = s.lineAt(0);+ while (cur) |l| : (cur = s.nextLine(l)) {+ if (acc + l.height > offset or s.nextLine(l) == null) {+ s.doc.top = l.seg.start;+ s.dy.* = offset - acc;+ break;+ }+ acc += l.height;+ }+ } else {+ const at = @min(@max(0, offset), @as(f64, @floatFromInt(s.text().len)));+ const cur = s.lineAt(@intFromFloat(at)) orelse return;+ const fraction = std.math.clamp((at - @as(f64, @floatFromInt(cur.seg.start))) / @as(f64, @floatFromInt(@max(1, cur.seg.len()))), 0, 1);+ s.doc.top = cur.seg.start;+ s.dy.* = fraction * cur.height;+ }+ s.clamp();+ }+};++fn testLayouts() Layouts {+ var l: Layouts = .{};+ l.configure("monospace", 13, null, 1);+ return l;+}++fn bigText(a_: std.mem.Allocator, lines_n: usize) !std.ArrayList(u8) {+ var text: std.ArrayList(u8) = .empty;+ errdefer text.deinit(a_);+ for (0..lines_n) |i| try text.print(a_, "line {d}: the quick brown fox jumps over the lazy dog\n", .{i});+ return text;+}++test "scrolling a large document only ever walks a few lines" {+ var source = try bigText(std.testing.allocator, 200_000);+ defer source.deinit(std.testing.allocator);+ var doc = try Document.init(source.items);+ defer doc.deinit();+ var layouts = testLayouts();+ defer layouts.deinit();+ var dy: f64 = 0;+ const port: Port = .{ .doc = &doc, .layouts = &layouts, .height = 400, .dy = &dy };+ var rows: std.ArrayList(Row) = .empty;+ defer rows.deinit(a);+ port.visible(&rows);+ try std.testing.expect(rows.items.len > 10 and rows.items.len < 60);+ const line_h = rows.items[0].line.height;+ port.scrollBy(line_h * 1000.5);+ port.visible(&rows);+ try std.testing.expectEqual(@as(usize, 1000), std.mem.count(u8, doc.text.items[0..doc.top], "\n"));+ try std.testing.expectApproxEqAbs(line_h / 2, dy, 0.01);+ port.scrollBy(-line_h * 10_000);+ try std.testing.expectEqual(@as(usize, 0), doc.top);+ try std.testing.expectEqual(@as(f64, 0), dy);+ port.scrollToEnd();+ port.visible(&rows);+ const last = rows.items[rows.items.len - 1];+ try std.testing.expectApproxEqAbs(@as(f64, 400), last.y + last.line.height, 0.01);+ try std.testing.expect(last.line.seg.start == doc.text.items.len);+ // Far positions are reached by jumping, near ones by walking.+ port.jumpTo(doc.text.items.len / 2);+ const mid = port.locate(doc.text.items.len / 2).?;+ try std.testing.expect(mid.y >= 0 and mid.y < 400);+ try std.testing.expect(port.locate(0) == null);+ port.scrollBy(line_h * 3);+ layouts.beginFrame();+ layouts.beginFrame();+ port.visible(&rows);+ try std.testing.expect(rows.items.len < 60);+}++test "a three megabyte single line is folded and stays addressable" {+ const mib3 = try std.testing.allocator.alloc(u8, 3 * 1024 * 1024);+ defer std.testing.allocator.free(mib3);+ for (mib3, 0..) |*b, i| b.* = if (i % 11 == 10) ' ' else 'a' + @as(u8, @intCast(i % 26));+ var doc = try Document.init(mib3);+ defer doc.deinit();+ var layouts = testLayouts();+ defer layouts.deinit();+ var dy: f64 = 0;+ const port: Port = .{ .doc = &doc, .layouts = &layouts, .height = 300, .dy = &dy };+ port.jumpTo(1_500_000);+ var rows: std.ArrayList(Row) = .empty;+ defer rows.deinit(a);+ port.visible(&rows);+ try std.testing.expect(rows.items.len >= 1);+ // A piece may be shorter or longer than the fold by the look-back for a space.+ for (rows.items) |r| try std.testing.expect(r.line.seg.len() <= lines.fold + 300);+ const hit = port.indexAt(30, 20);+ try std.testing.expect(hit > 1_000_000 and hit < 2_000_000);+ var memo: Measure = .{};+ const e = port.extent(&memo);+ try std.testing.expect(e.content > e.viewport and e.offset > 0 and e.offset < e.content - e.viewport);+ port.seek(&memo, 0);+ try std.testing.expectEqual(@as(usize, 0), doc.top);+}++test "small documents measure exactly and seek by pixels" {+ var doc = try Document.init("one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n");+ defer doc.deinit();+ var layouts = testLayouts();+ defer layouts.deinit();+ var dy: f64 = 0;+ const port: Port = .{ .doc = &doc, .layouts = &layouts, .height = 40, .dy = &dy };+ var memo: Measure = .{};+ var e = port.extent(&memo);+ const row = e.content / 9;+ try std.testing.expect(row > 5);+ port.seek(&memo, row * 2.5);+ e = port.extent(&memo);+ try std.testing.expectApproxEqAbs(row * 2.5, e.offset, 0.01);+ try std.testing.expectEqual(@as(usize, 8), doc.top);+ port.seek(&memo, 1e9);+ port.clamp();+ e = port.extent(&memo);+ try std.testing.expectApproxEqAbs(e.content - 40, e.offset, 0.01);+}diff --git a/src/editor_tests.zig b/src/editor_tests.zigindex 192e84b..7a62c62 100644--- a/src/editor_tests.zig+++ b/src/editor_tests.zig@@ -2,5 +2,7 @@ test {_ = @import("editor/caret.zig");_ = @import("editor/formats.zig");_ = @import("editor/document.zig");+ _ = @import("editor/lines.zig");+ _ = @import("editor/view.zig");_ = @import("editor/operation.zig");}diff --git a/tests/editor.py b/tests/editor.pyindex c68571d..5f74d01 100644--- a/tests/editor.py+++ b/tests/editor.py@@ -257,6 +257,30 @@ def run():window_control(24) # close all clean tabswait_for(lambda: not windows("rediwm-editor"), "editor closes")print("binary rejection and clean window close", flush=True)++ # Beyond the old 16 MiB limit, and past the size where a save is+ # copied: opening must not lay the whole text out, End must reach+ # the real end, and the file written must be exact.+ large = docs / "large.log"+ chunk = b"".join(b"line %d: the quick brown fox jumps over the lazy dog\n" % n for n in range(20000))+ with large.open("wb") as handle:+ handle.write(b"\xef\xbb\xbf")+ for _ in range(40):+ handle.write(chunk)+ original = large.read_bytes()+ assert len(original) > 40 * 1024 * 1024+ start("rediwm-editor", large)+ win = title("large.log")+ ipc.focus_window(win["id"])+ key(107, ctrl=True)+ ipc.type_text("END")+ title("* large.log")+ key(31, ctrl=True)+ wait_for(lambda: large.read_bytes() == original + b"END", "large file saved exactly with its BOM")+ title("large.log")+ key(17, ctrl=True)+ wait_for(lambda: not windows("rediwm-editor"), "large file tab closes")+ print("files beyond 16 MiB open, jump to the end and save exactly", flush=True)if env["WLR_RENDERER"] == "gles2":lines = (tmp / "rediwm-0.log").read_text().splitlines()for line in lines: