Skip to content

RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process

Editor: glide lines moved by an edit

oxydizer6bf756dc1e9f
diff --git a/src/config/default.zig b/src/config/default.zig
index 81d7249..e9948e2 100644
--- a/src/config/default.zig
+++ b/src/config/default.zig
@@ -105,7 +105,7 @@ pub const source =
\\cursor_size = 32
\\caret_blink_ms = 1060 # full on+off cycle; 0 = never blink
\\caret_blink_timeout = 10 # seconds idle before it goes solid; 0 = never
- \\caret_motion_ms = 80 # glide between positions; 0 = snap
+ \\caret_motion_ms = 80 # glide between positions (editor lines glide 1.5x as long); 0 = snap
\\# Pointer values above are defaults. Settings > Input saves only changed
\\# values in [[input_device]] records keyed by a stable generated id.
\\# Omitted device fields inherit these defaults; delete a field to reset it.
diff --git a/src/editor/AGENTS.md b/src/editor/AGENTS.md
index 3e85beb..0de5e15 100644
--- a/src/editor/AGENTS.md
+++ b/src/editor/AGENTS.md
@@ -30,6 +30,43 @@
* 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).
+## Line glide
+
+* **Edits that move lines glide instead of snapping** (`reflow.zig`): Enter
+ pushes the lines below down and carries the rest of its line onto a new one,
+ Backspace/Delete/undo joining or removing lines pulls them up, and a word
+ that now wraps shifts what follows. Layout, hit tests and the scrollbar
+ never see it: rows stay at rest and `paintLine` only gets an `Offset`
+ (`dx`, `dy`, `alpha`) for the row that starts at one byte offset. Plain
+ typing and cursor movement produce no offsets, so they cost one loop over
+ the visible rows.
+* **The edit span, not a diff, finds the same line again.** `Document.replace`
+ merges every edit since `takeChange` into `Change` (`lo`, `suffix`, lengths):
+ a row starting before `lo` keeps its start, a row at or after `hi()` started
+ `new_len - old_len` bytes earlier. `stepReflow` runs before `stepCaret` in
+ each loop pass, takes the change and plans; `render` ends with `remember`,
+ which stores the visible rows at *rest*. Where a row was drawn is its rest
+ place plus the move still in flight at `now`, so an edit during a glide
+ continues from the screen, not from the old target.
+* **All or nothing.** A line the edit made that has text (paste), a vertical
+ move over `max_glide` (120 px, the caret's jump rule), another tab, rebuilt
+ layouts (resize, font, wrap), a change the remembered rows don't describe,
+ or `caret_motion_ms = 0`/reduced motion snap every row. Lines that are
+ empty (Enter at a line's end or start) are fine. The rest of a split line
+ starts where the text before the break ends and fades in, so it doesn't
+ overprint the line above while it crosses it.
+* **The caret rides its line** (`Caret.Shift`): its box is the rest position
+ plus the offset of the row holding the cursor, solid while any line moves,
+ so the two never drift apart; a join leaves the cursor's row at rest and
+ the caret snaps as before.
+* **Frames are paced by the display.** The duration is 1.5 x `caret_motion_ms`
+ (one setting for both). `reflow_dirty` asks for a full repaint (damage is
+ not just the caret) and, unlike `caret_dirty`, waits for the frame callback;
+ one last frame is drawn at rest when it ends. Nothing runs when idle.
+ `tests/editor_visuals.py` samples a frame mid-glide (screenshots show the
+ frame at request time, so sample ~100 ms after the key); unit tests are in
+ `reflow.zig`.
+
## Drafts
* **Unsaved text survives closing, crashes and reboots.** `drafts.zig` owns
diff --git a/src/editor/app.zig b/src/editor/app.zig
index e3a5272..cafeff0 100644
--- a/src/editor/app.zig
+++ b/src/editor/app.zig
@@ -11,6 +11,7 @@ const dialog = @import("ui").widgets.dialog;
const menu = @import("ui").context_menu;
const p = @import("pango.zig");
const caret_mod = @import("caret.zig");
+const reflow_mod = @import("reflow.zig");
const input = @import("ui").input;
const Document = @import("document.zig").Document;
const view = @import("view.zig");
@@ -91,6 +92,12 @@ pub const App = struct {
/// callback instead of following every pointer motion.
glow_dirty: bool = false,
caret_activity: usize = 0,
+ /// Lines an edit moved, gliding to their new places (see `reflow.zig`).
+ reflow: reflow_mod.Reflow = .{},
+ /// The animation has a frame to paint; follows the display like `glow_dirty`.
+ reflow_dirty: bool = false,
+ /// The loop time of the frame being prepared, shared by the caret and the rows.
+ frame_ms: i64 = 0,
menu_open: bool = false,
menu_selected: ?usize = null,
menu_anchor: f64 = 0,
@@ -147,6 +154,7 @@ pub const App = struct {
self.clipboard.deinit(a);
self.preedit.deinit(a);
self.rows.deinit(a);
+ self.reflow.deinit();
self.layouts.deinit();
}
pub fn current(self: *App) *Tab {
@@ -195,6 +203,7 @@ pub const App = struct {
pub const CaretState = app_paint.CaretState;
pub const caretState = app_paint.caretState;
pub const stepCaret = app_paint.stepCaret;
+ pub const stepReflow = app_paint.stepReflow;
pub const caretDamage = app_paint.caretDamage;
pub const paintCaret = app_paint.paintCaret;
pub const tabRight = app_paint.tabRight;
diff --git a/src/editor/app_paint.zig b/src/editor/app_paint.zig
index a9936e8..e5a1740 100644
--- a/src/editor/app_paint.zig
+++ b/src/editor/app_paint.zig
@@ -13,6 +13,8 @@ const dialog = @import("ui").widgets.dialog;
const menu = @import("ui").context_menu;
const p = @import("pango.zig");
const caret_mod = @import("caret.zig");
+const reflow_mod = @import("reflow.zig");
+const input = @import("ui").input;
const view = @import("view.zig");
const lines = @import("lines.zig");
const app_mod = @import("app.zig");
@@ -76,10 +78,38 @@ pub fn stepCaret(self: *App, now: i64, active: bool, restart: bool, snap: bool)
if (self.find_open) {
if (self.layouts.cr) |cr| target = self.searchCaret(cr);
}
- if (self.caret.update(now, active, restart, target, snap or self.caret_snap)) self.caret_dirty = true;
+ if (self.caret.update(now, active, restart, target, snap or self.caret_snap, caretShift(self, now))) self.caret_dirty = true;
self.caret_snap = false;
}
+/// How far the line holding the cursor is from rest, for a caret that rides it.
+fn caretShift(self: *App, now: i64) caret_mod.Shift {
+ // The find bar's caret sits in its own box, not in a line.
+ if (self.find_open or !self.reflow.moving(now)) return .{};
+ const row = self.port().locate(self.document().cursor) orelse return .{ .active = true };
+ const o = self.reflow.offset(row.line.seg.start, now).snapped(@floatFromInt(self.scale));
+ return .{ .dx = o.dx, .dy = o.dy, .active = true };
+}
+
+fn reflowKey(self: *App) reflow_mod.Key {
+ return .{ .tab = self.tabId(), .epoch = self.layouts.epoch, .width = @floatFromInt(self.w) };
+}
+
+/// Starts the glide of lines an edit moved and advances one in flight. Runs
+/// before `stepCaret` in each pass of the loop: the caret rides its line.
+pub fn stepReflow(self: *App, now: i64) void {
+ self.frame_ms = now;
+ if (self.document().takeChange()) |change| {
+ const pt = self.port();
+ pt.clamp();
+ pt.visible(&self.rows);
+ const motion = input.caret_config.motion_ms;
+ _ = self.reflow.apply(now, motion + motion / 2, reflowKey(self), change, self.rows.items);
+ }
+ // One more frame once it ends, so the lines are drawn at rest.
+ if (self.reflow.settle(now) or self.reflow.moving(now)) self.reflow_dirty = true;
+}
+
pub fn caretDamage(self: *App) p.Rectangle {
const before = self.caret_painted;
const after = self.caret.box;
@@ -209,7 +239,17 @@ pub fn render(self: *App, cr: *c.cairo_t) void {
c.cairo_save(cr);
c.cairo_rectangle(cr, 12, self.viewTop(), @floatFromInt(self.w - 30), self.viewHeight());
c.cairo_clip(cr);
- for (self.rows.items) |row| self.paintLine(cr, tab, row, sel);
+ for (self.rows.items) |row| {
+ const o = self.reflow.offset(row.line.seg.start, self.frame_ms).snapped(@floatFromInt(self.scale));
+ // A line carried in from elsewhere fades in over the line it passes.
+ if (o.alpha < 1) c.cairo_push_group(cr);
+ self.paintLine(cr, tab, row, sel, o);
+ if (o.alpha < 1) {
+ c.cairo_pop_group_to_source(cr);
+ c.cairo_paint_with_alpha(cr, o.alpha);
+ }
+ }
+ self.reflow.remember(reflowKey(self), tab.doc.text.items.len, self.rows.items);
if (!self.find_open) self.paintCaret(cr);
c.cairo_restore(cr);
if (self.scrollbarGeometry()) |bar| ui.drawScrollbar(cr, scrollbar.look(bar, self.bar_appearance, theme.global.scrollbar_width, theme.shellPalette()));
@@ -232,7 +272,7 @@ pub fn render(self: *App, cr: *c.cairo_t) void {
}
/// Draws one segment's selection, text and any preedit at the cursor.
-pub fn paintLine(self: *App, cr: *c.cairo_t, tab: *Tab, row: view.Row, sel: [2]usize) void {
+pub fn paintLine(self: *App, cr: *c.cairo_t, tab: *Tab, row: view.Row, sel: [2]usize, shift: reflow_mod.Offset) void {
const t = theme.global;
const l = row.line;
const seg = l.seg;
@@ -240,7 +280,8 @@ pub fn paintLine(self: *App, cr: *c.cairo_t, tab: *Tab, row: view.Row, sel: [2]u
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 row_y = row.y + shift.dy;
+ c.cairo_translate(cr, 16 - tab.scroll_x + shift.dx, 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
@@ -258,8 +299,8 @@ pub fn paintLine(self: *App, cr: *c.cairo_t, tab: *Tab, row: view.Row, sel: [2]u
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) {
+ 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);
diff --git a/src/editor/caret.zig b/src/editor/caret.zig
index b7e64b8..933996b 100644
--- a/src/editor/caret.zig
+++ b/src/editor/caret.zig
@@ -2,25 +2,32 @@
const std = @import("std");
const input = @import("ui").input;
pub const Rect = struct { x: f32 = 0, y: f32 = 0, w: f32 = 1.5, h: f32 = 18 };
+/// How far the line holding the caret is from rest while lines glide after an
+/// edit (`reflow.zig`): the caret rides along, solid, instead of animating itself.
+pub const Shift = struct { dx: f32 = 0, dy: f32 = 0, active: bool = false };
pub const Caret = struct {
motion: input.Caret = .{},
+ /// Where the caret is drawn; `rest` is where it sits once lines stop moving.
box: Rect = .{},
+ rest: Rect = .{},
visible: bool = false,
deadline_ms: ?i64 = null,
- pub fn update(self: *Caret, now: i64, active: bool, restart: bool, target: Rect, snap: bool) bool {
+ pub fn update(self: *Caret, now: i64, active: bool, restart: bool, target: Rect, snap: bool, shift: Shift) bool {
const previous = self.box;
const was_visible = self.visible;
if (restart) self.motion.noteEdit(now);
// A different line, viewport or field must never sweep through text.
- if (snap or !active or target.y != self.box.y or target.h != self.box.h) self.motion.snap = true;
+ if (snap or !active or target.y != self.rest.y or target.h != self.rest.h) self.motion.snap = true;
self.motion.track(now, target.x);
+ self.rest = target;
self.box = target;
- self.box.x = self.motion.offset(now);
- self.visible = active and self.motion.visible(now);
+ self.box.x = self.motion.offset(now) + shift.dx;
+ self.box.y = target.y + shift.dy;
+ self.visible = active and (shift.active or self.motion.visible(now));
self.deadline_ms = null;
if (active) {
- if (self.motion.moving(now)) {
+ if (shift.active or self.motion.moving(now)) {
self.deadline_ms = now + 8;
} else if (input.caret_config.blink_ms >= 2 and !self.motion.blinkExpired(now)) {
const half: i64 = @intCast(input.caret_config.blink_ms / 2);
@@ -41,39 +48,55 @@ pub const Caret = struct {
test "caret glides like search, snaps lines and bursts, and stops waking on blur and idle" {
var caret: Caret = .{};
const target: Rect = .{ .x = 10, .y = 40 };
- try std.testing.expect(caret.update(100, true, true, target, true));
+ try std.testing.expect(caret.update(100, true, true, target, true, .{}));
try std.testing.expectEqual(@as(c_int, 530), caret.timeout(100, -1));
- try std.testing.expect(caret.update(630, true, false, target, false));
+ try std.testing.expect(caret.update(630, true, false, target, false, .{}));
try std.testing.expect(!caret.visible);
var next = target;
next.x = 30;
- _ = caret.update(700, true, true, next, false);
- _ = caret.update(720, true, false, next, false);
+ _ = caret.update(700, true, true, next, false, .{});
+ _ = caret.update(720, true, false, next, false, .{});
try std.testing.expect(caret.box.x > 10 and caret.box.x < 30);
try std.testing.expect(caret.visible);
try std.testing.expect(caret.timeout(720, -1) <= 8);
next.x = 40;
- _ = caret.update(730, true, true, next, false);
+ _ = caret.update(730, true, true, next, false, .{});
try std.testing.expectEqual(next.x, caret.box.x); // repeat burst catches up
next.y = 60;
next.x = 10;
- _ = caret.update(900, true, true, next, false);
+ _ = caret.update(900, true, true, next, false, .{});
try std.testing.expectEqual(next, caret.box);
- _ = caret.update(10_900, true, false, next, false);
+ _ = caret.update(10_900, true, false, next, false, .{});
try std.testing.expect(caret.visible and caret.deadline_ms == null);
- _ = caret.update(10_901, false, true, next, false);
+ _ = caret.update(10_901, false, true, next, false, .{});
try std.testing.expect(!caret.visible and caret.deadline_ms == null);
}
+test "a caret riding a gliding line follows it, stays solid and wakes the loop" {
+ var caret: Caret = .{};
+ const target: Rect = .{ .x = 16, .y = 60 };
+ _ = caret.update(100, true, true, target, true, .{});
+ // Enter at the end of a line: the line starts far right and one row up.
+ _ = caret.update(2000, true, true, target, false, .{ .dx = 200, .dy = -18, .active = true });
+ try std.testing.expectEqual(@as(f32, 216), caret.box.x);
+ try std.testing.expectEqual(@as(f32, 42), caret.box.y);
+ try std.testing.expect(caret.visible);
+ try std.testing.expect(caret.timeout(2000, -1) <= 8);
+ // The line arrives; the caret rests on its target and blinks again.
+ _ = caret.update(2100, true, false, target, false, .{});
+ try std.testing.expectEqual(target, caret.box);
+ try std.testing.expect(caret.timeout(2100, -1) > 8);
+}
+
test "disabled blink is solid and zero idle timeout blinks indefinitely" {
const saved = input.caret_config;
defer input.caret_config = saved;
input.caret_config.blink_ms = 0;
var caret: Caret = .{};
- _ = caret.update(100, true, true, .{}, true);
+ _ = caret.update(100, true, true, .{}, true, .{});
try std.testing.expect(caret.visible and caret.deadline_ms == null);
input.caret_config = .{ .blink_timeout_s = 0 };
- _ = caret.update(0, true, true, .{}, true);
- _ = caret.update(106_530, true, false, .{}, false);
+ _ = caret.update(0, true, true, .{}, true, .{});
+ _ = caret.update(106_530, true, false, .{}, false, .{});
try std.testing.expect(!caret.visible and caret.deadline_ms != null);
}
diff --git a/src/editor/client_render.zig b/src/editor/client_render.zig
index 69c1246..bcf71f9 100644
--- a/src/editor/client_render.zig
+++ b/src/editor/client_render.zig
@@ -30,9 +30,11 @@ pub fn acquireBuffer(self: *Client, w: i32, h: i32) !?*Buffer {
pub fn render(self: *Client) !void {
self.updateCursor();
- if (!self.configured or (!self.app.dirty and !self.app.caret_dirty and !self.app.glow_dirty) or self.outstanding >= 2) return;
- if (!self.app.dirty and !self.app.caret_dirty and self.frame_callback != null) return;
- const full = self.app.dirty or self.app.glow_dirty;
+ if (!self.configured or (!self.app.dirty and !self.app.caret_dirty and !self.app.glow_dirty and !self.app.reflow_dirty) or self.outstanding >= 2) return;
+ // Glow and gliding lines follow the display, not the loop's own timer; the
+ // caret moving with them must not make them run ahead of it.
+ if (!self.app.dirty and self.frame_callback != null and (!self.app.caret_dirty or self.app.reflow_dirty)) return;
+ const full = self.app.dirty or self.app.glow_dirty or self.app.reflow_dirty;
const tbh = self.titlebarHeight();
const w = self.app.w;
@@ -95,6 +97,7 @@ pub fn render(self: *Client) !void {
self.app.dirty = false;
self.app.caret_dirty = false;
self.app.glow_dirty = false;
+ self.app.reflow_dirty = false;
self.app.caret_painted = self.app.caret.box;
}
diff --git a/src/editor/document.zig b/src/editor/document.zig
index 5b9ebc7..28448e6 100644
--- a/src/editor/document.zig
+++ b/src/editor/document.zig
@@ -22,6 +22,26 @@ const Edit = struct {
a.free(e.after);
}
};
+/// Which part of the text an edit left alone: the first `lo` bytes and the
+/// last `suffix` bytes are the same before and after, so a position in either
+/// can be mapped between the old and the new text. Edits since the last
+/// `takeChange` are merged into one span.
+pub const Change = struct {
+ lo: usize,
+ suffix: usize,
+ old_len: usize,
+ new_len: usize,
+
+ /// End of the changed part of the new text.
+ pub fn hi(c: Change) usize {
+ return c.new_len - c.suffix;
+ }
+ /// The offset in the old text of the byte now at `new`, which must be at
+ /// or after `hi()`.
+ pub fn oldAfter(c: Change, new: usize) usize {
+ return new + c.old_len - c.new_len;
+ }
+};
pub const Document = struct {
text: std.ArrayList(u8) = .empty,
cursor: usize = 0,
@@ -42,6 +62,9 @@ pub const Document = struct {
/// 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 } = .{},
+ /// What edits changed since `takeChange`; the view uses it to glide the
+ /// lines an edit moved instead of snapping them.
+ change: ?Change = null,
pub fn deinit(d: *Document) void {
d.text.deinit(a);
@@ -112,6 +135,7 @@ pub const Document = struct {
if (size > limit) return error.FileTooLarge;
try d.text.ensureTotalCapacity(a, size);
d.retarget(at, len, bytes);
+ d.noteChange(at, len, bytes.len);
const old = d.text.items.len;
if (size > old) d.text.items.len = size;
@memmove(d.text.items[at + bytes.len .. size], d.text.items[at + len .. old]);
@@ -119,6 +143,21 @@ pub const Document = struct {
@memcpy(d.text.items[at..][0..bytes.len], bytes);
d.revision +%= 1;
}
+ fn noteChange(d: *Document, at: usize, len: usize, added: usize) void {
+ const old = d.text.items.len;
+ const tail = old - at - len;
+ d.change = if (d.change) |c| .{
+ .lo = @min(c.lo, at),
+ .suffix = @min(c.suffix, tail),
+ .old_len = c.old_len,
+ .new_len = old - len + added,
+ } else .{ .lo = at, .suffix = tail, .old_len = old, .new_len = old - len + added };
+ }
+ /// The merged span of every edit since the last call, then forgets it.
+ pub fn takeChange(d: *Document) ?Change {
+ defer d.change = null;
+ return d.change;
+ }
/// 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 {
@@ -358,6 +397,34 @@ test "line numbers and the view anchor survive edits across waypoints" {
try std.testing.expectEqualStrings(source.items, d.text.items);
}
+test "edits since the last look merge into one span of what they left alone" {
+ var d = try Document.init("0123456789");
+ defer d.deinit();
+ try std.testing.expectEqual(@as(?Change, null), d.takeChange());
+ d.move(4, false);
+ try d.insert("ab");
+ const one = d.takeChange().?;
+ try std.testing.expectEqual(Change{ .lo = 4, .suffix = 6, .old_len = 10, .new_len = 12 }, one);
+ // The "4" that followed the edit was at 4 and is now at 6.
+ try std.testing.expectEqual(@as(usize, 6), one.hi());
+ try std.testing.expectEqual(@as(usize, 4), one.oldAfter(6));
+ try std.testing.expectEqual(@as(?Change, null), d.takeChange());
+ // Two edits, the second before and shorter: one span covering both.
+ try d.insert("c");
+ d.move(1, false);
+ d.anchor = 2;
+ try d.insert("");
+ try d.insert("xyz");
+ const two = d.takeChange().?;
+ try std.testing.expectEqual(@as(usize, 1), two.lo);
+ try std.testing.expectEqual(@as(usize, 6), two.suffix);
+ try std.testing.expectEqual(@as(usize, 12), two.old_len);
+ try std.testing.expectEqual(d.text.items.len, two.new_len);
+ // Undo is an edit too.
+ try d.undo(false);
+ try std.testing.expect(d.takeChange() != null);
+}
+
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]);
diff --git a/src/editor/main.zig b/src/editor/main.zig
index d2ab7fa..513b521 100644
--- a/src/editor/main.zig
+++ b/src/editor/main.zig
@@ -302,6 +302,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo
before.top != caret_state.top or before.dy != caret_state.dy or before.scroll_x != caret_state.scroll_x or
before.width != caret_state.width or before.height != caret_state.height or before.scale != caret_state.scale else true;
self.caret_state = caret_state;
+ self.app.stepReflow(now);
self.app.stepCaret(now, caret_state.active, restart, snap);
try self.render();
if (self.configured and self.applied_scale > 0 and pending_token.len > 0) {
diff --git a/src/editor/reflow.zig b/src/editor/reflow.zig
new file mode 100644
index 0000000..e2b2aa0
--- /dev/null
+++ b/src/editor/reflow.zig
@@ -0,0 +1,370 @@
+//! Glides the lines an edit moved. Enter pushes every line below it down and
+//! carries the rest of its line onto a new one; Backspace joining two lines,
+//! deleting lines, undo or a word that now wraps move lines too. Instead of
+//! snapping, each visible line that changed place is drawn where it was and
+//! eased to where it is, over the caret's motion time, and the caret rides the
+//! line it sits in.
+//!
+//! Layout never animates: rows are laid out and hit-tested at rest. A `Move`
+//! is only a paint offset for the row starting at one byte offset, and it ends
+//! with the animation. Rows are matched to the lines of the previous frame
+//! through the span an edit left alone (`Document.Change`): a row before it
+//! keeps its start, a row after it starts `new_len - old_len` bytes later.
+const std = @import("std");
+const anim = @import("ui").anim;
+const p = @import("pango.zig");
+const view = @import("view.zig");
+const Change = @import("document.zig").Change;
+const a = std.heap.c_allocator;
+
+/// A line that would have to travel further than this vertically is a jump,
+/// not a glide (the caret's own rule, see `input.caret_snap_distance`), so the
+/// whole edit snaps.
+pub const max_glide: f64 = 120;
+
+/// Where a row is drawn relative to its rest place.
+pub const Offset = struct {
+ dx: f32 = 0,
+ dy: f32 = 0,
+ alpha: f32 = 1,
+
+ /// Whole device pixels: a fractional offset re-hints every glyph.
+ pub fn snapped(o: Offset, scale: f32) Offset {
+ return .{ .dx = @round(o.dx * scale) / scale, .dy = @round(o.dy * scale) / scale, .alpha = o.alpha };
+ }
+};
+
+/// What the remembered rows belong to: a different tab, or layouts that were
+/// rebuilt (resize, font, wrapping), make them meaningless.
+pub const Key = struct { tab: usize, epoch: usize, width: f64 };
+
+const Shown = struct { start: usize, next: usize, y: f64 };
+const Move = struct { start: usize, dx: f32, dy: f32, fade: bool };
+
+pub const Reflow = struct {
+ /// The visible rows as last laid out, in order: where each began and its
+ /// rest place. Where it was drawn is that plus whatever `moves` still has.
+ shown: std.ArrayList(Shown) = .empty,
+ moves: std.ArrayList(Move) = .empty,
+ /// 1 when an edit lands, easing to 0 when every row is at rest.
+ clock: anim.Anim = .{},
+ key: Key = .{ .tab = 0, .epoch = 0, .width = 0 },
+ /// Length of the text `shown` describes; null until a frame was seen.
+ len: ?usize = null,
+
+ pub fn deinit(r: *Reflow) void {
+ r.shown.deinit(a);
+ r.moves.deinit(a);
+ }
+
+ /// Drops what was remembered and whatever is moving.
+ pub fn forget(r: *Reflow) void {
+ r.shown.clearRetainingCapacity();
+ r.moves.clearRetainingCapacity();
+ r.len = null;
+ }
+
+ pub fn moving(r: *const Reflow, now: i64) bool {
+ return r.moves.items.len > 0 and !r.clock.settled(now);
+ }
+
+ /// Ends a finished animation. True once, when it ends, so the rows are
+ /// drawn once more at rest.
+ pub fn settle(r: *Reflow, now: i64) bool {
+ if (r.moves.items.len == 0 or !r.clock.settled(now)) return false;
+ r.moves.clearRetainingCapacity();
+ return true;
+ }
+
+ /// Where the row beginning at byte `start` is drawn now, relative to rest.
+ pub fn offset(r: *const Reflow, start: usize, now: i64) Offset {
+ if (!r.moving(now)) return .{};
+ const left = r.clock.value(now);
+ for (r.moves.items) |m| {
+ if (m.start != start) continue;
+ return .{ .dx = m.dx * left, .dy = m.dy * left, .alpha = if (m.fade) 1 - left else 1 };
+ }
+ return .{};
+ }
+
+ /// Remembers the rows just laid out, so the next edit can start from
+ /// where they are on screen. Call it when a frame is drawn.
+ pub fn remember(r: *Reflow, key: Key, len: usize, rows: []const view.Row) void {
+ r.shown.clearRetainingCapacity();
+ r.key = key;
+ r.len = len;
+ for (rows) |row| {
+ r.shown.append(a, .{ .start = row.line.seg.start, .next = row.line.seg.next, .y = row.y }) catch return r.forget();
+ }
+ }
+
+ /// Where a remembered row is drawn at `now`.
+ const Found = struct { start: usize, dx: f64, y: f64 };
+
+ /// The remembered row holding old offset `o`, as drawn at `now`.
+ fn find(r: *const Reflow, o: usize, now: i64) ?Found {
+ var low: usize = 0;
+ var high = r.shown.items.len;
+ while (low < high) {
+ const mid = (low + high) / 2;
+ if (r.shown.items[mid].start <= o) low = mid + 1 else high = mid;
+ }
+ if (low == 0) return null;
+ const row = r.shown.items[low - 1];
+ if (o > row.next or (o == row.next and row.next != r.len)) return null;
+ const at = r.offset(row.start, now);
+ return .{ .start = row.start, .dx = at.dx, .y = row.y + at.dy };
+ }
+
+ /// Starts moving the rows an `edit` displaced; `rows` are the visible rows
+ /// of the new text, at rest. Returns whether anything glides. If not
+ /// (nothing moved, it moved too far, lines with new text appeared, motion
+ /// is off) every row is at rest. Either way the new rows are remembered.
+ pub fn apply(r: *Reflow, now: i64, ms: u32, key: Key, edit: Change, rows: []const view.Row) bool {
+ const glided = r.plan(now, ms, key, edit, rows);
+ if (!glided) r.moves.clearRetainingCapacity();
+ r.remember(key, edit.new_len, rows);
+ return glided;
+ }
+
+ fn plan(r: *Reflow, now: i64, ms: u32, key: Key, edit: Change, rows: []const view.Row) bool {
+ const known = r.len orelse return false;
+ if (known != edit.old_len or r.key.tab != key.tab or r.key.epoch != key.epoch) return false;
+ const clock = anim.Anim.initDuration(1, 0, now, ms, .out_cubic);
+ if (ms == 0 or clock.completesInstantly()) return false;
+ var moves: std.ArrayList(Move) = .empty;
+ var keep = false;
+ defer if (!keep) moves.deinit(a);
+ const lo = edit.lo;
+ const hi = edit.hi();
+ // Where the previous row was drawn relative to rest: the text after a
+ // line break starts where the text before it ended.
+ var before: Offset = .{};
+ for (rows, 0..) |row, i| {
+ const n = row.line.seg.start;
+ const m = row.line.seg.next;
+ var here: Offset = .{};
+ var fade = false;
+ if (n < lo or (n == lo and m > hi)) {
+ // Before the edit, or the line it happened in: the same line.
+ if (r.find(n, now)) |at| if (at.start == n) {
+ here = .{ .dx = @floatCast(at.dx), .dy = @floatCast(at.y - row.y) };
+ };
+ } else if (n < hi or (n == lo and m <= hi)) {
+ // A line the edit made: nothing to glide from, and drawing
+ // it at once would overprint the line it pushes down.
+ if (row.line.textLen() > 0) return false;
+ } else if (r.find(edit.oldAfter(n), now)) |at| {
+ if (at.start == edit.oldAfter(n)) {
+ here = .{ .dx = @floatCast(at.dx), .dy = @floatCast(at.y - row.y) };
+ } else if (n == hi and i > 0 and rows[i - 1].line.seg.next == n and rows[i - 1].line.seg.terminated()) {
+ // The rest of a line that was split starts where the
+ // text before the break now ends.
+ const above = rows[i - 1];
+ var end: p.Rectangle = undefined;
+ p.pango_layout_get_cursor_pos(above.line.layout, @intCast(above.line.textLen()), &end, null);
+ here = .{
+ .dx = before.dx + @as(f32, @floatFromInt(end.x)) / 1024,
+ .dy = @floatCast(above.y + before.dy + @as(f64, @floatFromInt(end.y)) / 1024 - row.y),
+ };
+ fade = true;
+ }
+ }
+ before = here;
+ if (@abs(here.dy) > max_glide or @abs(here.dx) > key.width) return false;
+ if (!fade and @abs(here.dx) < 0.5 and @abs(here.dy) < 0.5) continue;
+ moves.append(a, .{ .start = n, .dx = here.dx, .dy = here.dy, .fade = fade }) catch return false;
+ }
+ if (moves.items.len == 0) return false;
+ keep = true;
+ r.moves.deinit(a);
+ r.moves = moves;
+ r.clock = clock;
+ return true;
+ }
+};
+
+fn testLayouts() view.Layouts {
+ var l: view.Layouts = .{};
+ l.configure("monospace", 13, 400, 1);
+ return l;
+}
+
+/// A document, the layouts of its rows and a `Reflow` watching them.
+const Scene = struct {
+ doc: @import("document.zig").Document,
+ layouts: view.Layouts,
+ dy: f64 = 0,
+ rows: std.ArrayList(view.Row) = .empty,
+ reflow: Reflow = .{},
+
+ fn init(text: []const u8) !Scene {
+ return .{ .doc = try @import("document.zig").Document.init(text), .layouts = testLayouts() };
+ }
+ fn deinit(s: *Scene) void {
+ s.reflow.deinit();
+ s.rows.deinit(a);
+ s.layouts.deinit();
+ s.doc.deinit();
+ }
+ fn key(s: *const Scene) Key {
+ return .{ .tab = 1, .epoch = s.layouts.epoch, .width = 400 };
+ }
+ fn show(s: *Scene) void {
+ const port: view.Port = .{ .doc = &s.doc, .layouts = &s.layouts, .height = 300, .dy = &s.dy };
+ port.clamp();
+ port.visible(&s.rows);
+ }
+ fn height(s: *const Scene) f32 {
+ return @floatCast(s.rows.items[0].line.height);
+ }
+ /// Draws the first frame, so there is something to glide from.
+ fn start(s: *Scene) void {
+ s.show();
+ s.reflow.forget();
+ s.reflow.remember(s.key(), s.doc.text.items.len, s.rows.items);
+ }
+ fn edit(s: *Scene, now: i64) bool {
+ s.show();
+ return s.reflow.apply(now, 120, s.key(), s.doc.takeChange().?, s.rows.items);
+ }
+ fn at(s: *const Scene, row: usize, now: i64) Offset {
+ return s.reflow.offset(s.rows.items[row].line.seg.start, now);
+ }
+};
+
+test "Enter carries the rest of the line down and pushes later lines after it" {
+ var s = try Scene.init("abcdef\nlast");
+ defer s.deinit();
+ s.start();
+ s.doc.move(3, false);
+ try s.doc.insert("\n");
+ try std.testing.expect(s.edit(1000));
+ try std.testing.expectEqual(@as(usize, 3), s.rows.items.len);
+ const h = s.height();
+ // The old last line was one line higher, and has not moved sideways.
+ try std.testing.expectApproxEqAbs(-h, s.at(2, 1000).dy, 0.01);
+ try std.testing.expectEqual(@as(f32, 0), s.at(2, 1000).dx);
+ try std.testing.expectEqual(@as(f32, 1), s.at(2, 1000).alpha);
+ // The tail starts right after "abc" on the first line, and fades in.
+ const tail = s.at(1, 1000);
+ try std.testing.expectApproxEqAbs(-h, tail.dy, 0.01);
+ try std.testing.expect(tail.dx > 10);
+ try std.testing.expectEqual(@as(f32, 0), tail.alpha);
+ // The line the edit happened in does not move.
+ try std.testing.expectEqual(Offset{}, s.at(0, 1000));
+ // It eases out: a quarter of the way in, most of the distance is covered.
+ const early = s.at(2, 1030);
+ try std.testing.expect(early.dy < 0 and early.dy > -h / 2);
+ try std.testing.expect(s.reflow.moving(1100));
+ try std.testing.expect(!s.reflow.moving(1200));
+ try std.testing.expect(s.reflow.settle(1200));
+ try std.testing.expect(!s.reflow.settle(1200));
+ try std.testing.expectEqual(Offset{}, s.at(2, 1200));
+}
+
+test "Enter at the start or end of a line glides without a sideways jump" {
+ var s = try Scene.init("abc\ndef");
+ defer s.deinit();
+ s.start();
+ s.doc.move(0, false);
+ try s.doc.insert("\n");
+ try std.testing.expect(s.edit(0));
+ // "abc" was on the first line and is now on the second.
+ try std.testing.expectApproxEqAbs(-s.height(), s.at(1, 0).dy, 0.01);
+ try std.testing.expectEqual(@as(f32, 0), s.at(1, 0).dx);
+ try std.testing.expectEqual(@as(f32, 1), s.at(1, 0).alpha);
+
+ var end = try Scene.init("abc\ndef");
+ defer end.deinit();
+ end.start();
+ end.doc.move(end.doc.lineEnd(0), false);
+ try end.doc.insert("\n");
+ try std.testing.expect(end.edit(0));
+ // The new line is empty, but the caret still rides it from the line end.
+ try std.testing.expect(end.at(1, 0).dx > 10);
+ try std.testing.expectApproxEqAbs(-end.height(), end.at(1, 0).dy, 0.01);
+}
+
+test "joining lines glides the lines below up; typing glides nothing" {
+ var s = try Scene.init("abc\ndef\nghi");
+ defer s.deinit();
+ s.start();
+ s.doc.cursor = 4;
+ s.doc.anchor = 3;
+ try s.doc.insert("");
+ try std.testing.expect(s.edit(0));
+ try std.testing.expectEqual(@as(usize, 2), s.rows.items.len);
+ try std.testing.expectApproxEqAbs(s.height(), s.at(1, 0).dy, 0.01);
+ try std.testing.expectEqual(Offset{}, s.at(0, 0));
+
+ var typing = try Scene.init("abc\ndef\nghi");
+ defer typing.deinit();
+ typing.start();
+ try typing.doc.insert("x");
+ try std.testing.expect(!typing.edit(0));
+ try std.testing.expect(!typing.reflow.moving(0));
+}
+
+test "edits that cannot glide snap: new lines with text, far moves, other tabs, motion off" {
+ var pasted = try Scene.init("abc\ndef");
+ defer pasted.deinit();
+ pasted.start();
+ try pasted.doc.insert("one\ntwo\n");
+ try std.testing.expect(!pasted.edit(0));
+ try std.testing.expectEqual(@as(usize, 0), pasted.reflow.moves.items.len);
+
+ // A few empty lines glide; enough to push a line across the window do not.
+ const lines = try std.testing.allocator.alloc(u8, 83);
+ defer std.testing.allocator.free(lines);
+ for (0..40) |i| @memcpy(lines[i * 2 ..][0..2], "a\n");
+ @memcpy(lines[80..], "end");
+ var many = try Scene.init(lines);
+ defer many.deinit();
+ many.start();
+ try many.doc.insert("\n\n");
+ try std.testing.expect(many.edit(0));
+ many.start();
+ try many.doc.insert("\n\n\n\n\n\n\n\n\n\n\n\n");
+ try std.testing.expect(!many.edit(0));
+
+ var other = try Scene.init("abc");
+ defer other.deinit();
+ other.start();
+ try other.doc.insert("\n");
+ other.show();
+ var key = other.key();
+ key.tab = 2;
+ try std.testing.expect(!other.reflow.apply(0, 120, key, other.doc.takeChange().?, other.rows.items));
+
+ var still = try Scene.init("abc");
+ defer still.deinit();
+ still.start();
+ try still.doc.insert("\n");
+ still.show();
+ try std.testing.expect(!still.reflow.apply(0, 0, still.key(), still.doc.takeChange().?, still.rows.items));
+
+ // Changes that were not seen from the start of the text are refused.
+ var unseen = try Scene.init("abc");
+ defer unseen.deinit();
+ unseen.start();
+ try unseen.doc.insert("x");
+ _ = unseen.doc.takeChange();
+ try unseen.doc.insert("\n");
+ try std.testing.expect(!unseen.edit(0));
+}
+
+test "a second edit during a glide continues from where the rows are drawn" {
+ var s = try Scene.init("abc\ndef");
+ defer s.deinit();
+ s.start();
+ try s.doc.insert("\n");
+ try std.testing.expect(s.edit(1000));
+ const h = s.height();
+ const drawn = s.at(2, 1030);
+ try std.testing.expect(drawn.dy < 0 and drawn.dy > -h);
+ try s.doc.insert("\n");
+ try std.testing.expect(s.edit(1030));
+ // The last line starts the new glide where the old one had left it.
+ try std.testing.expectApproxEqAbs(drawn.dy - h, s.at(3, 1030).dy, 0.01);
+}
diff --git a/src/editor_tests.zig b/src/editor_tests.zig
index 65a632f..bdce040 100644
--- a/src/editor_tests.zig
+++ b/src/editor_tests.zig
@@ -5,6 +5,7 @@ test {
_ = @import("editor/document_search.zig");
_ = @import("editor/drafts_tests.zig");
_ = @import("editor/lines.zig");
+ _ = @import("editor/reflow.zig");
_ = @import("editor/view.zig");
_ = @import("editor/operation.zig");
}
diff --git a/src/ui/input_caret.zig b/src/ui/input_caret.zig
index c2db659..7195eb9 100644
--- a/src/ui/input_caret.zig
+++ b/src/ui/input_caret.zig
@@ -20,7 +20,8 @@ pub const CaretConfig = struct {
/// 0 means blink forever, which costs a repaint every half cycle for as
/// long as the field keeps focus.
blink_timeout_s: u32 = 10,
- /// Glide duration when the caret moves. 0 snaps.
+ /// Glide duration when the caret moves. 0 snaps. The editor's lines glide
+ /// 1.5 times as long when an edit moves them (`editor/reflow.zig`).
motion_ms: u32 = 80,
};
diff --git a/tests/editor_visuals.py b/tests/editor_visuals.py
index 145587d..3146b19 100644
--- a/tests/editor_visuals.py
+++ b/tests/editor_visuals.py
@@ -227,6 +227,64 @@ def run():
time.sleep(.7)
assert switches()==before, 'caret timer keeps waking the idle editor'
print('caret becomes solid and makes no idle wakeups',flush=True)
+ # Enter pushes the lines below it down and joining lines pulls
+ # them up. Both glide, over the caret's motion time plus half
+ # (600 ms here), instead of snapping.
+ text_top=box['y']+40+(46 if csd else 0)
+ def last_row_y():
+ shot=capture()
+ factor=shot.width/ipc.get_outputs()[0]['logical_width']
+ region=(round((box['x']+20)*factor), round(text_top*factor), round((box['x']+120)*factor), round((text_top+200)*factor))
+ # Text is the only bright, uncoloured thing in this strip.
+ ink=shot.crop(region).convert('L').point(lambda value: 255 if value > 155 else 0).getbbox()
+ assert ink, 'no text painted'
+ return (region[1]+ink[3])/factor, shot
+ def glide(press, name):
+ """Rest, a frame 100-150 ms into the glide, then rest again.
+ A screenshot shows the frame at the time it was asked for,
+ so the sample lands well inside the 600 ms."""
+ rest,_=last_row_y()
+ press()
+ time.sleep(.1)
+ middle,shot=last_row_y()
+ if os.environ.get('REDIWM_EDITOR_VISUALS'):
+ shot.save(Path(os.environ['REDIWM_EDITOR_VISUALS'])/f'{name}-middle.png')
+ time.sleep(1)
+ final,_=last_row_y()
+ return rest,middle,final
+ for row in range(3):
+ if row:
+ ipc.key_down_up(28) # Return
+ ipc.type_text('mmmmmmmm')
+ time.sleep(.9)
+ for _ in range(2):
+ ipc.key_down_up(103) # Up to the first line.
+ for _ in range(4):
+ ipc.key_down_up(105) # Left into the middle of it.
+ time.sleep(.2)
+ # Which frame a screenshot shows depends on compositor timing, so
+ # a pair that was sampled too late is tried again; a snapping
+ # editor never shows an intermediate frame at all.
+ down=up=False
+ for attempt in range(3):
+ rest,middle,final=glide(lambda: ipc.key_down_up(28), 'enter')
+ line=final-rest
+ assert line > 8, f'Enter did not push the last line down: {rest} -> {final}'
+ down=down or rest+1 < middle < final-1
+ rest,middle,final=glide(lambda: ipc.key_down_up(14), 'join') # Backspace joins them again.
+ assert final < rest-8, f'joining lines did not pull the last line up: {rest} -> {final}'
+ assert abs((rest-final)-line) < 2, f'joining moved a different distance than Enter: {rest} -> {final}'
+ up=up or final+1 < middle < rest-1
+ if down and up: break
+ assert down, 'Enter snapped the lines instead of gliding'
+ print('Enter glides the lines below it down',flush=True)
+ assert up, 'joining snapped the lines instead of gliding'
+ print('Backspace joining lines glides the lines below it up',flush=True)
+ ipc.key(29,True)
+ ipc.key_down_up(30) # Ctrl+A
+ ipc.key(29,False)
+ ipc.key_down_up(111) # Delete everything again.
+ time.sleep(.9)
# A longer configured glide makes intermediate rendered
# positions observable without relying on screenshot latency.
ipc.type_text('m')
@@ -257,7 +315,7 @@ def run():
if row:
ipc.key_down_up(28) # Return; TypeText only inserts printable text.
ipc.type_text('mmmmmmmmmmmm')
- time.sleep(.2)
+ time.sleep(.9) # The last Return's lines are still gliding for 600 ms.
plain=capture()
if output := os.environ.get('REDIWM_EDITOR_PREVIEW'):
plain.save(output)