summaryrefslogtreecommitdiff
path: root/anim/src/source.zig
blob: 0705f5b430a51ba5e1c886143e84c5594f27a41b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
//! `source` (design/README.md, "3. Panels"): a window on the whole file,
//! scrolled by whole lines to keep the current line in its middle third:
//! fourteen lines, eight beside a lens, ten when the lens is the subject.
//! Its rows are `line`s, pardes's colours; the current mark is a gold
//! plaque on the number and its ember across, the three lines before it
//! the trail. The mark fires on the line about to run and moves on last:
//! a slide to a line near by, a jump (out, then in) into a call or out
//! of one. Reads `Moment.line` (through the recording's index of it).
const std = @import("std");
const sk = @import("sketch");
const anim = @import("anim");
const pardes = @import("pardes-syntax");
const ui = @import("ui.zig");
const rows = @import("rows.zig");
const context = @import("context.zig");
const ties = @import("ties.zig");
const map = @import("map.zig");
const cursors = @import("cursor.zig");
const Stage = @import("stage.zig").Stage;
const Recording = @import("Recording.zig");
const Cursor = cursors.Cursor;
const theme = ui.theme;
const Rect = ui.Rect;
const m = theme.metric.context;

const gpa = std.heap.smp_allocator;

pub const Source = struct {
    cursor: Cursor,
    stage: *const Stage,
    focus: bool = false,
    /// In a `descent`: while the pc is in code without source, the line it
    /// called from waits, ringed, and the tag says where the pc is.
    descent: bool = false,
    /// Which box of its stage it is in: on the map the source may go on in `source_more`.
    part: @import("stage.zig").Part = .source,

    pub fn draw(p: *const Source, f: *sk.Frame, placed: anim.Placed) void {
        const box = p.stage.box(placed, p.part);
        if (box.h < m.tag + m.row) return;
        const u = context.at(f, placed, box);
        const rec = p.cursor.rec;
        const now = p.cursor.now(placed);
        const text = prepared(rec.source, rec.file) orelse return;
        // Its window, and on the map the lines of both its boxes (`continued`): this one from `skip` lines in.
        const head = theme.layout.rowsIn(p.stage.box(placed, .source).h);
        const tail = theme.layout.rowsIn(p.stage.box(placed, .source_more).h);
        const fit: u32 = @intCast(theme.layout.rowsIn(box.h));
        const span_fit: u32 = @intCast(head + tail);
        const skip: f32 = if (p.part == .source_more) @floatFromInt(head) else 0;
        // The mark: leaving the line of one moment for that of the next.
        const was = rec.own[now.marks[0]];
        const here = rec.own[now.marks[1]];
        // The window: where the line it is on has it, and (as the mark
        // moves on) gliding to where the next one does. It never cuts.
        const going = now.advancing();
        const windows = [2]f32{ @as(f32, @floatFromInt(rec.viewFirst(span_fit, was))) + skip, @as(f32, @floatFromInt(rec.viewFirst(span_fit, here))) + skip };
        // Farther than its own height (another function far off): what
        // leaves has left before what replaces it arrives; a scroll of more
        // lines than the window shows would be a blur, and say nothing.
        const far = @abs(windows[1] - windows[0]) > @as(f32, @floatFromInt(fit));
        const first = if (far) windows[if (going >= 0.5) 1 else 0] else std.math.lerp(windows[0], windows[1], cursors.glide(going));
        const lit = if (far and going < 1) u.faded(@abs(2 * going - 1)) else u;
        const from: u32 = @intFromFloat(@floor(first));
        const last: u32 = @min(from + @as(u32, @intCast(context.rowsOf(box))), rec.line_count);
        const shown_first: u32 = @intFromFloat(windows[if (going >= 0.5) 1 else 0]);
        // Waiting: the pc is in code with no source, under this line's call.
        const waits = p.descent and !rec.sourced(now.marked()) and rec.own[now.marked()] != 0;
        const lines_note = if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ shown_first, @min(shown_first + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count});
        // Where the pc is, said where it waits: a change of it (on through a
        // stub) crossfades over the 12 f before the advance, never in a frame.
        var notes: [2][]const u8 = undefined;
        for (now.marks, &notes) |mk, *note| note.* = if (p.descent and !rec.sourced(mk) and rec.own[mk] != 0) u.print("{s} waits at line {d} \u{00b7} the pc is in {s}", .{ context.frameName(u, rec, rec.register(firstOwn(rec, mk), "rip")), rec.own[mk], whereIs(u, rec, mk) }) else lines_note;
        const swap = !std.mem.eql(u8, notes[0], notes[1]) and (notes[0].ptr != lines_note.ptr or notes[1].ptr != lines_note.ptr) and now.walking();
        const body = u.panel(box.w, box.h, if (p.part == .source_more) u.print("{s}, continued", .{rec.file}) else rec.file, .{ .focus = p.focus, .note = if (swap) "" else if (waits) notes[if (going >= 0.5) 1 else 0] else lines_note });
        if (swap) {
            const c = now.renaming();
            u.faded(1 - c).tagNote(box.w, notes[0]);
            u.faded(c).tagNote(box.w, notes[1]);
        }
        const top = body.y + m.pad;

        // Where the mark is, and how much of it.
        const travel = now.plan.travel;
        const moved = going * travel;
        var mark_line = here;
        var mark_at: f32 = @floatFromInt(here);
        var shows: f32 = 1;
        if (going < 1) {
            if (!now.plan.wave and !cursors.jumps(rec, now.marks[0], now.marks[1])) {
                // A line near by: it slides, off promptly and settling on
                // the next. The step's follow-through.
                mark_at = std.math.lerp(@as(f32, @floatFromInt(was)), mark_at, cursors.standard(going));
                if (@abs(mark_at - @as(f32, @floatFromInt(was))) < 0.5) mark_line = was;
            } else {
                // A call, a return, a line far off, a continue: a jump. Out
                // there, then in here; it does not cross the lines between.
                const half = @min(theme.time.current_jump, travel / 2);
                if (moved < travel - half) {
                    mark_line = was;
                    mark_at = @floatFromInt(was);
                    shows = 1 - std.math.clamp(moved / half, 0, 1);
                } else shows = std.math.clamp((moved - (travel - half)) / half, 0, 1);
            }
        }
        const mark_y = top + (mark_at - first) * m.row;
        // The numbers as wide as the program's largest: a scroll does not shift the text.
        const widen = rows.numberRoom(rec.line_count);
        context.clipBody(u, box);
        defer u.unclip();
        // The plaque over the number. Fire: on the line about to run its
        // edges go out and come back, once, and nothing else moves.
        if (waits) {
            // The number ringed: a 2-unit primary frame where the plaque would be, no wash.
            u.faded(shows).frame(.{ .x = theme.stroke.rule + 1, .y = mark_y + 1, .w = theme.metric.plaque.line + widen - 2, .h = m.row - 2 }, theme.color.text.primary, theme.stroke.rule);
            if (!ui.mapping) ties.thread_waits = true;
        } else if (shows > 0) u.faded(shows).current(.{ .x = theme.stroke.rule, .y = mark_y, .w = box.w - 2 * theme.stroke.rule, .h = m.row }, theme.metric.plaque.line + widen, now.fires(.source));
        if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= box.h) ties.anchor(u, .source, .{ .x = 0, .y = mark_y, .w = box.w, .h = m.row });

        // The trail: the last three other lines it was on, as the mark left
        // them and as it finds them: a bar that moves crossfades with the advance.
        var trails: [2][3]u32 = @splat(@splat(0));
        var founds = [2]usize{ 0, 0 };
        for (now.marks, &trails, &founds) |mk, *trail, *found| {
            const on_line = rec.own[mk];
            var back = mk;
            while (back > 0 and found.* < trail.len) {
                back -= 1;
                const l = rec.own[back];
                if (l == 0 or l == on_line or std.mem.indexOfScalar(u32, trail[0..found.*], l) != null) continue;
                trail[found.*] = l;
                found.* += 1;
            }
        }

        const lines_of = struct {
            fn of(at: f32, n: u32, lines: u32) [2]u64 {
                const a: u32 = @intFromFloat(at);
                return .{ a, @min(a + n - 1, lines) };
            }
        }.of;
        map.window(.source, lines_of(windows[1], fit, rec.line_count), lines_of(windows[0], fit, rec.line_count), cursors.glide(going));
        var line = @max(from, 1);
        while (line <= last) : (line += 1) {
            const y = top + (@as(f32, @floatFromInt(line)) - first) * m.row;
            map.row(.source, line, u, .{ .x = 0, .y = y, .w = box.w, .h = m.row });
            const span = text.lines[line - 1];
            const ks = [2]?usize{ std.mem.indexOfScalar(u32, trails[0][0..founds[0]], line), std.mem.indexOfScalar(u32, trails[1][0..founds[1]], line) };
            const k = if (going >= 0.5) ks[1] else ks[0];
            const on = shows >= 0.5 and line == mark_line;
            const fading = !std.meta.eql(ks[0], ks[1]) and going > 0 and going < 1;
            rows.line(lit, y, box.w, line, widen, text.bytes[span[0]..span[1]], text.styles[span[0]..span[1]], if (on and !waits) .marked else if (fading) .plain else if (k) |n| .{ .trail = n } else .plain);
            if (fading and !(on and !waits)) for (ks, [2]f32{ 1 - going, going }) |kk, amount| if (kk) |n| lit.faded(amount).trail(theme.stroke.rule, y, n);
        }
        // The source is read at a run; at a sprint it is veiled too.
        context.veiled(u, box, now.sprint_veil);
    }
};

