summaryrefslogtreecommitdiff
path: root/src/dump.zig
blob: 37ba83c07cca541d9f194e0205f4a42cbd959bf4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
const std = @import("std");
const builtin = @import("builtin");

// scoped, not bare std.log: main.zig's logFn drops the unscoped .default scope
// wholesale (ghostty and uucode log there too), and a corrupt dump's parse
// diagnostic is the only thing that says WHICH field went bad.
const log = std.log.scoped(.dump);

/// Where the next dump goes. $PARDES_DUMP wins verbatim (the snapshot harness
/// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share
/// /pardes/pardes-<utc>.zon — timestamped so dumps never overwrite each other.
/// Creates the pardes dir (parents assumed; a failure surfaces at open).
pub fn outPath(buf: *[1024:0]u8) ?[:0]const u8 {
    if (std.c.getenv("PARDES_DUMP")) |p|
        return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null;
    var dir_buf: [900]u8 = undefined;
    const dir = if (std.c.getenv("XDG_DATA_HOME")) |x|
        std.fmt.bufPrint(&dir_buf, "{s}/pardes", .{std.mem.span(x)}) catch return null
    else if (std.c.getenv("HOME")) |h|
        std.fmt.bufPrint(&dir_buf, "{s}/.local/share/pardes", .{std.mem.span(h)}) catch return null
    else
        return null;
    var dz: [901:0]u8 = undefined;
    @memcpy(dz[0..dir.len], dir);
    dz[dir.len] = 0;
    _ = std.c.mkdir(dz[0..dir.len :0], 0o755); // EEXIST is fine
    var ts: std.c.timespec = undefined;
    _ = std.c.clock_gettime(.REALTIME, &ts);
    const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) };
    const yd = es.getEpochDay().calculateYearDay();
    const md = yd.calculateMonthDay();
    const ds = es.getDaySeconds();
    return std.fmt.bufPrintSentinel(buf, "{s}/pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}.zon", .{
        dir,                       yd.year,              md.month.numeric(),
        @as(u8, md.day_index) + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(),
        ds.getSecondsIntoMinute(),
    }, 0) catch null;
}
pub const magic = "pardes-dump";
pub const version: u32 = 1;
pub const max_panes: usize = 16;
pub const max_cols: usize = 6;
/// Bounds the only user-editable, schema-owned tag fragment. Keep this beside
/// the dump limits so readers can reject data before copying it into a pane.
/// It IS the storage bound: `Pane.tag_tail` is `[max_tag_tail]u8`, and every
/// writer (appendTag, tagInsert, restoreDumpTail, the acmefs `tag` file)
/// refuses input that does not fit rather than truncating it, so the schema
/// limit and the buffer can never disagree.
///
/// 512 on the P4 firmware. A tag is ONE line — a pane's path plus its command
/// words — and 4 KiB of it is 4 KiB per pane out of a 384 KiB heap. A serial
/// console is 80 columns; 512 is six of those.
pub const max_tag_tail: usize =
    if (@import("pardes_config").platform == .p4) 512 else 4096;
/// Output arguments are typed in the same bounded one-line tag storage. Keep
/// the schema limit named independently so a dump reader can validate it
/// without importing the output-pane implementation.
pub const max_origin_arg: usize = max_tag_tail;

pub const Size = struct {
    cols: u16,
    rows: u16,
};

pub const Cursor = struct {
    col: u16 = 0,
    row: u16 = 0,
};

pub const PaneKind = enum {
    terminal,
    file,
    image,
};

pub const Terminal = struct {
    cwd: []const u8 = "",
    stream: []const u8 = "",
    stream_b64: []const u8 = "",
    cursor: Cursor = .{},
};

pub const File = struct {
    path: []const u8 = "",
    content: []const u8 = "",
    content_b64: []const u8 = "",
    /// non-empty = an output buffer (no file behind the name): the WORD of the
    /// command that opened it, plus that command's argument — see
    /// output_pane.Origin. A word rather than an integer for the reason every
    /// other command in here is a word: reordering builtins.zig stays free,
    /// and a dump stays something a person can read.
    origin: []const u8 = "",
    origin_arg: []const u8 = "",
};

