summary refs log tree commit diff
path: root/src/main.zig
blob: 7cfb0f6d9f9b2d98ef08bac7b4dd325abc8d74f4 (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
// Entry point
// SPDX-FileCopyrightText: 2025 Nguyễn Gia Phong
// SPDX-License-Identifier: GPL-3.0-or-later

const Allocator = std.mem.Allocator;
const DebugAllocator = std.heap.DebugAllocator;
const argsAlloc = std.process.argsAlloc;
const argsFree = std.process.argsFree;
const builtin = @import("builtin");
const cwd = std.fs.cwd;
const eql = std.mem.eql;
const maxInt = std.math.maxInt;
const ns_per_s = std.time.ns_per_s;
const smp_allocator = std.heap.smp_allocator;
const std = @import("std");

const CursorShape = vaxis.Cell.CursorShape;
const Graphemes = vaxis.Graphemes;
const Key = vaxis.Key;
const Loop = vaxis.Loop;
const Style = vaxis.Cell.Style;
const Tty = vaxis.Tty;
const Unicode = vaxis.Unicode;
const Vaxis = vaxis.Vaxis;
const Window = vaxis.Window;
const Winsize = vaxis.Winsize;
const gwidth = vaxis.gwidth.gwidth;
const ctlseqs = vaxis.ctlseqs;
const vaxis = @import("vaxis");
pub const panic = vaxis.panic_handler;

const zsanett = @import("zsanett");
pub fn zsanettIntern(T: type) bool {
    return switch (T) {
        Buffer, Environment, Key, Loop(Event),
        Selection, Selection.Unit => true,
        else => false,
    };
}

const Buffer = @import("Buffer.zig");
const Config = @import("Config.zig");
const Selection = @import("Selection.zig");

pub var graphemes: Graphemes = undefined;

const Event = union(enum) {
    key_press: Key,
    winsize: Winsize,
    paste: []const u8,
};

const Environment = struct {
    allocator: Allocator,
    loop: *Loop(Event),
    tty: *Tty,
    vaxis: *Vaxis,

    pub fn nextEvent(self: Environment) Event {
        return self.loop.nextEvent();
    }

    pub fn render(self: Environment, buffer: Buffer) !void {
        const window = self.vaxis.window();
        window.clear();
        const sel_start = buffer.selection.startByte();
        window.screen.cursor_vis = sel_start == buffer.selection.endByte();
        var col: u16 = 0;
        var row: u16 = 0;
        var graphemes_iter = buffer.iterate();
        while (graphemes_iter.next()) |grapheme| {
            if (window.screen.cursor_vis and grapheme.offset == sel_start) {
                window.setCursorShape(.beam);
                window.showCursor(col, row);
            }
            const in_head = buffer.selection.inHead(grapheme);
            const in_body = buffer.selection.inBody(grapheme);
            const style = Style {
                .reverse = in_head,
                .ul_style = if (in_body) .single else .off,
            };
            const bytes = buffer.bytes(grapheme);
            if (eql(u8, bytes, "\n")) {
                while (col < window.width) : (col += 1)
                    window.writeCell(col, row, .{
                        .char = .{ .grapheme = " " },
                        .style = style,
                    });
                col = 0;
                row += 1;
                if (row >= window.height)
                    break;
            } else if (eql(u8, bytes, "\t")) {
                var tab = graphemes.iterator("  ");
                while (tab.next()) |g| {
                    const b = g.bytes("  ");
                    const width = window.gwidth(b);
                    defer col += width;
                    window.writeCell(col, row, .{
                        .char = .{ .grapheme = b, .width = @intCast(width) },
                        .style = style,
                    });
                }
            } else {
                const width = window.gwidth(bytes);
                defer col += width;
                window.writeCell(col, row, .{
                    .char = .{ .grapheme = bytes, .width = @intCast(width) },
                    .style = style,
                });
            }
        }
        try self.vaxis.render(self.tty.anyWriter());
    }

    pub fn resize(env: Environment, ws: Winsize) !void {
        try env.vaxis.resize(env.allocator, env.tty.anyWriter(), ws);
    }

    pub fn yank(env: Environment, buffer: Buffer) !void {
        try env.vaxis.copyToSystemClipboard(env.tty.anyWriter(),
                                            buffer.selectedBytes(),
                                            env.allocator);
    }

    pub fn requestPaste(env: Environment) !void {
        try env.vaxis.requestSystemClipboard(env.tty.anyWriter());
    }

    pub fn paste(env: Environment, buffer: Buffer, data: []const u8) Buffer {
        defer env.vaxis.opts.system_clipboard_allocator.?.free(data);
        return buffer.paste(data);
    }
};

pub fn main() !void {
    var debug_allocator = DebugAllocator(.{}).init;
    defer _ = debug_allocator.deinit();
    const allocator = switch (builtin.mode) {
        .Debug, .ReleaseSafe => debug_allocator.allocator(),
        .ReleaseFast, .ReleaseSmall => smp_allocator,
    };
    zsanett.init();
    defer zsanett.deinit();

    var tty = try Tty.init();
    defer tty.deinit();
    defer tty.anyWriter().print(ctlseqs.cursor_shape, .{
        @intFromEnum(CursorShape.block), // FIXME: make configurable
    }) catch {};
    var vx = try vaxis.init(allocator, .{
        .system_clipboard_allocator = allocator,
    });
    defer vx.deinit(allocator, tty.anyWriter());
    graphemes = vx.unicode.width_data.graphemes;
    defer graphemes = undefined;

    var loop = Loop(Event){ .tty = &tty, .vaxis = &vx };
    try loop.init();
    try loop.start();
    defer loop.stop();

    const args = try argsAlloc(allocator);
    defer argsFree(allocator, args);
    try vx.enterAltScreen(tty.anyWriter());
    try vx.queryTerminal(tty.anyWriter(), 1 * ns_per_s); // for alt screen

    try zsanett.def("kay/path", args[1], "Path to file.");
    try zsanett.def("kay/env", Environment{
        .allocator = allocator,
        .loop = &loop,
        .tty = &tty,
        .vaxis = &vx,
    }, "Eval environment.");
    try zsanett.defn(Buffer.open, .{
        .prefix = "kay",
        .name = "open",
        .documentation = "(kay/open text)\n\nOpen text for editing.",
        .source = @src(),
    });
    switch (try zsanett.eval(void, @embedFile("main.janet"), "main.janet")) {
        .ret => {},
        .err => |err| @panic(err),
    }
}