/// The last moment at or before `i` whose pc was on a line of the program's source.
fn firstOwn(rec: *const Recording, i: u64) u64 {
    var at = i;
    while (at > 0 and !rec.sourced(at)) at -= 1;
    return at;
}

/// Where the pc is at moment `i`, for the waiting line's tag: `the PLT`,
/// `libc's open`, `the vdso`.
fn whereIs(u: ui.Ui, rec: *const Recording, i: u64) []const u8 {
    const name = context.frameName(u, rec, rec.register(i, "rip"));
    if (std.mem.endsWith(u8, name, "@plt")) return "the PLT";
    var module: []const u8 = "";
    var buf: [256]u8 = undefined;
    _ = (rec.moment(i).mapping(rec.register(i, "rip"), &module, &buf) catch null);
    const base = std.fs.path.basename(module);
    const short = base[0 .. std.mem.indexOfScalar(u8, base, '.') orelse base.len];
    return u.print("{s}'s {s}", .{ short, name });
}

/// A source ready to draw: a class for each byte, and where each line is.
const Text = struct {
    bytes: []const u8,
    styles: []const u8,
    lines: []const [2]usize,
};

/// Made once for each source and kept: a scene draws the same few.
var texts: std.ArrayList(Text) = .empty;

fn prepared(source: []const u8, file: []const u8) ?*const Text {
    for (texts.items) |*t| if (t.bytes.ptr == source.ptr) return t;
    texts.append(gpa, prepare(source, file) catch return null) catch return null;
    return &texts.items[texts.items.len - 1];
}