pub const ImagePalette = enum {
    commodore,
    terminal,
};

pub const Image = struct {
    path: []const u8 = "",
    bytes_b64: []const u8 = "",
    // Defaults are the renderer's historical state, so version-1 dumps which
    // predate these fields remain readable without a schema fork.
    petscii: bool = false,
    palette: ImagePalette = .commodore,
    ascii: bool = true,
};

pub const Pane = struct {
    kind: PaneKind,
    tag: []const u8,
    body: []const u8,
    scroll: usize = 0,
    cols: u16 = 0,
    rows: u16 = 0,
    vweight: f32 = 1,
    /// Exact editable tail when the user touched it. Null retains the live
    /// default; a present empty slice deliberately restores an empty tail.
    tag_tail: ?[]const u8 = null,
    terminal: ?Terminal = null,
    file: ?File = null,
    image: ?Image = null,
};

pub const Column = struct {
    weight: f32 = 1,
    panes: []const usize = &.{},
};

pub const State = struct {
    magic: []const u8 = magic,
    version: u32 = version,
    screen: Size,
    active: usize = 0,
    topbar: []const u8 = "",
    theme: []const u8 = "dark",
    columns: []const Column = &.{},
    panes: []const Pane = &.{},
};

pub fn validate(state: State) !void {
    if (!std.mem.eql(u8, state.magic, magic)) return error.BadDumpMagic;
    if (state.version != version) return error.BadDumpVersion;
    if (state.panes.len == 0 or state.panes.len > max_panes) return error.BadDumpPanes;
    if (state.columns.len == 0 or state.columns.len > max_cols) return error.BadDumpColumns;
    if (state.active >= state.panes.len) return error.BadDumpActive;
    for (state.columns) |col| {
        if (!std.math.isFinite(col.weight) or col.weight <= 0) return error.BadDumpColumns;
        if (col.panes.len == 0 or col.panes.len > max_panes) return error.BadDumpColumns;
        for (col.panes) |pane| {
            if (pane >= state.panes.len) return error.BadDumpPaneRef;
        }
    }
    for (state.panes) |pane| {
        if (!std.math.isFinite(pane.vweight) or pane.vweight <= 0)
            return error.BadDumpPaneWeight;
        if (pane.scroll > std.math.maxInt(i32)) return error.BadDumpPaneScroll;
        if (pane.tag_tail) |tail| if (tail.len > max_tag_tail)
            return error.BadDumpTagTail;
        if (pane.file) |file| if (file.origin_arg.len > max_origin_arg)
            return error.BadDumpOriginArg;
        switch (pane.kind) {
            .terminal => if (pane.terminal == null) return error.BadDumpPaneKind,
            .file => if (pane.file == null) return error.BadDumpPaneKind,
            .image => if (pane.image == null) return error.BadDumpPaneKind,
        }
    }
}

test "oversized recognized output argument is rejected before restore" {
    var oversized: [max_origin_arg + 1]u8 = @splat('x');
    const pane_ids = [_]usize{0};
    const columns = [_]Column{.{ .panes = &pane_ids }};
    const panes = [_]Pane{.{
        .kind = .file,
        .tag = "+Search",
        .body = "",
        .file = .{
            .path = "/tmp/+Search",
            .origin = "Find",
            .origin_arg = &oversized,
        },
    }};
    const state: State = .{
        .screen = .{ .cols = 80, .rows = 24 },
        .columns = &columns,
        .panes = &panes,
    };

    // Serialize without writeFile: that writer correctly rejects the state
    // too, while this exercises the hostile bytes a restore actually reads.
    var encoded: std.Io.Writer.Allocating = .init(std.testing.allocator);
    defer encoded.deinit();
    try std.zon.stringify.serialize(state, .{}, &encoded.writer);
    try std.testing.expectError(
        error.BadDumpOriginArg,
        readZon(std.testing.allocator, encoded.written(), "oversized-origin-arg"),
    );
}

pub fn writeFile(io: std.Io, gpa: std.mem.Allocator, path: []const u8, state: State) !void {
    try validate(state);
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);

    var file = try std.Io.Dir.createFileAbsolute(io, path, .{});
    defer file.close(io);
    try file.writeStreamingAll(io, out.written());
}

