summaryrefslogtreecommitdiff
path: root/src/glide.zig
blob: ced0ca85f26f6fb5550ad01931b514ba299cd2b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! The view's glide (G6, anim 3, 9, 12): the text's picture following
//! its core's rows, one system on every shell. The GUI draws it at the
//! pixel; the tty at whole rows (panel_compositor.glideRows).

const std = @import("std");
const pardes = @import("pardes.zig");
const config = @import("config.zig");

/// G6 (docs/render-pipeline.md §9.1): whatever scrolls a text (a wheel's
/// lines, Ctrl-d, a page, G, n, a Look) scrolls the core at once, so every
/// key and click acts on where the text is, and the picture glides there
/// on the Motion flavour's spring (critically damped: text never passes its
/// mark), every distance on the same law. How far the rows moved is
/// measured on the next frame against the last, a line wrapped over several
/// rows or a terminal's output included, and the rows that left are kept to
/// draw in the gap. A move past what the two frames share (a page and more,
/// G) has no rows between them to show: the picture comes from the last
/// frame's body as if it lay just past the new one, one body away, so a
/// jump of any length reads as one body's slide.
///
/// The picture's motion is one system with its own state, integrated in
/// one place every frame (`advance`), and every scroll, whatever made it,
/// is an input into it (`kick`): it moves the target by the rows the core
/// moved and leaves the motion as it is. What the system was doing decides
/// how it is absorbed: inputs coming as a stream (each like the last, at a
/// steady spacing: a held key, a spun wheel) feed it, and it moves at the
/// stream's own rate, a lag of an input or so behind, never easing toward
/// each target (that was a bounce a line); an input into a resting view,
/// or against the way it moves, starts the spring from the speed it has
/// (an ease, a turn through zero); a jump mid-glide adds its rows with the
/// speed kept. The spring's settle only comes once the inputs stop.
pub const Glide = struct {
    /// The picture's lag behind the core's rows and its motion (rows).
    follow: pardes.animation.Follow = .{},
    now_ns: u64 = 0,
    pane: usize = 0,
    rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 },
    body_y: u16 = 0,
    body_h: u16 = 0,
    /// A scroll made and not yet measured: its direction, and the body's
    /// rows before it.
    pending: bool = false,
    dir: i8 = 0,
    before: []pardes.Cell = &.{},
    /// The rows past the body's top (`above`) and bottom (`below`), nearest
    /// first, `bw` cells each: what the gap shows while the picture lags.
    above: []pardes.Cell = &.{},
    below: []pardes.Cell = &.{},
    nabove: u16 = 0,
    nbelow: u16 = 0,
    /// The core's lines a scroll moved, not yet measured; and what the
    /// glide in flight has moved, in lines and in the picture's rows. A
    /// wrapped line is several rows, and the thumb counts lines.
    pending_lines: f32 = 0,
    lines_moved: f32 = 0,
    rows_moved: f32 = 0,
    /// The caret's row as the last frame drew it, and whether the move
    /// measured carried it with its line (a wheel's) or left it on its row
    /// (a page, a held key's): the tty draws a carried caret with the rows.
    caret_row: ?u16 = null,
    caret_rides: bool = false,
    /// The Motion flavour the last loop step read.
    motion: pardes.animation.Motion = .{},
    /// Each pane's view as the last loop step saw it (stepGlide): its
    /// serial, first line and file, so a view that moved since is found
    /// whatever moved it.
    seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i64 = 0, file: u64 = 0, revision: u32 = 0 } = @splat(.{}),

    /// The rows kept past each edge, in bodies, so a jump made while one
    /// glides carries on from where it is: as far as the picture may lag.
    pub const reach = pardes.animation.Follow.reach;

    pub fn moving(glide: *const Glide) bool {
        return glide.follow.moving() or glide.pending;
    }

    pub fn stop(glide: *Glide) void {
        glide.follow = .{ .at_ns = glide.follow.at_ns };
        glide.pending = false;
        glide.nabove = 0;
        glide.nbelow = 0;
        glide.pending_lines = 0;
        glide.lines_moved = 0;
        glide.rows_moved = 0;
    }

    /// The glide's lag in the core's lines: its rows, scaled by the lines
    /// they carried.
    pub fn lagLines(glide: *const Glide) f32 {
        if (glide.rows_moved == 0) return glide.follow.offset;
        return glide.follow.offset * glide.lines_moved / glide.rows_moved;
    }

    pub fn deinit(glide: *Glide, gpa: std.mem.Allocator) void {
        gpa.free(glide.before);
        gpa.free(glide.above);
        gpa.free(glide.below);
    }

    pub fn bw(glide: *const Glide) u16 {
        return glide.rect.w -| config.GUTTER;
    }

    /// The rules at this body's size: a tenth of a pixel is 5e-3 rows.
    pub fn pace(glide: *const Glide, motion: pardes.animation.Motion) pardes.animation.Follow.Pace {
        return pardes.animation.Follow.pace(motion, @floatFromInt(glide.body_h), 5e-3);
    }

    pub fn advance(glide: *Glide, now_ns: u64, motion: pardes.animation.Motion) void {
        glide.follow.advance(now_ns, glide.pace(motion));
    }

    /// Finds how far the pane's body rows moved, `dir` rows at a time, by
    /// the rows of `surface` against `before`; keeps the rows that left.
    pub fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void {
        glide.pending = false;
        const w = glide.bw();
        const h = glide.body_h;
        const x0 = glide.rect.x + config.GUTTER;
        if (w == 0 or h == 0 or x0 + w > surface.cols or glide.body_y + h > surface.rows or glide.before.len < @as(usize, w) * h) return glide.stop();
        const now = struct {
            fn row(s: *const pardes.Surface, x: u16, y: u16, n: u16) []const pardes.Cell {
                return s.cells[@as(usize, y) * s.cols + x ..][0..n];
            }
        };
        // The least shift under which the rows agree, but for a few: the
        // cursor's line and its number's weight move with the scroll. The
        // lines the core moved are tried first: unwrapped, they are the
        // rows, and one pass over the body settles it (the search over
        // every shift was 6 ms of the first frame of a page in Debug).
        const agrees = struct {
            fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool {
                if (kk == 0 or kk + 3 > height) return false;
                const allowed = @max(2, (height - kk) / 8);
                var misses: usize = 0;
                for (0..height - kk) |r| {
                    const rr: u16 = @intCast(r);
                    const old_row = gl.before[@as(usize, if (gl.dir > 0) rr + kk else rr) * width ..][0..width];
                    const new_row = now.row(surf, x, gl.body_y + if (gl.dir > 0) rr else rr + kk, width);
                    if (!sameRow(old_row, new_row)) {
                        misses += 1;
                        if (misses > allowed) return false;
                    }
                }
                return true;
            }
        };
        const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h))));
        // A body's lines or more: every row moved off, none in common.
        var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| {
            if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k);
        } else 0;
        // Rows that disagree under every shift though the core moved a few
        // lines: their colours changed as they moved (a paint arriving as a
        // spin stops). Unwrapped, the rows moved are the lines: glide those
        // (it landed from wherever it was, a snap at a spin's end).
        if (shift == 0 and guess > 0 and guess < h) shift = guess;
        // None in common: a body's move from the last frame's body, if the
        // lines moved are that many (rows that merely changed, a small
        // scroll the rows cannot show, land at once).
        if (shift == 0 and glide.pending_lines + 3 < @as(f32, @floatFromInt(h))) return glide.stop();
        const far = shift == 0;
        if (far) shift = h;
        glide.caret_rides = !far and if (glide.caret_row) |old| if (surface.cursor) |c|
            @as(i32, c.y) == @as(i32, old) - @as(i32, shift) * glide.dir
        else
            false else false;
        glide.rows_moved += @floatFromInt(shift);
        glide.lines_moved += glide.pending_lines;
        glide.pending_lines = 0;
        // The rows that left: past the top going down, the bottom going up.
        if (!glide.ensure(gpa)) return glide.stop();
        const keep = if (glide.dir > 0) &glide.above else &glide.below;
        const count = if (glide.dir > 0) &glide.nabove else &glide.nbelow;
        const kept = @min(count.*, h * reach - shift);
        std.mem.copyBackwards(pardes.Cell, keep.*[@as(usize, shift) * w ..][0 .. @as(usize, kept) * w], keep.*[0 .. @as(usize, kept) * w]);
        for (0..shift) |i| {
            const src_row: usize = if (glide.dir > 0) shift - 1 - i else h - shift + i;
            @memcpy(keep.*[i * w ..][0..w], glide.before[src_row * w ..][0..w]);
        }
        count.* = kept + shift;
        // What came into view is no longer past the other edge.
        const other = if (glide.dir > 0) &glide.below else &glide.above;
        const other_n = if (glide.dir > 0) &glide.nbelow else &glide.nabove;
        // ...and after a jump, the rows past it are another place's.
        const dropped = if (far) other_n.* else @min(other_n.*, shift);
        std.mem.copyForwards(pardes.Cell, other.*[0 .. @as(usize, other_n.* - dropped) * w], other.*[@as(usize, dropped) * w ..][0 .. @as(usize, other_n.* - dropped) * w]);
        other_n.* -= dropped;
        // An input: the core's rows moved by as many (down positive).
        glide.follow.kick(@as(f32, @floatFromInt(shift)) * @as(f32, @floatFromInt(glide.dir)), glide.now_ns, glide.pace(glide.motion));
    }

    /// Finds the text whose view moved since the last loop step, however
    /// it moved (the wheel, a key, a Look), and snapshots its body as the
    /// last frame drew it (`core.surface`), so the frame about to be drawn
    /// can measure the move (`measure`); moves the glide on to now. A
    /// terminal's view glides only under the wheel (`wheeled`: its output
    /// scrolls it at every line, and that is no glide); not one the shell
    /// moves by the pixel (`direct`).
    pub fn step(glide: *Glide, core: *pardes.Pardes, gpa: std.mem.Allocator, wheeled: ?usize, direct: ?usize) void {
        glide.now_ns = core.now_ns;
        glide.motion = pardes.animation.Motion.of(core.settings.motion);
        if (glide.follow.moving()) {
            glide.advance(core.now_ns, glide.motion);
            core.needs_frame = true;
            if (glide.follow.offset == 0) {
                glide.nabove = 0;
                glide.nbelow = 0;
                glide.lines_moved = 0;
                glide.rows_moved = 0;
            }
        }
        // ponytail: one glide at a time, the focused pane's, else the one that
        // moved most; a second pane scrolled in the same step lands. A glide a
        // pane (and a scissor each) if two ever need to move together.
        // The view that moved: the focused pane's, else the one that moved
        // most; not one showing another file now.
        const s = &core.surface;
        var pick: ?usize = null;
        var delta: i64 = 0;
        for (core.panes, 0..) |slot, id| {
            const pane = slot orelse {
                glide.seen[id] = .{};
                continue;
            };
            const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) pardes.panes.terminal.gridOffset(pane) else 0;
            const file: u64 = if (pane.file) |f| std.hash.Wyhash.hash(0, f.path) else 0;
            const revision: u32 = if (pane.file) |f| f.revision else 0;
            const was = glide.seen[id];
            glide.seen[id] = .{ .serial = pane.serial, .line = line, .file = file, .revision = revision };
            if (was.serial != pane.serial or was.file != file or was.line == line or pane.collapsed or pane.hasPdf()) continue;
            // Generated text rewritten as its view moved (a query pane's live
            // rows, a +Search refilled, Callstack): the rows are another
            // text's, not this one's moved; it lands.
            if (pane.file) |f| if (f.output != null and revision != was.revision) continue;
            if (pane.file == null and wheeled != id) continue;
            if (direct == id) continue;
            const moved = line - was.line;
            if (pick) |best| if (best == core.active or (id != core.active and @abs(moved) <= @abs(delta))) continue;
            pick = id;
            delta = moved;
        }
        const id = pick orelse return;
        const pane = core.panes[id].?;
        const r = core.rects[id];
        if (r.h <= pane.tag_rows or r.w <= config.GUTTER) return;
        const body_y = core.bodyTop(pane, r);
        const body_h = r.h -| pane.tag_rows;
        const w = r.w - config.GUTTER;
        const x0 = r.x + config.GUTTER;
        // The last frame drew this body where it is now: a pane that moved or
        // was resized in the same step has no picture to glide from.
        const drawn = for (s.regionList()) |region| {
            if (region.kind == .body and region.owner == id and region.serial == pane.serial) break std.meta.eql(region.rect, pardes.Rect{ .x = x0, .y = body_y, .w = w, .h = body_h });
        } else false;
        // A new pane or place: what was kept belongs to another picture.
        if (glide.pane != id or !std.meta.eql(glide.rect, r) or glide.body_y != body_y or glide.body_h != body_h or glide.pending) glide.stop();
        glide.pane = id;
        glide.rect = r;
        glide.body_y = body_y;
        glide.body_h = body_h;
        if (glide.motion.instant or !drawn or x0 + w > s.cols or body_y + body_h > s.rows or s.cells.len == 0) return glide.stop();
        // The body as the last frame drew it, which the move is measured from.
        const n = @as(usize, w) * body_h;
        if (glide.before.len < n) glide.before = gpa.realloc(glide.before, n) catch &.{};
        if (glide.before.len < n) return glide.stop();
        for (0..body_h) |row| @memcpy(glide.before[row * w ..][0..w], s.cells[(@as(usize, body_y) + row) * s.cols + x0 ..][0..w]);
        glide.pending = true;
        glide.caret_row = if (s.cursor) |c| c.y else null;
        glide.dir = @intCast(std.math.sign(delta));
        glide.pending_lines += @floatFromInt(@abs(delta));
        core.needs_frame = true;
    }

    pub fn ensure(glide: *Glide, gpa: std.mem.Allocator) bool {
        const n = @as(usize, glide.bw()) * glide.body_h * reach;
        inline for (.{ &glide.above, &glide.below }) |buffer| if (buffer.len < n) {
            const grown = gpa.realloc(buffer.*, n) catch return false;
            buffer.* = grown;
        };
        return true;
    }
};

pub fn sameRow(a: []const pardes.Cell, b: []const pardes.Cell) bool {
    for (a, b) |x, y| {
        if (x.default != y.default) return false;
        if (x.default) continue;
        if (!std.mem.eql(u8, x.grapheme(), y.grapheme()) or !std.meta.eql(x.style, y.style)) return false;
    }
    return true;
}