fn prepare(source: []const u8, file: []const u8) !Text {
    var analysis = try pardes.analyzeSource(gpa, file, source, false, true);
    var lines: std.ArrayList([2]usize) = .empty;
    var start: usize = 0;
    while (start < source.len) {
        const end = std.mem.indexOfScalarPos(u8, source, start, '\n') orelse source.len;
        try lines.append(gpa, .{ start, end });
        start = end + 1;
    }
    // A language pardes has no grammar for is drawn plain.
    if (analysis.colors.len != source.len) {
        analysis.deinit(gpa);
        const plain = try gpa.alloc(u8, source.len);
        @memset(plain, 0);
        analysis.colors = plain;
    }
    return .{ .bytes = source, .styles = analysis.colors, .lines = try lines.toOwnedSlice(gpa) };
}

test "a source is cut into lines and classed byte by byte" {
    const source = "int main(void) {\n    return 0; // done\n}\n";
    const text = try prepare(source, "main.c");
    defer gpa.free(text.lines);
    defer gpa.free(text.styles);
    try std.testing.expectEqual(@as(usize, 3), text.lines.len);
    try std.testing.expectEqualStrings("    return 0; // done", source[text.lines[1][0]..text.lines[1][1]]);
    const at = std.mem.indexOf(u8, source, "return").?;
    try std.testing.expectEqual(pardes.Syn.keyword, @as(pardes.Syn, @enumFromInt(text.styles[at])));
    try std.testing.expectEqual(pardes.Syn.number, @as(pardes.Syn, @enumFromInt(text.styles[at + 7])));
    try std.testing.expectEqual(pardes.Syn.comment, @as(pardes.Syn, @enumFromInt(text.styles[at + 10])));
    // rows.line reads these classes by number.
    try std.testing.expectEqual(@as(u8, 1), @intFromEnum(pardes.Syn.keyword));
    try std.testing.expectEqual(@as(u8, 4), @intFromEnum(pardes.Syn.comment));
}