pub fn readFile(io: std.Io, gpa: std.mem.Allocator, path: []const u8) !State {
    const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(64 * 1024 * 1024));
    defer gpa.free(bytes);
    return readZon(gpa, bytes, path);
}

pub fn readZon(gpa: std.mem.Allocator, bytes: []const u8, label: []const u8) !State {
    const source = try gpa.dupeZ(u8, bytes);
    defer gpa.free(source);
    return readZonZ(gpa, source, label);
}

pub fn readZonZ(gpa: std.mem.Allocator, source: [:0]const u8, label: []const u8) !State {
    if (builtin.os.tag == .emscripten or builtin.os.tag == .freestanding) {
        const state = std.zon.parse.fromSliceAlloc(State, gpa, source, null, .{}) catch |err| {
            log.err("parse dump {s}: {s}", .{ label, @errorName(err) });
            return err;
        };
        errdefer std.zon.parse.free(gpa, state);
        try validate(state);
        return state;
    }

    var diag: std.zon.parse.Diagnostics = .{};
    defer diag.deinit(gpa);
    const state = std.zon.parse.fromSliceAlloc(State, gpa, source, &diag, .{}) catch |err| {
        log.err("parse dump {s}: {f}", .{ label, diag });
        return err;
    };
    errdefer std.zon.parse.free(gpa, state);
    try validate(state);
    return state;
}

pub fn free(gpa: std.mem.Allocator, state: State) void {
    std.zon.parse.free(gpa, state);
}

pub fn encodeBytes(alloc: std.mem.Allocator, bytes: []const u8) ![]const u8 {
    const enc = std.base64.standard.Encoder;
    const out = try alloc.alloc(u8, enc.calcSize(bytes.len));
    return enc.encode(out, bytes);
}

pub fn decodeBytes(alloc: std.mem.Allocator, b64: []const u8) ![]u8 {
    const dec = std.base64.standard.Decoder;
    const n = try dec.calcSizeForSlice(b64);
    const out = try alloc.alloc(u8, n);
    errdefer alloc.free(out);
    try dec.decode(out, b64);
    return out;
}

test "dump zon roundtrip" {
    const gpa = std.testing.allocator;
    const tty_b64 = try encodeBytes(gpa, "old\nhello\nworld");
    defer gpa.free(tty_b64);
    const file_b64 = try encodeBytes(gpa, "alpha\nbeta\n");
    defer gpa.free(file_b64);
    const panes = [_]Pane{
        .{
            .kind = .terminal,
            .tag = "nm /tmp Del",
            .body = "hello\nworld",
            .scroll = 1,
            .cols = 40,
            .rows = 10,
            .terminal = .{ .cwd = "/tmp", .stream = "old\nhello\nworld", .stream_b64 = tty_b64, .cursor = .{ .col = 3, .row = 2 } },
        },
        .{
            .kind = .file,
            .tag = "nm /tmp/a.txt Save Del",
            .body = "   1 alpha",
            .cols = 20,
            .rows = 5,
            .file = .{ .path = "/tmp/a.txt", .content = "alpha\nbeta\n", .content_b64 = file_b64 },
        },
    };
    const col_panes = [_]usize{ 0, 1 };
    const columns = [_]Column{.{ .weight = 1, .panes = &col_panes }};
    const state: State = .{
        .screen = .{ .cols = 80, .rows = 24 },
        .topbar = "Kill Newcol Dump",
        .theme = "dark",
        .columns = &columns,
        .panes = &panes,
    };

    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
    const source = try out.toOwnedSliceSentinel(0);
    defer gpa.free(source);

    var diag: std.zon.parse.Diagnostics = .{};
    defer diag.deinit(gpa);
    const parsed = try std.zon.parse.fromSliceAlloc(State, gpa, source, &diag, .{});
    defer std.zon.parse.free(gpa, parsed);
    try validate(parsed);
    try std.testing.expectEqual(@as(usize, 2), parsed.panes.len);
    try std.testing.expectEqualStrings("dark", parsed.theme);
    try std.testing.expectEqualStrings("old\nhello\nworld", parsed.panes[0].terminal.?.stream);
    try std.testing.expectEqualStrings("alpha\nbeta\n", parsed.panes[1].file.?.content);
    {
        const bytes = try decodeBytes(gpa, parsed.panes[0].terminal.?.stream_b64);
        defer gpa.free(bytes);
        try std.testing.expectEqualStrings("old\nhello\nworld", bytes);
    }
    {
        const bytes = try decodeBytes(gpa, parsed.panes[1].file.?.content_b64);
        defer gpa.free(bytes);
        try std.testing.expectEqualStrings("alpha\nbeta\n", bytes);
    }
}

