summaryrefslogtreecommitdiff
path: root/anim/src/source.zig
blob: 6c10b505de96cd400b4f81f9d8fc3b2022fe3011 (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
//! The source panel: the program's text as pardes colours it, line numbers,
//! the current mark (gold: a band along the line and a plaque over its
//! number), and the three lines before it (the trail, gold cooling). The
//! mark fires on the line about to run, and moves on last, when what the
//! line did has been seen: 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 cursors = @import("cursor.zig");
const Cursor = cursors.Cursor;
const theme = ui.theme;
const Rect = ui.Rect;

const gpa = std.heap.smp_allocator;

pub const Source = struct {
    cursor: Cursor,
    box: Rect,
    focus: bool = false,

    pub fn draw(p: *const Source, f: *sk.Frame, at: anim.Placed) void {
        const u: ui.Ui = .{ .f = f, .at = at };
        const rec = p.cursor.rec;
        const now = p.cursor.now(at);
        const size = theme.size.mono.context;
        const adv = ui.advance(size);
        const text = prepared(rec.source, rec.file) orelse return;
        const fit: u32 = @intFromFloat(@floor((p.box.h - m.tag - 2 * m.pad) / m.row));
        // 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]];
        const on_line = rec.own[now.marked()];
        // 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{ @floatFromInt(rec.viewFirst(fit, was)), @floatFromInt(rec.viewFirst(fit, here)) };
        const first = std.math.lerp(windows[0], windows[1], cursors.glide(going));
        const from: u32 = @intFromFloat(@floor(first));
        const last: u32 = @min(from + fit, rec.line_count);
        const body = u.panel(p.box.w, p.box.h, rec.file, .{ .focus = p.focus, .note = if (rec.line_count > fit) u.print("lines {d} to {d} of {d}", .{ from, @min(from + fit - 1, rec.line_count), rec.line_count }) else u.print("{d} lines", .{rec.line_count}) });
        const top = body.y + m.pad;
        const gutter = 3 * adv + 22;
        const code_x = gutter + 12;
        const max_chars: usize = @intFromFloat(@floor((p.box.w - code_x - m.side) / adv));

        // Where the mark is, and how much of it.
        const current = theme.mark(.current);
        const travel = now.plan.travel;
        const moved = going * travel;
        const scrolls = windows[0] != windows[1];
        var mark_line = here;
        var mark_at: f32 = @floatFromInt(here);
        var shows: f32 = 1;
        if (going < 1) {
            if (!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 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;
        u.clip(.{ .x = theme.stroke.rule, .y = body.y + 2, .w = p.box.w - 2 * theme.stroke.rule, .h = body.h - 4 });
        const marked = u.faded(shows);
        if (shows > 0) marked.fill(.{ .x = theme.stroke.rule, .y = mark_y, .w = p.box.w - 2 * theme.stroke.rule, .h = m.row }, current.ember);

        // The trail: the last three other lines it was on. It shifts without animation.
        var trail: [3]u32 = @splat(0);
        var found: usize = 0;
        var back = now.marked();
        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;
        }
        for (trail[0..found], 0..) |l, k| u.fill(.{ .x = theme.stroke.rule, .y = top + (@as(f32, @floatFromInt(l)) - first) * m.row + 2, .w = 4, .h = m.row - 4 }, theme.color.trail[k]);

        // The plaque over the number. Fire: on the line about to run its
        // edges go out and come back, once, and nothing else moves.
        const out = now.fires(.source);
        if (shows > 0) marked.fill(.{ .x = theme.stroke.rule - out, .y = mark_y - out, .w = gutter - 2 + 2 * out, .h = m.row + 2 * out }, current.solid);
        if (shows >= 1 and mark_y >= body.y and mark_y + m.row <= body.y + body.h) @import("ties.zig").anchor(u, .source, .{ .x = 0, .y = mark_y, .w = gutter, .h = m.row });

        var line = @max(from, 1);
        while (line <= last) : (line += 1) {
            const y = top + (@as(f32, @floatFromInt(line)) - first) * m.row;
            const row: Rect = .{ .x = 0, .y = y, .w = gutter - 10, .h = m.row };
            // The number under the plaque is the one in ink.
            const on = shows >= 0.5 and line == mark_line and !(scrolls and going > 0 and going < 1 and line != here);
            u.label(if (on) .mono_bold else .mono, size, row, .right, u.print("{d}", .{line}), if (on) current.on_solid else theme.color.text.faint);
            const span = text.lines[line - 1];
            const bytes = text.bytes[span[0]..span[1]];
            const styles = text.styles[span[0]..span[1]];
            // Runs of one class, each set where its column is.
            var i: usize = 0;
            const end = @min(bytes.len, max_chars);
            while (i < end) {
                var j = i + 1;
                while (j < end and styles[j] == styles[i]) j += 1;
                const class: pardes.Syn = @enumFromInt(styles[i]);
                const x = code_x + @as(f32, @floatFromInt(i)) * adv;
                if (std.mem.indexOfNone(u8, bytes[i..j], " ") != null) u.text(face(class), size, x, theme.baseline(y, m.row, size), bytes[i..j], ink(class));
                i = j;
            }
            // A line longer than the panel is cut, and says so.
            if (bytes.len > max_chars) u.text(.mono, size, code_x + @as(f32, @floatFromInt(max_chars)) * adv, theme.baseline(y, m.row, size), "\u{2026}", theme.color.text.faint);
        }
        u.unclip();
    }
};

const m = theme.metric.context;

fn ink(class: pardes.Syn) u24 {
    const c = theme.color.code;
    return switch (class) {
        .none => c.plain,
        .keyword => c.keyword,
        .string, .number => c.literal,
        .comment => c.comment,
    };
}

fn face(class: pardes.Syn) ui.Face {
    return switch (class) {
        .keyword => .mono_bold,
        .comment => .mono_italic,
        else => .mono,
    };
}

/// 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])));
}