package ded import "base:runtime" import hm "core:container/handle_map" import "core:container/queue" import "core:log" import "core:os" import "core:strings" import "core:time" import "core:unicode/utf8" import "janet" import "keys" import "msgpack" @(thread_local, private) is_main_thread: bool g_editor: Editor editor_instance :: proc "c" () -> ^Editor { if !is_main_thread { // TODO: ded/schedule janet.panic("ded API called off the main thread") } return &g_editor } Editor :: struct { clients: hm.Dynamic_Handle_Map(Client, Client_Handle), bufs: hm.Dynamic_Handle_Map(Buffer, Buffer_Handle), wins: hm.Dynamic_Handle_Map(Window, Window_Handle), cur_win: Window_Handle, keymap: keys.Keymap(Key_Action), // Janet ctx: runtime.Context, // Needed because cfuns are contextless env: ^janet.JanetTable, env_internal: ^janet.JanetTable, // Rendering render_requested: bool, rerender_fn: ^janet.JanetFunction, rendered_at: time.Tick, // Misc rpc_log_enabled: bool, } editor_init :: proc() -> (ed: ^Editor, err: Error) { defer if err != nil { log.debugf("init failed: {}", err) editor_destroy(ed) } is_main_thread = true g_editor = Editor{} ed = &g_editor hm.dynamic_init(&ed.clients, context.allocator) hm.dynamic_init(&ed.bufs, context.allocator) hm.dynamic_init(&ed.wins, context.allocator) keys.keymap_init(&ed.keymap, key_action_destroy) ed.ctx = context ed.rpc_log_enabled = context.logger.lowest_level <= .Debug if res := janet.init(); res != 0 { log.fatalf("janet_init failed: {}", res) return } log.info("loading api") ed.env = janet.core_env(nil) janet_register_api(ed) // create a separate, private env for internal use ed.env_internal = janet.table_clone(ed.env) janet.gcroot(janet.wrap_table(ed.env_internal)) janet_register_api_internal(ed) log.info("loading boot") if janet.dostring(ed.env_internal, `(dofile "./boot/init.janet" :env (curenv))`, "boot-loader", nil) != 0 { log.panic("boot/init.janet failed to load") } rerender_fn: janet.Janet log.assert( janet.resolve(ed.env_internal, janet.csymbol("ded/internal/rerender"), &rerender_fn) != .NONE, "boot has no `ded/internal/rerender`", ) ed.rerender_fn = janet.unwrap_function(rerender_fn) hscratch, herr := editor_create_buf(ed, name = "*scratch*", path = nil) log.assertf(herr == nil, "failed to create scratch buf: {}", herr) ed.cur_win = editor_create_win(ed, hscratch) or_return return ed, nil } editor_destroy :: proc(ed: ^Editor) { keys.keymap_destroy(&ed.keymap) { it := hm.iterator_make(&ed.bufs) for b, _ in hm.iterate(&it) {buffer_destroy(b)} hm.dynamic_destroy(&ed.bufs) } hm.dynamic_destroy(&ed.wins) { it := hm.iterator_make(&ed.clients) for client, _ in hm.iterate(&it) {client_destroy(client)} hm.dynamic_destroy(&ed.clients) } janet.deinit() ed^ = {} } editor_loop :: proc(ed: ^Editor) -> Error { log.debug("main loop starting") defer log.debug("main loop exited") main_fn: janet.Janet log.assert( janet.resolve(ed.env_internal, janet.csymbol("ded/internal/main"), &main_fn) != .NONE, "boot/init.janet has no `ded/internal/main`", ) janet.schedule(janet.fiber(janet.unwrap_function(main_fn), 64, 0, nil), janet.wrap_nil()) for janet.loop_done() != 1 { defer free_all(context.temp_allocator) interrupted := janet.loop1() if interrupted != nil { // TODO: cancellation/interruption // if sync.atomic_exchange(&cancel_interrupted, false) { // janet.cancel(interrupted, janet.wrap_string(janet.cstring_("interrupted"))) // } else { janet.schedule(interrupted, janet.wrap_nil()) // } janet.interpreter_interrupt_handled(nil) } } return nil } editor_create_client :: proc(ed: ^Editor, rpc: Rpc) -> (h: Client_Handle, err: runtime.Allocator_Error) { h = hm.add(&ed.clients, Client{rpc = rpc}) or_return FN_NAME :: "ded/internal/client-loop" client_loop: janet.Janet log.assertf( janet.resolve(ed.env_internal, janet.csymbol(FN_NAME), &client_loop) != .NONE, "boot/init.janet has no `{}`", FN_NAME, ) argv := [?]janet.Janet{janet_wrap_client(h)} janet.schedule(janet.fiber(janet.unwrap_function(client_loop), 64, 1, raw_data(argv[:])), janet.wrap_nil()) return h, nil } client_on_input :: proc(ed: ^Editor, client: ^Client, input: ^[]byte) -> (action: Maybe(Key_Action), err: Error) { defer if err != nil { queue.clear(&client.typeahead) clear(&client.pending_chord) } for { for k in queue.pop_front_safe(&client.typeahead) { if a, ok := handle_key(ed, client, k).?; ok {return a, nil} } msg, merr, ok := rpc_iterate_msg(&client.rpc, Client_Msg) if !ok { n := copy(rpc_recv_buf(&client.rpc), input^) if n == 0 {break} rpc_commit_bytes(&client.rpc, n) input^ = input[n:] continue } merr or_return if ed.rpc_log_enabled { log.debugf("rpc <- {}", msgpack.dump(client.rpc.object)) } editor_handle_client_msg(ed, client, msg) or_return } editor_render(ed) or_return return nil, nil } @(private) client_send :: proc(ed: ^Editor, client: ^Client, msgs: ..$Server_Msg) -> Error { if len(msgs) == 0 {return nil} buf := make([dynamic]byte, context.temp_allocator) for msg in msgs { start := len(buf) encode_rpc_msg(&buf, msg) or_return if ed.rpc_log_enabled { log.debugf("rpc -> {}", msgpack.dump(buf[start:])) } } _, w_file := rpc_files(&client.rpc) rest := buf[:] for len(rest) > 0 { n, err := os.write(w_file, rest) if err != nil {return err} if n <= 0 {break} rest = rest[n:] } return nil } editor_handle_client_msg :: proc(ed: ^Editor, client: ^Client, msg: Client_Msg) -> Error { log.infof("msg: {}", msg) switch msg in msg { case Client_Msg_Attach: client_attach(client, msg) or_return case Client_Msg_Events: for ev in msg.events { switch ev in ev { case keys.Key: queue.push_back(&client.typeahead, ev) or_return } } case Client_Msg_Resume: client_resume(client, msg) case Client_Msg_Resize: client_resize(client, msg) } return nil } RENDER_INTERVAL :: time.Second / 30 // 30fps editor_request_render :: proc(ed: ^Editor) { if ed.render_requested {return} ed.render_requested = true wait_secs := max(0, RENDER_INTERVAL - time.tick_since(ed.rendered_at)) arg := janet.wrap_number(time.duration_seconds(wait_secs)) janet.schedule(janet.fiber(ed.rerender_fn, 64, 1, &arg), janet.wrap_nil()) } editor_request_exit :: proc(ed: ^Editor) { log.debug("exit requested") // TODO: should interrupt current fiber instead of quitting. remove once we have `:q` it := hm.iterator_make(&ed.clients) for client, _ in hm.iterate(&it) { client_send(ed, client, ..[]Server_Msg{Server_Msg_Exit{}}) } } editor_request_suspend :: proc(ed: ^Editor) { log.debug("suspend requested") it := hm.iterator_make(&ed.clients) for client, _ in hm.iterate(&it) { client_send(ed, client, ..[]Server_Msg{Server_Msg_Suspend{}}) } } editor_rerender :: proc(ed: ^Editor) -> (err: Error) { ed.render_requested = false ed.rendered_at = time.tick_now() return editor_render(ed) } editor_render :: proc(ed: ^Editor) -> (err: Error) { defer if err != nil { log.debugf("render failed: {}", err) } it := hm.iterator_make(&ed.clients) for client, _ in hm.iterate(&it) { if client.state != .Attached {continue} grid_clear(&client.grid) // TODO: iterate all windows editor_render_win(ed, &client.grid, ed.cur_win) msgs := make([dynamic]Server_Msg, context.temp_allocator) cells := make([dynamic]Grid_Line_Cell, context.temp_allocator) lines := make([dynamic]Grid_Line, context.temp_allocator) starts := make([dynamic]int, context.temp_allocator) // index into `cells` where each line begins if client.refresh {reserve(&cells, len(client.grid.back)) or_return} next := Point{-1, -1} it := grid_diff_iterator(&client.grid, full = client.refresh) for gcell, point in grid_diff_iterate(&it) { if client.refresh && cell_is_blank(gcell.cell) {continue} if point != next { append(&lines, Grid_Line{point = point}) or_return append(&starts, len(cells)) or_return } append(&cells, gcell) or_return next = { row = point.row, col = point.col + int(gcell.width) * int(gcell.repeat), } } for &line, i in lines { end := i + 1 < len(starts) ? starts[i + 1] : len(cells) line.cells = cells[starts[i]:end] } client.grid.front, client.grid.back = client.grid.back, client.grid.front // swap grid buffers // send to client if client.refresh {append(&msgs, Server_Msg_Grid_Clear{})} if len(lines) > 0 {append(&msgs, Server_Msg_Grid_Lines{lines = lines[:]})} if len(msgs) == 0 {continue} append(&msgs, Server_Msg_Flush{}) client_send(ed, client, ..msgs[:]) or_return client.refresh = false } return } @(private = "file") editor_render_win :: proc(ed: ^Editor, grid: ^Grid, win: Window_Handle) { win, ok := hm.get(&ed.wins, win) if !ok { log.warn("stale window") return } buf, bok := hm.get(&ed.bufs, win.buf) if !bok { log.warn("stale win.buf") return } editor_render_win_buf(ed, grid, win, buf) } @(private = "file") editor_render_win_buf :: proc(ed: ^Editor, grid: ^Grid, win: ^Window, buf: ^Buffer) { pcursor := buffer_offset_to_point(buf, win.sel.cursor) top_row := win_scroll_to(win, buf, grid, pcursor) // TODO: maybe a line-col-display-width cache in Buffer would be useful for horizontal scrolling. buf_start_col := -win.left // where `buf` starts in relation to the window's horizontal offset buf_height := grid.size.h // TODO: - 1 to reserve height for statusline row: int = 0 col := buf_start_col it := buffer_iterator(buf, win.top) for g in buffer_iterate(&it) { if is_nl(g.text) { row += 1 if row >= buf_height {break} col = buf_start_col continue } width := display_width(g, col - buf_start_col, buf.options.tab_width) if col < 0 || col + width > int(grid.size.w) { col += width continue } text := g.text if text == "\t" { text = strings.repeat(" ", width, context.temp_allocator) } else if !is_grapheme_printable(g.text) { text = "\uFFFD" // string(utf8.REPLACEMENT_CHAR) } grid_set(grid, {row, col}, text, u8(width)) col += width } grid_set_style(grid, win_point_to_view(win, top_row, pcursor), {flags = {.Reverse}}) } // TODO: highlight unprintable characters @(private = "file") is_grapheme_printable :: proc(text: string) -> bool { if !utf8.valid_string(text) {return false} for r in text { if utf8.is_control(r) {return false} switch r { case 0x2028, 0x2029, 0xfff9 ..= 0xfffb: return false } } return true } Editor_Error :: enum { None, Buffer_Name_Taken, } editor_create_buf :: proc(ed: ^Editor, name: string, path: Maybe(string)) -> (h: Buffer_Handle, err: Error) { if _, exists := editor_buf_find(ed, name, nil); exists { return {}, Editor_Error.Buffer_Name_Taken } b: Buffer buffer_init(&b, name, path) or_return defer if err != nil {buffer_destroy(&b)} h = hm.add(&ed.bufs, b) or_return return h, nil } // Find a buffer by name and/or path. editor_buf_find :: proc(ed: ^Editor, name: Maybe(string), path: Maybe(string)) -> (h: Buffer_Handle, found: bool) { it := hm.iterator_make(&ed.bufs) for buf, handle in hm.iterate(&it) { if n, ok := name.?; ok && buf.name != n { continue } if p, ok := path.?; ok { buf_path, has_path := buf.path.? if !has_path || buf_path != p { continue } } return handle, true } return {}, false } editor_create_win :: proc(ed: ^Editor, buf: Buffer_Handle) -> (h: Window_Handle, err: runtime.Allocator_Error) { return hm.add(&ed.wins, Window{buf = buf}) } editor_current_win :: proc(ed: ^Editor) -> (win: ^Window, ok: bool) { return hm.get(&ed.wins, ed.cur_win) } editor_current_buf :: proc(ed: ^Editor) -> (win: ^Window, buf: ^Buffer, ok: bool) { win = hm.get(&ed.wins, ed.cur_win) or_return buf = hm.get(&ed.bufs, win.buf) or_return return win, buf, true } // TODO: could be an iterator instead // Callee is responsible for deleting `wins` editor_win_find_buf :: proc(ed: ^Editor, buf: Buffer_Handle) -> (wins: [dynamic]^Window) { it := hm.iterator_make(&ed.wins) for win, _ in hm.iterate(&it) { if (win.buf == buf) { append(&wins, win) } } return wins } @(private) editor_insert_text :: proc(ed: ^Editor, s: string) { win, ok := editor_current_win(ed) log.assert(ok, "stale current win") tx: Transaction defer transaction_destroy(&tx) from, to := selection_range(win.sel) transaction_change(&tx, from, to, s) editor_commit_transaction(ed, win.buf, &tx) } editor_with_context :: proc "c" (f: proc(ed: ^Editor)) { ed := editor_instance() context = ed.ctx f(ed) } editor_insert_newline :: proc(ed: ^Editor) { editor_insert_text(ed, "\n") editor_request_render(ed) } editor_insert_tab :: proc(ed: ^Editor) { editor_insert_text(ed, "\t") editor_request_render(ed) } editor_delete_backward :: proc(ed: ^Editor) { win, buf, wok := editor_current_buf(ed) log.assert(wok, "stale current win/buf") tx: Transaction defer transaction_destroy(&tx) if win.sel.anchor != win.sel.cursor { from, to := selection_range(win.sel) transaction_delete(&tx, from, to) } else { it := buffer_iterator(buf, win.sel.cursor) _, off, iok := buffer_iterate_back(&it) if !iok {return} transaction_delete(&tx, off, win.sel.cursor) } log.assert(editor_commit_transaction(ed, win.buf, &tx), "failed applying transaction") } editor_move_cursor :: proc(ed: ^Editor, by: Point) { win, buf, ok := editor_current_buf(ed) log.assert(ok, "stale current win/buf") win_cursor_move(win, buf, by) editor_request_render(ed) } Key_Action :: struct { f: janet.Janet, // either JanetFunction or JanetCFunction. chord: string, } @(private) key_action_destroy :: proc(action: Key_Action) { janet.gcunroot(action.f) delete(action.chord) } handle_key :: proc(ed: ^Editor, client: ^Client, k: keys.Key) -> (action: Maybe(Key_Action)) { log.debugf("handle_key: modifiers={} codepoint={}", k.modifiers, k.codepoint) append(&client.pending_chord, k) bound, match := keys.keymap_match(&ed.keymap, client.pending_chord[:]) switch match { case .Matched: clear(&client.pending_chord) if janet.checktype(bound.f, .FUNCTION) != 0 { return bound } else if janet.checktype(bound.f, .CFUNCTION) != 0 { janet.unwrap_cfunction(bound.f)(0, nil) } else { log.panic("key binding is not a function or cfunction") } case .Prefix: // wait for more keys case .None: clear(&client.pending_chord) if codepoint, ok := keys.codepoint(k); ok { bytes, n := utf8.encode_rune(codepoint) editor_insert_text(ed, string(bytes[:n])) } else { log.debugf("unhandled key: modifiers={} codepoint={}", k.modifiers, k.codepoint) } } return nil } Client :: struct { handle: Client_Handle, state: Client_State, grid: Grid, rpc: Rpc, refresh: bool, typeahead: queue.Queue(keys.Key), pending_chord: [dynamic]keys.Key, } Client_Handle :: distinct hm.Handle64 Client_State :: enum { None, Attached, } client_destroy :: proc(client: ^Client) { grid_destroy(&client.grid) rpc_destroy(&client.rpc) queue.destroy(&client.typeahead) delete(client.pending_chord) client.state = .None } client_resume :: proc(client: ^Client, msg: Client_Msg_Resume) { client_resize(client, {size = msg.size}) } client_resize :: proc(client: ^Client, msg: Client_Msg_Resize) { if client.state != .Attached {return} if msg.size.w <= 0 || msg.size.h <= 0 { log.warnf("client: ignoring bad resize to {}", msg.size) return } grid_resize(&client.grid, msg.size) client.refresh = true } client_attach :: proc(client: ^Client, msg: Client_Msg_Attach) -> (err: Error) { log.assertf(client.state == .None, "client: can't attach a client in state {}", client.state) if msg.size.w <= 0 || msg.size.h <= 0 { log.errorf("client: attach with invalid size {}", msg.size) return Rpc_Error.Bad_Size } grid_init(&client.grid, msg.size) or_return client.state = .Attached client.refresh = true return } editor_commit_transaction :: proc(ed: ^Editor, hbuf: Buffer_Handle, tx: ^Transaction) -> bool { if len(tx.change_set.changes) == 0 { return true } buf := hm.get(&ed.bufs, hbuf) or_return if !change_set_apply(&tx.change_set, buf) { log.debug("transaction does not fit the buffer") return false } buf.version += 1 wins := editor_win_find_buf(ed, hbuf) defer delete(wins) for win in wins { win.sel = selection_map(win.sel, &tx.change_set) win.sel.target_col = nil // an edit in selection invalidates `target_col` win.top = change_set_map_off(&tx.change_set, win.top, .Before) } editor_request_render(ed) return true }