test "version-one image records default old fields and roundtrip new state" {
    const gpa = std.testing.allocator;
    const legacy =
        \\.{
        \\    .magic = "pardes-dump",
        \\    .version = 1,
        \\    .screen = .{ .cols = 80, .rows = 24 },
        \\    .active = 0,
        \\    .topbar = "",
        \\    .theme = "dark",
        \\    .columns = .{.{ .panes = .{0} }},
        \\    .panes = .{.{
        \\        .kind = .image,
        \\        .tag = "img /tmp/old.ppm New Del",
        \\        .body = "",
        \\        .image = .{ .path = "/tmp/old.ppm", .bytes_b64 = "" },
        \\    }},
        \\}
    ;
    const old = try readZon(gpa, legacy, "legacy-image");
    defer free(gpa, old);
    const old_image = old.panes[0].image.?;
    try std.testing.expect(!old_image.petscii);
    try std.testing.expectEqual(ImagePalette.commodore, old_image.palette);
    try std.testing.expect(old_image.ascii);
    try std.testing.expect(old.panes[0].tag_tail == null);

    const pane = Pane{
        .kind = .image,
        .tag = "img petscii:on palette:terminal ascii:off /tmp/new.ppm",
        .body = "",
        .tag_tail = "",
        .image = .{
            .path = "/tmp/new.ppm",
            .petscii = true,
            .palette = .terminal,
            .ascii = false,
        },
    };
    const ids = [_]usize{0};
    const columns = [_]Column{.{ .panes = &ids }};
    const panes = [_]Pane{pane};
    const state = State{
        .screen = .{ .cols = 80, .rows = 24 },
        .columns = &columns,
        .panes = &panes,
    };
    var out: std.Io.Writer.Allocating = .init(gpa);
    defer out.deinit();
    try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer);
    const parsed = try readZon(gpa, out.written(), "new-image");
    defer free(gpa, parsed);
    const restored = parsed.panes[0].image.?;
    try std.testing.expect(restored.petscii);
    try std.testing.expectEqual(ImagePalette.terminal, restored.palette);
    try std.testing.expect(!restored.ascii);
    try std.testing.expect(parsed.panes[0].tag_tail != null);
    try std.testing.expectEqualStrings("", parsed.panes[0].tag_tail.?);
}

test "validation bounds pane restore state" {
    const ids = [_]usize{0};
    const columns = [_]Column{.{ .panes = &ids }};
    var panes = [_]Pane{.{
        .kind = .terminal,
        .tag = "term",
        .body = "",
        .terminal = .{},
    }};
    const state = State{
        .screen = .{ .cols = 80, .rows = 24 },
        .columns = &columns,
        .panes = &panes,
    };
    try validate(state);

    panes[0].vweight = 0;
    try std.testing.expectError(error.BadDumpPaneWeight, validate(state));
    panes[0].vweight = std.math.inf(f32);
    try std.testing.expectError(error.BadDumpPaneWeight, validate(state));
    panes[0].vweight = 1;

    panes[0].scroll = @as(usize, @intCast(std.math.maxInt(i32))) + 1;
    try std.testing.expectError(error.BadDumpPaneScroll, validate(state));
    panes[0].scroll = 0;

    var oversized_tail: [max_tag_tail + 1]u8 = @splat('x');
    panes[0].tag_tail = &oversized_tail;
    try std.testing.expectError(error.BadDumpTagTail, validate(state));
    panes[0].tag_tail = oversized_tail[0..max_tag_tail];
    try validate(state);
}