diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/FrameStats.zig | 4 | ||||
| -rw-r--r-- | src/Messages.zig | 5 | ||||
| -rw-r--r-- | src/animation.zig | 656 | ||||
| -rw-r--r-- | src/builtins.zig | 2 | ||||
| -rw-r--r-- | src/config.zig | 17 | ||||
| -rw-r--r-- | src/draw.zig | 7 | ||||
| -rw-r--r-- | src/glide.zig | 383 | ||||
| -rw-r--r-- | src/gui/gui.zig | 164 | ||||
| -rw-r--r-- | src/layout.zig | 11 | ||||
| -rw-r--r-- | src/pardes.zig | 48 | ||||
| -rw-r--r-- | src/pdf_view.zig | 137 | ||||
| -rw-r--r-- | src/surface.zig | 4 | ||||
| -rw-r--r-- | src/tape.zig | 2 | ||||
| -rw-r--r-- | src/tui/tui.zig | 67 | ||||
| -rw-r--r-- | src/views.zig | 14 |
15 files changed, 461 insertions, 1060 deletions
diff --git a/src/FrameStats.zig b/src/FrameStats.zig index 623acd24..34a629dd 100644 --- a/src/FrameStats.zig +++ b/src/FrameStats.zig @@ -24,7 +24,7 @@ //! on a real display. const std = @import("std"); const pardes = @import("pardes.zig"); -const animation = @import("animation.zig"); +const frame_ns = @import("pardes.zig").frame_ns; const FrameStats = @This(); @@ -85,7 +85,7 @@ long: ?*[long_capacity]Frame = null, /// Frames recorded since the start; the ring holds the last of them. count: u64 = 0, /// The display's refresh period, as the shell knows it. -period_ns: u64 = animation.frame_ns, +period_ns: u64 = frame_ns, /// The end of the last drawn frame's present, and whether anything was /// still moving then (the next frame was owed at once). last_end_ns: u64 = 0, diff --git a/src/Messages.zig b/src/Messages.zig index 0ab10dab..e18815e3 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -5,7 +5,6 @@ const pardes = @import("pardes.zig"); const memory = @import("memory.zig"); const std = @import("std"); const layout = @import("layout.zig"); -const animation = @import("animation.zig"); const ctlfs = @import("ninep/tree.zig"); const panes = @import("panes.zig"); const CellStyle = @import("surface.zig").CellStyle; @@ -307,7 +306,7 @@ pub fn messageWake(p: *const Pardes, pane: *const Pane) ?u64 { /// Animation frames a message timing lasts; at least one. pub fn messageFrames(ms: u16) u16 { - return @intCast(@max(1, (@as(u32, ms) + animation.frame_ms - 1) / animation.frame_ms)); + return @intCast(@max(1, (@as(u32, ms) + pardes.frame_ms - 1) / pardes.frame_ms)); } /// What notice band `i` says. The grid pass and the band layers both @@ -874,7 +873,7 @@ test "an idle core wants no wake and a lingering message sleeps to its linger's const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const frame = animation.frame_ns; + const frame = pardes.frame_ns; p.advance(1_000_000); try std.testing.expectEqual(@as(?u64, null), p.nextWake()); const pane = p.panes[p.active].?; diff --git a/src/animation.zig b/src/animation.zig deleted file mode 100644 index 25abf421..00000000 --- a/src/animation.zig +++ /dev/null @@ -1,656 +0,0 @@ -//! The springs that settle a view and the cursor, and the Motion flavours -//! they move by (colors.zig fades the chrome). -const std = @import("std"); - -/// The curves a theme change's chrome fades on (colors.ChromeAnimation). -pub const Easing = enum(u8) { smooth, out_cubic }; - -pub fn sample(easing: Easing, raw: f32) f32 { - const t = std.math.clamp(raw, 0.0, 1.0); - return switch (easing) { - .smooth => t * t * (3.0 - 2.0 * t), - .out_cubic => 1.0 - (1.0 - t) * (1.0 - t) * (1.0 - t), - }; -} - -/// A fractional box in grid cells: the cursor's quad aims at one. -pub const Box = extern struct { - x: f32 = 0, - y: f32 = 0, - w: f32 = 0, - h: f32 = 0, -}; - -pub const frame_ms: u32 = 16; -pub const frame_ns: u64 = frame_ms * std.time.ns_per_ms; -pub const transition_steps: u16 = 10; - -/// How the fx track moves (`Motion <flavour>`, docs/effects.md): one set of -/// parameters a flavour picks, read by every animation that follows the -/// classic principles, so a flavour is data and no effect branches on it. -pub const Motion = struct { - pub const Flavour = enum(u8) { off, crisp, smooth, bouncy, playful }; - - /// Nothing moves: every change lands at once (reduced motion). - instant: bool = false, - /// Timing: the spring's natural frequency, rad/s; slow in / slow out - /// come from the spring itself. - omega: f32 = 36, - /// Follow-through: 1 is critically damped (no overshoot); below 1 it - /// settles past its target and back. - zeta: f32 = 1, - /// Anticipation: a move from rest first winds up the other way, by - /// this fraction of the distance. - anticipate: f32 = 0, - /// Squash and stretch: how much a moving thing lengthens along its - /// velocity and squashes as it lands (G3's cursor, G7's panes). - stretch: f32 = 0, - /// Secondary action: how far behind a follower trails its leader (the - /// shadow behind a pane, a notice's text behind its chip), as the - /// follower's frequency over the leader's; 1 is in step. - follow: f32 = 1, - /// Arcs: how far a two-dimensional path bows, as a fraction of its - /// length (the cursor's glide). - arc: f32 = 0, - /// Exaggeration: how far a small motion goes, as a multiple of its - /// plain distance (a lift of 1 rises `gain`), so a flavour's character - /// shows on a motion only a few pixels big. - gain: f32 = 1, - /// Timing: a move from rest leaves at this fraction of full speed (1: - /// out of the gate at once and easing in, 0: slow in and slow out). - launch: f32 = 0, - /// For a motion of fixed length (a pane's move, a notice's drop): its - /// length as a multiple of the effect's own, and the spring's frequency - /// over that length (`ease`). - span: f32 = 1, - norm: f32 = 10, - - pub fn of(flavour: Flavour) Motion { - return switch (flavour) { - .off => .{ .instant = true }, - // Productivity: quick and exact, nothing past its mark. - .crisp => .{ .omega = 60, .launch = 1, .span = 0.6, .norm = 10 }, - // Longer and softer, easing in and out, still without a bounce. - // The default: within §8.1's 220 ms for an arrival. - .smooth => .{ .omega = 34, .follow = 0.85, .arc = 0.04, .span = 1.1, .norm = 6 }, - // Clearly past its mark and back, once or twice, stretching - // with its speed. - .bouncy => .{ .omega = 24, .zeta = 0.35, .stretch = 0.15, .follow = 0.8, .arc = 0.08, .gain = 1.25, .span = 1.4, .norm = 13 }, - // A cartoon's: winds up, flies past, squashes as it lands, - // its followers trailing. - .playful => .{ .omega = 18, .zeta = 0.28, .anticipate = 0.15, .stretch = 0.35, .follow = 0.55, .arc = 0.15, .gain = 1.4, .span = 1.7, .norm = 18 }, - }; - } - - /// A move of fixed length from 0 to 1, `u` of the way through it: the - /// flavour's spring (wind-up, overshoot and all), landing exactly on 1 - /// at its end. `instant` is there at once. - pub fn ease(motion: Motion, u: f32) f32 { - return motion.easeFrom(u, 0); - } - - /// `ease` for a move that starts already moving at `launch` lengths - /// per unit of `u` (a retarget): no wind-up then, the speed carried on. - pub fn easeFrom(motion: Motion, u: f32, launch: f32) f32 { - if (motion.instant or u >= 1) return 1; - if (u <= 0) return 0; - const kick = if (launch != 0) launch else (motion.launch - 2 * motion.anticipate) * motion.norm; - const spring: Spring = .{ .omega = motion.norm, .zeta = motion.zeta, .target = 1, .from = 0, .velocity = kick, .settled = false }; - return spring.value(@intFromFloat(u * std.time.ns_per_s)); - } - - /// The same move's speed at `u`, in lengths per unit of `u`, set off at - /// `launch` as `easeFrom` is. - pub fn speedFrom(motion: Motion, u: f32, launch: f32) f32 { - const h: f32 = 1.0 / 256.0; - return (motion.easeFrom(@min(1, u + h), launch) - motion.easeFrom(@max(0, u - h), launch)) / (@min(1, u + h) - @max(0, u - h)); - } -}; - -/// A value that follows its target on a damped spring, in closed form -/// (docs/render-pipeline.md §7.2), critically damped or under: a new target -/// taken partway keeps the value AND its velocity, so a quick run of changes -/// never snaps or starts over. A move from rest can wind up first -/// (Motion.anticipate). Settled, it is exactly its target and asks for no -/// frames. -pub const Spring = struct { - omega: f32 = 36, - zeta: f32 = 1, - target: f32 = 0, - /// The value and velocity (per second) at `from_ns`. - from: f32 = 0, - velocity: f32 = 0, - from_ns: u64 = 0, - settled: bool = true, - - const State = struct { value: f32, velocity: f32 }; - - fn at(spring: *const Spring, now_ns: u64) State { - if (spring.settled) return .{ .value = spring.target, .velocity = 0 }; - const t: f32 = @floatCast(@as(f64, @floatFromInt(now_ns -| spring.from_ns)) / std.time.ns_per_s); - const w = spring.omega; - const x0 = spring.from - spring.target; - const v0 = spring.velocity; - if (spring.zeta >= 1) { - const c = v0 + w * x0; - const decay = @exp(-w * t); - return .{ .value = spring.target + (x0 + c * t) * decay, .velocity = (v0 - w * t * c) * decay }; - } - // Underdamped: it rings about its target as it decays. - const z = spring.zeta; - const wd = w * @sqrt(1 - z * z); - const b = (v0 + z * w * x0) / wd; - const decay = @exp(-z * w * t); - const cos = @cos(wd * t); - const sin = @sin(wd * t); - return .{ - .value = spring.target + decay * (x0 * cos + b * sin), - .velocity = decay * ((b * wd - z * w * x0) * cos - (x0 * wd + z * w * b) * sin), - }; - } - - pub fn value(spring: *const Spring, now_ns: u64) f32 { - return spring.at(now_ns).value; - } - - /// Moves what it shows by `by` at `now_ns`, its speed kept, toward the - /// same target (a scroll's picture falling behind the text it follows), - /// at `motion`'s pace, never past its mark. - pub fn carry(spring: *Spring, by: f32, now_ns: u64, motion: Motion) void { - const state = spring.at(now_ns); - spring.* = .{ .omega = motion.omega, .zeta = 1, .target = spring.target, .from = state.value + by, .velocity = state.velocity, .from_ns = now_ns, .settled = false }; - } - - /// Heads for `target` from wherever it is at `now_ns`, moving as it was, - /// at the pace and damping `motion` gives: at once when it is `off`. - pub fn retarget(spring: *Spring, target: f32, now_ns: u64, motion: Motion) void { - if (target == spring.target) return; - if (motion.instant) { - spring.* = .{ .omega = motion.omega, .zeta = motion.zeta, .target = target, .from = target }; - return; - } - const state = spring.at(now_ns); - // From rest, a launch, or a wind-up: set off the other way, a little. - const kick: f32 = if (spring.settled) (motion.launch - 2 * motion.anticipate) * (target - state.value) * motion.omega else 0; - spring.* = .{ .omega = motion.omega, .zeta = motion.zeta, .target = target, .from = state.value, .velocity = state.velocity + kick, .from_ns = now_ns, .settled = false }; - } - - /// Settles once it is within half a percent of its target and barely - /// moving (no pixel of a shadow tells the rest): it is its target from - /// then on. True while it still moves. - pub fn step(spring: *Spring, now_ns: u64) bool { - if (spring.settled) return false; - const state = spring.at(now_ns); - if (@abs(state.value - spring.target) < 5e-3 and @abs(state.velocity) < 5e-2) spring.settled = true; - return !spring.settled; - } -}; - -test "a carried spring keeps its speed, heads back to its mark and never passes it" { - const ms = std.time.ns_per_ms; - var spring: Spring = .{}; - const smooth = Motion.of(.smooth); - spring.carry(-3, 0, smooth); - try std.testing.expectEqual(@as(f32, -3), spring.value(0)); - const mid = spring.at(40 * ms); - try std.testing.expect(mid.value > -3 and mid.value < 0 and mid.velocity > 0); - // Another notch mid-way: one more row behind, still moving back. - spring.carry(-1, 40 * ms, smooth); - const after = spring.at(40 * ms); - try std.testing.expectApproxEqAbs(mid.value - 1, after.value, 1e-5); - try std.testing.expectApproxEqAbs(mid.velocity, after.velocity, 1e-4); - var t: u64 = 40 * ms; - while (spring.step(t)) : (t += frame_ns) try std.testing.expect(spring.value(t) <= 1e-4); - try std.testing.expect(t < 400 * ms); -} - -test "a spring settles without overshoot and keeps its velocity when retargeted" { - var spring: Spring = .{}; - const ms = std.time.ns_per_ms; - const crisp = Motion.of(.crisp); - spring.retarget(1, 0, crisp); - var last: f32 = 0; - var t: u64 = 0; - while (spring.step(t)) : (t += frame_ns) { - const v = spring.value(t); - try std.testing.expect(v >= last and v <= 1); - last = v; - } - try std.testing.expect(t >= 80 * ms and t <= 200 * ms); - try std.testing.expectEqual(@as(f32, 1), spring.value(t + 5 * ms)); - // Back the other way partway up: it carries on up for a moment, then - // turns, never jumping. - spring = .{}; - spring.retarget(1, 0, crisp); - const before = spring.at(60 * ms); - spring.retarget(0, 60 * ms, crisp); - const after = spring.at(60 * ms); - try std.testing.expectApproxEqAbs(before.value, after.value, 1e-6); - try std.testing.expectApproxEqAbs(before.velocity, after.velocity, 1e-4); - try std.testing.expect(spring.value(60 * ms + 500_000) > before.value); -} - -test "each flavour is its own motion: off lands at once, bouncy overshoots, playful winds up first" { - const ms = std.time.ns_per_ms; - var spring: Spring = .{}; - spring.retarget(1, 0, Motion.of(.off)); - try std.testing.expect(spring.settled); - try std.testing.expectEqual(@as(f32, 1), spring.value(0)); - var settle: [5]u64 = @splat(0); - for ([_]Motion.Flavour{ .crisp, .smooth, .bouncy, .playful }) |flavour| { - spring = .{}; - spring.retarget(1, 0, Motion.of(flavour)); - var peak: f32 = 0; - var low: f32 = 0; - var t: u64 = 0; - var last = spring.at(0); - while (spring.step(t)) : (t += ms) { - const now = spring.at(t); - peak = @max(peak, now.value); - low = @min(low, now.value); - // Continuous, a millisecond at a time: no jump anywhere. - try std.testing.expect(@abs(now.value - last.value) < 0.07); - last = now; - } - try std.testing.expect(t < 1600 * ms); - settle[@backingInt(flavour)] = t; - switch (flavour) { - .crisp, .smooth => try std.testing.expect(peak <= 1.0005 and low >= 0), - // Clearly past the mark, not a hint of it. - .bouncy => try std.testing.expect(peak > 1.25 and low >= 0), - .playful => try std.testing.expect(peak > 1.35 and low < -0.03), - .off => unreachable, - } - } - // Smooth takes twice crisp's time and more: a character, not a tuning. - // Yet as the default a pane's arrival (a slide's 12 frames, scaled) is - // inside §8.1's 220 ms, and a lift is still before 300 ms. - try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] > 2 * settle[@backingInt(Motion.Flavour.crisp)]); - try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] <= 300 * ms); - try std.testing.expect(@round(@as(f32, 12) * Motion.of(.smooth).span) * frame_ms <= 220); - // A fixed-length move lands exactly on its mark, whatever the flavour. - for (std.enums.values(Motion.Flavour)) |flavour| try std.testing.expectEqual(@as(f32, 1), Motion.of(flavour).ease(1)); -} - -/// A view that follows its input (anim 9, 11): the picture's offset from -/// the core's position now (in the view's own unit: rows of text, pixels of -/// a PDF strip; negative, the picture still shows what is above), its speed -/// (units a second), when it was last integrated, and what has been feeding -/// it. The text body (the GUI's Glide) and a PDF strip are each one. -pub const Follow = struct { - offset: f32 = 0, - speed: f32 = 0, - at_ns: u64 = 0, - /// The last inputs (down positive), their spacing, the last's time, and - /// how many came as one stream. - feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, - - /// How far the picture may lag, in bodies (a flick past that jumps); - /// how fast it may move, in bodies a second, so moving text stays - /// readable. - pub const reach = 2; - pub const bodies_per_s: f32 = 15; - /// Inputs this close, each the way the last went, are one stream. - pub const stream_ns = 150 * std.time.ns_per_ms; - - /// What a view's size and the flavour make of the rules: the spring at - /// 1.5x the flavour's pace, the speed cap, the lag cap, and the offset - /// under which it is at rest (a tenth of a pixel, in its unit). - pub const Pace = struct { omega: f32, cap: f32, limit: f32, rest: f32 }; - - pub fn pace(motion: Motion, body: f32, rest: f32) Pace { - return .{ .omega = motion.omega * 1.5, .cap = body * bodies_per_s, .limit = body * reach, .rest = rest }; - } - - pub fn moving(follow: *const Follow) bool { - return follow.offset != 0 or follow.speed != 0; - } - - /// An input: the core moved `amount` (down positive). The picture now - /// lags by as much more, its speed as it was. - pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void { - follow.advance(now_ns, p); - follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit); - const f = &follow.feed; - const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns; - if (like) { - const gap = now_ns -| f.last_ns; - f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; - f.amount = (f.amount + amount) / 2; - f.count +|= 1; - } else f.* = .{ .amount = amount, .count = 1 }; - f.last_ns = now_ns; - } - - /// The system moved on to `now_ns`. Fed by a stream, at the stream's - /// rate (an input's amount over their spacing), held a lag `lead` - /// behind so a late input never finds it stopped and the stream's end - /// never runs it past its mark; else on the spring, critically damped, - /// from the speed it has. Never faster than `p.cap`. - pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void { - const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s); - follow.at_ns = now_ns; - if (follow.offset == 0 and follow.speed == 0) return; - const omega = p.omega; - const toward: f32 = if (follow.offset < 0) 1 else -1; - const f = follow.feed; - if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { - const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); - const rate = @abs(f.amount) / gap; - const lead = @max(@abs(f.amount), rate / omega); - // ponytail: a gentle pull to the lead (a tenth an input), so the - // per-frame step varies by a tenth; a stream's own jitter beyond - // that shows. An estimate of the input clock if it ever matters. - // A slow stream's lag runs out before its next input: never - // faster than the spring's own pace from there (omega a unit of - // lag a second), so it eases onto the mark, not into it at speed. - const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset))); - const step = @min(v * dt, @abs(follow.offset)); - follow.offset += toward * step; - follow.speed = if (follow.offset == 0) 0 else toward * v; - return; - } - const x = follow.offset; - // Coming to rest from a stream: never faster than the spring's own - // pace from here (omega a unit of lag a second), so it eases in and - // does not pass its mark. - if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x); - const lead_v = follow.speed + omega * x; - const decay = @exp(-omega * dt); - var next = (x + lead_v * dt) * decay; - var speed = (follow.speed - omega * dt * lead_v) * decay; - if (@abs(next - x) > p.cap * dt) { - next = x + std.math.sign(next - x) * p.cap * dt; - speed = std.math.sign(next - x) * p.cap; - } - follow.offset = next; - follow.speed = speed; - if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns }; - } -}; - -test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" { - // A flick's spin (a stream of notches, then nothing), one page, and - // notches slow enough that each lag runs out before the next (its - // stream must ease onto each mark, never pass it). - const p = Follow.pace(.{}, 600, 0.1); - for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| { - var f: Follow = .{}; - var now: u64 = std.time.ns_per_s; - for (0..run.n) |_| { - f.kick(if (run.n == 1) 600 else 25, now, p); - var waited: u64 = 0; - while (waited < run.gap_ms) : (waited += 8) { - now += 8 * std.time.ns_per_ms; - const was = f.offset; - f.advance(now, p); - // Toward its mark only, and onto it from under a pixel. - try std.testing.expect(f.offset <= 0 and f.offset >= was); - if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest); - } - } - var last: f32 = std.math.inf(f32); - var before = f.offset; - var frames: usize = 0; - var fastest: f32 = 0; - while (f.moving()) : (frames += 1) { - now += frame_ns; - f.advance(now, p); - const step = @abs(f.offset - before); - try std.testing.expect(@abs(f.offset) <= @abs(before)); - if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest); - fastest = @max(fastest, step); - if (step < fastest) try std.testing.expect(step <= last); - last = step; - before = f.offset; - try std.testing.expect(frames < 120); - } - try std.testing.expect(last <= 0.1); - } -} - -/// The focused cursor's quad (docs/render-pipeline.md §5.4), in grid cells: -/// four corners, each on its own springs, so a jump smears along its path -/// (the leading corners stiffer than the trailing ones, Motion.follow) and -/// collapses at rest; a long jump bows (Motion.arc). A step of a cell or -/// less (a key held, typing) eases there whole, its corners together, on a -/// spring `step_pace` times stiffer still: in ~60 ms on the default, so at -/// a keyboard's repeat it trails by half a cell and never smears a caret. -/// Any move the caller calls a snap, and every move under Motion off, -/// lands at once. -pub const CursorGlide = struct { - /// Top left, top right, bottom right, bottom left; x then y. - corners: [4][2]Spring = @splat(@splat(.{})), - target: Box = .{}, - from_centre: [2]f32 = .{ 0, 0 }, - placed: bool = false, - /// When the last step (a move of a cell or less) came. - step_ns: u64 = 0, - - /// How much faster than the flavour's own pace a cursor moves: it - /// follows input (§8.1: settles in 90-150 ms on the default). - pub const pace: f32 = 2.4; - /// A jump longer than this, in cells, bows. - pub const arc_from: f32 = 8; - /// How much stiffer a step's spring is than a jump's. - pub const step_pace: f32 = 1.5; - /// Steps this close are a stream (a held key, typing): each lands, the - /// caret at the keys' own rate, as an eased step a key would bounce. - pub const stream_ns: u64 = 150 * std.time.ns_per_ms; - - fn cornersOf(box: Box) [4][2]f32 { - return .{ .{ box.x, box.y }, .{ box.x + box.w, box.y }, .{ box.x + box.w, box.y + box.h }, .{ box.x, box.y + box.h } }; - } - - fn centre(box: Box) [2]f32 { - return .{ box.x + box.w / 2, box.y + box.h / 2 }; - } - - /// Heads for `box` at `now_ns`. - /// How a new mark is gone to: eased (a step, or a jump's smear and - /// bow), or landed at once (a scroll: the text moved under it, not the - /// caret; a shell carries it with the text's own glide). - pub const How = enum { ease, land }; - - pub fn aim(glide: *CursorGlide, box: Box, now_ns: u64, motion: Motion, how: How) void { - // The same mark: nothing to do, unless a snap lands a glide under way. - if (glide.placed and std.meta.eql(box, glide.target) and !(how == .land and glide.moving())) return; - const to = cornersOf(box); - const from_c = if (glide.placed) glide.centreAt(now_ns) else centre(box); - const to_c = centre(box); - const dx = to_c[0] - from_c[0]; - const dy = to_c[1] - from_c[1]; - const jump = @abs(dx) > 1.01 or @abs(dy) > 1.01; - // A step is measured mark to mark, not from where an ease under way - // has got to (a held key's steps read as jumps from there). - const last = centre(glide.target); - const one_step = glide.placed and @abs(to_c[0] - last[0]) <= 1.01 and @abs(to_c[1] - last[1]) <= 1.01; - const streaming = one_step and glide.step_ns != 0 and now_ns -| glide.step_ns < stream_ns; - if (one_step) glide.step_ns = now_ns; - const land = !glide.placed or how == .land or motion.instant or streaming; - glide.from_centre = from_c; - glide.target = box; - glide.placed = true; - for (&glide.corners, to) |*corner, point| { - // Leading: the corner ahead of the move, on the side it goes. - const ahead = (point[0] - to_c[0]) * dx + (point[1] - to_c[1]) * dy; - var own = motion; - own.omega *= if (jump) pace * (if (ahead > 0) 1 else motion.follow) else pace * step_pace; - // A step neither winds up nor overshoots: it is a caret moving. - if (!jump) { - own.zeta = 1; - own.anticipate = 0; - } - if (land) { - for (corner, point) |*axis, value| axis.* = .{ .omega = own.omega, .zeta = own.zeta, .target = value, .from = value }; - continue; - } - for (corner, point) |*axis, value| axis.retarget(value, now_ns, own); - } - } - - pub fn centreAt(glide: *const CursorGlide, now_ns: u64) [2]f32 { - var c: [2]f32 = .{ 0, 0 }; - for (glide.corners) |corner| for (&c, corner) |*sum, axis| { - sum.* += axis.value(now_ns) / 4; - }; - return c; - } - - /// Text under the cursor moved by (dx, dy) cells (a scroll): the quad - /// moves with it, rather than gliding against text that jumped. - pub fn shift(glide: *CursorGlide, dx: f32, dy: f32) void { - for (&glide.corners) |*corner| for (corner, [2]f32{ dx, dy }) |*axis, d| { - axis.from += d; - axis.target += d; - }; - glide.from_centre = .{ glide.from_centre[0] + dx, glide.from_centre[1] + dy }; - glide.target.x += dx; - glide.target.y += dy; - } - - /// The quad at `now_ns`, bowed on a long jump by the flavour's arc. - pub fn sample(glide: *const CursorGlide, now_ns: u64, motion: Motion) [4][2]f32 { - var out: [4][2]f32 = undefined; - for (&out, glide.corners) |*point, corner| for (point, corner) |*value, axis| { - value.* = axis.value(now_ns); - }; - const to_c = centre(glide.target); - const dx = to_c[0] - glide.from_centre[0]; - const dy = to_c[1] - glide.from_centre[1]; - const length = @sqrt(dx * dx + dy * dy); - if (motion.arc == 0 or length < arc_from) return out; - const now_c = glide.centreAt(now_ns); - const left = @sqrt((to_c[0] - now_c[0]) * (to_c[0] - now_c[0]) + (to_c[1] - now_c[1]) * (to_c[1] - now_c[1])); - const travelled = std.math.clamp(1 - left / length, 0, 1); - const bow = motion.arc * length * 4 * travelled * (1 - travelled); - // Perpendicular to the path, to its left. - for (&out) |*point| { - point[0] += -dy / length * bow; - point[1] += dx / length * bow; - } - return out; - } - - /// Steps the springs to `now_ns`; true while the quad still moves. - pub fn step(glide: *CursorGlide, now_ns: u64) bool { - var any = false; - for (&glide.corners) |*corner| for (corner) |*axis| { - if (axis.step(now_ns)) any = true; - }; - return any; - } - - /// How far, in cells, the furthest corner still is from its mark. - pub fn remaining(glide: *const CursorGlide, now_ns: u64) f32 { - var most: f32 = 0; - for (glide.corners) |corner| for (corner) |axis| { - most = @max(most, @abs(axis.value(now_ns) - axis.target)); - }; - return most; - } - - pub fn moving(glide: *const CursorGlide) bool { - for (glide.corners) |corner| for (corner) |axis| { - if (!axis.settled) return true; - }; - return false; - } -}; - -/// The cursor's opacity under blink (§5.4): solid while typing and for -/// `hold_ns` after, then on and off with an eased edge, solid again after -/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is -/// owed), `next_ns` when the next edge starts (a wake). -pub const Blink = struct { - pub const hold_ns: u64 = 500 * std.time.ns_per_ms; - pub const idle_ns: u64 = 10 * std.time.ns_per_s; - pub const half_ns: u64 = 530 * std.time.ns_per_ms; - pub const edge_ns: u64 = 80 * std.time.ns_per_ms; - - alpha: f32, - edge: bool, - next_ns: ?u64, - - pub fn at(now_ns: u64, input_ns: u64) Blink { - const since = now_ns -| input_ns; - if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns }; - if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null }; - const t = (since - hold_ns) % (2 * half_ns); - const cycle_start = now_ns - t; - // On for a half, easing out over its last `edge_ns`; off for a half, - // easing back in over its last. - if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns }; - if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns }; - return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; - } - - fn smooth(x: f32) f32 { - const u = std.math.clamp(x, 0, 1); - return u * u * (3 - 2 * u); - } -}; - -test "a cursor eases a cell at a time, keeps up with typing, and glides a jump, smearing, bowing and landing exactly" { - const ms = std.time.ns_per_ms; - const smooth_motion = Motion.of(.smooth); - var glide: CursorGlide = .{}; - const cell: Box = .{ .x = 3, .y = 4, .w = 1, .h = 1 }; - glide.aim(cell, 0, smooth_motion, .ease); - try std.testing.expect(!glide.moving()); - // One cell over: eases there whole, no wider than a cell, in ~60 ms. - glide.aim(.{ .x = 4, .y = 4, .w = 1, .h = 1 }, ms, smooth_motion, .ease); - try std.testing.expect(glide.moving()); - var step_t: u64 = ms; - while (glide.step(step_t)) : (step_t += ms) { - const q = glide.sample(step_t, smooth_motion); - try std.testing.expect(q[1][0] - q[0][0] <= 1.0 + 1e-3 and q[0][0] >= 3 - 1e-3 and q[0][0] <= 4 + 1e-3); - } - try std.testing.expect(step_t - ms >= 30 * ms and step_t - ms <= 90 * ms); - // At a keyboard's repeat the steps are a stream: each lands. - var typed: f32 = 4; - var key_t: u64 = step_t; - for (0..20) |_| { - typed += 1; - glide.aim(.{ .x = typed, .y = 4, .w = 1, .h = 1 }, key_t, smooth_motion, .ease); - key_t += 33 * ms; - try std.testing.expect(typed - glide.sample(key_t, smooth_motion)[0][0] <= 0.6); - } - while (glide.step(key_t)) key_t += ms; - // A jump of 30 cells: glides, the leading edge ahead of the trailing one. - glide.aim(cell, key_t, smooth_motion, .land); - const j0 = key_t; - const far: Box = .{ .x = 34, .y = 4, .w = 1, .h = 1 }; - glide.aim(far, j0 + 2 * ms, smooth_motion, .ease); - try std.testing.expect(glide.moving()); - const mid = glide.sample(j0 + 40 * ms, smooth_motion); - const width = mid[1][0] - mid[0][0]; - try std.testing.expect(width > 1.5); - // Bowed off the straight line on a long jump. - try std.testing.expect(@abs(mid[0][1] - 4) > 0.05); - var t: u64 = j0 + 2 * ms; - while (glide.step(t)) t += ms; - // Arrives within §8.1's 90-150 ms on the default, within a twentieth of - // a cell (under a pixel); settles to rest just after, landing exactly. - const arrived = glide.sample(j0 + 152 * ms, smooth_motion); - try std.testing.expect(@abs(arrived[3][0] - 34) < 0.05 and @abs(arrived[1][0] - 35) < 0.05); - try std.testing.expect(t - j0 <= 220 * ms); - const rest = glide.sample(t, smooth_motion); - try std.testing.expectEqual([2]f32{ 34, 4 }, rest[0]); - try std.testing.expectEqual([2]f32{ 35, 5 }, rest[2]); - // A scroll carries it with the text. - glide.shift(0, -3); - try std.testing.expectEqual([2]f32{ 34, 1 }, glide.sample(t, smooth_motion)[0]); -} - -test "a blink holds while typing, eases at its edges and stops when idle" { - const ms = std.time.ns_per_ms; - try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); - const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); - try std.testing.expectEqual(@as(f32, 0), out.alpha); - const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); - try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); - try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); - try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); -} diff --git a/src/builtins.zig b/src/builtins.zig index cbde62da..c1d7c50b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -243,7 +243,7 @@ pub const registry = struct { if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default - .toggle, .dump_dir, .choice, .motion, .shell => false, + .toggle, .dump_dir, .choice, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_linger, .inactive_dim, .grip_width => true, // bare, it says the current value (exec.applySettingBuiltin) .tab, .callstack_depth, .search_rows => false, diff --git a/src/config.zig b/src/config.zig index 9a7e6848..50748b60 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1,7 +1,6 @@ const std = @import("std"); const builtin = @import("builtin"); const layout = @import("layout.zig"); -const animation = @import("animation.zig"); const limits = @import("memory.zig").limits; const pardes = @import("pardes.zig"); const builtins = @import("builtins.zig"); @@ -166,7 +165,6 @@ pub const leader_path = paths: { if (builtins.capabilities.lift) table.set(.CursorBlink, null); table.set(.JumpTrail, null); table.set(.ProgramEsc, null); - table.set(.Motion, null); if (builtins.capabilities.lift) table.set(.GripWidth, null); table.set(.InactiveDim, null); if (builtins.capabilities.lift) table.set(.Pet, null); @@ -713,11 +711,6 @@ pub const Runtime = struct { /// of the theme's `rail_px` (acme's 12px Scrollwid at a 17px tagline): /// a pixel shell's (docs/typ/themes.typ). grip_width: u16 = 150, - /// How the fx track's animations move (animation.Motion): off for - /// reduced motion. - /// Smooth by default, tuned so arrivals land inside §8.1's 220 ms; the - /// slower flavours are a choice. - motion: animation.Motion.Flavour = .smooth, /// Builtins announce themselves on the message row. verbose: bool = true, @@ -879,8 +872,6 @@ pub const Runtime = struct { window_blur, message_linger, dump_dir, - /// A motion flavour. - motion, /// A percentage, 0 through 100. inactive_dim, grip_width, @@ -937,7 +928,6 @@ pub const Runtime = struct { .{ .word = "CursorBlink", .action = .{ .toggle = .cursor_blink }, .doc = "The cursor blinks, solid while typing, on or off." }, .{ .word = "JumpTrail", .action = .{ .toggle = .jump_trail }, .doc = "A jump of the cursor leaves a short trail that fades, on or off." }, .{ .word = "ProgramEsc", .action = .{ .toggle = .program_esc }, .doc = "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them." }, - .{ .word = "Motion", .action = .motion, .doc = "How animations move: off, crisp, smooth, bouncy or playful." }, .{ .word = "GripWidth", .action = .grip_width, .doc = "The grip and scrollbar width, as a percent of the theme's rail." }, .{ .word = "InactiveDim", .action = .inactive_dim, .doc = "Fade the unfocused panes' text by a percentage, 0 through 100, 0 off." }, .{ .word = "Pet", .action = .{ .choice = .pet }, .doc = "The window's companion in the workspace tag's blank space: off, cat or frog." }, @@ -1035,7 +1025,6 @@ pub const Runtime = struct { now.* = stepped(@TypeOf(now.*), now.*, argument) orelse return false; }, }, - .motion => state.motion = stepped(animation.Motion.Flavour, state.motion, argument) orelse return false, .inactive_dim => state.inactive_dim = number(u8, argument, " \t\r\n%", 0, 100) orelse return false, .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, @@ -1062,7 +1051,6 @@ pub const Runtime = struct { .choice => |which| switch (which) { inline else => |field| comptime words.of(@FieldType(Runtime, @tagName(field))), }, - .motion => comptime words.of(animation.Motion.Flavour), else => null, }; } @@ -1194,7 +1182,6 @@ pub const Runtime = struct { .choice => |which| switch (which) { inline else => |field| try out.print("{s} {s}\n", .{ setting.word, @tagName(@field(state, @tagName(field))) }), }, - .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); } @@ -1370,8 +1357,8 @@ pub const Runtime = struct { .{ "TaglineSize", "73" }, .{ "WindowOpacity", "85" }, .{ "WindowBlur", "40" }, .{ "MessageLinger", "1500" }, .{ "DumpDir", "~/dumps" }, .{ "TermImages", "petscii" }, .{ "JumpScope", "all" }, .{ "SearchPlace", "column" }, .{ "SearchPane", "new" }, - .{ "Motion", "playful" }, .{ "GripWidth", "200" }, .{ "InactiveDim", "35" }, - .{ "CallstackDepth", "16" }, .{ "Tab", "8" }, .{ "SearchRows", "12" }, + .{ "GripWidth", "200" }, .{ "InactiveDim", "35" }, .{ "CallstackDepth", "16" }, + .{ "Tab", "8" }, .{ "SearchRows", "12" }, }; for (values) |v| try std.testing.expect(apply(&state, find(v[0]).?, v[1])); try std.testing.expect(state.font.requested_name.set("Wanted Mono")); diff --git a/src/draw.zig b/src/draw.zig index fe4921ff..75d6378b 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -7,7 +7,6 @@ const std = @import("std"); const vaxis = @import("vaxis"); const pardes = @import("pardes.zig"); const layout = @import("layout.zig"); -const animation = @import("animation.zig"); const config = @import("config.zig"); const panes = @import("panes.zig"); const modal = @import("modal.zig"); @@ -61,7 +60,11 @@ pub fn place(p: *Pardes, s: *Surface) void { if (pane.collapsed) continue; const body_h = r.h -| pane.tag_rows; const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; - s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); + // The text it shows, for a frontend's glide to tell apart: a file's + // path, a generated text's revision with it (rows rewritten as its + // view moved are another text's); none for a terminal or a picture. + const doc: u64 = if (pane.file) |f| std.hash.Wyhash.hash(if (f.output != null) f.revision else 0, f.path) else 0; + s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .doc = doc, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // An image's rail has no thumb; a native PDF's is measured as its // pages are placed (Pdf.draw); every other pane's is here. diff --git a/src/glide.zig b/src/glide.zig index ced0ca85..723beba9 100644 --- a/src/glide.zig +++ b/src/glide.zig @@ -1,45 +1,41 @@ -//! 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). +//! The view's glide (G6, anim 3, 9, 12): a frontend's own picture of a +//! scroll, on its own clock, from the frames it draws alone. 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; the +//! frontend sees a body's first line move between two frames (Region.line) +//! and its picture follows there, critically damped (text never passes its +//! mark), every distance on the same law. The GUI draws it at the pixel; +//! the tty at whole rows (tui.zig's glideRows). Nothing here reaches back +//! into the core. 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. +/// How far the rows moved is measured on the frame against the last drawn, +/// 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. +/// one place every frame (`Follow.advance`), and every scroll, whatever +/// made it, is an input into it (`Follow.kick`): it moves the target by the +/// rows the core moved and leaves the motion as it is. Inputs coming as a +/// stream (each like the last, at a steady spacing: a held key, a spun +/// wheel) feed it at the stream's own rate; an input into a resting view, +/// or against the way it moves, starts the spring from the speed it has; a +/// jump mid-glide adds its rows with the speed kept. pub const Glide = struct { /// The picture's lag behind the core's rows and its motion (rows). - follow: pardes.animation.Follow = .{}, + follow: 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, + /// The way the last scroll went, and the body's rows before it. dir: i8 = 0, before: []pardes.Cell = &.{}, /// The rows past the body's top (`above`) and bottom (`below`), nearest @@ -59,24 +55,25 @@ pub const Glide = struct { /// (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 + /// Each body as the last frame showed it, by its pane: its serial, + /// first line, text and place, 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(.{}), + seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i32 = 0, doc: u64 = 0, rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 } } = @splat(.{}), + /// The last frame's cells, which a move is measured against. + last: []pardes.Cell = &.{}, + last_cols: u16 = 0, + last_rows: u16 = 0, /// 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 const reach = Follow.reach; pub fn moving(glide: *const Glide) bool { - return glide.follow.moving() or glide.pending; + return glide.follow.moving(); } 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; @@ -95,6 +92,7 @@ pub const Glide = struct { gpa.free(glide.before); gpa.free(glide.above); gpa.free(glide.below); + gpa.free(glide.last); } pub fn bw(glide: *const Glide) u16 { @@ -102,18 +100,94 @@ pub const Glide = struct { } /// 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 pace(glide: *const Glide) Follow.Pace { + return Follow.pace(@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)); + /// The frame about to be drawn, at `now_ns` on the frontend's clock: + /// the glide moves on to now, and a body whose first line moved since + /// the last frame (the same text in the same place) is measured against + /// that frame and kicks it. 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 frontend moves by the pixel (`direct`). One glide + /// at a time: the focused body's, else the one that moved most. + pub fn frame(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface, now_ns: u64, wheeled: ?usize, direct: ?usize) void { + glide.now_ns = now_ns; + defer glide.remember(gpa, surface); + if (glide.follow.moving()) { + glide.follow.advance(now_ns, glide.pace()); + if (glide.follow.offset == 0) { + glide.nabove = 0; + glide.nbelow = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + } + var pick: ?pardes.Region = null; + var delta: i64 = 0; + var shown: [pardes.MAX_PANES]bool = @splat(false); + for (surface.regionList()) |region| { + if (region.kind != .body or region.owner >= glide.seen.len) continue; + const id: usize = region.owner; + shown[id] = true; + const was = glide.seen[id]; + glide.seen[id] = .{ .serial = region.serial, .line = region.line, .doc = region.doc, .rect = region.rect }; + if (was.serial != region.serial or was.doc != region.doc or was.line == region.line) continue; + // 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. + if (!std.meta.eql(was.rect, region.rect)) continue; + if (region.doc == 0 and wheeled != id) continue; + if (direct == id) continue; + const moved = @as(i64, region.line) - was.line; + if (pick) |best| if (best.active or (!region.active and @abs(moved) <= @abs(delta))) continue; + pick = region; + delta = moved; + } + for (&glide.seen, shown) |*seen, here| if (!here) { + seen.* = .{}; + }; + const body = pick orelse return; + const r = body.rect; + const rect: pardes.Rect = .{ .x = r.x -| config.GUTTER, .y = r.y, .w = r.w + config.GUTTER, .h = r.h }; + // A new pane or place: what was kept belongs to another picture. + if (glide.pane != body.owner or !std.meta.eql(glide.rect, rect)) glide.stop(); + glide.pane = body.owner; + glide.rect = rect; + glide.body_y = r.y; + glide.body_h = r.h; + const w = r.w; + if (w == 0 or r.h == 0 or glide.last_cols != surface.cols or glide.last_rows != surface.rows or + r.x + w > surface.cols or r.y + r.h > surface.rows) return glide.stop(); + // The body as the last frame drew it, which the move is measured from. + const n = @as(usize, w) * r.h; + if (glide.before.len < n) glide.before = gpa.realloc(glide.before, n) catch &.{}; + if (glide.before.len < n) return glide.stop(); + for (0..r.h) |row| @memcpy(glide.before[row * w ..][0..w], glide.last[(@as(usize, r.y) + row) * glide.last_cols + r.x ..][0..w]); + glide.dir = @intCast(std.math.sign(delta)); + glide.pending_lines += @floatFromInt(@abs(delta)); + glide.measure(gpa, surface); + } + + /// This frame's cells and caret, for the next frame's measure. + fn remember(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + if (glide.last.len != surface.cells.len) { + gpa.free(glide.last); + glide.last = gpa.alloc(pardes.Cell, surface.cells.len) catch &.{}; + } + if (glide.last.len != surface.cells.len) { + glide.last_cols = 0; + return; + } + @memcpy(glide.last, surface.cells); + glide.last_cols = surface.cols; + glide.last_rows = surface.rows; + glide.caret_row = if (surface.cursor) |c| c.y else null; } /// 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; + fn measure(glide: *Glide, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { const w = glide.bw(); const h = glide.body_h; const x0 = glide.rect.x + config.GUTTER; @@ -187,89 +261,7 @@ pub const Glide = struct { 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; + glide.follow.kick(@as(f32, @floatFromInt(shift)) * @as(f32, @floatFromInt(glide.dir)), glide.now_ns, glide.pace()); } pub fn ensure(glide: *Glide, gpa: std.mem.Allocator) bool { @@ -290,3 +282,144 @@ pub fn sameRow(a: []const pardes.Cell, b: []const pardes.Cell) bool { } return true; } + +/// A frame's length at 60 Hz, what a tick of the follow is clamped to. +const frame_ns: u64 = 16 * std.time.ns_per_ms; + +/// A view that follows its input (anim 9, 11): the picture's offset from +/// the core's position now (rows of text; negative, the picture still +/// shows what is above), its speed (rows a second), when it was last +/// integrated, and what has been feeding it. +pub const Follow = struct { + offset: f32 = 0, + speed: f32 = 0, + at_ns: u64 = 0, + /// The last inputs (down positive), their spacing, the last's time, and + /// how many came as one stream. + feed: struct { amount: f32 = 0, gap_ns: u64 = 0, last_ns: u64 = 0, count: u16 = 0 } = .{}, + + /// How far the picture may lag, in bodies (a flick past that jumps); + /// how fast it may move, in bodies a second, so moving text stays + /// readable. + pub const reach = 2; + pub const bodies_per_s: f32 = 15; + /// Inputs this close, each the way the last went, are one stream. + pub const stream_ns = 150 * std.time.ns_per_ms; + /// The spring's natural frequency, rad/s: arrivals land inside §8.1's + /// 220 ms. + pub const omega: f32 = 51; + + /// What a view's size makes of the rules: the speed cap, the lag cap, + /// and the offset under which it is at rest (a tenth of a pixel, in + /// rows). + pub const Pace = struct { cap: f32, limit: f32, rest: f32 }; + + pub fn pace(body: f32, rest: f32) Pace { + return .{ .cap = body * bodies_per_s, .limit = body * reach, .rest = rest }; + } + + pub fn moving(follow: *const Follow) bool { + return follow.offset != 0 or follow.speed != 0; + } + + /// An input: the core moved `amount` (down positive). The picture now + /// lags by as much more, its speed as it was. + pub fn kick(follow: *Follow, amount: f32, now_ns: u64, p: Pace) void { + follow.advance(now_ns, p); + follow.offset = std.math.clamp(follow.offset - amount, -p.limit, p.limit); + const f = &follow.feed; + const like = f.count > 0 and (amount > 0) == (f.amount > 0) and now_ns -| f.last_ns < stream_ns; + if (like) { + const gap = now_ns -| f.last_ns; + f.gap_ns = if (f.count == 1) gap else (f.gap_ns + gap) / 2; + f.amount = (f.amount + amount) / 2; + f.count +|= 1; + } else f.* = .{ .amount = amount, .count = 1 }; + f.last_ns = now_ns; + } + + /// The system moved on to `now_ns`. Fed by a stream, at the stream's + /// rate (an input's amount over their spacing), held a lag `lead` + /// behind so a late input never finds it stopped and the stream's end + /// never runs it past its mark; else on the spring, critically damped, + /// from the speed it has. Never faster than `p.cap`. + pub fn advance(follow: *Follow, now_ns: u64, p: Pace) void { + const dt: f32 = @floatCast(@as(f64, @floatFromInt(@min(now_ns -| follow.at_ns, 2 * frame_ns))) / std.time.ns_per_s); + follow.at_ns = now_ns; + if (follow.offset == 0 and follow.speed == 0) return; + const toward: f32 = if (follow.offset < 0) 1 else -1; + const f = follow.feed; + if (f.count >= 2 and f.gap_ns > 0 and now_ns -| f.last_ns < f.gap_ns * 3 / 2) { + const gap: f32 = @floatCast(@as(f64, @floatFromInt(f.gap_ns)) / std.time.ns_per_s); + const rate = @abs(f.amount) / gap; + const lead = @max(@abs(f.amount), rate / omega); + // ponytail: a gentle pull to the lead (a tenth an input), so the + // per-frame step varies by a tenth; a stream's own jitter beyond + // that shows. An estimate of the input clock if it ever matters. + // A slow stream's lag runs out before its next input: never + // faster than the spring's own pace from there (omega a unit of + // lag a second), so it eases onto the mark, not into it at speed. + const v = std.math.clamp(rate + 0.1 / gap * (@abs(follow.offset) - lead), 0, @min(p.cap, omega * @abs(follow.offset))); + const step = @min(v * dt, @abs(follow.offset)); + follow.offset += toward * step; + follow.speed = if (follow.offset == 0) 0 else toward * v; + return; + } + const x = follow.offset; + // Coming to rest from a stream: never faster than the spring's own + // pace from here (omega a unit of lag a second), so it eases in and + // does not pass its mark. + if (follow.speed * x < 0 and @abs(follow.speed) > omega * @abs(x)) follow.speed = std.math.sign(follow.speed) * omega * @abs(x); + const lead_v = follow.speed + omega * x; + const decay = @exp(-omega * dt); + var next = (x + lead_v * dt) * decay; + var speed = (follow.speed - omega * dt * lead_v) * decay; + if (@abs(next - x) > p.cap * dt) { + next = x + std.math.sign(next - x) * p.cap * dt; + speed = std.math.sign(next - x) * p.cap; + } + follow.offset = next; + follow.speed = speed; + if (@abs(next) < p.rest and @abs(speed) < 10 * p.rest) follow.* = .{ .at_ns = now_ns }; + } +}; + +test "a follow comes to rest without a snap: past its fastest frame each step is shorter, the last under a tenth of a pixel" { + // A flick's spin (a stream of notches, then nothing), one page, and + // notches slow enough that each lag runs out before the next (its + // stream must ease onto each mark, never pass it). + const p = Follow.pace(600, 0.1); + for ([_]struct { n: u16, gap_ms: u64 }{ .{ .n = 12, .gap_ms = 16 }, .{ .n = 1, .gap_ms = 16 }, .{ .n = 6, .gap_ms = 144 } }) |run| { + var f: Follow = .{}; + var now: u64 = std.time.ns_per_s; + for (0..run.n) |_| { + f.kick(if (run.n == 1) 600 else 25, now, p); + var waited: u64 = 0; + while (waited < run.gap_ms) : (waited += 8) { + now += 8 * std.time.ns_per_ms; + const was = f.offset; + f.advance(now, p); + // Toward its mark only, and onto it from under a pixel. + try std.testing.expect(f.offset <= 0 and f.offset >= was); + if (f.offset == 0) try std.testing.expect(-was <= 3 * p.rest); + } + } + var last: f32 = std.math.inf(f32); + var before = f.offset; + var frames: usize = 0; + var fastest: f32 = 0; + while (f.moving()) : (frames += 1) { + now += frame_ns; + f.advance(now, p); + const step = @abs(f.offset - before); + try std.testing.expect(@abs(f.offset) <= @abs(before)); + if (f.offset == 0) try std.testing.expect(step <= 3 * p.rest); + fastest = @max(fastest, step); + if (step < fastest) try std.testing.expect(step <= last); + last = step; + before = f.offset; + try std.testing.expect(frames < 120); + } + try std.testing.expect(last <= 0.1); + } +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 343ad991..8d69ed80 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -999,6 +999,12 @@ const Gui = struct { trail: JumpTrail = .{}, /// The caret's ease, on the window's own clock (Caret). caret: Caret = .{}, + /// The window's clock for the frame being drawn (Shell.ownNow), and + /// what moved the glide's view since the last (stepGlide): the pane a + /// wheel scrolled, one a touchpad moves by the pixel. + now_ns: u64 = 0, + glide_wheeled: ?usize = null, + glide_direct: ?usize = null, /// The last key, click or wheel, which the blink holds for. input_ns: u64 = 0, live_ctrl: bool = false, @@ -2214,7 +2220,7 @@ fn remoteSession(init: std.process.Init, g: *Gui, opts_in: pardes.Options, test_ } } -const frame_ms: c_int = @intCast(pardes.animation.frame_ns / std.time.ns_per_ms); +const frame_ms: c_int = @intCast(pardes.frame_ns / std.time.ns_per_ms); const StdinFeed = struct { parser: vaxis.Parser = .{}, @@ -3253,6 +3259,12 @@ const Shell = struct { s.closeTheWindow(); } + /// The window's own clock: the test's virtual one, the paced tick, else + /// SDL's. + fn ownNow(s: *const Shell) u64 { + return s.test_clock orelse s.paced_ns orelse c.SDL_GetTicksNS(); + } + /// The Gui holds the window of the core's live view. fn follow(s: *Shell) void { const g = s.gui orelse return; @@ -3646,7 +3658,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // a present to retry. A minimized window sleeps through the core's animation // too: nothing shows it, and it is caught up at once when the window // is back. - const polls = g.scroll_lag != 0 or g.scroll_delta != 0 or g.scroll_notch != 0 or g.glide.moving() or g.gamepad != null or s.test_mode or core.needs_frame; + const polls = g.scroll_lag != 0 or g.scroll_delta != 0 or g.scroll_notch != 0 or frontendMoving(g) or g.gamepad != null or s.test_mode or core.needs_frame; const minimized = !s.test_mode and c.SDL_GetWindowFlags(g.window) & (c.SDL_WINDOW_MINIMIZED | c.SDL_WINDOW_OCCLUDED) != 0; // A latency trace is fed on stdin, whose poll below paces the loop: // waiting here too would make every tick cost two frames. @@ -3674,7 +3686,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // phase is our own, not the display's (no vblank time to read on the // soft present); a 59.94 Hz display drifts a tick every 17 s. The // upgrade: the presentation feedback protocol's timestamps. - const paced = s.test_clock == null and latency_fd < 0 and !s.test_mode and !minimized and core.continuous(); + const paced = s.test_clock == null and latency_fd < 0 and !s.test_mode and !minimized and frontendMoving(g); var tick: u64 = 0; if (paced) { const period = refreshNs(g); @@ -3704,7 +3716,7 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // frame with the new alpha, no core render (§5.5 level B). if (blink_ms != null and (blink.?.edge or !got)) g.blink_due = true; if (s.test_clock) |*virtual| { - if (core.continuous()) { + if (frontendMoving(g)) { const display = virtual.* + std.time.ns_per_s / s.test_hz; virtual.* = if (core.nextWake()) |due| @max(virtual.*, @min(due, display)) else display; } else if (timeout_ms != 0 and (!got or !core.needs_frame)) { @@ -3868,9 +3880,11 @@ fn pollFrame(ctx: ?*anyopaque) void { if (updateCoreResize(core, geom.cols, geom.rows, g.cell_w, g.cell_h, g.tagline_width, g.tagline_height)) resetScroll(g); stepScroll(g, core, s.gpa); if (s.test_mode) writeTestStatus(g, core, s.presented); - // A blink edge: the last frame again, the cursor's alpha moved on. - if (g.blink_due and !core.needs_frame and s.presented) if (s.surface) |frame| { + // A blink edge, or the window's own motion (its glide, its caret, a + // jump's trail): the last frame again, moved on, no core render. + if ((g.blink_due or frontendMoving(g)) and !core.needs_frame and s.presented) if (s.surface) |frame| { g.blink_due = false; + g.now_ns = s.ownNow(); s.presented = renderFrame(g, s.gpa, core, frame) catch false; }; } @@ -3975,20 +3989,65 @@ fn runDemo(g: *Gui, in: *Input, core: *pardes.Pardes) void { /// The blink now, from the frame's time since input and how long ago it /// arrived; null where nothing blinks (off, idle, an unfocused window). -fn blinkNow(g: *const Gui, on: bool) ?pardes.animation.Blink { +/// The cursor's opacity under blink (§5.4): solid while typing and for +/// `hold_ns` after, then on and off with an eased edge, solid again after +/// `idle_ns` of no input. `edge` says whether it is mid-edge (a frame is +/// owed), `next_ns` when the next edge starts (a wake). +pub const Blink = struct { + pub const hold_ns: u64 = 500 * std.time.ns_per_ms; + pub const idle_ns: u64 = 10 * std.time.ns_per_s; + pub const half_ns: u64 = 530 * std.time.ns_per_ms; + pub const edge_ns: u64 = 80 * std.time.ns_per_ms; + + alpha: f32, + edge: bool, + next_ns: ?u64, + + pub fn at(now_ns: u64, input_ns: u64) Blink { + const since = now_ns -| input_ns; + if (since < hold_ns) return .{ .alpha = 1, .edge = false, .next_ns = input_ns + hold_ns + half_ns - edge_ns }; + if (since >= hold_ns + idle_ns) return .{ .alpha = 1, .edge = false, .next_ns = null }; + const t = (since - hold_ns) % (2 * half_ns); + const cycle_start = now_ns - t; + // On for a half, easing out over its last `edge_ns`; off for a half, + // easing back in over its last. + if (t < half_ns - edge_ns) return .{ .alpha = 1, .edge = false, .next_ns = cycle_start + half_ns - edge_ns }; + if (t < half_ns) return .{ .alpha = 1 - smooth(@as(f32, @floatFromInt(t - (half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; + if (t < 2 * half_ns - edge_ns) return .{ .alpha = 0, .edge = false, .next_ns = cycle_start + 2 * half_ns - edge_ns }; + return .{ .alpha = smooth(@as(f32, @floatFromInt(t - (2 * half_ns - edge_ns))) / @as(f32, @floatFromInt(edge_ns))), .edge = true, .next_ns = null }; + } + + fn smooth(x: f32) f32 { + const u = std.math.clamp(x, 0, 1); + return u * u * (3 - 2 * u); + } +}; + +test "a blink holds while typing, eases at its edges and stops when idle" { + const ms = std.time.ns_per_ms; + try std.testing.expectEqual(@as(f32, 1), Blink.at(100 * ms, 0).alpha); + const out = Blink.at(Blink.hold_ns + Blink.half_ns + 100 * ms, 0); + try std.testing.expectEqual(@as(f32, 0), out.alpha); + const edge = Blink.at(Blink.hold_ns + Blink.half_ns - Blink.edge_ns / 2, 0); + try std.testing.expect(edge.edge and edge.alpha > 0.2 and edge.alpha < 0.8); + try std.testing.expectEqual(@as(?u64, null), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).next_ns); + try std.testing.expectEqual(@as(f32, 1), Blink.at(Blink.hold_ns + Blink.idle_ns + ms, 0).alpha); +} + +fn blinkNow(g: *const Gui, on: bool) ?Blink { if (g.no_blink or !on or !g.caret.placed) return null; if (c.SDL_GetWindowFlags(g.window) & c.SDL_WINDOW_INPUT_FOCUS == 0) return null; const since = monoNs() -| g.input_ns; // Relative to now: `next_ns` is how long until the next edge. - const b = pardes.animation.Blink.at(since, 0); + const b = Blink.at(since, 0); return .{ .alpha = b.alpha, .edge = b.edge, .next_ns = if (b.next_ns) |next| next -| since else null }; } /// One refresh of the display the window is on, in ns; a frame of the /// core's where the display does not say. fn refreshNs(g: *const Gui) u64 { - const mode = c.SDL_GetCurrentDisplayMode(c.SDL_GetDisplayForWindow(g.window)) orelse return pardes.animation.frame_ns; - if (!(mode.*.refresh_rate > 1)) return pardes.animation.frame_ns; + const mode = c.SDL_GetCurrentDisplayMode(c.SDL_GetDisplayForWindow(g.window)) orelse return pardes.frame_ns; + if (!(mode.*.refresh_rate > 1)) return pardes.frame_ns; return @intFromFloat(@as(f64, std.time.ns_per_s) / mode.*.refresh_rate); } @@ -4045,6 +4104,7 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { const frame = surface; s.surface = frame; g.frame_arrival_ns = monoNs(); + g.now_ns = s.ownNow(); s.presented = renderFrame(g, s.gpa, core, frame) catch |err| blk: { log.err("render: {t}", .{err}); break :blk false; @@ -4559,13 +4619,10 @@ test "a wheel over codex in a terminal reaches its pty as the mouse reports it a const Glide = pardes.glide.Glide; -/// Feeds a wheel's notches to the core, then steps the glide (Glide.step) -/// and asks for frames while it moves. +/// Feeds a wheel's notches to the core, and keeps what moved the view for +/// the frame's glide (Glide.frame). fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { - const glide = &g.glide; - // The glide runs on the core's continuous path: frames every loop, and - // a virtual clock carried on. - defer core.shell_continuous = glide.moving() or g.trail.active or g.caret.moving(); + _ = gpa; const notch = g.scroll_notch; g.scroll_notch = 0; var wheeled: ?usize = null; @@ -4592,9 +4649,22 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } if (wheeled != null) core.needs_frame = true; } + if (wheeled != null) g.glide_wheeled = wheeled; // Not a view a touchpad is moving by the pixel. - const direct: ?usize = if (g.scroll_lag != 0 or g.scroll_delta != 0) g.scroll_pane else null; - glide.step(core, gpa, wheeled, direct); + g.glide_direct = if (g.scroll_lag != 0 or g.scroll_delta != 0) g.scroll_pane else null; +} + +/// The window's own motions under way (its glide, its caret, a jump's +/// trail): it draws their frames itself, on its own clock. +fn frontendMoving(g: *const Gui) bool { + return g.glide.moving() or g.caret.moving() or g.trail.active; +} + +/// The frame's glide (Glide.frame) on the window's clock, with what moved +/// its view since the last. +fn glideFrame(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { + g.glide.frame(gpa, surface, g.now_ns, g.glide_wheeled, g.glide_direct); + g.glide_wheeled = null; } test "a notch scrolls the core at once and the picture glides after it, a wrapped line's rows at a time" { @@ -4610,7 +4680,6 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe try text.append(gpa, '\n'); } _ = try core.setTestFile(text.items); - core.settings.motion = .smooth; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const ms = std.time.ns_per_ms; @@ -4626,19 +4695,19 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe const body_y = core.bodyTop(core.panes[core.active].?, r); const row_before = try gpa.dupe(pardes.Cell, s.cells[@as(usize, body_y + 1) * s.cols + r.x + config.GUTTER ..][0 .. r.w - config.GUTTER]); defer gpa.free(row_before); - // The loop has seen the view once (stepGlide finds a view that moved). - stepGlide(&g, core, gpa); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); // One notch down: the core is a line on at once. g.scroll_notch = 1; const scrolled = core.panes[core.active].?.scroll(); stepGlide(&g, core, gpa); try std.testing.expectEqual(scrolled + 1, core.panes[core.active].?.scroll()); - try std.testing.expect(g.glide.pending); - // On the core's continuous path while it moves: frames every loop. - try std.testing.expect(core.shell_continuous and core.continuous()); _ = arena.reset(.retain_capacity); s = try core.render(arena.allocator()); - g.glide.measure(gpa, s); + glideFrame(&g, gpa, s); + // The window's own motion: it draws its frames while it moves. + try std.testing.expect(frontendMoving(&g)); // Its two rows: the picture two rows behind, the rows that left kept, // nearest first. try std.testing.expectApproxEqAbs(@as(f32, -2), g.glide.follow.offset, 1e-4); @@ -4650,17 +4719,14 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe now += 7 * ms; core.advance(now); stepGlide(&g, core, gpa); + g.now_ns = now; + glideFrame(&g, gpa, s); try std.testing.expect(g.glide.follow.offset <= 1e-4); if (frames > 200) return error.NeverSettled; } try std.testing.expect(frames > 5); try std.testing.expectEqual(@as(f32, 0), g.glide.follow.offset); - try std.testing.expect(!core.shell_continuous); - // Motion off: a notch lands at once. - core.settings.motion = .off; - g.scroll_notch = 1; - stepGlide(&g, core, gpa); - try std.testing.expect(!g.glide.pending and !g.glide.moving()); + try std.testing.expect(!frontendMoving(&g)); } test "a wheel's caret rides with its line, the text's own glide, never a spring of its own" { @@ -4672,7 +4738,6 @@ test "a wheel's caret rides with its line, the text's own glide, never a spring defer text.deinit(gpa); for (0..200) |i| try text.print(gpa, "line {d}\n", .{i}); _ = try core.setTestFile(text.items); - core.settings.motion = .smooth; core.settings.cursor_blink = false; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); @@ -4691,6 +4756,9 @@ test "a wheel's caret rides with its line, the text's own glide, never a spring g.scroll_col = r.x + 10; g.scroll_row = r.y + r.h - 2; stepGlide(&g, core, gpa); + // The window has drawn the view once (Glide.frame finds a view that moved). + g.now_ns = now; + glideFrame(&g, gpa, s); const before: f32 = @floatFromInt(s.cursor.?.y); g.scroll_notch = 1; stepGlide(&g, core, gpa); @@ -4700,7 +4768,8 @@ test "a wheel's caret rides with its line, the text's own glide, never a spring core.advance(now); _ = arena.reset(.retain_capacity); s = try core.render(arena.allocator()); - if (g.glide.pending) g.glide.measure(gpa, s); + g.now_ns = now; + glideFrame(&g, gpa, s); seeCaret(&g, s, fixedCellLayout(&g), 480, now); if (frames == 0) { try std.testing.expect(g.glide.caret_rides); @@ -4738,8 +4807,8 @@ const GlideRun = struct { stepGlide(g, core, gpa); _ = arena.reset(.retain_capacity); const s = try core.render(arena.allocator()); - if (g.glide.pending) g.glide.measure(gpa, s); - if (g.glide.moving()) g.glide.advance(g.glide.now_ns, g.glide.motion); + g.now_ns = now; + glideFrame(g, gpa, s); seeCaret(g, s, fixedCellLayout(g), @floatFromInt(@as(u32, s.rows) * g.cell_h), now); seq.offsets[frame] = g.glide.follow.offset; seq.lines[frame] = @intCast(core.panes[core.active].?.file.?.scroll); @@ -4772,7 +4841,7 @@ const GlideRun = struct { } }; -test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting, and Motion off lands at once" { +test "every scroll glides on one law: a half page, a page, the far jumps, a run of them retargeting" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .cols = 100, .rows = 40 }); defer core.deinit(); @@ -4781,7 +4850,6 @@ test "every scroll glides on one law: a half page, a page, the far jumps, a run // Numbered lines no two alike, short enough never to wrap. for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); _ = try core.setTestFile(text.items); - core.settings.motion = .smooth; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); core.advance(std.time.ns_per_s); @@ -4837,12 +4905,6 @@ test "every scroll glides on one law: a half page, a page, the far jumps, a run // done as soon after the last as one half page alone takes. for (160..180) |k| try std.testing.expect(seq.offsets[k] != 0); try std.testing.expect(seq.settle(175) <= seq.settle(2) + 4); - // Motion off: the same scroll lands at once. - core.settings.motion = .off; - var off: GlideRun = .{}; - try off.play(&g, core, gpa, &arena, &.{.{ .frame = 1, .key = ctrl.key('u') }}, 10); - try std.testing.expect(off.lines[1] != off.lines[0]); - for (off.offsets[0..off.frames]) |offset| try std.testing.expectEqual(@as(f32, 0), offset); } test "a held key moves the view at the stream's own rate, never a bounce a line, and settles once it stops" { @@ -4853,7 +4915,6 @@ test "a held key moves the view at the stream's own rate, never a bounce a line, defer text.deinit(gpa); for (0..3000) |i| try text.print(gpa, "{d:0>5} line {d} of the long file\n", .{ i, i * 7 % 13 }); _ = try core.setTestFile(text.items); - core.settings.motion = .smooth; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); core.advance(std.time.ns_per_s); @@ -5418,10 +5479,9 @@ fn renderFrame( const chrome = &surface.chrome; // G6: what the scroll just done moved the pane's rows by, measured on // this frame against the last (the glide follows it from there). - if (g.glide.pending) g.glide.measure(gpa, surface); - if (g.glide.moving()) g.glide.advance(g.glide.now_ns, g.glide.motion); + glideFrame(g, gpa, surface); var groups: Groups = .{}; - const now = monoNs(); + const now = g.now_ns; seeCaret(g, surface, layout, win_h, now); // While the cursor glides or blinks the cells' cursors are not drawn; // the focused one is the overlay's quad. One or the other every frame @@ -5435,17 +5495,13 @@ fn renderFrame( // stay legible; solid again as it lands. const caret_alpha: f32 = if (gliding) 0.85 + 0.15 * std.math.clamp(1 - g.caret.remaining(now) / 0.5, 0, 1) else 1; g.cursor_quad_alpha = if (quad_mode) caret_alpha * blink_alpha else 0; - // A gliding caret asks for the frames it glides through. - if (gliding) core.shell_continuous = true; // The probe's view of this frame's motion (FrameStats.Frame). // A focused PDF's strip is the core's (pdf_view.draw). const pdf_focus = if (core.panes[core.active]) |pane| pane.hasPdf() else false; if (!pdf_focus) core.frames.scroll = g.glide.follow.offset; core.frames.caret = caretRow(g, surface, now) orelse 0; const cursors_shown = !quad_mode; - var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail and core.settings.motion != .off, surface, now, sw, sh); - // A trail fading asks for the frames it fades through. - if (g.trail.active) core.shell_continuous = true; + var overlay_count = buildOverlay(g, core.settings.pet, core.settings.jump_trail, surface, now, sw, sh); if (overlay_count != 0 and !uploadOverlayGpu(g, cmd, overlay_count)) overlay_count = 0; if (!prepareNativeImages(g, gpa, cmd, surface, &groups, sw, sh)) { @@ -7361,11 +7417,11 @@ var test_status_step: u64 = 0; fn writeTestStatus(g: *const Gui, core: *const pardes.Pardes, presented: bool) void { test_status_step +%= 1; if (g.capture_dir.len == 0) return; - const idle = presented and !core.needs_frame and !core.continuous() and core.nextWake() == null and + const idle = presented and !core.needs_frame and !frontendMoving(g) and core.nextWake() == null and !g.glide.moving() and g.scroll_lag == 0 and g.scroll_delta == 0 and g.scroll_notch == 0; var line_buf: [64]u8 = undefined; // What keeps it busy, after: owes a frame, moves, waits, not shown. - const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(core.continuous()), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch return; + const line = std.fmt.bufPrint(&line_buf, "{d} {d} {d} {d}{d}{d}{d}\n", .{ test_status_step, g.captured, @intFromBool(idle), @intFromBool(core.needs_frame), @intFromBool(frontendMoving(g)), @intFromBool(core.nextWake() != null), @intFromBool(!presented) }) catch return; var tmp_buf: [4096]u8 = undefined; var final_buf: [4096]u8 = undefined; const tmp_path = std.fmt.bufPrintSentinel(&tmp_buf, "{s}/status.tmp", .{g.capture_dir}, 0) catch return; diff --git a/src/layout.zig b/src/layout.zig index 46db6439..9c600cd7 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -4,8 +4,6 @@ const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const config = @import("config.zig"); const panes = @import("panes.zig"); -const animation = @import("animation.zig"); -const Box = animation.Box; const Pardes = pardes.Pardes; const Pane = pardes.Pane; pub const Rect = struct { x: u16 = 0, y: u16 = 0, w: u16 = 0, h: u16 = 0 }; @@ -1167,15 +1165,6 @@ fn collapseGroup(p: *Pardes, c: usize, start: usize, end: usize) void { compute(p); } -pub fn panelBox(rect: Rect) Box { - return .{ - .x = @floatFromInt(rect.x), - .y = @floatFromInt(rect.y), - .w = @floatFromInt(rect.w), - .h = @floatFromInt(rect.h), - }; -} - pub fn columnBoundary(width: u16, prefix: u128, total: u128) u16 { if (total == 0) return 0; const pixels = (@as(u128, width) * prefix + total / 2) / total; diff --git a/src/pardes.zig b/src/pardes.zig index fb5b7f43..ec684b78 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1,6 +1,9 @@ const std = @import("std"); pub const layout = @import("layout.zig"); -pub const animation = @import("animation.zig"); +/// The core's step: `advance` runs a `.tick` a frame of this, and +/// `nextWake` answers in whole frames of it. +pub const frame_ms: u32 = 16; +pub const frame_ns: u64 = frame_ms * std.time.ns_per_ms; pub const glide = @import("glide.zig"); pub const FrameStats = @import("FrameStats.zig"); pub const modal = @import("modal.zig"); @@ -446,7 +449,6 @@ test { _ = @import("upgrade.zig"); _ = @import("recent.zig"); _ = @import("Store.zig"); - _ = @import("animation.zig"); _ = @import("pager.zig"); _ = @import("Places.zig"); _ = @import("FrameStats.zig"); @@ -3369,10 +3371,6 @@ pub const Pardes = struct { chrome: colors.ChromeTheme = colors.initial_chrome, /// Every drawn frame's timings (FrameStats: the Debug box, PARDES_FRAMES). frames: FrameStats = .{}, - /// A pixel shell's own render-time motion is under way (its smooth - /// scroll, G6): the core then keeps the continuous path running, so the - /// shell draws every loop and a virtual clock moves on, as for a lift. - shell_continuous: bool = false, native_images: bool = false, /// The shell can take a changed image a few rows at a time (a texture row /// upload, a shared-memory hand-off), so a PDF selection is repainted as @@ -3499,7 +3497,7 @@ pub const Pardes = struct { present_skipped: bool = false, /// Core time. `now_ns` is the shell's monotonic clock as `advance` was /// last given it; `stepped_ns` is how far animation has been stepped - /// along it, in whole frames of `animation.frame_ns`. Idle, the two are + /// along it, in whole frames of `frame_ns`. Idle, the two are /// the same instant. now_ns: u64 = 0, stepped_ns: u64 = 0, @@ -3591,7 +3589,7 @@ pub const Pardes = struct { // A frame, and the animations and timings that make it. "surface", "frames", "chrome", "frame_arena", "scratch", - "needs_frame", "present_skipped", "shell_continuous", "native_image_patches", + "needs_frame", "present_skipped", "native_image_patches", "echo", // Drained by every pump before its digest; a replica's queues // are its own. @@ -5016,7 +5014,7 @@ pub const Pardes = struct { // waits on is its own (a picture decoding wakes only a frame // that draws it), and the tape has the same calls either way. const now = if (v.now) |clock| clock(h.ctx) else p.now_ns; - const timeout: u32 = if (p.continuous()) 1 else if (p.nextWake()) |due| wake: { + const timeout: u32 = if (p.nextWake()) |due| wake: { const ms = ((due -| now) + std.time.ns_per_ms - 1) / std.time.ns_per_ms; break :wake @intCast(std.math.clamp(ms, 1, std.math.maxInt(u32))); } else 0; @@ -5038,7 +5036,7 @@ pub const Pardes = struct { // rendering and nothing else. // A shell with a clock draws what `advance` stepped; one without // steps its own `.tick`s and draws while anything animates. - if (!p.needs_frame and !p.continuous() and (v.now != null or !p.animationActive())) return p.frames.idle(); + if (!p.needs_frame and (v.now != null or !p.animationActive())) return p.frames.idle(); // No one to see it: the frame stays owed (needs_frame), not drawn. // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. @@ -5063,8 +5061,8 @@ pub const Pardes = struct { p.present_skipped = false; if (v.post_present) |f| f(h.ctx); // Still moving: the next frame is owed a period from now. - const owed = if (p.nextWake()) |due| due <= p.stepped_ns + animation.frame_ns else false; - p.frames.record(FrameStats.nowNs(), owed or p.continuous(), skipped); + const owed = if (p.nextWake()) |due| due <= p.stepped_ns + frame_ns else false; + p.frames.record(FrameStats.nowNs(), owed, skipped); } /// What a pump does between its wait and its frame: the queued inputs @@ -6809,7 +6807,7 @@ pub const Pardes = struct { /// the core owns is in this one list, which is what lets every shell /// sleep exactly as long as nothing changes. pub fn nextWake(p: *const Pardes) ?u64 { - const next = p.stepped_ns + animation.frame_ns; + const next = p.stepped_ns + frame_ns; // Held 9P writes go in when they pause: wake for it, never before // the next frame (writes served before the shell's clock was first // seen are stamped 0, which `advance` would count back from). @@ -6827,7 +6825,7 @@ pub const Pardes = struct { const streaming = p.stream.wake(next); if (streaming) |due| if (due <= next) return next; var frames: ?u64 = null; - if (streaming) |due| frames = @max(1, (due -| p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); + if (streaming) |due| frames = @max(1, (due -| p.stepped_ns + frame_ns - 1) / frame_ns); if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames; frames = @max(1, delay -| waiting.frames); @@ -6839,13 +6837,13 @@ pub const Pardes = struct { // Del's question goes up at the end of its delay: a frame then, and // none after (stepped time has reached it). for (p.panes) |slot| if (slot) |pane| if (pane.prompt == .del_side and pane.question_due_ns > p.stepped_ns) { - const wait = @max(1, (pane.question_due_ns - p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); + const wait = @max(1, (pane.question_due_ns - p.stepped_ns + frame_ns - 1) / frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; }; // A paste's Enter waiting on its REPL goes at the end of its wait, // a time on the clock: the frames from `stepped_ns` that reach it. for (p.panes) |slot| if (slot) |pane| if (pane.repl_enter > 0) { - const wait = @max(1, (pane.repl_enter_due_ns -| p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); + const wait = @max(1, (pane.repl_enter_due_ns -| p.stepped_ns + frame_ns - 1) / frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; }; // A terminal's kitty animation, at its next frame. Only a time still @@ -6854,25 +6852,17 @@ pub const Pardes = struct { for (p.panes) |slot| if (slot) |pane| if (panes.terminal.animationDueMs(pane)) |due_ms| { const due = due_ms *| std.time.ns_per_ms; if (due > p.stepped_ns) { - const wait = @max(1, (due - p.stepped_ns + animation.frame_ns - 1) / animation.frame_ns); + const wait = @max(1, (due - p.stepped_ns + frame_ns - 1) / frame_ns); frames = if (frames) |soonest| @min(soonest, wait) else wait; } }; - return if (frames) |n| p.stepped_ns + n * animation.frame_ns else null; - } - - /// A render-time animation is moving (a pane's lift): it is sampled at - /// each frame's own `now`, so while it moves the shell draws every loop - /// and its present (vsync) paces it, at the display's rate. `nextWake` - /// is for the stepped animations, which count frames of `frame_ns`. - pub fn continuous(p: *const Pardes) bool { - return p.shell_continuous or panes.Pdf.moving(p); + return if (frames) |n| p.stepped_ns + n * frame_ns else null; } /// For shells that only need a yes or no: macOS, which keeps its own /// frame bank. pub fn animationActive(p: *const Pardes) bool { - return p.nextWake() != null or p.continuous(); + return p.nextWake() != null; } /// Bring core animation up to `now_ns`, the shell's monotonic clock: one @@ -6889,7 +6879,7 @@ pub const Pardes = struct { p.clock_started = true; p.now_ns = now_ns; if (!started) p.stepped_ns = now_ns; - const frame = animation.frame_ns; + const frame = frame_ns; var moving: u32 = 0; // The session's ticks are the recording session's: a picture still // decoding or a fade still moving asks for frames the way a message @@ -7503,7 +7493,7 @@ test "the Del question shows only once its delay is up: a quick SPC d j never se for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt); // The loop wakes for it, at the end of the delay and not before. const wake = p.nextWake().?; - try std.testing.expect(wake >= pane.question_due_ns and wake < pane.question_due_ns + animation.frame_ns); + try std.testing.expect(wake >= pane.question_due_ns and wake < pane.question_due_ns + frame_ns); p.now_ns = pane.question_due_ns - 1; _ = try p.render(frame.allocator()); for (pane.notices.kinds[0..pane.notices.len]) |kind| try std.testing.expect(kind != .prompt); diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 5a371720..e615521d 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -193,81 +193,6 @@ test "PDF selections retain their owning page across page focus" { try std.testing.expectEqual(@as(usize, 0), state.selection_text.len); } -test "a PDF strip glides a notch and a page to their marks, eased and never past them, and follows a touchpad's fraction at once" { - if (comptime !enabled) return; - const gpa = std.testing.allocator; - var state = try State.open(gpa, "docs/design.pdf", 1); - defer state.deinit(gpa); - const view: Viewport = .{ .pixel_w = 800, .pixel_h = 600 }; - const motion = pardes.animation.Motion.of(.smooth); - ensureLayout(&state, view); - var now: u64 = std.time.ns_per_s; - try std.testing.expectEqual(state.document_scroll_y, stripAt(&state, view, motion, now)); - for ([_]f64{ 20, 600 }) |step| { - const from = state.document_scroll_y; - _ = scrollDocument(&state, view, step); - const mark = state.document_scroll_y; - // The input's frame still shows where it was; then it eases in. - var shown = stripAt(&state, view, motion, now); - try std.testing.expectEqual(from, shown); - var last_step: f64 = 0; - var peaked = false; - for (0..60) |_| { - now += pardes.animation.frame_ns; - const next = stripAt(&state, view, motion, now); - const moved = next - shown; - try std.testing.expect(moved >= 0 and next <= mark); - // Past its fastest, each frame's step is no longer than the last. - if (moved < last_step) peaked = true; - if (peaked) try std.testing.expect(moved <= last_step + 1e-9); - last_step = moved; - shown = next; - } - try std.testing.expectEqual(mark, shown); - try std.testing.expect(!state.follow.moving()); - try std.testing.expect(last_step <= 1); - } - // A touchpad's fraction: drawn where the core is, the same frame. - const from = state.document_scroll_y; - _ = scrollDocument(&state, view, 0.25); - state.direct_y += state.document_scroll_y - from; - try std.testing.expectEqual(from + 0.25, stripAt(&state, view, motion, now)); -} - -test "a PDF glide renders the pages it crosses in its input's frame, but a far jump's only where it comes to rest" { - if (comptime !enabled) return; - const gpa = std.testing.allocator; - var state = try State.open(gpa, "docs/design.pdf", 1); - defer state.deinit(gpa); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - const view: Viewport = .{ .pixel_w = 400, .pixel_h = 300 }; - const motion = pardes.animation.Motion.of(.smooth); - const key: TintKey = .{ .mode = .disabled, .colors = undefined }; - const none: HighlightInput = .{ .hover_color = .{ 0, 0, 0 }, .selection_color = .{ 0, 0, 0 } }; - ensureLayout(&state, view); - const frame = struct { - fn f(st: *State, a: *std.heap.ArenaAllocator, m: pardes.animation.Motion, k: TintKey, h: HighlightInput) void { - const v: Viewport = .{ .pixel_w = 400, .pixel_h = 300 }; - const shown = stripAt(st, v, m, std.time.ns_per_s); - st.document_scroll_y = shown; - _ = renderFrame(st, std.testing.allocator, a.allocator(), v, pardes.pdf_raster_policy, k, h, st.drawn_y - shown, st.far); - st.document_scroll_y = st.drawn_y; - } - }.f; - frame(&state, &arena, motion, key, none); - // A body down, onto page one's lower part: what it crosses is drawn. - _ = scrollDocument(&state, view, 300); - frame(&state, &arena, motion, key, none); - try std.testing.expect(!state.far and rasterForPage(&state, 0) != null); - // Far, to page three: only it; the slide comes in over page two's place. - state.document_scroll_y = @floatFromInt(state.page_starts[3]); - frame(&state, &arena, motion, key, none); - try std.testing.expect(state.far); - try std.testing.expect(rasterForPage(&state, 3) != null); - try std.testing.expect(rasterForPage(&state, 2) == null); -} - test "off the loop: pages land from lanes, a stale request's raster never lands, and a job nobody waits for is aborted" { if (comptime !enabled) return; const gpa = std.testing.allocator; @@ -631,11 +556,8 @@ pub const State = if (enabled) struct { layout_fit: FitMode = .width, layout_valid: bool = false, document_scroll_y: f64 = 0, - /// The strip as drawn lags `document_scroll_y` by `follow` (anim 11, - /// the text's motion system, in pixels): `drawn_y` is where the core - /// stood at the last frame, `direct_y` what moved it since that the - /// picture takes as it comes (a touchpad, a relayout). - follow: pardes.animation.Follow = .{}, + /// Where the core stood at the last frame (`drawn_y`), and what moved + /// it since by the pixel (`direct_y`: a touchpad, a relayout). drawn_y: f64 = 0, direct_y: f64 = 0, /// The last kick was a jump past a body (renderFrame's `far`). @@ -2540,7 +2462,6 @@ pub fn ensureLayout(state: *State, viewport: Viewport) void { state.drawn_y += state.document_scroll_y - before; state.relayout_keeps_motion = false; } else if (relaid) { - state.follow = .{}; state.drawn_y = state.document_scroll_y; state.direct_y = 0; } @@ -2973,10 +2894,9 @@ pub fn placeY(pane: *const pardes.Pane, at: Place) ?f64 { @as(f64, @floatFromInt(at.at)) / place_scale * @as(f64, @floatFromInt(state.page_heights[page])); } -/// A jump to `at` (Back, Forward): the core is there at once and the strip -/// follows through the motion system, a far one as one body's slide, the -/// page rendered where it comes to rest. Not laid out yet (a pane just -/// reopened), it is anchored there for the first layout. +/// A jump to `at` (Back, Forward): the strip is there at once. Not laid +/// out yet (a pane just reopened), it is anchored there for the first +/// layout. pub fn landAt(core: *pardes.Pardes, pane: *pardes.Pane, at: Place) void { if (comptime !enabled) return; const state = pane.pdf orelse return; @@ -3330,8 +3250,8 @@ pub fn highlightInput( }; } -/// `glide`: a notch, which the strip glides; else a touchpad's fraction, -/// which it follows as it comes. +/// `glide`: a notch; else a touchpad's fraction, counted as moved by the +/// pixel (`direct_y`). pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64, glide: bool) bool { if (comptime !enabled) return false; const tz = tracy.zone(@src(), "pdf.scroll_notch"); @@ -3345,33 +3265,16 @@ pub fn scrollPane(core: *pardes.Pardes, pane: *pardes.Pane, delta_pixels: f64, g return true; } -/// Where the strip is drawn this frame (anim 11): what moved the core's -/// position since the last frame kicks its follow, as a scroll kicks the -/// text's, all but what moved it directly; the follow then moves on to now. -fn stripAt(state: *State, view: Viewport, motion: pardes.animation.Motion, now_ns: u64) f64 { - const pace = pardes.animation.Follow.pace(motion, @floatFromInt(view.pixel_h), 0.1); - const moved = state.document_scroll_y - state.drawn_y - state.direct_y; +/// Where the strip is drawn this frame: where the core stands, a scroll +/// landing at once; which way it went, for the page rendered ahead. +fn stripAt(state: *State, view: Viewport) f64 { + const moved = state.document_scroll_y - state.drawn_y; + if (moved != 0) state.ahead = if (moved > 0) 1 else -1; state.drawn_y = state.document_scroll_y; state.direct_y = 0; - if (motion.instant) { - state.follow = .{}; - } else if (moved != 0) { - // A move past a body slides one, as a text's far jump does (G6): - // the pages between are rendered for the slide, not crossed. - const body: f64 = @floatFromInt(view.pixel_h); - state.far = @abs(moved) > body; - state.ahead = if (moved > 0) 1 else -1; - state.follow.kick(@floatCast(std.math.clamp(moved, -body, body)), now_ns, pace); - } else state.follow.advance(now_ns, pace); + state.far = false; const max_scroll = @as(f64, @floatFromInt(state.document_height -| view.pixel_h)); - return std.math.clamp(state.drawn_y + state.follow.offset, 0, max_scroll); -} - -/// A PDF strip is still on its way to where the core stands. -pub fn moving(core: *const pardes.Pardes) bool { - if (comptime !enabled) return false; - for (core.panes) |slot| if (slot) |pane| if (pane.pdf) |state| if (state.follow.moving()) return true; - return false; + return std.math.clamp(state.drawn_y, 0, max_scroll); } pub fn verticalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) void { @@ -3413,10 +3316,9 @@ pub fn draw( const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; applySizes(state, core.pdf_gpa); ensureLayout(state, view); - // Drawn where the strip's follow is; the core's position comes back - // after (`drawn_y`), unless a search's reveal moved it as it drew, - // which is then drawn there at once. - const shown = stripAt(state, view, pardes.animation.Motion.of(core.settings.motion), core.now_ns); + // Drawn where the core stands (`drawn_y`), unless a search's reveal + // moved it as it drew, which is then drawn there. + const shown = stripAt(state, view); state.document_scroll_y = shown; defer state.document_scroll_y = state.drawn_y; if (pane_id == core.active) core.frames.scroll = @floatCast(shown); @@ -3435,10 +3337,7 @@ pub fn draw( state.drawn_y - shown, state.far, ); - if (state.document_scroll_y != shown) { - state.follow = .{}; - state.drawn_y = state.document_scroll_y; - } + if (state.document_scroll_y != shown) state.drawn_y = state.document_scroll_y; var placed_any = false; var page = visible.first; const visible_end = visible.first + visible.len; diff --git a/src/surface.zig b/src/surface.zig index ec4d73b1..3716df4f 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -246,8 +246,10 @@ pub const Region = struct { /// A notice's index in its pane's `notices`. notice: u8 = 0, /// A body's view: the first line it shows (a file's scroll, a - /// terminal's grid offset). + /// terminal's grid offset), and the text it shows (`draw.place`'s doc: + /// 0 for a terminal or a picture), which a frontend's glide follows. line: i32 = 0, + doc: u64 = 0, /// Cells the column-move rail takes off the right edge while it runs /// there: layers and pixel shells stop short of them, the grid does not. clip: u16 = 0, diff --git a/src/tape.zig b/src/tape.zig index ad5a1c04..c76fd445 100644 --- a/src/tape.zig +++ b/src/tape.zig @@ -170,7 +170,7 @@ pub const shape = blk: { }; /// Fields a host writes straight into the core between its calls. -const watched = .{ "native_images", "native_image_patches", "present_skipped", "shell_continuous", "needs_frame", "quit", "windowed", "active", "unattended" }; +const watched = .{ "native_images", "native_image_patches", "present_skipped", "needs_frame", "quit", "windowed", "active", "unattended" }; const Kind = enum(u8) { input, done, host, ret, set, digest }; /// A digest record's kind byte (replica.zig reads a unit's last). diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 319e6c1b..05d29272 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -1335,7 +1335,7 @@ pub fn remote(init: std.process.Init, opts: pardes.Options, path: []const u8, se } if (link.owed or r.echo.changed) link.dirty = true; // Predictions out: judged a frame at a time while they are. - if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.animation.frame_ns / std.time.ns_per_ms)); + if (r.echo.n > 0 or r.echo.cursor != null or r.echo.nd > 0) requestWake(io, @intCast(pardes.frame_ns / std.time.ns_per_ms)); if (link.quietCheck()) |ms| requestWake(io, ms); if (r.diverged != null) link.quit = true; } @@ -1910,7 +1910,7 @@ const Shell = struct { .now = clockNow, .present = present, .post_present = postPresent, - .poll_frame = stepGlide, + .poll_frame = ownFrame, }; const vtable: host_io.Host.VTable = .{ @@ -2215,12 +2215,16 @@ const Shell = struct { const s = of(ctx); // The wait is the 9P connections' turn with the core. A timeout (the // core's next wake) arrives through the same queue (`wakeWatch`). - // While anything moves, a frame a tick (animation.frame_ns) on a grid + // While anything moves, a frame a tick (pardes.frame_ns) on a grid // of them, as the GUI paces to its display: the loop ran as fast as // the terminal answered, a frame every 2 ms, each a write. An input // ends the wait at once and its frame is drawn then; the ticks after // it run from it. var wait = timeout_ms; + // The tty's own motions (its glide, a jump's trail) wake it a frame at + // a time while they move: on a virtual clock a millisecond's wait + // moves it a frame (waitOnce), on the real one the pace below sets it. + if (s.moving()) wait = 1; // Detached, nobody's key dismisses a message: they go on the clock // (the pump's, after this wait), which wakes it. if (!s.attached()) { @@ -2229,10 +2233,10 @@ const Shell = struct { break; }; } - const paced = s.test_clock == null and s.core.continuous(); + const paced = s.test_clock == null and s.moving(); var tick: u64 = 0; if (paced) { - const period = pardes.animation.frame_ns; + const period = pardes.frame_ns; const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; if (tick < now) tick += (now - tick) / period * period; @@ -2266,7 +2270,7 @@ const Shell = struct { while (!paced and s.output_seen and !s.input_seen and !s.core.quit and s.test_clock == null) { if (s.input_ns > s.drawn_ns) break; if (s.focused_ns > s.drawn_ns and s.focused_ns -| s.input_ns < std.time.ns_per_s) break; - const due = s.drawn_ns + pardes.animation.frame_ns; + const due = s.drawn_ns + pardes.frame_ns; const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); if (now + std.time.ns_per_ms > due) break; s.waitOnce(@intCast((due - now) / std.time.ns_per_ms)); @@ -2280,9 +2284,9 @@ const Shell = struct { break :held held; } else next: { if (wait != 0) { - // A virtual clock moves a frame a wake while anything moves - // continuously (the glide), as the real one would. - s.wake_to = s.core.nextWake() orelse if (s.core.continuous()) s.core.now_ns + pardes.animation.frame_ns else 0; + // A virtual clock moves a frame a wake while the tty's own + // motions move (the glide), as the real one would. + s.wake_to = s.core.nextWake() orelse if (s.moving()) s.core.now_ns + pardes.frame_ns else 0; requestWake(s.io, wait); } pardes.turn.rest(); @@ -2567,17 +2571,22 @@ const Shell = struct { s.loop.postEvent(.files_changed) catch {}; } - /// ponytail: a terminal's scrollback under the wheel lands here (the - /// wheel reaches the core as a mouse event, not counted as the GUI's - /// notches are); `wheeled` from the mouse event if it should glide. - fn stepGlide(ctx: ?*anyopaque) void { + /// The tty's own motions (its glide, a jump's trail) are under way. + fn moving(s: *const Shell) bool { + const sc = s.term() orelse return false; + return sc.glide.moving() or sc.trail.active; + } + + /// The tty's own motions draw their frames themselves: the last frame + /// again, moved on, when the core has none to draw. + fn ownFrame(ctx: ?*anyopaque) void { const s = of(ctx); - if (s.term()) |sc| sc.glide.step(s.core, s.gpa, null, null); + if (s.moving() and !s.core.needs_frame and s.core.surface.cells.len != 0) present(ctx, &s.core.surface); } fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); - stepGlide(ctx); + defer ownFrame(ctx); if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; @@ -2611,15 +2620,14 @@ const Shell = struct { _ = s.frame.reset(.retain_capacity); const tz_cells = tracy.zone(@src(), "surface->vaxis"); const win = vx.window(); - if (sc.glide.pending) sc.glide.measure(s.gpa, canonical); - if (sc.glide.moving()) sc.glide.advance(s.core.now_ns, sc.glide.motion); + // The tty's own motions, on its own clock, from the frame alone. + const now: u64 = s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + sc.glide.frame(s.gpa, canonical, now, null, null); s.core.frames.scroll = @round(sc.glide.follow.offset); const glided = glideRows(s.frame.allocator(), canonical, &sc.glide) catch canonical; const truecolor = vx.caps.rgb or colortermTruecolor(); - const trail_on = s.core.settings.jump_trail and truecolor and s.core.settings.motion != .off; - const shown = trailCells(s.frame.allocator(), glided, &sc.trail, trail_on, s.test_clock orelse @intCast(std.Io.Clock.awake.now(s.io).nanoseconds)) catch glided; - // Each of the shell's own motions asks for frames while it runs. - s.core.shell_continuous = sc.glide.moving() or sc.trail.active; + const trail_on = s.core.settings.jump_trail and truecolor; + const shown = trailCells(s.frame.allocator(), glided, &sc.trail, trail_on, now) catch glided; paintCells(win, shown.cells, shown.cols, shown.rows); if (s.remote) |c| if (c.link.notice_len > 0) noticeLine(win, c.link.notice(), shown.cols, shown.rows); tz_cells.end(); @@ -3519,21 +3527,18 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste defer text.deinit(gpa); for (0..3000) |i| try text.print(gpa, "{d:0>5} line\n", .{i}); _ = try core.setTestFile(text.items); - core.settings.motion = .smooth; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); var glide: pardes.glide.Glide = .{}; defer glide.deinit(gpa); var now: u64 = std.time.ns_per_s; - // One tick of the tty: its loop step, the frame, the picture. + // One tick of the tty: the frame, the picture. const tick = struct { fn f(c: *pardes.Pardes, g: *pardes.glide.Glide, a: *std.heap.ArenaAllocator, t: u64) !i32 { c.advance(t); - g.step(c, std.testing.allocator, null, null); _ = a.reset(.retain_capacity); const s = try c.render(a.allocator()); - if (g.pending) g.measure(std.testing.allocator, s); - if (g.moving()) g.advance(t, g.motion); + g.frame(std.testing.allocator, s, t, null, null); _ = try glideRows(a.allocator(), s, g); return @intFromFloat(@round(g.follow.offset)); } @@ -3543,19 +3548,19 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste for (0..notches) |i| { core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = 20, .row = 10 } }); if (i % 2 == 1) { - now += pardes.animation.frame_ns; + now += pardes.frame_ns; _ = try tick(core, &glide, &arena, now); } } - var drawn = try tick(core, &glide, &arena, now + pardes.animation.frame_ns); - now += pardes.animation.frame_ns; + var drawn = try tick(core, &glide, &arena, now + pardes.frame_ns); + now += pardes.frame_ns; var last_step: i32 = std.math.maxInt(i32); var last_gap: usize = 0; var since: usize = 0; var ticks: usize = 0; while (glide.moving()) : (ticks += 1) { try std.testing.expect(ticks < 200); - now += pardes.animation.frame_ns; + now += pardes.frame_ns; const k = try tick(core, &glide, &arena, now); const step = k - drawn; drawn = k; @@ -3584,7 +3589,7 @@ test "the tty draws a glide at whole rows: once a flick or a spin slows, its ste const row = (core.surface.cursor orelse return error.NoCursor).y; for (0..20) |i| { if (i % 2 == 0) keys.j(core); - now += pardes.animation.frame_ns; + now += pardes.frame_ns; _ = try tick(core, &glide, &arena, now); const shown = try glideRows(arena.allocator(), &core.surface, &glide); try std.testing.expectEqual(row, (shown.cursor orelse return error.NoCursor).y); diff --git a/src/views.zig b/src/views.zig index 59910f5b..7e087523 100644 --- a/src/views.zig +++ b/src/views.zig @@ -37,7 +37,7 @@ pub const fields = [_][:0]const u8{ "col_tags", "col_serial", "finder", "rects", "col_x", "col_w", "active", "jumps", "njumps", "jcur", "jump_force", - "active_column", "shell_continuous", + "active_column", "native_images", "native_image_patches", "windowed", "drag", "mouse_grab", "window_focused", "focus_told", "hover_col", "hover_row", "pointer_raw_col", "pointer_raw_row", @@ -534,16 +534,11 @@ pub fn deinit(p: *Pardes) void { } } -/// What drawing a view keeps of its own (its animations, its panels as -/// presented), kept from a frame drawn while it was out. -const drawn_fields = [_][:0]const u8{"shell_continuous"}; - /// Each view but the live one drawn and presented, the live one put back /// after exactly as it was: no digested field moves, so a replica that -/// draws nothing (and skips this) stays the same. A view drawn keeps only -/// what its drawing made (`drawn_fields`); whatever its unpark brought -/// inside a changed text is not kept, and is done again when it is next -/// live. Before the live one's frame: the surface after the pump is its. +/// draws nothing (and skips this) stays the same. A view drawn keeps +/// nothing of its drawing: whatever its unpark brought inside a changed +/// text is not kept, and is done again when it is next live. Before the live one's frame: the surface after the pump is its. pub fn drawOthers(p: *Pardes, h: pardes.Host) !void { const live = p.view; const v = h.vtable; @@ -581,7 +576,6 @@ pub const Present = struct { ctx: ?*anyopaque, f: ?*const fn (?*anyopaque, *cons /// and a replica that draws nothing would keep them). fn drawParked(p: *Pardes, k: u8, present: Present) !void { try unparked(p, k, present, drawLive); - copy(&drawn_fields, &p.parked[k].?.view, p); } fn drawLive(present: Present, p: *Pardes) anyerror!void { |
