diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6bdae53d28..f8c8b0c546 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -26,7 +26,7 @@ Apps import the public packages; `internal/` holds the implementation, which onl | `base/textview`, `base/textview/highlight` | `nsh-base`'s `text_view`, `highlight` | `TextView`: Markdown, HTML or the app's blocks, and its code highlighting ([text view](docs/architecture/textview.md)) | | `base/formula` | — (MyGo's `contrib/mygo` adapter of Untie) | `View`: TeX and Typst math laid out by Untie and drawn as canvas shapes in New Computer Modern Math, and `RenderMath` for `TextView` ([formulas](docs/architecture/components.md#formulas)) | | `base/diagram` | — (limu's `limumygo`, its MyGo adapter) | `View`: Mermaid diagrams read and laid out by limu and drawn on a canvas in the platform's font, and `RenderDiagram` for `TextView` ([diagrams](docs/architecture/components.md#diagrams)) | -| `base/terminal`, `tools/libghostty` | — (Ghostty's libghostty-vt) | `Terminal` and its `View`: a program in a pseudo-terminal with libghostty-vt loaded through purego, and the command building the library ([terminal](docs/architecture/terminal.md)) | +| `base/terminal`, `tools/libghostty` | — (Ghostty's libghostty-vt) | `Terminal` and its `View`: local programs and remote byte streams with libghostty-vt loaded through purego or instantiated as browser WebAssembly, and the command building the library ([terminal](docs/architecture/terminal.md)) | | `base/editor`, `base/diff` | `nsh-base`'s `editor`, `diff` | `Editor`, a code editor, and `DiffView`, the changes between texts or of a patch ([editor](docs/architecture/editor.md)) | | `base/richeditor`, `ui/richeditor` | `nsh-base`'s `rich_editor` | `RichEditor`, a ProseMirror-style document with Tiptap's extensions, and its styled form ([rich editor](docs/architecture/richeditor.md)) | | `base/internal/*` | `nsh-base`'s `syntax`, `window` | What `base`'s packages share: highlighting, the rows a virtualized view makes, part styles and sheets | diff --git a/NOTICE b/NOTICE index cbc4b9dc8c..9f2d0fe9ad 100644 --- a/NOTICE +++ b/NOTICE @@ -77,6 +77,8 @@ https://github.com/egoist/mygo, Copyright (c) 2026 MyGo contributors, licensed under the MIT License. base/terminal/internal/library/lib holds libghostty-vt built from Ghostty, https://github.com/ghostty-org/ghostty, Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors, licensed under the MIT License. +The browser build also links Zig's standard library and Wuffs; their MIT +notices are retained in base/terminal/internal/library/LICENSE. base/terminal/ghostty_themes.go holds iTerm2-Color-Schemes' themes as Ghostty ships them, under the MIT License its header gives. diff --git a/base/terminal/browser_js_test.go b/base/terminal/browser_js_test.go new file mode 100644 index 0000000000..b1247e27de --- /dev/null +++ b/base/terminal/browser_js_test.go @@ -0,0 +1,18 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package terminal + +import ( + "strings" + "testing" +) + +func TestBrowserNeedsRemoteConnection(t *testing.T) { + term, err := New(Options{}) + if term != nil { + term.Close() + } + if err == nil || !strings.Contains(err.Error(), "give Options.Conn a remote session") { + t.Fatalf("a browser's local program request: %v", err) + } +} diff --git a/base/terminal/ghostty_test.go b/base/terminal/ghostty_test.go index a504a568af..23cab25941 100644 --- a/base/terminal/ghostty_test.go +++ b/base/terminal/ghostty_test.go @@ -3,6 +3,7 @@ package terminal import ( "os" "path/filepath" + "runtime" "slices" "strings" "testing" @@ -58,8 +59,11 @@ font-family = "Iosevka" } func TestGhosttyTheme(t *testing.T) { - config := t.TempDir() - t.Setenv("XDG_CONFIG_HOME", config) + config := "" + if runtime.GOOS != "js" { + config = t.TempDir() + t.Setenv("XDG_CONFIG_HOME", config) + } if len(ghosttyThemes) < 500 || !slices.IsSortedFunc(ghosttyThemes[:], func(a, b ghosttyTheme) int { return strings.Compare(a.name, b.name) }) { t.Fatalf("%d themes, sorted: want hundreds", len(ghosttyThemes)) } @@ -83,6 +87,14 @@ func TestGhosttyTheme(t *testing.T) { } } + // User files are native; the browser uses the bundled catalogs. + if runtime.GOOS == "js" { + if names := GhosttyThemes(); !slices.Contains(names, "Catppuccin Latte") || len(names) != len(ghosttyThemes) { + t.Errorf("browser theme catalog: %d names", len(names)) + } + return + } + // The user's themes come first, as in Ghostty. dir := filepath.Join(config, "ghostty", "themes") os.MkdirAll(dir, 0o755) diff --git a/base/terminal/internal/library/LICENSE b/base/terminal/internal/library/LICENSE new file mode 100644 index 0000000000..f1d9930711 --- /dev/null +++ b/base/terminal/internal/library/LICENSE @@ -0,0 +1,75 @@ +Ghostty + +MIT License + +Copyright (c) 2024 Mitchell Hashimoto, Ghostty contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +Zig standard library + +The MIT License (Expat) + +Copyright (c) Zig contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Wuffs + +Copyright 2023 The Wuffs Authors + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/base/terminal/internal/library/assets.go b/base/terminal/internal/library/assets.go new file mode 100644 index 0000000000..4d50238522 --- /dev/null +++ b/base/terminal/internal/library/assets.go @@ -0,0 +1,8 @@ +package library + +import _ "embed" + +// Keep the prebuilt library's notices when apps vendor this package. +// +//go:embed LICENSE +var _ string diff --git a/base/terminal/internal/library/lib/js-wasm/ghostty-vt.wasm b/base/terminal/internal/library/lib/js-wasm/ghostty-vt.wasm new file mode 100644 index 0000000000..fbdef4823a Binary files /dev/null and b/base/terminal/internal/library/lib/js-wasm/ghostty-vt.wasm differ diff --git a/base/terminal/internal/library/library.go b/base/terminal/internal/library/library.go index 14f1bee5ce..91fcb7707f 100644 --- a/base/terminal/internal/library/library.go +++ b/base/terminal/internal/library/library.go @@ -1,3 +1,5 @@ +//go:build !js || nsgominiprogram || nsgoharmony + // Package library finds libghostty-vt for the terminal: the file // $NSGO_GHOSTTY_VT names, the one the nsgo tool put into the app, or on // desktops the build for the platform the package embeds, written once diff --git a/base/terminal/internal/library/library_js.go b/base/terminal/internal/library/library_js.go new file mode 100644 index 0000000000..56ff12faf4 --- /dev/null +++ b/base/terminal/internal/library/library_js.go @@ -0,0 +1,14 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package library + +import _ "embed" + +//go:embed lib/js-wasm/ghostty-vt.wasm +var wasm []byte + +// Find returns the embedded browser module's identity; it needs no file system. +func Find() (string, error) { return "embedded:ghostty-vt.wasm", nil } + +// Wasm is the pinned WebAssembly library, used by the browser VT binding. +func Wasm() []byte { return wasm } diff --git a/base/terminal/internal/vt/abi.go b/base/terminal/internal/vt/abi.go new file mode 100644 index 0000000000..63e411e192 --- /dev/null +++ b/base/terminal/internal/vt/abi.go @@ -0,0 +1,63 @@ +package vt + +import "encoding/binary" + +func abiSize(m manifest, name string) uintptr { + switch name { + case "pointer": + return uintptr(m.ABI.PointerSize) + case "usize", "isize": + return uintptr(m.ABI.UsizeSize) + case "bool", "u8", "i8": + return 1 + case "u16", "i16": + return 2 + case "u32", "i32", "f32": + return 4 + case "u64", "i64", "f64": + return 8 + } + return m.Types[name].Size +} + +// convertABI copies values, never addresses Go memory from guest pointers. A pointer remains an opaque guest address until an explicit memory access. +func convertABI(dst, src []byte, name string, to, from manifest) { + t, ok := from.Types[name] + if !ok || t.Kind != "struct" { + if ok && t.Kind == "alias" { + convertABI(dst, src, t.Type, to, from) + return + } + clear(dst) + copy(dst, src) + return + } + for field, f := range t.Fields { + d := to.Types[name].Fields[field] + in, out := src[f.Offset:f.Offset+f.Size], dst[d.Offset:d.Offset+d.Size] + if field == "size" && unsignedABI(in) != 0 { + putUnsignedABI(out, uint64(len(dst))) + continue + } + if f.Type == "array" { + a, b := abiSize(from, f.Elem), abiSize(to, d.Elem) + for i := range f.Count { + convertABI(out[i*b:(i+1)*b], in[i*a:(i+1)*a], f.Elem, to, from) + } + } else { + convertABI(out, in, f.Type, to, from) + } + } +} + +func unsignedABI(b []byte) uint64 { + var buf [8]byte + copy(buf[:], b) + return binary.LittleEndian.Uint64(buf[:]) +} + +func putUnsignedABI(b []byte, value uint64) { + var buf [8]byte + binary.LittleEndian.PutUint64(buf[:], value) + copy(b, buf[:]) +} diff --git a/base/terminal/internal/vt/abi64.json b/base/terminal/internal/vt/abi64.json new file mode 100644 index 0000000000..357ca2e977 --- /dev/null +++ b/base/terminal/internal/vt/abi64.json @@ -0,0 +1 @@ +{"abi":{"endian":"little","environment":"none","max_alignment":8,"os":"macos","pointer_size":8,"target":"aarch64","usize_size":8},"commit":null,"dirty":null,"library_version":"0.1.0-dev","schema":1,"types":{"GhosttyAllocator":{"align":8,"fields":{"ctx":{"const":false,"elem":"opaque","offset":0,"size":8,"type":"pointer"},"vtable":{"const":true,"elem":"GhosttyAllocatorVtable","offset":8,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyAllocatorVtable":{"align":8,"fields":{"alloc":{"const":true,"elem":"function","offset":0,"size":8,"type":"pointer"},"free":{"const":true,"elem":"function","offset":24,"size":8,"type":"pointer"},"remap":{"const":true,"elem":"function","offset":16,"size":8,"type":"pointer"},"resize":{"const":true,"elem":"function","offset":8,"size":8,"type":"pointer"}},"kind":"struct","size":32},"GhosttyBuffer":{"align":8,"fields":{"cap":{"offset":8,"size":8,"type":"u64"},"len":{"offset":16,"size":8,"type":"u64"},"ptr":{"const":false,"elem":"u8","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":24},"GhosttyBuildInfo":{"align":4,"kind":"enum","prefix":"GHOSTTY_BUILD_INFO_","size":4,"underlying":"i32","values":{"INVALID":0,"KITTY_GRAPHICS":2,"MAX_VALUE":2147483647,"OPTIMIZE":4,"SIMD":1,"TMUX_CONTROL_MODE":3,"VERSION_BUILD":10,"VERSION_MAJOR":6,"VERSION_MINOR":7,"VERSION_PATCH":8,"VERSION_PRE":9,"VERSION_STRING":5}},"GhosttyCell":{"align":8,"bits":{"content":{"arms":{"BG_COLOR_PALETTE":{"bits":{"index":{"lsb":0,"type":"GhosttyColorPaletteIndex","width":8}},"kind":"packed","width":24},"BG_COLOR_RGB":{"bits":{"b":{"lsb":16,"type":"u8","width":8},"g":{"lsb":8,"type":"u8","width":8},"r":{"lsb":0,"type":"u8","width":8}},"kind":"packed","width":24},"CODEPOINT":{"bits":{"codepoint":{"lsb":0,"type":"u21","width":21}},"kind":"packed","width":24},"CODEPOINT_GRAPHEME":{"bits":{"codepoint":{"lsb":0,"type":"u21","width":21}},"kind":"packed","width":24}},"kind":"union","lsb":2,"tag":"content_tag","width":24},"content_tag":{"lsb":0,"type":"GhosttyCellContentTag","width":2},"hyperlink":{"lsb":45,"type":"bool","width":1},"protected":{"lsb":44,"type":"bool","width":1},"semantic_content":{"lsb":46,"type":"GhosttyCellSemanticContent","width":2},"style_id":{"lsb":26,"type":"GhosttyStyleId","width":16},"wide":{"lsb":42,"type":"GhosttyCellWide","width":2}},"kind":"packed","size":8,"underlying":"u64"},"GhosttyCellContentTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_CELL_CONTENT_","size":4,"underlying":"i32","values":{"BG_COLOR_PALETTE":2,"BG_COLOR_RGB":3,"CODEPOINT":0,"CODEPOINT_GRAPHEME":1,"TAG_MAX_VALUE":2147483647}},"GhosttyCellData":{"align":4,"kind":"enum","prefix":"GHOSTTY_CELL_DATA_","size":4,"underlying":"i32","values":{"CODEPOINT":1,"COLOR_PALETTE":10,"COLOR_RGB":11,"CONTENT_TAG":2,"HAS_HYPERLINK":7,"HAS_STYLING":5,"HAS_TEXT":4,"INVALID":0,"MAX_VALUE":2147483647,"PROTECTED":8,"SEMANTIC_CONTENT":9,"STYLE_ID":6,"WIDE":3}},"GhosttyCellSemanticContent":{"align":4,"kind":"enum","prefix":"GHOSTTY_CELL_SEMANTIC_","size":4,"underlying":"i32","values":{"INPUT":1,"MAX_VALUE":2147483647,"OUTPUT":0,"PROMPT":2}},"GhosttyCellWide":{"align":4,"kind":"enum","prefix":"GHOSTTY_CELL_WIDE_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"NARROW":0,"SPACER_HEAD":3,"SPACER_TAIL":2,"WIDE":1}},"GhosttyCellsView":{"align":8,"fields":{"len":{"offset":8,"size":8,"type":"u64"},"ptr":{"const":true,"elem":"GhosttyCell","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyClipboardContent":{"align":8,"fields":{"data":{"offset":16,"size":16,"type":"GhosttyString"},"mime":{"offset":0,"size":16,"type":"GhosttyString"}},"kind":"struct","size":32},"GhosttyClipboardLocation":{"align":4,"kind":"enum","prefix":"GHOSTTY_CLIPBOARD_LOCATION_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"PRIMARY":2,"SELECTION":1,"STANDARD":0}},"GhosttyClipboardRead":{"align":8,"fields":{"can_remember":{"offset":57,"size":1,"type":"bool"},"ctx":{"const":true,"elem":"opaque","offset":64,"size":8,"type":"pointer"},"granted":{"offset":56,"size":1,"type":"bool"},"list":{"offset":32,"size":1,"type":"bool"},"location":{"offset":8,"size":4,"type":"GhosttyClipboardLocation"},"mimes":{"const":true,"elem":"GhosttyString","nullable":true,"offset":16,"size":8,"type":"pointer"},"mimes_len":{"offset":24,"size":8,"type":"u64"},"name":{"offset":40,"size":16,"type":"GhosttyString"},"reply":{"const":true,"elem":"function","offset":72,"size":8,"type":"pointer"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":80},"GhosttyClipboardReadReply":{"align":8,"fields":{"available":{"const":true,"elem":"GhosttyString","nullable":true,"offset":32,"size":8,"type":"pointer"},"available_len":{"offset":40,"size":8,"type":"u64"},"contents":{"const":true,"elem":"GhosttyClipboardContent","nullable":true,"offset":16,"size":8,"type":"pointer"},"contents_len":{"offset":24,"size":8,"type":"u64"},"remember":{"offset":48,"size":1,"type":"bool"},"result":{"offset":8,"size":4,"type":"GhosttyClipboardReadResult"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":56},"GhosttyClipboardReadResult":{"align":4,"kind":"enum","prefix":"GHOSTTY_CLIPBOARD_READ_RESULT_","size":4,"underlying":"i32","values":{"BUSY":3,"DENIED":1,"IO_ERROR":4,"MAX_VALUE":2147483647,"SUCCESS":0,"UNSUPPORTED":2}},"GhosttyClipboardWrite":{"align":8,"fields":{"can_remember":{"offset":49,"size":1,"type":"bool"},"contents":{"const":true,"elem":"GhosttyClipboardContent","nullable":true,"offset":16,"size":8,"type":"pointer"},"contents_len":{"offset":24,"size":8,"type":"u64"},"ctx":{"const":true,"elem":"opaque","offset":56,"size":8,"type":"pointer"},"granted":{"offset":48,"size":1,"type":"bool"},"location":{"offset":8,"size":4,"type":"GhosttyClipboardLocation"},"name":{"offset":32,"size":16,"type":"GhosttyString"},"reply":{"const":true,"elem":"function","offset":64,"size":8,"type":"pointer"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":72},"GhosttyClipboardWriteReply":{"align":8,"fields":{"remember":{"offset":12,"size":1,"type":"bool"},"result":{"offset":8,"size":4,"type":"GhosttyClipboardWriteResult"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":16},"GhosttyClipboardWriteResult":{"align":4,"kind":"enum","prefix":"GHOSTTY_CLIPBOARD_WRITE_RESULT_","size":4,"underlying":"i32","values":{"BUSY":3,"DENIED":1,"INVALID_DATA":4,"IO_ERROR":5,"MAX_VALUE":2147483647,"SUCCESS":0,"UNSUPPORTED":2}},"GhosttyCodepoints":{"align":8,"fields":{"len":{"offset":8,"size":8,"type":"u64"},"ptr":{"const":true,"elem":"u32","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyColorPaletteIndex":{"align":1,"kind":"alias","size":1,"type":"u8"},"GhosttyColorPaletteMask":{"align":8,"fields":{"bits":{"count":4,"elem":"u64","offset":0,"size":32,"type":"array"}},"kind":"struct","size":32},"GhosttyColorRgb":{"align":1,"fields":{"b":{"offset":2,"size":1,"type":"u8"},"g":{"offset":1,"size":1,"type":"u8"},"r":{"offset":0,"size":1,"type":"u8"}},"kind":"struct","size":3},"GhosttyColorScheme":{"align":4,"kind":"enum","prefix":"GHOSTTY_COLOR_SCHEME_","size":4,"underlying":"i32","values":{"DARK":1,"LIGHT":0,"MAX_VALUE":2147483647}},"GhosttyColorX11Entry":{"align":8,"fields":{"color":{"offset":8,"size":3,"type":"GhosttyColorRgb"},"name":{"const":true,"elem":"u8","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyDeviceAttributes":{"align":8,"fields":{"primary":{"offset":0,"size":144,"type":"GhosttyDeviceAttributesPrimary"},"secondary":{"offset":144,"size":6,"type":"GhosttyDeviceAttributesSecondary"},"tertiary":{"offset":152,"size":4,"type":"GhosttyDeviceAttributesTertiary"}},"kind":"struct","size":160},"GhosttyDeviceAttributesPrimary":{"align":8,"fields":{"conformance_level":{"offset":0,"size":2,"type":"u16"},"features":{"count":64,"elem":"u16","offset":2,"size":128,"type":"array"},"num_features":{"offset":136,"size":8,"type":"u64"}},"kind":"struct","size":144},"GhosttyDeviceAttributesSecondary":{"align":2,"fields":{"device_type":{"offset":0,"size":2,"type":"u16"},"firmware_version":{"offset":2,"size":2,"type":"u16"},"rom_cartridge":{"offset":4,"size":2,"type":"u16"}},"kind":"struct","size":6},"GhosttyDeviceAttributesTertiary":{"align":4,"fields":{"unit_id":{"offset":0,"size":4,"type":"u32"}},"kind":"struct","size":4},"GhosttyFocusEvent":{"align":4,"kind":"enum","prefix":"GHOSTTY_FOCUS_","size":4,"underlying":"i32","values":{"GAINED":0,"LOST":1,"MAX_VALUE":2147483647}},"GhosttyFormatter":{"align":8,"kind":"opaque","size":8},"GhosttyFormatterFormat":{"align":4,"kind":"enum","prefix":"GHOSTTY_FORMATTER_FORMAT_","size":4,"underlying":"i32","values":{"HTML":2,"MAX_VALUE":2147483647,"PLAIN":0,"VT":1}},"GhosttyFormatterScreenExtra":{"align":8,"fields":{"charsets":{"offset":13,"size":1,"type":"bool"},"cursor":{"offset":8,"size":1,"type":"bool"},"hyperlink":{"offset":10,"size":1,"type":"bool"},"kitty_keyboard":{"offset":12,"size":1,"type":"bool"},"protection":{"offset":11,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"style":{"offset":9,"size":1,"type":"bool"}},"kind":"struct","size":16},"GhosttyFormatterTerminalExtra":{"align":8,"fields":{"keyboard":{"offset":13,"size":1,"type":"bool"},"modes":{"offset":9,"size":1,"type":"bool"},"palette":{"offset":8,"size":1,"type":"bool"},"pwd":{"offset":12,"size":1,"type":"bool"},"screen":{"offset":16,"size":16,"type":"GhosttyFormatterScreenExtra"},"scrolling_region":{"offset":10,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"tabstops":{"offset":11,"size":1,"type":"bool"}},"kind":"struct","size":32},"GhosttyFormatterTerminalOptions":{"align":8,"fields":{"emit":{"offset":8,"size":4,"type":"GhosttyFormatterFormat"},"extra":{"offset":16,"size":32,"type":"GhosttyFormatterTerminalExtra"},"selection":{"const":true,"elem":"GhosttySelection","nullable":true,"offset":48,"size":8,"type":"pointer"},"size":{"offset":0,"size":8,"type":"u64"},"trim":{"offset":13,"size":1,"type":"bool"},"unwrap":{"offset":12,"size":1,"type":"bool"}},"kind":"struct","size":56},"GhosttyGridRef":{"align":8,"fields":{"node":{"const":false,"elem":"opaque","nullable":true,"offset":8,"size":8,"type":"pointer"},"size":{"offset":0,"size":8,"type":"u64"},"x":{"offset":16,"size":2,"type":"u16"},"y":{"offset":18,"size":2,"type":"u16"}},"kind":"struct","size":24},"GhosttyKey":{"align":4,"kind":"enum","prefix":"GHOSTTY_KEY_","size":4,"underlying":"i32","values":{"A":20,"ALT_LEFT":51,"ALT_RIGHT":52,"ARROW_DOWN":75,"ARROW_LEFT":76,"ARROW_RIGHT":77,"ARROW_UP":78,"AUDIO_VOLUME_DOWN":169,"AUDIO_VOLUME_MUTE":170,"AUDIO_VOLUME_UP":171,"B":21,"BACKQUOTE":1,"BACKSLASH":2,"BACKSPACE":53,"BRACKET_LEFT":3,"BRACKET_RIGHT":4,"BROWSER_BACK":151,"BROWSER_FAVORITES":152,"BROWSER_FORWARD":153,"BROWSER_HOME":154,"BROWSER_REFRESH":155,"BROWSER_SEARCH":156,"BROWSER_STOP":157,"C":22,"CAPS_LOCK":54,"COMMA":5,"CONTEXT_MENU":55,"CONTROL_LEFT":56,"CONTROL_RIGHT":57,"CONVERT":65,"COPY":173,"CUT":174,"D":23,"DELETE":68,"DIGIT_0":6,"DIGIT_1":7,"DIGIT_2":8,"DIGIT_3":9,"DIGIT_4":10,"DIGIT_5":11,"DIGIT_6":12,"DIGIT_7":13,"DIGIT_8":14,"DIGIT_9":15,"E":24,"EJECT":158,"END":69,"ENTER":58,"EQUAL":16,"ESCAPE":120,"F":25,"F1":121,"F10":130,"F11":131,"F12":132,"F13":133,"F14":134,"F15":135,"F16":136,"F17":137,"F18":138,"F19":139,"F2":122,"F20":140,"F21":141,"F22":142,"F23":143,"F24":144,"F25":145,"F3":123,"F4":124,"F5":125,"F6":126,"F7":127,"F8":128,"F9":129,"FN":146,"FN_LOCK":147,"G":26,"H":27,"HELP":70,"HOME":71,"I":28,"INSERT":72,"INTL_BACKSLASH":17,"INTL_RO":18,"INTL_YEN":19,"J":29,"K":30,"KANA_MODE":66,"L":31,"LAUNCH_APP_1":159,"LAUNCH_APP_2":160,"LAUNCH_MAIL":161,"M":32,"MAX_VALUE":2147483647,"MEDIA_PLAY_PAUSE":162,"MEDIA_SELECT":163,"MEDIA_STOP":164,"MEDIA_TRACK_NEXT":165,"MEDIA_TRACK_PREVIOUS":166,"META_LEFT":59,"META_RIGHT":60,"MINUS":46,"N":33,"NON_CONVERT":67,"NUMPAD_0":80,"NUMPAD_1":81,"NUMPAD_2":82,"NUMPAD_3":83,"NUMPAD_4":84,"NUMPAD_5":85,"NUMPAD_6":86,"NUMPAD_7":87,"NUMPAD_8":88,"NUMPAD_9":89,"NUMPAD_ADD":90,"NUMPAD_BACKSPACE":91,"NUMPAD_BEGIN":113,"NUMPAD_CLEAR":92,"NUMPAD_CLEAR_ENTRY":93,"NUMPAD_COMMA":94,"NUMPAD_DECIMAL":95,"NUMPAD_DELETE":117,"NUMPAD_DIVIDE":96,"NUMPAD_DOWN":110,"NUMPAD_END":115,"NUMPAD_ENTER":97,"NUMPAD_EQUAL":98,"NUMPAD_HOME":114,"NUMPAD_INSERT":116,"NUMPAD_LEFT":112,"NUMPAD_MEMORY_ADD":99,"NUMPAD_MEMORY_CLEAR":100,"NUMPAD_MEMORY_RECALL":101,"NUMPAD_MEMORY_STORE":102,"NUMPAD_MEMORY_SUBTRACT":103,"NUMPAD_MULTIPLY":104,"NUMPAD_PAGE_DOWN":119,"NUMPAD_PAGE_UP":118,"NUMPAD_PAREN_LEFT":105,"NUMPAD_PAREN_RIGHT":106,"NUMPAD_RIGHT":111,"NUMPAD_SEPARATOR":108,"NUMPAD_SUBTRACT":107,"NUMPAD_UP":109,"NUM_LOCK":79,"O":34,"P":35,"PAGE_DOWN":73,"PAGE_UP":74,"PASTE":175,"PAUSE":150,"PERIOD":47,"POWER":167,"PRINT_SCREEN":148,"Q":36,"QUOTE":48,"R":37,"S":38,"SCROLL_LOCK":149,"SEMICOLON":49,"SHIFT_LEFT":61,"SHIFT_RIGHT":62,"SLASH":50,"SLEEP":168,"SPACE":63,"T":39,"TAB":64,"U":40,"UNIDENTIFIED":0,"V":41,"W":42,"WAKE_UP":172,"X":43,"Y":44,"Z":45}},"GhosttyKeyAction":{"align":4,"kind":"enum","prefix":"GHOSTTY_KEY_ACTION_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"PRESS":1,"RELEASE":0,"REPEAT":2}},"GhosttyKeyEncoder":{"align":8,"kind":"opaque","size":8},"GhosttyKeyEncoderOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_KEY_ENCODER_OPT_","size":4,"underlying":"i32","values":{"ALT_ESC_PREFIX":3,"BACKARROW_KEY_MODE":7,"CURSOR_KEY_APPLICATION":0,"IGNORE_KEYPAD_WITH_NUMLOCK":2,"KEYPAD_KEY_APPLICATION":1,"KITTY_FLAGS":5,"MACOS_OPTION_AS_ALT":6,"MAX_VALUE":2147483647,"MODIFY_OTHER_KEYS_STATE_2":4}},"GhosttyKeyEvent":{"align":8,"kind":"opaque","size":8},"GhosttyKittyGraphics":{"align":8,"kind":"opaque","size":8},"GhosttyKittyGraphicsData":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_GRAPHICS_DATA_","size":4,"underlying":"i32","values":{"GENERATION":2,"INVALID":0,"MAX_VALUE":2147483647,"PLACEMENT_ITERATOR":1}},"GhosttyKittyGraphicsImage":{"align":8,"kind":"opaque","size":8},"GhosttyKittyGraphicsImageData":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_IMAGE_DATA_","size":4,"underlying":"i32","values":{"COMPRESSION":6,"DATA_LEN":8,"DATA_PTR":7,"FORMAT":5,"GENERATION":9,"HEIGHT":4,"ID":1,"INVALID":0,"MAX_VALUE":2147483647,"NUMBER":2,"WIDTH":3}},"GhosttyKittyGraphicsPlacementData":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_","size":4,"underlying":"i32","values":{"COLUMNS":10,"IMAGE_ID":1,"INVALID":0,"IS_VIRTUAL":3,"MAX_VALUE":2147483647,"PLACEMENT_ID":2,"ROWS":11,"SOURCE_HEIGHT":9,"SOURCE_WIDTH":8,"SOURCE_X":6,"SOURCE_Y":7,"X_OFFSET":4,"Y_OFFSET":5,"Z":12}},"GhosttyKittyGraphicsPlacementIterator":{"align":8,"kind":"opaque","size":8},"GhosttyKittyGraphicsPlacementIteratorOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_","size":4,"underlying":"i32","values":{"LAYER":0,"MAX_VALUE":2147483647}},"GhosttyKittyGraphicsPlacementRenderInfo":{"align":8,"fields":{"grid_cols":{"offset":16,"size":4,"type":"u32"},"grid_rows":{"offset":20,"size":4,"type":"u32"},"pixel_height":{"offset":12,"size":4,"type":"u32"},"pixel_width":{"offset":8,"size":4,"type":"u32"},"size":{"offset":0,"size":8,"type":"u64"},"source_height":{"offset":48,"size":4,"type":"u32"},"source_width":{"offset":44,"size":4,"type":"u32"},"source_x":{"offset":36,"size":4,"type":"u32"},"source_y":{"offset":40,"size":4,"type":"u32"},"viewport_col":{"offset":24,"size":4,"type":"i32"},"viewport_row":{"offset":28,"size":4,"type":"i32"},"viewport_visible":{"offset":32,"size":1,"type":"bool"}},"kind":"struct","size":56},"GhosttyKittyImageCompression":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_IMAGE_COMPRESSION_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"NONE":0,"ZLIB_DEFLATE":1}},"GhosttyKittyImageFormat":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_IMAGE_FORMAT_","size":4,"underlying":"i32","values":{"GRAY":4,"GRAY_ALPHA":3,"MAX_VALUE":2147483647,"PNG":2,"RGB":0,"RGBA":1}},"GhosttyKittyKeyFlags":{"align":1,"kind":"alias","size":1,"type":"u8"},"GhosttyKittyPlacementLayer":{"align":4,"kind":"enum","prefix":"GHOSTTY_KITTY_PLACEMENT_LAYER_","size":4,"underlying":"i32","values":{"ABOVE_TEXT":3,"ALL":0,"BELOW_BG":1,"BELOW_TEXT":2,"MAX_VALUE":2147483647}},"GhosttyMimeReader":{"align":8,"fields":{"read":{"const":true,"elem":"function","nullable":true,"offset":0,"size":8,"type":"pointer"},"userdata":{"const":false,"elem":"opaque","nullable":true,"offset":8,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyMode":{"align":2,"kind":"alias","size":2,"type":"u16"},"GhosttyModeReportState":{"align":4,"kind":"enum","prefix":"GHOSTTY_MODE_REPORT_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"NOT_RECOGNIZED":0,"PERMANENTLY_RESET":4,"PERMANENTLY_SET":3,"RESET":2,"SET":1}},"GhosttyMods":{"align":2,"kind":"alias","size":2,"type":"u16"},"GhosttyMouseAction":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_ACTION_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"MOTION":2,"PRESS":0,"RELEASE":1}},"GhosttyMouseButton":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_BUTTON_","size":4,"underlying":"i32","values":{"EIGHT":8,"ELEVEN":11,"FIVE":5,"FOUR":4,"LEFT":1,"MAX_VALUE":2147483647,"MIDDLE":3,"NINE":9,"RIGHT":2,"SEVEN":7,"SIX":6,"TEN":10,"UNKNOWN":0}},"GhosttyMouseEncoder":{"align":8,"kind":"opaque","size":8},"GhosttyMouseEncoderOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_ENCODER_OPT_","size":4,"underlying":"i32","values":{"ANY_BUTTON_PRESSED":3,"EVENT":0,"FORMAT":1,"MAX_VALUE":2147483647,"SIZE":2,"TRACK_LAST_CELL":4}},"GhosttyMouseEncoderSize":{"align":8,"fields":{"cell_height":{"offset":20,"size":4,"type":"u32"},"cell_width":{"offset":16,"size":4,"type":"u32"},"padding_bottom":{"offset":28,"size":4,"type":"u32"},"padding_left":{"offset":36,"size":4,"type":"u32"},"padding_right":{"offset":32,"size":4,"type":"u32"},"padding_top":{"offset":24,"size":4,"type":"u32"},"screen_height":{"offset":12,"size":4,"type":"u32"},"screen_width":{"offset":8,"size":4,"type":"u32"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":40},"GhosttyMouseEvent":{"align":8,"kind":"opaque","size":8},"GhosttyMouseFormat":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_FORMAT_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"SGR":2,"SGR_PIXELS":4,"URXVT":3,"UTF8":1,"X10":0}},"GhosttyMousePosition":{"align":4,"fields":{"x":{"offset":0,"size":4,"type":"f32"},"y":{"offset":4,"size":4,"type":"f32"}},"kind":"struct","size":8},"GhosttyMouseShape":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_SHAPE_","size":4,"underlying":"i32","values":{"ALIAS":10,"ALL_SCROLL":17,"CELL":6,"COL_RESIZE":18,"CONTEXT_MENU":1,"COPY":11,"CROSSHAIR":7,"DEFAULT":0,"EW_RESIZE":28,"E_RESIZE":21,"GRAB":15,"GRABBING":16,"HELP":2,"MAX_VALUE":2147483647,"MOVE":12,"NESW_RESIZE":30,"NE_RESIZE":24,"NOT_ALLOWED":14,"NO_DROP":13,"NS_RESIZE":29,"NWSE_RESIZE":31,"NW_RESIZE":25,"N_RESIZE":20,"POINTER":3,"PROGRESS":4,"ROW_RESIZE":19,"SE_RESIZE":26,"SW_RESIZE":27,"S_RESIZE":22,"TEXT":8,"VERTICAL_TEXT":9,"WAIT":5,"W_RESIZE":23,"ZOOM_IN":32,"ZOOM_OUT":33}},"GhosttyMouseTrackingMode":{"align":4,"kind":"enum","prefix":"GHOSTTY_MOUSE_TRACKING_","size":4,"underlying":"i32","values":{"ANY":4,"BUTTON":3,"MAX_VALUE":2147483647,"NONE":0,"NORMAL":2,"X10":1}},"GhosttyOptimizeMode":{"align":4,"kind":"enum","prefix":"GHOSTTY_OPTIMIZE_","size":4,"underlying":"i32","values":{"DEBUG":0,"MODE_MAX_VALUE":2147483647,"RELEASE_FAST":3,"RELEASE_SAFE":1,"RELEASE_SMALL":2}},"GhosttyOptionAsAlt":{"align":4,"kind":"enum","prefix":"GHOSTTY_OPTION_AS_ALT_","size":4,"underlying":"i32","values":{"FALSE":0,"LEFT":2,"MAX_VALUE":2147483647,"RIGHT":3,"TRUE":1}},"GhosttyOscCommand":{"align":8,"kind":"opaque","size":8},"GhosttyOscCommandData":{"align":4,"kind":"enum","prefix":"GHOSTTY_OSC_DATA_","size":4,"underlying":"i32","values":{"CHANGE_WINDOW_TITLE_STR":1,"INVALID":0,"MAX_VALUE":2147483647,"UNKNOWN_CONTENT":2,"UNKNOWN_TERMINATOR":4,"UNKNOWN_TRUNCATED":3}},"GhosttyOscCommandType":{"align":4,"kind":"enum","prefix":"GHOSTTY_OSC_COMMAND_","size":4,"underlying":"i32","values":{"CHANGE_WINDOW_ICON":2,"CHANGE_WINDOW_TITLE":1,"CLIPBOARD_CONTENTS":4,"COLOR_OPERATION":7,"CONEMU_CHANGE_TAB_TITLE":14,"CONEMU_COMMENT":21,"CONEMU_GUIMACRO":17,"CONEMU_OUTPUT_ENVIRONMENT_VARIABLE":19,"CONEMU_PROGRESS_REPORT":15,"CONEMU_RUN_PROCESS":18,"CONEMU_SHOW_MESSAGE_BOX":13,"CONEMU_SLEEP":12,"CONEMU_WAIT_INPUT":16,"CONEMU_XTERM_EMULATION":20,"CONTEXT_SIGNAL":25,"HYPERLINK_END":11,"HYPERLINK_START":10,"INVALID":0,"KITTY_CLIPBOARD_PROTOCOL":23,"KITTY_COLOR_PROTOCOL":8,"KITTY_DESKTOP_NOTIFICATION":26,"KITTY_DND_PROTOCOL":24,"KITTY_TEXT_SIZING":22,"MOUSE_SHAPE":6,"REPORT_PWD":5,"SEMANTIC_PROMPT":3,"SHOW_DESKTOP_NOTIFICATION":9,"TYPE_MAX_VALUE":2147483647,"UNKNOWN":27}},"GhosttyOscOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_OSC_OPT_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"UNKNOWN_MAX_BYTES":0}},"GhosttyOscParser":{"align":8,"kind":"opaque","size":8},"GhosttyOscTerminator":{"align":4,"kind":"enum","prefix":"GHOSTTY_OSC_TERMINATOR_","size":4,"underlying":"i32","values":{"BEL":1,"MAX_VALUE":2147483647,"ST":0}},"GhosttyPaste":{"align":8,"fields":{"allow_unsafe":{"offset":48,"size":1,"type":"bool"},"location":{"offset":8,"size":4,"type":"GhosttyClipboardLocation"},"mimes":{"const":true,"elem":"GhosttyString","nullable":true,"offset":16,"size":8,"type":"pointer"},"mimes_len":{"offset":24,"size":8,"type":"u64"},"reader":{"offset":32,"size":16,"type":"GhosttyMimeReader"},"size":{"offset":0,"size":8,"type":"u64"},"source":{"offset":12,"size":4,"type":"GhosttyPasteSource"}},"kind":"struct","size":56},"GhosttyPasteSource":{"align":4,"kind":"enum","prefix":"GHOSTTY_PASTE_SOURCE_","size":4,"underlying":"i32","values":{"CLIPBOARD":0,"MAX_VALUE":2147483647,"TEXT":1}},"GhosttyPoint":{"align":8,"fields":{"tag":{"offset":0,"size":4,"type":"GhosttyPointTag"},"value":{"arms":{"ACTIVE":"coordinate","HISTORY":"coordinate","SCREEN":"coordinate","VIEWPORT":"coordinate"},"offset":8,"size":16,"tag":"tag","type":"GhosttyPointValue"}},"kind":"struct","size":24},"GhosttyPointCoordinate":{"align":4,"fields":{"x":{"offset":0,"size":2,"type":"u16"},"y":{"offset":4,"size":4,"type":"u32"}},"kind":"struct","size":8},"GhosttyPointTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_POINT_TAG_","size":4,"underlying":"i32","values":{"ACTIVE":0,"HISTORY":3,"MAX_VALUE":2147483647,"SCREEN":2,"VIEWPORT":1}},"GhosttyPointValue":{"align":8,"fields":{"_padding":{"count":2,"elem":"u64","offset":0,"size":16,"type":"array"},"coordinate":{"offset":0,"size":8,"type":"GhosttyPointCoordinate"}},"kind":"union","size":16},"GhosttyReader":{"align":8,"fields":{"read":{"const":true,"elem":"function","nullable":true,"offset":0,"size":8,"type":"pointer"},"userdata":{"const":false,"elem":"opaque","nullable":true,"offset":8,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyRenderState":{"align":8,"kind":"opaque","size":8},"GhosttyRenderStateColors":{"align":8,"fields":{"background":{"offset":8,"size":3,"type":"GhosttyColorRgb"},"cursor":{"offset":14,"size":3,"type":"GhosttyColorRgb"},"cursor_has_value":{"offset":17,"size":1,"type":"bool"},"foreground":{"offset":11,"size":3,"type":"GhosttyColorRgb"},"palette":{"count":256,"elem":"GhosttyColorRgb","offset":18,"size":768,"type":"array"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":792},"GhosttyRenderStateCursor":{"align":8,"fields":{"blinking":{"offset":16,"size":1,"type":"bool"},"password_input":{"offset":17,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"viewport_has_value":{"offset":8,"size":1,"type":"bool"},"viewport_x":{"offset":10,"size":2,"type":"u16"},"viewport_y":{"offset":12,"size":2,"type":"u16"},"visible":{"offset":15,"size":1,"type":"bool"},"visual_style":{"offset":20,"size":4,"type":"GhosttyRenderStateCursorVisualStyle"},"wide_tail":{"offset":14,"size":1,"type":"bool"}},"kind":"struct","size":24},"GhosttyRenderStateCursorVisualStyle":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_CURSOR_VISUAL_STYLE_","size":4,"underlying":"i32","values":{"BAR":0,"BLOCK":1,"BLOCK_HOLLOW":3,"MAX_VALUE":2147483647,"UNDERLINE":2}},"GhosttyRenderStateData":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_DATA_","size":4,"underlying":"i32","values":{"COLORS":19,"COLOR_BACKGROUND":5,"COLOR_CURSOR":7,"COLOR_CURSOR_HAS_VALUE":8,"COLOR_FOREGROUND":6,"COLOR_PALETTE":9,"COLS":1,"CURSOR":18,"CURSOR_BLINKING":12,"CURSOR_PASSWORD_INPUT":13,"CURSOR_VIEWPORT_HAS_VALUE":14,"CURSOR_VIEWPORT_WIDE_TAIL":17,"CURSOR_VIEWPORT_X":15,"CURSOR_VIEWPORT_Y":16,"CURSOR_VISIBLE":11,"CURSOR_VISUAL_STYLE":10,"DIRTY":3,"INVALID":0,"MAX_VALUE":2147483647,"OVERSCAN":20,"OVERSCAN_REQUEST":21,"ROWS":2,"ROW_ITERATOR":4}},"GhosttyRenderStateDirty":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_DIRTY_","size":4,"underlying":"i32","values":{"FALSE":0,"FULL":2,"MAX_VALUE":2147483647,"PARTIAL":1}},"GhosttyRenderStateOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_OPTION_","size":4,"underlying":"i32","values":{"DIRTY":0,"MAX_VALUE":2147483647,"OVERSCAN":1}},"GhosttyRenderStateOverscan":{"align":2,"fields":{"above":{"offset":0,"size":2,"type":"u16"},"below":{"offset":2,"size":2,"type":"u16"}},"kind":"struct","size":4},"GhosttyRenderStateRowCells":{"align":8,"kind":"opaque","size":8},"GhosttyRenderStateRowCellsData":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_ROW_CELLS_DATA_","size":4,"underlying":"i32","values":{"BG_COLOR":5,"FG_COLOR":6,"GRAPHEMES_BUF":4,"GRAPHEMES_LEN":3,"GRAPHEMES_UTF8":9,"HAS_STYLING":8,"INVALID":0,"MAX_VALUE":2147483647,"RAW":1,"SELECTED":7,"STYLE":2}},"GhosttyRenderStateRowData":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_ROW_DATA_","size":4,"underlying":"i32","values":{"CELLS":3,"CELLS_RAW":5,"DIRTY":1,"ID":7,"INVALID":0,"MAX_VALUE":2147483647,"RAW":2,"SELECTION":4,"VIEWPORT_Y":6}},"GhosttyRenderStateRowId":{"align":8,"fields":{"bits":{"count":2,"elem":"u64","offset":0,"size":16,"type":"array"}},"kind":"struct","size":16},"GhosttyRenderStateRowIterator":{"align":8,"kind":"opaque","size":8},"GhosttyRenderStateRowOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_RENDER_STATE_ROW_OPTION_","size":4,"underlying":"i32","values":{"DIRTY":0,"MAX_VALUE":2147483647}},"GhosttyRenderStateRowSelection":{"align":8,"fields":{"end_x":{"offset":10,"size":2,"type":"u16"},"size":{"offset":0,"size":8,"type":"u64"},"start_x":{"offset":8,"size":2,"type":"u16"}},"kind":"struct","size":16},"GhosttyResult":{"align":4,"kind":"enum","prefix":"GHOSTTY_","size":4,"underlying":"i32","values":{"INVALID_VALUE":-2,"IO_ERROR":-5,"LIMIT_EXCEEDED":-6,"NO_VALUE":-4,"OUT_OF_MEMORY":-1,"OUT_OF_SPACE":-3,"REJECTED":-7,"RESULT_MAX_VALUE":2147483647,"SUCCESS":0}},"GhosttyRow":{"align":8,"kind":"alias","size":8,"type":"u64"},"GhosttyRowData":{"align":4,"kind":"enum","prefix":"GHOSTTY_ROW_DATA_","size":4,"underlying":"i32","values":{"DIRTY":8,"GRAPHEME":3,"HYPERLINK":5,"INVALID":0,"KITTY_VIRTUAL_PLACEHOLDER":7,"MAX_VALUE":2147483647,"SEMANTIC_PROMPT":6,"STYLED":4,"WRAP":1,"WRAP_CONTINUATION":2}},"GhosttyRowSemanticPrompt":{"align":4,"kind":"enum","prefix":"GHOSTTY_ROW_SEMANTIC_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"NONE":0,"PROMPT":1,"PROMPT_CONTINUATION":2}},"GhosttySearch":{"align":8,"kind":"opaque","size":8},"GhosttySearchData":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEARCH_DATA_","size":4,"underlying":"i32","values":{"MATCHES":5,"MAX_VALUE":2147483647,"NEEDLE":1,"SELECTED_INDEX":3,"SELECTED_MATCH":4,"SELECT_SCROLL":7,"STATUS":0,"TOTAL_MATCHES":2,"VIEWPORT_MATCHES":6}},"GhosttySearchOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEARCH_OPT_","size":4,"underlying":"i32","values":{"MAX_VALUE":2147483647,"NEEDLE":0,"SELECT_NEXT":1,"SELECT_PREV":2,"SELECT_SCROLL":3}},"GhosttySearchScroll":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEARCH_SCROLL_","size":4,"underlying":"i32","values":{"IF_NEEDED":0,"MAX_VALUE":2147483647,"NONE":1}},"GhosttySearchStatus":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEARCH_STATUS_","size":4,"underlying":"i32","values":{"COMPLETE":2,"FEED_REQUIRED":1,"MAX_VALUE":2147483647,"RUNNING":0}},"GhosttySelection":{"align":8,"fields":{"end":{"offset":32,"size":24,"type":"GhosttyGridRef"},"rectangle":{"offset":56,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"start":{"offset":8,"size":24,"type":"GhosttyGridRef"}},"kind":"struct","size":64},"GhosttySelectionAdjust":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_ADJUST_","size":4,"underlying":"i32","values":{"BEGINNING_OF_LINE":8,"DOWN":3,"END":5,"END_OF_LINE":9,"HOME":4,"LEFT":0,"MAX_VALUE":2147483647,"PAGE_DOWN":7,"PAGE_UP":6,"RIGHT":1,"UP":2}},"GhosttySelectionBuffer":{"align":8,"fields":{"cap":{"offset":8,"size":8,"type":"u64"},"len":{"offset":16,"size":8,"type":"u64"},"ptr":{"const":false,"elem":"GhosttySelection","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":24},"GhosttySelectionGesture":{"align":8,"kind":"opaque","size":8},"GhosttySelectionGestureAutoscroll":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_GESTURE_AUTOSCROLL_","size":4,"underlying":"i32","values":{"DOWN":2,"MAX_VALUE":2147483647,"NONE":0,"UP":1}},"GhosttySelectionGestureBehavior":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_GESTURE_BEHAVIOR_","size":4,"underlying":"i32","values":{"CELL":0,"LINE":2,"MAX_VALUE":2147483647,"OUTPUT":3,"WORD":1}},"GhosttySelectionGestureBehaviors":{"align":4,"fields":{"double_click":{"offset":4,"size":4,"type":"GhosttySelectionGestureBehavior"},"single_click":{"offset":0,"size":4,"type":"GhosttySelectionGestureBehavior"},"triple_click":{"offset":8,"size":4,"type":"GhosttySelectionGestureBehavior"}},"kind":"struct","size":12},"GhosttySelectionGestureData":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_GESTURE_DATA_","size":4,"underlying":"i32","values":{"ANCHOR":4,"AUTOSCROLL":2,"BEHAVIOR":3,"CLICK_COUNT":0,"DRAGGED":1,"MAX_VALUE":2147483647}},"GhosttySelectionGestureEvent":{"align":8,"kind":"opaque","size":8},"GhosttySelectionGestureEventOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_GESTURE_EVENT_OPT_","size":4,"underlying":"i32","values":{"BEHAVIORS":6,"GEOMETRY":8,"MAX_VALUE":2147483647,"POSITION":1,"RECTANGLE":7,"REF":0,"REPEAT_DISTANCE":2,"REPEAT_INTERVAL_NS":4,"TIME_NS":3,"VIEWPORT":9,"WORD_BOUNDARY_CODEPOINTS":5}},"GhosttySelectionGestureEventType":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_","size":4,"underlying":"i32","values":{"AUTOSCROLL_TICK":3,"DEEP_PRESS":4,"DRAG":2,"MAX_VALUE":2147483647,"PRESS":0,"RELEASE":1}},"GhosttySelectionGestureGeometry":{"align":4,"fields":{"cell_width":{"offset":4,"size":4,"type":"u32"},"columns":{"offset":0,"size":4,"type":"u32"},"padding_left":{"offset":8,"size":4,"type":"u32"},"screen_height":{"offset":12,"size":4,"type":"u32"}},"kind":"struct","size":16},"GhosttySelectionOrder":{"align":4,"kind":"enum","prefix":"GHOSTTY_SELECTION_ORDER_","size":4,"underlying":"i32","values":{"FORWARD":0,"MAX_VALUE":2147483647,"MIRRORED_FORWARD":2,"MIRRORED_REVERSE":3,"REVERSE":1}},"GhosttySemanticPromptKind":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEMANTIC_PROMPT_","size":4,"underlying":"i32","values":{"COMMAND_END":4,"INPUT_START":2,"INVALID":0,"MAX_VALUE":2147483647,"OUTPUT_START":3,"PROMPT_START":1}},"GhosttySemanticPromptPromptKind":{"align":4,"kind":"enum","prefix":"GHOSTTY_SEMANTIC_PROMPT_PROMPT_","size":4,"underlying":"i32","values":{"CONTINUATION":2,"MAX_VALUE":2147483647,"PRIMARY":0,"RIGHT":1,"SECONDARY":3}},"GhosttySgrAttribute":{"align":8,"fields":{"tag":{"offset":0,"size":4,"type":"GhosttySgrAttributeTag"},"value":{"arms":{"BG_256":"bg_256","BG_8":"bg_8","BLINK":null,"BOLD":null,"BRIGHT_BG_8":"bright_bg_8","BRIGHT_FG_8":"bright_fg_8","DIRECT_COLOR_BG":"direct_color_bg","DIRECT_COLOR_FG":"direct_color_fg","FAINT":null,"FG_256":"fg_256","FG_8":"fg_8","INVERSE":null,"INVISIBLE":null,"ITALIC":null,"OVERLINE":null,"RESET_BG":null,"RESET_BLINK":null,"RESET_BOLD":null,"RESET_FG":null,"RESET_INVERSE":null,"RESET_INVISIBLE":null,"RESET_ITALIC":null,"RESET_OVERLINE":null,"RESET_STRIKETHROUGH":null,"RESET_UNDERLINE_COLOR":null,"STRIKETHROUGH":null,"UNDERLINE":"underline","UNDERLINE_COLOR":"underline_color","UNDERLINE_COLOR_256":"underline_color_256","UNKNOWN":"unknown","UNSET":null},"offset":8,"size":64,"tag":"tag","type":"GhosttySgrAttributeValue"}},"kind":"struct","size":72},"GhosttySgrAttributeTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_SGR_ATTR_","size":4,"underlying":"i32","values":{"BG_256":29,"BG_8":23,"BLINK":13,"BOLD":2,"BRIGHT_BG_8":27,"BRIGHT_FG_8":28,"DIRECT_COLOR_BG":22,"DIRECT_COLOR_FG":21,"FAINT":6,"FG_256":30,"FG_8":24,"INVERSE":15,"INVISIBLE":17,"ITALIC":4,"MAX_VALUE":2147483647,"OVERLINE":11,"RESET_BG":26,"RESET_BLINK":14,"RESET_BOLD":3,"RESET_FG":25,"RESET_INVERSE":16,"RESET_INVISIBLE":18,"RESET_ITALIC":5,"RESET_OVERLINE":12,"RESET_STRIKETHROUGH":20,"RESET_UNDERLINE_COLOR":10,"STRIKETHROUGH":19,"UNDERLINE":7,"UNDERLINE_COLOR":8,"UNDERLINE_COLOR_256":9,"UNKNOWN":1,"UNSET":0}},"GhosttySgrAttributeValue":{"align":8,"fields":{"_padding":{"count":8,"elem":"u64","offset":0,"size":64,"type":"array"},"bg_256":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"bg_8":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"bright_bg_8":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"bright_fg_8":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"direct_color_bg":{"offset":0,"size":3,"type":"GhosttyColorRgb"},"direct_color_fg":{"offset":0,"size":3,"type":"GhosttyColorRgb"},"fg_256":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"fg_8":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"underline":{"offset":0,"size":4,"type":"GhosttySgrUnderline"},"underline_color":{"offset":0,"size":3,"type":"GhosttyColorRgb"},"underline_color_256":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"unknown":{"offset":0,"size":32,"type":"GhosttySgrUnknown"}},"kind":"union","size":64},"GhosttySgrParser":{"align":8,"kind":"opaque","size":8},"GhosttySgrUnderline":{"align":4,"kind":"enum","prefix":"GHOSTTY_SGR_UNDERLINE_","size":4,"underlying":"i32","values":{"CURLY":3,"DASHED":5,"DOTTED":4,"DOUBLE":2,"MAX_VALUE":2147483647,"NONE":0,"SINGLE":1}},"GhosttySgrUnknown":{"align":8,"fields":{"full_len":{"offset":8,"size":8,"type":"u64"},"full_ptr":{"const":true,"elem":"u16","offset":0,"size":8,"type":"pointer"},"partial_len":{"offset":24,"size":8,"type":"u64"},"partial_ptr":{"const":true,"elem":"u16","offset":16,"size":8,"type":"pointer"}},"kind":"struct","size":32},"GhosttySizeReportSize":{"align":4,"fields":{"cell_height":{"offset":8,"size":4,"type":"u32"},"cell_width":{"offset":4,"size":4,"type":"u32"},"columns":{"offset":2,"size":2,"type":"u16"},"rows":{"offset":0,"size":2,"type":"u16"}},"kind":"struct","size":12},"GhosttySizeReportStyle":{"align":4,"kind":"enum","prefix":"GHOSTTY_SIZE_REPORT_","size":4,"underlying":"i32","values":{"CSI_14_T":1,"CSI_16_T":2,"CSI_18_T":3,"MODE_2048":0,"STYLE_MAX_VALUE":2147483647}},"GhosttySnapshotDecoder":{"align":8,"kind":"opaque","size":8},"GhosttySnapshotDecoderData":{"align":4,"kind":"enum","prefix":"GHOSTTY_SNAPSHOT_DECODER_DATA_","size":4,"underlying":"i32","values":{"COMPRESS_HISTORY":9,"HISTORY_ROWS_ALTERNATE":4,"HISTORY_ROWS_PRIMARY":3,"INVALID":0,"MAX_CONTINUATION_BYTES":1,"MAX_VALUE":2147483647,"PROGRESS_REMAINING":7,"PROGRESS_ROWS":6,"PROGRESS_SCREEN":5,"RETAIN_CONTINUATION":8,"SOURCE_OFFSET":2}},"GhosttySnapshotDecoderOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_SNAPSHOT_DECODER_OPT_","size":4,"underlying":"i32","values":{"COMPRESS_HISTORY":2,"MAX_CONTINUATION_BYTES":0,"MAX_VALUE":2147483647,"RETAIN_CONTINUATION":1}},"GhosttyString":{"align":8,"fields":{"len":{"offset":8,"size":8,"type":"u64"},"ptr":{"const":true,"elem":"u8","offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":16},"GhosttyStyle":{"align":8,"fields":{"bg_color":{"offset":24,"size":16,"type":"GhosttyStyleColor"},"blink":{"offset":59,"size":1,"type":"bool"},"bold":{"offset":56,"size":1,"type":"bool"},"faint":{"offset":58,"size":1,"type":"bool"},"fg_color":{"offset":8,"size":16,"type":"GhosttyStyleColor"},"inverse":{"offset":60,"size":1,"type":"bool"},"invisible":{"offset":61,"size":1,"type":"bool"},"italic":{"offset":57,"size":1,"type":"bool"},"overline":{"offset":63,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"strikethrough":{"offset":62,"size":1,"type":"bool"},"underline":{"offset":64,"size":4,"type":"i32"},"underline_color":{"offset":40,"size":16,"type":"GhosttyStyleColor"}},"kind":"struct","size":72},"GhosttyStyleColor":{"align":8,"fields":{"tag":{"offset":0,"size":4,"type":"GhosttyStyleColorTag"},"value":{"arms":{"NONE":null,"PALETTE":"palette","RGB":"rgb"},"offset":8,"size":8,"tag":"tag","type":"GhosttyStyleColorValue"}},"kind":"struct","size":16},"GhosttyStyleColorTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_STYLE_COLOR_","size":4,"underlying":"i32","values":{"NONE":0,"PALETTE":1,"RGB":2,"TAG_MAX_VALUE":2147483647}},"GhosttyStyleColorValue":{"align":8,"fields":{"_padding":{"offset":0,"size":8,"type":"u64"},"palette":{"offset":0,"size":1,"type":"GhosttyColorPaletteIndex"},"rgb":{"offset":0,"size":3,"type":"GhosttyColorRgb"}},"kind":"union","size":8},"GhosttyStyleId":{"align":2,"kind":"alias","size":2,"type":"u16"},"GhosttySurfacePosition":{"align":8,"fields":{"x":{"offset":0,"size":8,"type":"f64"},"y":{"offset":8,"size":8,"type":"f64"}},"kind":"struct","size":16},"GhosttySysImage":{"align":8,"fields":{"data":{"const":false,"elem":"u8","nullable":true,"offset":8,"size":8,"type":"pointer"},"data_len":{"offset":16,"size":8,"type":"u64"},"height":{"offset":4,"size":4,"type":"u32"},"width":{"offset":0,"size":4,"type":"u32"}},"kind":"struct","size":24},"GhosttySysLogLevel":{"align":4,"kind":"enum","prefix":"GHOSTTY_SYS_LOG_LEVEL_","size":4,"underlying":"i32","values":{"DEBUG":3,"ERROR":0,"INFO":2,"MAX_VALUE":2147483647,"WARNING":1}},"GhosttySysOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_SYS_OPT_","size":4,"underlying":"i32","values":{"DECODE_PNG":1,"LOG":2,"MAX_VALUE":2147483647,"RANDOM_SECURE":3,"USERDATA":0}},"GhosttyTerminal":{"align":8,"kind":"opaque","size":8},"GhosttyTerminalCompressionMode":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_COMPRESSION_MODE_","size":4,"underlying":"i32","values":{"FULL":1,"INCREMENTAL":0,"MAX_VALUE":2147483647}},"GhosttyTerminalCompressionResult":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_COMPRESSION_RESULT_","size":4,"underlying":"i32","values":{"COMPLETE":2,"MAX_VALUE":2147483647,"PENDING":1,"UNSUPPORTED":0}},"GhosttyTerminalCursorStyle":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_CURSOR_STYLE_","size":4,"underlying":"i32","values":{"BAR":0,"BLOCK":1,"BLOCK_HOLLOW":3,"MAX_VALUE":2147483647,"UNDERLINE":2}},"GhosttyTerminalData":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_DATA_","size":4,"underlying":"i32","values":{"ACTIVE_SCREEN":6,"CLIPBOARD_WRITE_MAX_BYTES":40,"COLOR_BACKGROUND":19,"COLOR_BACKGROUND_DEFAULT":23,"COLOR_CURSOR":20,"COLOR_CURSOR_DEFAULT":24,"COLOR_FOREGROUND":18,"COLOR_FOREGROUND_DEFAULT":22,"COLOR_PALETTE":21,"COLOR_PALETTE_DEFAULT":25,"COLS":1,"CONTINUATION_MAX_BYTES":36,"CURSOR_AT_PROMPT":39,"CURSOR_PENDING_WRAP":5,"CURSOR_STYLE":10,"CURSOR_VISIBLE":7,"CURSOR_X":3,"CURSOR_Y":4,"HEIGHT_PX":17,"INVALID":0,"KITTY_GRAPHICS":30,"KITTY_IMAGE_MEDIUM_FILE":27,"KITTY_IMAGE_MEDIUM_SHARED_MEM":29,"KITTY_IMAGE_MEDIUM_TEMP_FILE":28,"KITTY_IMAGE_STORAGE_LIMIT":26,"KITTY_KEYBOARD_FLAGS":8,"MAX_VALUE":2147483647,"MEMORY_USAGE":42,"MODE":37,"MOUSE_SHAPE":41,"MOUSE_TRACKING":11,"PWD":13,"ROWS":2,"SCROLLBACK_MAX_BYTES":34,"SCROLLBACK_MAX_LINES":35,"SCROLLBACK_ROWS":15,"SCROLLBAR":9,"SELECTION":31,"TITLE":12,"TOTAL_ROWS":14,"VIEWPORT_ACTIVE":32,"VT_GROUND":38,"VT_PROCESSING_ERROR":33,"WIDTH_PX":16}},"GhosttyTerminalDesktopNotification":{"align":8,"fields":{"body":{"offset":24,"size":16,"type":"GhosttyString"},"size":{"offset":0,"size":8,"type":"u64"},"title":{"offset":8,"size":16,"type":"GhosttyString"}},"kind":"struct","size":40},"GhosttyTerminalMemoryUsage":{"align":8,"fields":{"alternate_compressed_bytes":{"offset":96,"size":8,"type":"u64"},"alternate_compressed_pages":{"offset":88,"size":8,"type":"u64"},"alternate_image_bytes":{"offset":104,"size":8,"type":"u64"},"alternate_pages":{"offset":64,"size":8,"type":"u64"},"alternate_resident_bytes":{"offset":80,"size":8,"type":"u64"},"alternate_virtual_bytes":{"offset":72,"size":8,"type":"u64"},"compression_supported":{"offset":8,"size":1,"type":"bool"},"primary_compressed_bytes":{"offset":48,"size":8,"type":"u64"},"primary_compressed_pages":{"offset":40,"size":8,"type":"u64"},"primary_image_bytes":{"offset":56,"size":8,"type":"u64"},"primary_pages":{"offset":16,"size":8,"type":"u64"},"primary_resident_bytes":{"offset":32,"size":8,"type":"u64"},"primary_virtual_bytes":{"offset":24,"size":8,"type":"u64"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":112},"GhosttyTerminalModeConfig":{"align":2,"fields":{"mode":{"offset":0,"size":2,"type":"GhosttyMode"},"value":{"offset":2,"size":1,"type":"bool"}},"kind":"struct","size":4},"GhosttyTerminalOption":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_OPT_","size":4,"underlying":"i32","values":{"APC_MAX_BYTES":19,"APC_MAX_BYTES_KITTY":20,"BELL":2,"CLIPBOARD_READ":38,"CLIPBOARD_WRITE":26,"CLIPBOARD_WRITE_MAX_BYTES":39,"COLOR_BACKGROUND":12,"COLOR_CURSOR":13,"COLOR_FOREGROUND":11,"COLOR_PALETTE":14,"COLOR_SCHEME":7,"CONTINUATION_MAX_BYTES":31,"DEFAULT_CURSOR_BLINK":23,"DEFAULT_CURSOR_STYLE":22,"DESKTOP_NOTIFICATION":29,"DEVICE_ATTRIBUTES":8,"ENQUIRY":3,"GLYPH_PROTOCOL":24,"KITTY_IMAGE_MEDIUM_FILE":16,"KITTY_IMAGE_MEDIUM_SHARED_MEM":18,"KITTY_IMAGE_MEDIUM_TEMP_FILE":17,"KITTY_IMAGE_STORAGE_LIMIT":15,"MAX_VALUE":2147483647,"MODE":34,"MODE_DEFAULT":33,"PROGRESS_REPORT":30,"PWD":10,"PWD_CHANGED":25,"RENDER_HOLD":41,"RESET":43,"RESIZE_PULL_SCROLLBACK":40,"SCROLLBACK_MAX_BYTES":27,"SCROLLBACK_MAX_LINES":28,"SELECTION":21,"SEMANTIC_PROMPT":42,"SIZE":6,"TERMINFO_NAME":37,"TITLE":9,"TITLE_CHANGED":5,"TITLE_REPORT":32,"UNKNOWN_MAX_BYTES":36,"UNKNOWN_SEQUENCE":35,"USERDATA":0,"WRITE_PTY":1,"XTVERSION":4}},"GhosttyTerminalProgressReport":{"align":8,"fields":{"progress":{"offset":12,"size":1,"type":"i8"},"size":{"offset":0,"size":8,"type":"u64"},"state":{"offset":8,"size":4,"type":"GhosttyTerminalProgressState"}},"kind":"struct","size":16},"GhosttyTerminalProgressState":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_PROGRESS_STATE_","size":4,"underlying":"i32","values":{"ERROR":2,"INDETERMINATE":3,"MAX_VALUE":2147483647,"PAUSE":4,"REMOVE":0,"SET":1}},"GhosttyTerminalScreen":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_SCREEN_","size":4,"underlying":"i32","values":{"ALTERNATE":1,"MAX_VALUE":2147483647,"PRIMARY":0}},"GhosttyTerminalScrollViewport":{"align":8,"fields":{"tag":{"offset":0,"size":4,"type":"GhosttyTerminalScrollViewportTag"},"value":{"arms":{"BOTTOM":null,"DELTA":"delta","ROW":"row","TOP":null},"offset":8,"size":16,"tag":"tag","type":"GhosttyTerminalScrollViewportValue"}},"kind":"struct","size":24},"GhosttyTerminalScrollViewportTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_SCROLL_VIEWPORT_","size":4,"underlying":"i32","values":{"BOTTOM":1,"DELTA":2,"MAX_VALUE":2147483647,"ROW":3,"TOP":0}},"GhosttyTerminalScrollViewportValue":{"align":8,"fields":{"_padding":{"count":2,"elem":"u64","offset":0,"size":16,"type":"array"},"delta":{"offset":0,"size":8,"type":"i64"},"row":{"offset":0,"size":8,"type":"u64"}},"kind":"union","size":16},"GhosttyTerminalScrollbar":{"align":8,"fields":{"len":{"offset":16,"size":8,"type":"u64"},"offset":{"offset":8,"size":8,"type":"u64"},"total":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":24},"GhosttyTerminalSelectLineOptions":{"align":8,"fields":{"ref":{"offset":8,"size":24,"type":"GhosttyGridRef"},"semantic_prompt_boundary":{"offset":48,"size":1,"type":"bool"},"size":{"offset":0,"size":8,"type":"u64"},"whitespace":{"const":true,"elem":"u32","nullable":true,"offset":32,"size":8,"type":"pointer"},"whitespace_len":{"offset":40,"size":8,"type":"u64"}},"kind":"struct","size":56},"GhosttyTerminalSelectWordBetweenOptions":{"align":8,"fields":{"boundary_codepoints":{"const":true,"elem":"u32","nullable":true,"offset":56,"size":8,"type":"pointer"},"boundary_codepoints_len":{"offset":64,"size":8,"type":"u64"},"end":{"offset":32,"size":24,"type":"GhosttyGridRef"},"size":{"offset":0,"size":8,"type":"u64"},"start":{"offset":8,"size":24,"type":"GhosttyGridRef"}},"kind":"struct","size":72},"GhosttyTerminalSelectWordOptions":{"align":8,"fields":{"boundary_codepoints":{"const":true,"elem":"u32","nullable":true,"offset":32,"size":8,"type":"pointer"},"boundary_codepoints_len":{"offset":40,"size":8,"type":"u64"},"ref":{"offset":8,"size":24,"type":"GhosttyGridRef"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":48},"GhosttyTerminalSelectionFormatOptions":{"align":8,"fields":{"emit":{"offset":8,"size":4,"type":"GhosttyFormatterFormat"},"selection":{"const":true,"elem":"GhosttySelection","nullable":true,"offset":16,"size":8,"type":"pointer"},"size":{"offset":0,"size":8,"type":"u64"},"trim":{"offset":13,"size":1,"type":"bool"},"unwrap":{"offset":12,"size":1,"type":"bool"}},"kind":"struct","size":24},"GhosttyTerminalSemanticPrompt":{"align":8,"fields":{"command":{"offset":24,"size":16,"type":"GhosttyString"},"error":{"offset":40,"size":16,"type":"GhosttyString"},"exit_code":{"offset":20,"size":4,"type":"i32"},"has_exit_code":{"offset":16,"size":1,"type":"bool"},"kind":{"offset":8,"size":4,"type":"GhosttySemanticPromptKind"},"prompt_kind":{"offset":12,"size":4,"type":"GhosttySemanticPromptPromptKind"},"size":{"offset":0,"size":8,"type":"u64"}},"kind":"struct","size":56},"GhosttyTerminalUnknownOscSequence":{"align":8,"fields":{"content":{"offset":8,"size":16,"type":"GhosttyString"},"terminator":{"offset":24,"size":4,"type":"GhosttyOscTerminator"},"truncated":{"offset":0,"size":1,"type":"bool"}},"kind":"struct","size":32},"GhosttyTerminalUnknownSequence":{"align":8,"fields":{"tag":{"offset":0,"size":4,"type":"GhosttyTerminalUnknownSequenceTag"},"value":{"arms":{"APC":"apc","OSC":"osc"},"offset":8,"size":128,"tag":"tag","type":"GhosttyTerminalUnknownSequenceValue"}},"kind":"struct","size":136},"GhosttyTerminalUnknownSequenceTag":{"align":4,"kind":"enum","prefix":"GHOSTTY_TERMINAL_UNKNOWN_SEQUENCE_","size":4,"underlying":"i32","values":{"APC":0,"MAX_VALUE":2147483647,"OSC":1}},"GhosttyTerminalUnknownSequenceValue":{"align":8,"fields":{"_padding":{"count":16,"elem":"u64","offset":0,"size":128,"type":"array"},"apc":{"offset":0,"size":24,"type":"GhosttyTerminalUnknownStringSequence"},"osc":{"offset":0,"size":32,"type":"GhosttyTerminalUnknownOscSequence"}},"kind":"union","size":128},"GhosttyTerminalUnknownStringSequence":{"align":8,"fields":{"content":{"offset":8,"size":16,"type":"GhosttyString"},"truncated":{"offset":0,"size":1,"type":"bool"}},"kind":"struct","size":24},"GhosttyTrackedGridRef":{"align":8,"kind":"opaque","size":8},"GhosttyWriter":{"align":8,"fields":{"userdata":{"const":false,"elem":"opaque","nullable":true,"offset":8,"size":8,"type":"pointer"},"write":{"const":true,"elem":"function","nullable":true,"offset":0,"size":8,"type":"pointer"}},"kind":"struct","size":16}}} diff --git a/base/terminal/internal/vt/abi_generate_test.go b/base/terminal/internal/vt/abi_generate_test.go new file mode 100644 index 0000000000..c71dd5a81b --- /dev/null +++ b/base/terminal/internal/vt/abi_generate_test.go @@ -0,0 +1,29 @@ +//go:build !js + +package vt + +import ( + "encoding/json" + "os" + "testing" +) + +// TestWriteWasmHostABI records the 64-bit C ABI the shared Go structs mirror. The browser uses it to marshal the separate 32-bit guest ABI. Rebuild it with the pinned native library whenever the binding's commit changes. +func TestWriteWasmHostABI(t *testing.T) { + path := os.Getenv("NSGO_GHOSTTY_ABI_OUT") + if path == "" { + t.Skip("set NSGO_GHOSTTY_ABI_OUT on a native 64-bit target") + } + loadLib(t) + var value any + if err := json.Unmarshal([]byte(cStringAt(call(fnTypeJSON))), &value); err != nil { + t.Fatal(err) + } + data, err := json.Marshal(value) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, append(data, '\n'), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/base/terminal/internal/vt/abi_js_test.go b/base/terminal/internal/vt/abi_js_test.go new file mode 100644 index 0000000000..421f6dcc2e --- /dev/null +++ b/base/terminal/internal/vt/abi_js_test.go @@ -0,0 +1,66 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package vt + +import ( + "bytes" + "encoding/json" + "testing" + "unsafe" +) + +func TestBrowserMemoryABI(t *testing.T) { + before := wasm + defer func() { wasm = before }() + if _, err := open("embedded:ghostty-vt.wasm"); err != nil { + t.Fatal(err) + } + p := uintptr(uint32(wasm.exports.Get("ghostty_type_json").Invoke().Int())) + var m manifest + if err := json.Unmarshal([]byte(foreignCString(p)), &m); err != nil { + t.Fatal(err) + } + if err := checkManifest(m); err != nil { + t.Fatal(err) + } + if wasm.guest.ABI.PointerSize != 4 || wasm.host.ABI.PointerSize != int(unsafe.Sizeof(uintptr(0))) { + t.Fatal("guest and host pointer widths were not distinguished") + } + old := wasm.exports.Get("memory").Get("buffer") + const size = 32 << 20 + allocation := uintptr(uint32(wasm.exports.Get("ghostty_wasm_alloc").Invoke(size).Int())) + if allocation == 0 { + t.Fatal("allocation failed") + } + defer wasm.exports.Get("ghostty_wasm_free").Invoke(int(allocation), size) + if old.Equal(wasm.exports.Get("memory").Get("buffer")) { + t.Fatal("control allocation did not grow guest memory") + } + want := []byte("memory after growth") + writeForeignBytes(allocation, want) + if got := foreignBytes(allocation, uintptr(len(want))); !bytes.Equal(got, want) { + t.Fatalf("after guest memory growth: %q", got) + } +} + +func TestBrowserPromptBoolABI(t *testing.T) { + loadLib(t) + term, err := NewTerminal(20, 5, Effects{}) + if err != nil { + t.Fatal(err) + } + defer term.Free() + for _, test := range []struct { + input string + want bool + }{{"", false}, {"\x1b]133;A\x07$ \x1b]133;B\x07", true}, {"\x1b[?1049h", false}} { + term.Write([]byte(test.input)) + var got bool + if err := result(call(fnTerminalGet, term.h, 39, uintptr(unsafe.Pointer(&got)))); err != nil { + t.Fatal(err) + } + if got != test.want { + t.Fatalf("cursor at prompt after %q: %v, want %v", test.input, got, test.want) + } + } +} diff --git a/base/terminal/internal/vt/ffi.go b/base/terminal/internal/vt/ffi.go index 670082ae08..b32aede28b 100644 --- a/base/terminal/internal/vt/ffi.go +++ b/base/terminal/internal/vt/ffi.go @@ -20,4 +20,6 @@ func call(fn uintptr, args ...uintptr) uintptr { func registerFunc(fptr any, addr uintptr) { purego.RegisterFunc(fptr, addr) } -func newCallback(fn any) uintptr { return purego.NewCallback(fn) } +func newCallback(_ string, fn any) uintptr { return purego.NewCallback(fn) } + +func setupPlatform() {} diff --git a/base/terminal/internal/vt/ffi_js.go b/base/terminal/internal/vt/ffi_js.go new file mode 100644 index 0000000000..7e85c2cdb9 --- /dev/null +++ b/base/terminal/internal/vt/ffi_js.go @@ -0,0 +1,222 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package vt + +import ( + "crypto/rand" + "fmt" + "reflect" + "runtime" + "strconv" + "syscall/js" + "unsafe" + + "github.com/nsgo-dev/nsgo/base/terminal/internal/library" +) + +// Supported reports whether this target can instantiate the embedded module. +const Supported = true +const wasmExport = uintptr(1 << 32) + +var wasm struct { + exports js.Value + memory, array, alloc, free js.Value + bound map[uintptr]js.Value + guest, host manifest + functions map[uintptr]string + callbacks []js.Func + retained map[uintptr]wasmAllocation + replies map[uintptr]string + depth, calls uint64 +} + +func open(path string) (handle uintptr, err error) { + defer func() { + if failure := recover(); failure != nil { + err = fmt.Errorf("WebAssembly module: %v", failure) + } + }() + bytes := library.Wasm() + wasm.array = js.Global().Get("Uint8Array") + array := wasm.array.New(len(bytes)) + js.CopyBytesToJS(array, bytes) + api := js.Global().Get("WebAssembly") + module := api.Get("Module").New(array) + instance := api.Get("Instance").New(module) + wasm.exports = instance.Get("exports") + wasm.memory = wasm.exports.Get("memory") + wasm.alloc = wasm.exports.Get("ghostty_wasm_alloc") + wasm.free = wasm.exports.Get("ghostty_wasm_free") + wasm.bound = map[uintptr]js.Value{} + wasm.functions = map[uintptr]string{} + wasm.retained = map[uintptr]wasmAllocation{} + wasm.replies = map[uintptr]string{} + return 1, nil +} + +func sym(_ uintptr, name string) (uintptr, error) { + function := wasm.exports.Get(name) + if function.Type() != js.TypeFunction { + return 0, fmt.Errorf("missing WebAssembly export %s", name) + } + handle := wasmExport + uintptr(len(wasm.functions)) + wasm.functions[handle] = name + wasm.bound[handle] = function + return handle, nil +} + +//go:uintptrescapes +func call(fn uintptr, args ...uintptr) uintptr { + wasm.depth++ + defer func() { + wasm.depth-- + wasm.calls++ + // Wasm has no asynchronous Go preemption. Long bursts must let finalizers release JavaScript references, outside guest callbacks. + if wasm.depth == 0 && wasm.calls >= 256 { + wasm.calls = 0 + runtime.Gosched() + } + }() + name, exported := wasm.functions[fn] + var function js.Value + if exported { + function = wasm.bound[fn] + } else { + function = wasm.exports.Get("__indirect_function_table").Call("get", int(fn)) + } + scope := wasmCall{} + defer scope.free() + values := append([]uintptr(nil), args...) + parameters := []wasmParameter(nil) + if exported { + parameters = wasmParameters(name, args) + } else if typ := wasm.replies[fn]; typ != "" { + parameters = []wasmParameter{{1, typ, 1}} + } else { + panic("vt: unknown guest callback reply") + } + for _, param := range parameters { + if values[param.index] == 0 { + continue + } + values[param.index] = scope.marshal(values[param.index], param.typ, param.count) + } + jsArgs := make([]any, len(values)) + for i, value := range values { + jsArgs[i] = int(value) + } + if name == "ghostty_row_get" { + jsArgs[0] = js.Global().Get("BigInt").Invoke(strconv.FormatUint(uint64(values[0]), 10)) + } + result := function.Invoke(jsArgs...) + scope.copyBack() + if name == "ghostty_key_event_set_utf8" { + scope.retain(args[0]) + } + if name == "ghostty_key_event_free" { + empty := wasmCall{} + empty.retain(args[0]) + } + if result.IsUndefined() { + return 0 + } + return uintptr(uint32(result.Int())) +} + +func registerFunc(pointer any, fn uintptr) { + switch f := pointer.(type) { + case *func(uintptr, scrollViewport): + *f = func(t uintptr, value scrollViewport) { call(fn, t, uintptr(unsafe.Pointer(&value))) } + case *func(uintptr, point, *GridRef) int32: + *f = func(t uintptr, value point, out *GridRef) int32 { + return int32(call(fn, t, uintptr(unsafe.Pointer(&value)), uintptr(unsafe.Pointer(out)))) + } + case *func(uintptr, mousePosition): + *f = func(event uintptr, value mousePosition) { call(fn, event, uintptr(unsafe.Pointer(&value))) } + case *func(uintptr, uintptr, selectionFormatOptions, *uintptr, *uintptr) int32: + *f = func(t, alloc uintptr, value selectionFormatOptions, out, n *uintptr) int32 { + return int32(call(fn, t, alloc, uintptr(unsafe.Pointer(&value)), uintptr(unsafe.Pointer(out)), uintptr(unsafe.Pointer(n)))) + } + case *func(uintptr, *uintptr, uintptr, formatterOptions) int32: + *f = func(alloc uintptr, out *uintptr, t uintptr, value formatterOptions) int32 { + return int32(call(fn, alloc, uintptr(unsafe.Pointer(out)), t, uintptr(unsafe.Pointer(&value)))) + } + default: + panic(fmt.Sprintf("vt: no WebAssembly function adapter for %T", pointer)) + } +} + +// newCallback installs a typed Wasm trampoline in the guest's function table. A JavaScript function alone is not a valid table entry. +func newCallback(signature string, callback any) uintptr { + noRead := signature == "mime-reader" + if noRead { + signature = "iiii" + } // userdata, indirect String, indirect Writer + fn := reflect.ValueOf(callback) + wrapped := js.FuncOf(func(_ js.Value, args []js.Value) any { + if noRead { + return 0 + } + values := make([]reflect.Value, len(args)) + for i, arg := range args { + values[i] = reflect.ValueOf(uintptr(uint32(arg.Int()))) + } + result := fn.Call(values) + if signature[0] == 'v' { + return nil + } + return int(result[0].Uint()) + }) + wasm.callbacks = append(wasm.callbacks, wrapped) + bytes := callbackModule(signature) + array := wasm.array.New(len(bytes)) + js.CopyBytesToJS(array, bytes) + api := js.Global().Get("WebAssembly") + module := api.Get("Module").New(array) + imports := map[string]any{"env": map[string]any{"call": wrapped}} + instance := api.Get("Instance").New(module, imports) + table := wasm.exports.Get("__indirect_function_table") + index := table.Call("grow", 1).Int() + table.Call("set", index, instance.Get("exports").Get("callback")) + return uintptr(index) +} + +func callbackModule(signature string) []byte { + section := func(kind byte, body []byte) []byte { return append([]byte{kind, byte(len(body))}, body...) } + params := len(signature) - 1 + types := []byte{1, 0x60, byte(params)} + for range params { + types = append(types, 0x7f) + } + if signature[0] == 'v' { + types = append(types, 0) + } else { + types = append(types, 1, 0x7f) + } + imports := []byte{1, 3, 'e', 'n', 'v', 4, 'c', 'a', 'l', 'l', 0, 0} + body := []byte{0} + for i := range params { + body = append(body, 0x20, byte(i)) + } + body = append(body, 0x10, 0, 0x0b) + module := []byte{0, 'a', 's', 'm', 1, 0, 0, 0} + module = append(module, section(1, types)...) + module = append(module, section(2, imports)...) + module = append(module, section(3, []byte{1, 0})...) + module = append(module, section(7, []byte{1, 8, 'c', 'a', 'l', 'l', 'b', 'a', 'c', 'k', 0, 1})...) + module = append(module, section(10, append([]byte{1, byte(len(body))}, body...))...) + return module +} + +// Browser modules have no OS entropy source. Supply the C API's secure random effect through Go's browser crypto adapter, never through Math.random. +func setupPlatform() { + callback := newCallback("iiii", func(_, data, n uintptr) uintptr { + bytes := make([]byte, n) + if _, err := rand.Read(bytes); err != nil { + return 0 + } + writeForeignBytes(data, bytes) + return 1 + }) + call(fnSysSet, 3 /* GHOSTTY_SYS_OPT_RANDOM_SECURE */, callback) +} diff --git a/base/terminal/internal/vt/ffi_other.go b/base/terminal/internal/vt/ffi_other.go index e8859943a4..fa9be4b3ff 100644 --- a/base/terminal/internal/vt/ffi_other.go +++ b/base/terminal/internal/vt/ffi_other.go @@ -1,4 +1,4 @@ -//go:build !(darwin || (linux && !android && (amd64 || arm64)) || (windows && (amd64 || arm64))) +//go:build (js && (nsgominiprogram || nsgoharmony)) || (!js && !(darwin || (linux && !android && (amd64 || arm64)) || (windows && (amd64 || arm64)))) package vt @@ -15,4 +15,6 @@ func call(uintptr, ...uintptr) uintptr { panic("vt: libghostty-vt is not support func registerFunc(any, uintptr) {} -func newCallback(any) uintptr { return 0 } +func newCallback(string, any) uintptr { return 0 } + +func setupPlatform() {} diff --git a/base/terminal/internal/vt/images.go b/base/terminal/internal/vt/images.go index 63012f8805..9c9bf8c74e 100644 --- a/base/terminal/internal/vt/images.go +++ b/base/terminal/internal/vt/images.go @@ -197,7 +197,7 @@ func (t *Terminal) Image(id uint32) (Image, bool) { } call(fnKittyImageGet, img, imageDataLen, uintptr(unsafe.Pointer(&n))) pixels := make([]byte, n) - copy(pixels, unsafe.Slice((*byte)(mem(p)), n)) + copy(pixels, foreignBytes(p, n)) return Image{ID: id, Width: int(w), Height: int(h), Format: ImageFormat(format), Pixels: pixels, Generation: gen}, true } @@ -224,17 +224,13 @@ func imageFits(w, h int) bool { return w > 0 && h > 0 && w <= maxImageSide && h <= maxImageSide && 4*w*h <= maxImageBytes } -// decodePNG gives the library a PNG decoder, without which it refuses -// images sent as PNG (Kitty graphics, f=100), as grok sends them. A PNG -// whose header gives it more pixels than Ghostty's limits take is refused -// before it is decoded, as its size is the program's to claim; the pixels -// are converted into the library's memory, with no copy of them between. +// decodePNG gives the library a PNG decoder, without which it refuses images sent as PNG (Kitty graphics, f=100), as grok sends them. A PNG whose header gives it more pixels than Ghostty's limits take is refused before it is decoded, as its size is the program's to claim; the pixels are converted into the library's memory through the platform adapter. func decodePNG() { - cb := newCallback(func(_, alloc, data, n, out uintptr) uintptr { + cb := newCallback("iiiiii", func(_, alloc, data, n, out uintptr) uintptr { if data == 0 || n == 0 { return 0 } - src := unsafe.Slice((*byte)(mem(data)), n) + src := foreignBytes(data, n) cfg, err := png.DecodeConfig(bytes.NewReader(src)) if err != nil || !imageFits(cfg.Width, cfg.Height) { return 0 @@ -253,13 +249,15 @@ func decodePNG() { if p == 0 { return 0 } - dst := &image.NRGBA{Pix: unsafe.Slice((*byte)(mem(p)), size), Stride: 4 * w, Rect: image.Rect(0, 0, w, h)} - if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Stride == 4*w && b.Min == (image.Point{}) { - copy(dst.Pix, nrgba.Pix) - } else { - draw.Draw(dst, dst.Rect, img, b.Min, draw.Src) - } - *(*sysImage)(mem(out)) = sysImage{width: uint32(w), height: uint32(h), data: p, dataLen: size} + withForeignBytes(p, size, func(pixels []byte) { + dst := &image.NRGBA{Pix: pixels, Stride: 4 * w, Rect: image.Rect(0, 0, w, h)} + if nrgba, ok := img.(*image.NRGBA); ok && nrgba.Stride == 4*w && b.Min == (image.Point{}) { + copy(dst.Pix, nrgba.Pix) + } else { + draw.Draw(dst, dst.Rect, img, b.Min, draw.Src) + } + }) + foreignWrite(out, sysImage{width: uint32(w), height: uint32(h), data: p, dataLen: size}) return 1 }) call(fnSysSet, sysDecodePNG, cb) diff --git a/base/terminal/internal/vt/lib.go b/base/terminal/internal/vt/lib.go index bb5570906f..dc7ed5494b 100644 --- a/base/terminal/internal/vt/lib.go +++ b/base/terminal/internal/vt/lib.go @@ -1,9 +1,4 @@ -// Package vt binds libghostty-vt, the terminal emulator of Ghostty, which -// it loads at run time through purego: no cgo. It mirrors the structs of -// the C API it passes, checks them against the layouts the library -// describes (ghostty_type_json) as it loads, and reads packed cells by the -// bit positions the library reports, so that a library of another version -// fails to load instead of corrupting memory. +// Package vt binds libghostty-vt, Ghostty's terminal emulator, through purego on native targets and an embedded WebAssembly module in a browser: no cgo. Native structs mirror its C ABI; the browser marshals the separate guest memory. Both validate the library's type manifest before use. // // Nothing here is safe for concurrent use: callers serialize the calls on a // Terminal and on what is made from it. @@ -197,6 +192,7 @@ func load(path string) error { registerFunc(&selectionFormatAlloc, fnSelectionFormatAlloc) registerFunc(&formatterTerminalNew, fnFormatterTerminalNew) makeCallbacks() + setupPlatform() decodePNG() return nil } @@ -264,24 +260,20 @@ func b2u(b bool) uintptr { return 0 } -// mem converts an address the library gave into a pointer. -func mem(p uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&p)) } +// hostMemory addresses the host process only. Browser guest addresses must go through the foreign-memory helpers. +func hostMemory(p uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&p)) } // goString copies a string the library owns. func goString(p, n uintptr) string { if p == 0 || n == 0 { return "" } - return string(unsafe.Slice((*byte)(mem(p)), n)) + return string(foreignBytes(p, n)) } // cStringAt copies a NUL-terminated string the library owns. func cStringAt(p uintptr) string { - n := uintptr(0) - for *(*byte)(unsafe.Add(mem(p), n)) != 0 { - n++ - } - return goString(p, n) + return foreignCString(p) } // cell is the layout of the packed GhosttyCell, from the manifest. @@ -299,12 +291,15 @@ func (f bitField) of(v uint64) uint64 { return v >> f.lsb & (1< 0 { + a := s.allocations[0] + if len(s.allocations) != 1 { + panic(fmt.Sprintf("vt: unexpected UTF-8 allocations: %d", len(s.allocations))) + } + wasm.retained[event] = *a + a.guest = 0 + } +} diff --git a/base/terminal/internal/vt/memory_js.go b/base/terminal/internal/vt/memory_js.go new file mode 100644 index 0000000000..b5a6294194 --- /dev/null +++ b/base/terminal/internal/vt/memory_js.go @@ -0,0 +1,154 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package vt + +import ( + _ "embed" + "encoding/json" + "fmt" + "reflect" + "syscall/js" + "unsafe" +) + +//go:embed abi64.json +var hostABIData []byte + +func checkManifest(m manifest) error { + if m.ABI.PointerSize != 4 || m.ABI.UsizeSize != 4 || m.ABI.Endian != "little" { + return fmt.Errorf("unsupported WebAssembly ABI: %+v", m.ABI) + } + var host manifest + if err := json.Unmarshal(hostABIData, &host); err != nil { + return err + } + if err := host.check(); err != nil { + return fmt.Errorf("host marshaling layout: %w", err) + } + for _, enum := range enums { + if value, ok := m.Types[enum.typ].Values[enum.name]; !ok || value != enum.value { + return fmt.Errorf("guest enum %s.%s differs", enum.typ, enum.name) + } + } + for name, expected := range layouts() { + t, ok := m.Types[name] + if !ok || t.Size == 0 { + return fmt.Errorf("missing guest type %s", name) + } + for field := range expected.fields { + if _, ok := t.Fields[field]; !ok { + return fmt.Errorf("missing guest field %s.%s", name, field) + } + } + } + if !reflect.DeepEqual(m.Types["GhosttyCell"].Bits, host.Types["GhosttyCell"].Bits) { + return fmt.Errorf("guest packed cell layout differs") + } + wasm.guest, wasm.host = m, host + return nil +} + +// Every memory access obtains the current ArrayBuffer: any guest allocation can grow memory and detach all previously obtained JavaScript views. +func foreignBytes(p, n uintptr) []byte { + if n == 0 { + return nil + } + v := wasm.array.New(wasm.memory.Get("buffer"), int(p), int(n)) + out := make([]byte, n) + js.CopyBytesToGo(out, v) + return out +} + +func writeForeignBytes(p uintptr, b []byte) { + if len(b) > 0 { + v := wasm.array.New(wasm.memory.Get("buffer"), int(p), len(b)) + js.CopyBytesToJS(v, b) + } +} + +func foreignValue[T any](p uintptr) T { + var value T + name := foreignType[T]() + src := foreignBytes(p, abiSize(wasm.guest, name)) + dst := unsafe.Slice((*byte)(unsafe.Pointer(&value)), unsafe.Sizeof(value)) + convertABI(dst, src, name, wasm.host, wasm.guest) + switch v := any(value).(type) { + case clipboardRead: + wasm.replies[v.reply] = "GhosttyClipboardReadReply" + case clipboardWrite: + wasm.replies[v.reply] = "GhosttyClipboardWriteReply" + } + return value +} + +func foreignSlice[T any](p, n uintptr) []T { + values := make([]T, n) + if n == 0 { + return values + } + name := foreignType[T]() + guestSize := abiSize(wasm.guest, name) + src := foreignBytes(p, n*guestSize) + for i := range n { + dst := unsafe.Slice((*byte)(unsafe.Pointer(&values[i])), unsafe.Sizeof(values[i])) + convertABI(dst, src[i*guestSize:(i+1)*guestSize], name, wasm.host, wasm.guest) + } + return values +} + +func foreignWrite[T any](p uintptr, value T) { + name := foreignType[T]() + src := unsafe.Slice((*byte)(unsafe.Pointer(&value)), unsafe.Sizeof(value)) + dst := make([]byte, abiSize(wasm.guest, name)) + convertABI(dst, src, name, wasm.guest, wasm.host) + writeForeignBytes(p, dst) +} + +func withForeignBytes(p, n uintptr, write func([]byte)) { + bytes := foreignBytes(p, n) + write(bytes) + writeForeignBytes(p, bytes) +} + +func foreignCString(p uintptr) string { + if p == 0 { + return "" + } + view := wasm.array.New(wasm.memory.Get("buffer")) + n := uintptr(0) + for view.Index(int(p+n)).Int() != 0 { + n++ + } + return string(foreignBytes(p, n)) +} + +func foreignType[T any]() string { + var value T + switch any(value).(type) { + case uint64: + return "u64" + case int32: + return "i32" + case cString: + return "GhosttyString" + case clipboardRead: + return "GhosttyClipboardRead" + case clipboardWrite: + return "GhosttyClipboardWrite" + case clipboardContent: + return "GhosttyClipboardContent" + case sizeReport: + return "GhosttySizeReportSize" + case deviceAttributes: + return "GhosttyDeviceAttributes" + case desktopNotification: + return "GhosttyTerminalDesktopNotification" + case progressReport: + return "GhosttyTerminalProgressReport" + case semanticPrompt: + return "GhosttyTerminalSemanticPrompt" + case sysImage: + return "GhosttySysImage" + } + panic("vt: no guest memory type for " + reflect.TypeFor[T]().String()) +} diff --git a/base/terminal/internal/vt/memory_native.go b/base/terminal/internal/vt/memory_native.go new file mode 100644 index 0000000000..5693234009 --- /dev/null +++ b/base/terminal/internal/vt/memory_native.go @@ -0,0 +1,25 @@ +//go:build !js || nsgominiprogram || nsgoharmony + +package vt + +import "unsafe" + +func checkManifest(m manifest) error { return m.check() } + +func foreignBytes(p, n uintptr) []byte { return unsafe.Slice((*byte)(hostMemory(p)), n) } + +func foreignValue[T any](p uintptr) T { return *(*T)(hostMemory(p)) } + +func foreignSlice[T any](p, n uintptr) []T { return unsafe.Slice((*T)(hostMemory(p)), n) } + +func foreignWrite[T any](p uintptr, value T) { *(*T)(hostMemory(p)) = value } + +func withForeignBytes(p, n uintptr, write func([]byte)) { write(foreignBytes(p, n)) } + +func foreignCString(p uintptr) string { + n := uintptr(0) + for *(*byte)(unsafe.Add(hostMemory(p), n)) != 0 { + n++ + } + return goString(p, n) +} diff --git a/base/terminal/internal/vt/parameters_js.go b/base/terminal/internal/vt/parameters_js.go new file mode 100644 index 0000000000..fdcef3f5c2 --- /dev/null +++ b/base/terminal/internal/vt/parameters_js.go @@ -0,0 +1,195 @@ +//go:build js && !nsgominiprogram && !nsgoharmony + +package vt + +import "fmt" + +type wasmParameter struct { + index int + typ string + count uintptr +} + +func wasmParameters(name string, args []uintptr) []wasmParameter { + one := func(index int, typ string) []wasmParameter { return []wasmParameter{{index, typ, 1}} } + two := func(a int, at string, b int, bt string) []wasmParameter { + return []wasmParameter{{a, at, 1}, {b, bt, 1}} + } + switch name { + case "ghostty_type_json", "ghostty_alloc", "ghostty_free", "ghostty_sys_set", + "ghostty_terminal_free", "ghostty_terminal_reset", "ghostty_terminal_resize", + "ghostty_render_state_free", "ghostty_render_state_begin_update", "ghostty_render_state_end_update", "ghostty_render_state_clean", + "ghostty_render_state_row_iterator_free", "ghostty_render_state_row_iterator_next", "ghostty_render_state_row_cells_free", "ghostty_render_state_row_cells_select", + "ghostty_key_encoder_free", "ghostty_key_encoder_setopt_from_terminal", "ghostty_key_event_free", + "ghostty_key_event_set_action", "ghostty_key_event_set_key", "ghostty_key_event_set_mods", "ghostty_key_event_set_consumed_mods", "ghostty_key_event_set_composing", "ghostty_key_event_set_unshifted_codepoint", + "ghostty_mouse_encoder_free", "ghostty_mouse_encoder_setopt_from_terminal", "ghostty_mouse_encoder_reset", "ghostty_mouse_event_free", "ghostty_mouse_event_set_action", "ghostty_mouse_event_set_button", "ghostty_mouse_event_clear_button", "ghostty_mouse_event_set_mods", + "ghostty_selection_gesture_free", "ghostty_selection_gesture_reset", "ghostty_selection_gesture_event_free", + "ghostty_kitty_graphics_image", "ghostty_kitty_graphics_placement_iterator_free", "ghostty_kitty_graphics_placement_next", + "ghostty_formatter_free", "ghostty_search_free", "ghostty_search_feed": + return nil + case "ghostty_terminal_new", "ghostty_render_state_new", "ghostty_render_state_row_iterator_new", "ghostty_render_state_row_cells_new", + "ghostty_key_encoder_new", "ghostty_key_event_new", "ghostty_mouse_encoder_new", "ghostty_mouse_event_new", + "ghostty_selection_gesture_new", "ghostty_selection_gesture_event_new", "ghostty_kitty_graphics_placement_iterator_new", "ghostty_search_new": + return one(1, "pointer") + case "ghostty_terminal_vt_write", "ghostty_key_event_set_utf8": + return []wasmParameter{{1, "u8", args[2]}} + case "ghostty_paste_is_safe": + return []wasmParameter{{0, "u8", args[1]}} + case "ghostty_terminal_set": + typ := map[uintptr]string{ + optColorForeground: "GhosttyColorRgb", optColorBackground: "GhosttyColorRgb", optColorCursor: "GhosttyColorRgb", + optKittyImageLimit: "u64", optDefaultCursorStyle: "i32", optDefaultCursorBlink: "bool", optScrollbackMaxBytes: "usize", + optMode: "GhosttyTerminalModeConfig", optModeDefault: "GhosttyTerminalModeConfig", optTerminfoName: "GhosttyString", optResizePullBack: "bool", 21: "GhosttySelection", + }[args[1]] + if args[1] == optColorPalette { + return []wasmParameter{{2, "GhosttyColorRgb", 256}} + } + if typ != "" { + return one(2, typ) + } + if args[1] == optUserdata || args[1] == optWritePTY || args[1] == optBell || args[1] == optTitleChanged || args[1] == optPwdChanged || args[1] == optRenderHold || args[1] == optClipboardWrite || args[1] == optClipboardRead || args[1] == optSize || args[1] == optColorScheme || args[1] == optDeviceAttributes || args[1] == optDesktopNotification || args[1] == optProgressReport || args[1] == optSemanticPrompt { + return nil + } + case "ghostty_terminal_get": + // CURSOR_AT_PROMPT is another bool output, independent of host size_t. + if args[1] == 39 { + return one(2, "bool") + } + typ := map[uintptr]string{ + dataCols: "u16", dataRows: "u16", dataCursorX: "u16", dataCursorY: "u16", dataActiveScreen: "i32", dataKittyKeyboardFlags: "u8", dataScrollbar: "GhosttyTerminalScrollbar", dataMouseTracking: "bool", dataTitle: "GhosttyString", dataPwd: "GhosttyString", dataScrollbackRows: "usize", dataViewportActive: "bool", dataMode: "GhosttyTerminalModeConfig", dataMouseShape: "i32", dataKittyGraphics: "pointer", 31: "GhosttySelection", + }[args[1]] + if args[1] >= dataColorFg && args[1] < dataColorFg+3 || args[1] >= dataColorFgDefault && args[1] < dataColorFgDefault+3 { + typ = "GhosttyColorRgb" + } + if args[1] == dataColorFg+3 || args[1] == dataColorFgDefault+3 { + return []wasmParameter{{2, "GhosttyColorRgb", 256}} + } + if typ != "" { + return one(2, typ) + } + case "ghostty_terminal_compress": + return one(2, "i32") + case "ghostty_terminal_compression_activity": + return one(1, "u64") + case "ghostty_terminal_scroll_viewport": + return one(1, "GhosttyTerminalScrollViewport") + case "ghostty_terminal_grid_ref": + return two(1, "GhosttyPoint", 2, "GhosttyGridRef") + case "ghostty_render_state_get": + typ := map[uintptr]string{rsDataCols: "u16", rsDataRows: "u16", rsDataDirty: "i32", rsDataRowIterator: "pointer", rsDataCursor: "GhosttyRenderStateCursor", rsDataColors: "GhosttyRenderStateColors"}[args[1]] + if typ != "" { + return one(2, typ) + } + case "ghostty_render_state_row_get": + typ := map[uintptr]string{rowDataDirty: "bool", rowDataRaw: "u64", rowDataCells: "pointer", rowDataSelection: "GhosttyRenderStateRowSelection", rowDataCellsRaw: "GhosttyCellsView", rowDataID: "GhosttyRenderStateRowId"}[args[1]] + if typ != "" { + return one(2, typ) + } + case "ghostty_render_state_row_cells_get": + if args[1] == cellDataStyle { + return one(2, "GhosttyStyle") + } + if args[1] == cellDataGraphemesLen { + return one(2, "u32") + } + if args[1] == cellDataGraphemesBuf { + n := wasm.alloc.Invoke(4).Int() + defer wasm.free.Invoke(n, 4) + wasm.exports.Get(name).Invoke(int(args[0]), cellDataGraphemesLen, n) + return []wasmParameter{{2, "u32", uintptr(unsignedABI(foreignBytes(uintptr(n), 4)))}} + } + case "ghostty_row_get": + if args[1] == rowDataWrap { + return one(2, "bool") + } + if args[1] == rowDataSemanticPrompt { + return one(2, "i32") + } + case "ghostty_key_encoder_setopt": + if args[1] == 5 { + return one(2, "u8") + } + if args[1] == 6 { + return one(2, "i32") + } + case "ghostty_mouse_encoder_setopt": + typ := map[uintptr]string{2: "GhosttyMouseEncoderSize", 3: "bool", 4: "bool"}[args[1]] + if typ != "" { + return one(2, typ) + } + case "ghostty_mouse_event_set_position": + return one(1, "GhosttyMousePosition") + case "ghostty_key_encoder_encode", "ghostty_mouse_encoder_encode": + return []wasmParameter{{2, "u8", args[3]}, {4, "usize", 1}} + case "ghostty_focus_encode": + return []wasmParameter{{1, "u8", args[2]}, {3, "usize", 1}} + case "ghostty_paste_encode": + return []wasmParameter{{0, "u8", args[1]}, {3, "u8", args[4]}, {5, "usize", 1}} + case "ghostty_terminal_paste": + return two(1, "GhosttyPaste", 2, "bool") + case "ghostty_selection_gesture_get": + if args[2] == gestureDataDragged { + return one(3, "bool") + } + if args[2] == gestureDataAutoscroll { + return one(3, "i32") + } + case "ghostty_selection_gesture_event": + return one(3, "GhosttySelection") + case "ghostty_selection_gesture_event_set": + typ := map[uintptr]string{gestureOptRef: "GhosttyGridRef", gestureOptPosition: "GhosttySurfacePosition", gestureOptRepeatDistance: "f64", gestureOptTime: "u64", gestureOptRepeatInterval: "u64", gestureOptRectangle: "bool", gestureOptGeometry: "GhosttySelectionGestureGeometry", gestureOptViewport: "GhosttyPointCoordinate"}[args[1]] + if typ != "" { + return one(2, typ) + } + case "ghostty_terminal_select_all": + return one(1, "GhosttySelection") + case "ghostty_terminal_selection_format_alloc": + return []wasmParameter{{2, "GhosttyTerminalSelectionFormatOptions", 1}, {3, "pointer", 1}, {4, "usize", 1}} + case "ghostty_grid_ref_hyperlink_uri": + return []wasmParameter{{0, "GhosttyGridRef", 1}, {1, "u8", args[2]}, {3, "usize", 1}} + case "ghostty_grid_ref_graphemes": + return []wasmParameter{{0, "GhosttyGridRef", 1}, {1, "u32", args[2]}, {3, "usize", 1}} + case "ghostty_grid_ref_cell", "ghostty_grid_ref_row": + return two(0, "GhosttyGridRef", 1, "u64") + case "ghostty_terminal_point_from_grid_ref": + return two(1, "GhosttyGridRef", 3, "GhosttyPointCoordinate") + case "ghostty_formatter_terminal_new": + return two(1, "pointer", 3, "GhosttyFormatterTerminalOptions") + case "ghostty_formatter_format_alloc": + return two(2, "pointer", 3, "usize") + case "ghostty_kitty_graphics_get": + if args[1] == kittyPlacementIterator { + return one(2, "pointer") + } + case "ghostty_kitty_graphics_image_get": + typ := map[uintptr]string{imageWidth: "u32", imageHeight: "u32", imageFormat: "i32", imageData: "pointer", imageDataLen: "usize", imageGeneration: "u64"}[args[1]] + if typ != "" { + return one(2, typ) + } + case "ghostty_kitty_graphics_placement_get": + if args[1] == placementVirtual { + return one(2, "bool") + } + return one(2, "u32") + case "ghostty_kitty_graphics_placement_render_info": + return one(3, "GhosttyKittyGraphicsPlacementRenderInfo") + case "ghostty_search_set": + if args[1] == searchOptNeedle { + return one(2, "GhosttyString") + } + if args[1] == searchOptSelectScroll { + return one(2, "i32") + } + if args[1] == searchOptSelectNext || args[1] == searchOptSelectPrev { + return nil + } + case "ghostty_search_tick": + return one(1, "i32") + case "ghostty_search_get": + typ := map[uintptr]string{searchDataStatus: "i32", searchDataTotal: "usize", searchDataSelectedIndex: "usize", searchDataSelectedMatch: "GhosttySelection", searchDataViewportMatches: "GhosttySelectionBuffer"}[args[1]] + if typ != "" { + return one(2, typ) + } + } + panic(fmt.Sprintf("vt: no WebAssembly pointer schema for %s %v", name, args)) +} diff --git a/base/terminal/internal/vt/render.go b/base/terminal/internal/vt/render.go index ebeb94e2b4..104f97de25 100644 --- a/base/terminal/internal/vt/render.go +++ b/base/terminal/internal/vt/render.go @@ -254,7 +254,7 @@ func (r *RenderState) RowCells() []Cell { if !r.rowGet(rowDataCellsRaw, unsafe.Pointer(&v)) || v.ptr == 0 { return nil } - raw := unsafe.Slice((*uint64)(mem(v.ptr)), v.len) + raw := foreignSlice[uint64](v.ptr, v.len) r.raw = r.raw[:0] for _, c := range raw { var out Cell diff --git a/base/terminal/internal/vt/terminal.go b/base/terminal/internal/vt/terminal.go index 3d123ac610..376d03b08d 100644 --- a/base/terminal/internal/vt/terminal.go +++ b/base/terminal/internal/vt/terminal.go @@ -733,19 +733,18 @@ var ( ) func makeCallbacks() { - cbSemanticPrompt = newCallback(func(_, id, req uintptr) uintptr { + cbSemanticPrompt = newCallback("viii", func(_, id, req uintptr) uintptr { if t := terminalOf(id); t != nil && req != 0 { - p := (*semanticPrompt)(mem(req)) - t.promptInput = p.kind == 2 + t.promptInput = foreignValue[semanticPrompt](req).kind == 2 } return 0 }) // A GhosttyMimeReader for PasteEvent, which the library never calls // (it reads nothing for an event); it gives no data if it did. - cbNoRead = newCallback(func(_, _, _, _, _ uintptr) uintptr { return 0 }) - cbWritePTY = newCallback(func(_, id, data, n uintptr) uintptr { + cbNoRead = newCallback("mime-reader", func(_, _, _, _, _ uintptr) uintptr { return 0 }) + cbWritePTY = newCallback("viiii", func(_, id, data, n uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.WritePTY != nil && n > 0 { - p := unsafe.Slice((*byte)(mem(data)), n) + p := foreignBytes(data, n) if d := t.deferred; d != nil { // A deferred read: what the library writes now is its // refusal, which the read's answer replaces. @@ -768,15 +767,15 @@ func makeCallbacks() { } return 0 }) - cbClipboardRead = newCallback(func(_, id, req uintptr) uintptr { - r := (*clipboardRead)(mem(req)) + cbClipboardRead = newCallback("viii", func(_, id, req uintptr) uintptr { + r := foreignValue[clipboardRead](req) t := terminalOf(id) if t == nil || t.effects.ClipboardRead == nil { return 0 // refused by the library } var in ClipboardRead in.List, in.Primary, in.Granted, in.CanRemember = r.list, r.location != 0, r.granted, r.canRemember - for _, m := range unsafe.Slice((*cString)(mem(r.mimes)), r.mimesLen) { + for _, m := range foreignSlice[cString](r.mimes, r.mimesLen) { in.Mimes = append(in.Mimes, goString(m.ptr, m.len)) } out, answer := t.effects.ClipboardRead(in) @@ -827,39 +826,39 @@ func makeCallbacks() { } return 0 }) - cbBell = newCallback(func(_, id uintptr) uintptr { + cbBell = newCallback("vii", func(_, id uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.Bell != nil { t.effects.Bell() } return 0 }) - cbTitleChanged = newCallback(func(_, id uintptr) uintptr { + cbTitleChanged = newCallback("vii", func(_, id uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.TitleChanged != nil { t.effects.TitleChanged() } return 0 }) - cbPwdChanged = newCallback(func(_, id uintptr) uintptr { + cbPwdChanged = newCallback("vii", func(_, id uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.PwdChanged != nil { t.effects.PwdChanged() } return 0 }) - cbRenderHold = newCallback(func(_, id, held uintptr) uintptr { + cbRenderHold = newCallback("viii", func(_, id, held uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.RenderHold != nil { t.effects.RenderHold(cbool(held)) } return 0 }) - cbClipboardWrite = newCallback(func(_, id, req uintptr) uintptr { - w := (*clipboardWrite)(mem(req)) + cbClipboardWrite = newCallback("viii", func(_, id, req uintptr) uintptr { + w := foreignValue[clipboardWrite](req) reply := clipboardWriteReply{size: unsafe.Sizeof(clipboardWriteReply{}), result: 1} // denied t := terminalOf(id) if t != nil && t.effects.Clipboard != nil { // No contents clears the clipboard; otherwise the first plain // text, else the first text of another kind, is written. text, found := "", w.contentsLen == 0 - for _, c := range unsafe.Slice((*clipboardContent)(mem(w.contents)), w.contentsLen) { + for _, c := range foreignSlice[clipboardContent](w.contents, w.contentsLen) { mime := goString(c.mime.ptr, c.mime.len) if strings.HasPrefix(mime, "text/plain") || strings.HasPrefix(mime, "text/") && !found { text, found = goString(c.data.ptr, c.data.len), true @@ -875,16 +874,16 @@ func makeCallbacks() { call(w.reply, req, uintptr(unsafe.Pointer(&reply))) return 0 }) - cbSize = newCallback(func(_, id, out uintptr) uintptr { + cbSize = newCallback("iiii", func(_, id, out uintptr) uintptr { t := terminalOf(id) if t == nil || t.effects.Size == nil { return 0 } cols, rows, cw, ch := t.effects.Size() - *(*sizeReport)(mem(out)) = sizeReport{rows: uint16(clamp16(rows)), columns: uint16(clamp16(cols)), cellWidth: uint32(max(cw, 1)), cellHeight: uint32(max(ch, 1))} + foreignWrite(out, sizeReport{rows: uint16(clamp16(rows)), columns: uint16(clamp16(cols)), cellWidth: uint32(max(cw, 1)), cellHeight: uint32(max(ch, 1))}) return 1 }) - cbColorScheme = newCallback(func(_, id, out uintptr) uintptr { + cbColorScheme = newCallback("iiii", func(_, id, out uintptr) uintptr { t := terminalOf(id) if t == nil || t.effects.Dark == nil { return 0 @@ -893,27 +892,27 @@ func makeCallbacks() { if t.effects.Dark() { v = 1 } - *(*int32)(mem(out)) = v + foreignWrite(out, v) return 1 }) - cbDeviceAttributes = newCallback(func(_, id, out uintptr) uintptr { + cbDeviceAttributes = newCallback("iiii", func(_, id, out uintptr) uintptr { // As Ghostty answers: a VT220 with ANSI colors (DA1), of type 1 // and version 10 (DA2). - da := (*deviceAttributes)(mem(out)) - *da = deviceAttributes{conformance: 62, numFeatures: 1, deviceType: 1, firmware: 10} + da := deviceAttributes{conformance: 62, numFeatures: 1, deviceType: 1, firmware: 10} da.features[0] = 22 + foreignWrite(out, da) return 1 }) - cbDesktopNotification = newCallback(func(_, id, req uintptr) uintptr { + cbDesktopNotification = newCallback("viii", func(_, id, req uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.Notify != nil { - n := (*desktopNotification)(mem(req)) + n := foreignValue[desktopNotification](req) t.effects.Notify(goString(n.title.ptr, n.title.len), goString(n.body.ptr, n.body.len)) } return 0 }) - cbProgressReport = newCallback(func(_, id, req uintptr) uintptr { + cbProgressReport = newCallback("viii", func(_, id, req uintptr) uintptr { if t := terminalOf(id); t != nil && t.effects.Progress != nil { - p := (*progressReport)(mem(req)) + p := foreignValue[progressReport](req) t.effects.Progress(int(p.state), int(p.progress)) } return 0 diff --git a/base/terminal/link_test.go b/base/terminal/link_test.go index 4819015c49..e5b6d1882c 100644 --- a/base/terminal/link_test.go +++ b/base/terminal/link_test.go @@ -126,6 +126,9 @@ func TestPathUsesShellDirectory(t *testing.T) { } func TestViewOpensPaths(t *testing.T) { + if runtime.GOOS == "js" { + t.Skip("paths require a local filesystem") + } term := pathTerminal(t) dir := t.TempDir() file := filepath.Join(dir, "路径") diff --git a/base/terminal/terminal.go b/base/terminal/terminal.go index 69d62aff9e..7001238fa7 100644 --- a/base/terminal/terminal.go +++ b/base/terminal/terminal.go @@ -2,13 +2,7 @@ // user's shell, or any program, in a pseudo-terminal, with Ghostty's // terminal emulator, libghostty-vt, loaded at run time with no cgo. // -// It runs programs on macOS, Linux and Windows, and remote sessions -// (Options.Conn) there and on iOS; elsewhere New returns an error. -// It does what terminals do: colors (16, 256 and 24-bit) and styles, -// wide characters and grapheme clusters, a scrollback that reflows, the -// alternate screen, the keyboard as programs ask (legacy sequences, -// modifyOtherKeys or the Kitty keyboard protocol), bracketed paste, the -// title (OSC 0 and 2) and the working directory (OSC 7). +// It runs programs on macOS, Linux and Windows, and remote sessions (Options.Conn) there, on iOS and in the browser; elsewhere New returns an error. It does what terminals do: colors (16, 256 and 24-bit) and styles, wide characters and grapheme clusters, a scrollback that reflows, the alternate screen, the keyboard as programs ask (legacy sequences, modifyOtherKeys or the Kitty keyboard protocol), bracketed paste, the title (OSC 0 and 2) and the working directory (OSC 7). package terminal import ( @@ -156,7 +150,7 @@ func Load() error { return load.err } -// LibraryPath returns the libghostty-vt the terminal loads, the first of: the file $NSGO_GHOSTTY_VT names; the one beside the executable, or in its iOS or Catalyst GhosttyVT.framework or macOS Frameworks; the build the package embeds for the platform, written once into the user's cache (/nsgo/libghostty-vt//). +// LibraryPath returns the embedded module identity in a browser, or the libghostty-vt the native terminal loads, the first of: the file $NSGO_GHOSTTY_VT names; the one beside the executable, or in its iOS or Catalyst GhosttyVT.framework or macOS Frameworks; the build the package embeds for the platform, written once into the user's cache (/nsgo/libghostty-vt//). func LibraryPath() (string, error) { return library.Find() } // New makes a terminal running opts.Command, or connected to opts.Conn. @@ -208,7 +202,7 @@ func New(opts Options) (*Terminal, error) { t.run() return t, nil } - if runtime.GOOS == "ios" || runtime.GOOS == "android" { + if runtime.GOOS == "ios" || runtime.GOOS == "android" || runtime.GOOS == "js" { t.rs.Free() t.term.Free() return nil, fmt.Errorf("terminal: %s runs no local programs; give Options.Conn a remote session", runtime.GOOS) diff --git a/base/terminal/terminal_test.go b/base/terminal/terminal_test.go index e79a3f9978..bc231ec166 100644 --- a/base/terminal/terminal_test.go +++ b/base/terminal/terminal_test.go @@ -14,6 +14,9 @@ import ( // newTerminal makes a terminal of opts, skipping where none runs. func newTerminal(t *testing.T, opts Options) *Terminal { t.Helper() + if runtime.GOOS == "js" && opts.Conn == nil { + t.Skip("the browser runs remote sessions only") + } if runtime.GOOS == "windows" { t.Skip("runs /bin/sh") } diff --git a/changelog.d/terminal-web.md b/changelog.d/terminal-web.md new file mode 100644 index 0000000000..6eb88e8644 --- /dev/null +++ b/changelog.d/terminal-web.md @@ -0,0 +1,3 @@ +### Added + +- Run remote terminal sessions in the browser with libghostty-vt WebAssembly (#1455 by @houko). diff --git a/cmd/nsgo/terminalweb_test.go b/cmd/nsgo/terminalweb_test.go new file mode 100644 index 0000000000..0b26f5482e --- /dev/null +++ b/cmd/nsgo/terminalweb_test.go @@ -0,0 +1,142 @@ +//go:build !js && !android && !ios + +package main + +import ( + "context" + "crypto/rand" + "encoding/xml" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "runtime" + "strings" + "sync/atomic" + "testing" + "time" + + "golang.org/x/net/websocket" + + terminalview "github.com/nsgo-dev/nsgo/base/terminal" +) + +// TestTerminalBrowserSession runs a real local shell in a PTY and transports its mirror over a real WebSocket to the browser's own libghostty-vt module. +func TestTerminalBrowserSession(t *testing.T) { + if testing.Short() || runtime.GOOS == "windows" { + t.Skip("runs /bin/sh and a browser") + } + if _, err := findBrowser(); err != nil { + t.Skip(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute) + defer cancel() + token := rand.Text() + failures := make(chan error, 1) + fail := func(err error) { + select { + case failures <- err: + default: + } + } + var received, sent atomic.Int64 + server := websocket.Server{ + Handshake: func(_ *websocket.Config, r *http.Request) error { + origin, err := url.Parse(r.Header.Get("Origin")) + if err != nil || origin.Hostname() != "127.0.0.1" || r.URL.Path != "/"+token { + return fmt.Errorf("unexpected test socket origin or path") + } + return nil + }, + Handler: func(conn *websocket.Conn) { + defer conn.Close() + term, err := terminalview.New(terminalview.Options{Command: []string{"/bin/sh", "-c", "printf '\\033]2;WebSocket remote\\007\\033[32mREMOTE_READY\\033[0m\\r\\n'; exec /bin/sh -i"}, Env: []string{"PS1=socket$ "}}) + if err != nil { + fail(err) + return + } + defer func() { term.Close(); <-term.Done() }() + term.Resize(80, 24) + mirror, err := term.NewMirror() + if err != nil { + fail(err) + return + } + defer mirror.Close() + closed := make(chan struct{}) + go func() { + defer close(closed) + buf := make([]byte, 4096) + for { + n, err := conn.Read(buf) + if n > 0 { + received.Add(int64(n)) + term.Send(buf[:n]) + } + if err != nil { + return + } + } + }() + conn.PayloadType = websocket.BinaryFrame + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-closed: + return + case <-ticker.C: + } + frame, _ := mirror.Frame() + if len(frame) == 0 { + continue + } + if _, err := conn.Write(frame); err != nil { + return + } + sent.Add(int64(len(frame))) + } + }, + } + srv := httptest.NewServer(server) + defer func() { cancel(); srv.Close() }() + p, err := loadForTest(filepath.Join("..", "..", "internal", "testhost", "testdata", "terminalweb"), nil) + if err != nil { + t.Fatal(err) + } + report := filepath.Join(t.TempDir(), "tests.xml") + address := "ws" + strings.TrimPrefix(srv.URL, "http") + "/" + token + if err := runTests(ctx, p, testOptions{target: "web", junit: report, timeout: time.Minute, env: []string{"NSGO_TERMINAL_WS=" + address}, screenshots: os.Getenv("NSGO_TERMINAL_WEB_SCREENSHOTS")}); err != nil { + t.Fatal(err) + } + select { + case err := <-failures: + t.Fatal(err) + default: + } + data, err := os.ReadFile(report) + if err != nil { + t.Fatal(err) + } + var suites junitSuites + if err := xml.Unmarshal(data, &suites); err != nil { + t.Fatal(err) + } + if suites.Tests != 1 || suites.Failures != 0 { + t.Fatalf("browser results: %s", data) + } + for _, suite := range suites.Suites { + for _, c := range suite.Cases { + if c.Skipped != nil { + t.Fatalf("browser terminal test skipped: %+v", c.Skipped) + } + } + } + if received.Load() == 0 || sent.Load() == 0 { + t.Fatalf("WebSocket did not carry bidirectional session data: received %d, sent %d", received.Load(), sent.Load()) + } +} diff --git a/docs/architecture/layers.md b/docs/architecture/layers.md index e1dc9b6d1a..901b3a88e4 100644 --- a/docs/architecture/layers.md +++ b/docs/architecture/layers.md @@ -157,7 +157,7 @@ A line means "imports". `internal/moduletest/layering_test.go` checks the graph - `updater` imports only `core` and its catalogs; `internal/backend` imports it, to check as the app starts where the platform's updater keeps no schedule. - `ui` imports `base`, `core`, `mobile`, `desktop` and the icons; `base` never imports it. - `tsx/tsxtest` is the one package that imports both `tsx` and `nsgotest`, and `tsx/ui` with the packages below it the TSX packages that import `ui`. `tsx/internal/js`, the engines' API, imports nothing of NSGo's, and on the web reaches the page through `syscall/js`. -- `base/terminal` is the one package of `base` that is not portable: it loads libghostty-vt through purego, runs programs on desktops and remote sessions there and on iOS, and elsewhere builds to report that it cannot (`unportable` in `layering_test.go`). +- `base/terminal` is the one package of `base` that is not portable: it loads native libghostty-vt through purego or an embedded browser WebAssembly module, runs programs on desktops and remote sessions there, on iOS and in the browser, and elsewhere builds to report that it cannot (`unportable` in `layering_test.go`). ## Why core and backends do not meet diff --git a/docs/architecture/terminal.md b/docs/architecture/terminal.md index 6266bb6f9c..e4a1c22ffd 100644 --- a/docs/architecture/terminal.md +++ b/docs/architecture/terminal.md @@ -1,6 +1,6 @@ # Terminal -`base/terminal` is a terminal for NSGo apps: a `View` that runs the user's shell, or any program, in a pseudo-terminal, with Ghostty's emulator, libghostty-vt, loaded at run time through purego. NSH's `term` module draws a replaceable emulator as native text rows; NSGo uses Ghostty's state and a canvas, with Ghostty as the reference for behavior and names. Read this before changing the package. +`base/terminal` is a terminal for NSGo apps: a `View` that runs the user's shell, or any program, in a pseudo-terminal, with Ghostty's emulator, libghostty-vt, loaded at run time through purego on native targets or instantiated as WebAssembly in a browser. NSH's `term` module draws a replaceable emulator as native text rows; NSGo uses Ghostty's state and a canvas, with Ghostty as the reference for behavior and names. Read this before changing the package. ## Packages @@ -8,19 +8,30 @@ | --- | --- | | `base/terminal` | `Terminal` (the emulator, the program and their goroutines), `View`, themes with Ghostty's, keys | | `base/terminal/locales` | The lines the terminal writes when its program ends, in the language the view's app shows | -| `base/terminal/internal/vt` | The binding of libghostty-vt's C API: structs checked against the layouts the library reports as it loads, so a library of another version fails to load rather than corrupt memory | +| `base/terminal/internal/vt` | The binding of libghostty-vt's C API: validated native layouts or marshaling across browser guest memory | | `base/terminal/internal/pty` | Pseudo-terminals in pure Go: `/dev/ptmx` on macOS and Linux, ConPTY on Windows | | `tsx/terminal` | `Terminal` in TSX's `nsgo/base`: the view over a session its props start ([TSX](tsx.md#go-components)) | -| `base/terminal/internal/library` | Finds the library: `$NSGO_GHOSTTY_VT`; the one the nsgo tool put into the app, an iOS app's `GhosttyVT.framework` or a macOS app's `Frameworks`, or one beside the executable; else on desktops the build it embeds for the platform, written once into `/nsgo/libghostty-vt//` | +| `base/terminal/internal/library` | Provides the embedded browser module, or finds a native library: `$NSGO_GHOSTTY_VT`; the one the nsgo tool put into the app, an iOS app's `GhosttyVT.framework` or a macOS app's `Frameworks`, or one beside the executable; else on desktops the build it embeds for the platform, written once into `/nsgo/libghostty-vt//` | -It is a package under `base` because it links what an app without it should not, and the one there that is not portable: it reaches libghostty-vt through purego and programs through `syscall` ([package layers](layers.md)). Desktops run local programs and remote sessions; iOS, which forbids child processes, runs remote sessions only (`Options.Conn`), and `New` without one returns an error there. Android and the web build, and `New` returns an error ([roadmap](../roadmap.md#terminal)). It imports `core` and `i18n`. Its only look is the terminal's palette, as `Editor`'s is its highlighting's: `Theme` and `DarkTheme`, Visual Studio Code's colors when unset; the app styles the view around the grid. +It is a package under `base` because it links what an app without it should not, and the one there that is not portable: it reaches native libghostty-vt through purego, the browser's guest through `syscall/js`, and programs through `syscall` ([package layers](layers.md)). Desktops run local programs and remote sessions; iOS and the browser run remote sessions only (`Options.Conn`), and `New` without one returns an error there. Android, mini programs and HarmonyOS still return an unsupported error ([roadmap](../roadmap.md#terminal)). It imports `core` and `i18n`. Its only look is the terminal's palette, as `Editor`'s is its highlighting's: `Theme` and `DarkTheme`, Visual Studio Code's colors when unset; the app styles the view around the grid. ## The library -libghostty-vt is built from Ghostty's sources at the commit the binding names, by `go run ./tools/libghostty` on a Mac with Xcode: it clones Ghostty into the user's cache, downloads the Zig its `build.zig.zon` asks for from ziglang.org, checked against the index's SHA-256, and builds every desktop target, iOS devices, both simulator architectures and Mac Catalyst, stripping the Linux builds' debug sections. The builds are committed in `internal/library/lib/`, as users have no Zig ([principles](../../AGENTS.md#principles)), so nothing is downloaded at run time. A desktop's is embedded in the apps that link the terminal, so `go run` and `go test` find it; the nsgo tool also signs it into macOS apps, where hardened apps load only signed libraries, and into iOS apps as a framework, the only way iOS loads native code ([tool](tool.md#packages)). Windows and Linux packages put the library beside their executable; iOS `-embed` writes a companion `GhosttyVT.xcframework` with all app slices, which hosts embed and sign for static and dynamic apps alike. An arm64 AAR carries the Android library supplied by #1452 in its JNI ABI directory. `-target` selects comma-separated library storage keys, such as `iossimulator-amd64,ioscatalyst-arm64`, or `all` (the default). The command also writes `ghostty_themes.go`, the themes Ghostty ships; `-themes` writes them alone. +libghostty-vt is built from Ghostty's sources at the commit the binding names, by `go run ./tools/libghostty` on a Mac with Xcode: it clones Ghostty into the user's cache, downloads the Zig its `build.zig.zon` asks for from ziglang.org, checked against the index's SHA-256, and builds every desktop target, iOS devices, both simulator architectures and Mac Catalyst, and the browser module, stripping the Linux builds' debug sections. The builds are committed in `internal/library/lib/`, as users have no Zig ([principles](../../AGENTS.md#principles)), so nothing is downloaded at run time. A desktop's is embedded in the apps that link the terminal, so `go run` and `go test` find it; the nsgo tool also signs it into macOS apps, where hardened apps load only signed libraries, and into iOS apps as a framework, the only way iOS loads native code ([tool](tool.md#packages)). Windows and Linux packages put the library beside their executable; iOS `-embed` writes a companion `GhosttyVT.xcframework` with all app slices, which hosts embed and sign for static and dynamic apps alike. An arm64 AAR carries the Android library supplied by #1452 in its JNI ABI directory. `-target` selects comma-separated library storage keys, such as `iossimulator-amd64,ioscatalyst-arm64`, or `all` (the default). The command also writes `ghostty_themes.go`, the themes Ghostty ships; `-themes` writes them alone. The library runs on macOS 13 or later, Linux with glibc 2.28 or later (Debian 10, Ubuntu 20.04) and Windows 10 1809 or later, whose ConPTY runs the program. +## Browser binding + +The browser embeds `internal/library/lib/js-wasm/ghostty-vt.wasm`; `LibraryPath` is its embedded identity, not a file. `tools/libghostty -target js-wasm` builds the pinned source as `wasm32-freestanding` with `ReleaseSmall`, archiving it into a temporary tree before enabling its graphics feature and refusing file-based image media. The source checkout and every native target stay unchanged. Shared-memory media already refuse freestanding targets; inline RGB/RGBA/PNG images retain the Go decoder. The generator writes the linked Ghostty, Zig and Wuffs notices into `internal/library/LICENSE`. + +- The Go and guest modules own separate memories and have different pointer widths. Each export has an explicit argument schema; structs marshal by the guest manifest and the generated 64-bit `internal/vt/abi64.json`, checked against Go's mirrored structs. Guest pointers never address Go memory. Rebuild that manifest with `go tool nsgo test -run TestWriteWasmHostABI -env NSGO_GHOSTTY_ABI_OUT= ./base/terminal/internal/vt` on a native target after changing the pin. +- Every foreign memory access reacquires the guest buffer after allocations can grow it. Opaque handles stay guest values; host input buffers copy in, outputs copy back, and key-event UTF-8 remains allocated until the event releases it. +- Typed Wasm trampolines occupy the exported indirect-function table for callbacks. The C API's secure-random effect uses Go's browser cryptographic source, so clipboard paste grants have real entropy without OS services. +- Long export bursts yield outside guest callbacks so Go's finalizers can release JavaScript references; cached exports and constructors limit handle churn. The 3,000-frame randomized mirror test exercises that path. + +The app adapts its WebSocket to `io.ReadWriteCloser`, joining and splitting binary messages as a byte stream; NSGo defines no server/control protocol. A connection's existing optional resize methods carry the app's own protocol. `cmd/nsgo/TestTerminalBrowserSession` drives a real browser against a native PTY over a real WebSocket, checking typed command output, ANSI pixels, alternate-screen restoration and close. Other JavaScript hosts stay unsupported until their module-loading and input paths are verified. + ## Terminal `Terminal` takes `Command`, `Dir`, `Env`, `Conn`, `Scrollback`, `Cursor` (which `SetCursor` changes in a running terminal), `CursorBlink` and the `OnTitle`, `OnExit` and `OnBell` callbacks. A reader goroutine writes the program's output into the emulator under the terminal's lock; a queue writes input on a goroutine of its own, so a program that reads nothing never blocks the reader answering its queries. The program starts at the first size a view gives, or at 80×24 after half a second. Its end writes a line of `locales` in the language the view last drew in. diff --git a/docs/public/en/terminal.md b/docs/public/en/terminal.md index a24ca6ae4f..98493ce3a7 100644 --- a/docs/public/en/terminal.md +++ b/docs/public/en/terminal.md @@ -5,7 +5,7 @@ group: Core concepts order: 63 --- -`base/terminal` provides a session (`Terminal`) and its `View`. Desktops run local programs; iOS uses `Options.Conn`, an `io.ReadWriteCloser` connected to a remote program. The app owns the session and closes it when finished. +`base/terminal` provides a session (`Terminal`) and its `View`. Desktops run local programs; iOS and browsers use `Options.Conn`, an `io.ReadWriteCloser` connected to a remote program. The app owns the session and closes it when finished. ```go t, err := terminal.New(terminal.Options{CursorBlink: true}) @@ -36,6 +36,12 @@ return terminal.View{ TSX apps import `tsx/terminal` for its effect to register `Terminal` in `nsgo/base`. The props are `cursorBlink`, `minimumContrast` and `paddingColor`; the latter accepts `background`, `extend` and `extend-always`. Appearance props can change while the session continues. +## In a browser + +The app embeds the pinned libghostty-vt WebAssembly module and runs the same terminal view and input path. Building the app needs no Zig, native library installation or runtime download. + +Adapt the browser's WebSocket to `io.ReadWriteCloser`: send binary bytes and join or split incoming messages as a stream. The app and its server own authentication, reconnecting and any resize/control messages; NSGo consumes terminal bytes. The [browser acceptance fixture](https://github.com/nsgo-dev/nsgo/blob/main/internal/testhost/testdata/terminalweb/socket_js_test.go) shows a complete byte-stream adapter with close handling. + ## Actions and zoom `View.Keybinds` overrides defaults with `Keybind{Key, Action, Amount}`. Keys use the same names as `Scope.OnKey`, such as `mod+=` or `ctrl+shift+c`. Later entries win. Bindings run while this terminal's input has the focus and no input method is composing. diff --git a/docs/public/zh/terminal.md b/docs/public/zh/terminal.md index 97438df8d5..0591642830 100644 --- a/docs/public/zh/terminal.md +++ b/docs/public/zh/terminal.md @@ -5,7 +5,7 @@ group: 核心概念 order: 63 --- -`base/terminal` 提供会话 `Terminal` 及其 `View`。桌面运行本地程序;iOS 使用 `Options.Conn`,即连接远程程序的 `io.ReadWriteCloser`。应用持有会话,并在结束时关闭它。 +`base/terminal` 提供会话 `Terminal` 及其 `View`。桌面运行本地程序;iOS 和浏览器使用 `Options.Conn`,即连接远程程序的 `io.ReadWriteCloser`。应用持有会话,并在结束时关闭它。 ```go t, err := terminal.New(terminal.Options{CursorBlink: true}) @@ -36,6 +36,12 @@ return terminal.View{ TSX 应用通过副作用导入 `tsx/terminal`,将 `Terminal` 注册到 `nsgo/base`。对应属性为 `cursorBlink`、`minimumContrast` 和 `paddingColor`;后者接受 `background`、`extend` 或 `extend-always`。外观属性变化时,会话仍继续运行。 +## 在浏览器中 + +应用内嵌固定版本的 libghostty-vt WebAssembly 模块,使用相同的终端视图和输入路径。构建应用无需 Zig、额外安装原生库,也不需要在运行时下载库。 + +将浏览器的 WebSocket 适配为 `io.ReadWriteCloser`:发送二进制字节,并把收到的消息合并或拆分为连续字节流。认证、重连以及尺寸和控制消息由应用与服务器决定;NSGo 只处理终端字节。[浏览器验收用例](https://github.com/nsgo-dev/nsgo/blob/main/internal/testhost/testdata/terminalweb/socket_js_test.go) 提供了包含关闭处理的完整字节流适配器。 + ## 动作与缩放 `View.Keybinds` 用 `Keybind{Key, Action, Amount}` 覆盖默认快捷键。键名与 `Scope.OnKey` 相同,例如 `mod+=` 或 `ctrl+shift+c`;后面的绑定优先。只有当前终端输入框获得焦点且输入法未在组词时,绑定才生效。 diff --git a/docs/roadmap.md b/docs/roadmap.md index b2353493ca..5c91f56462 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -231,11 +231,12 @@ What `base/terminal` still lacks of a terminal app's features, Ghostty's the ref | Android | [#1452](https://github.com/nsgo-dev/nsgo/issues/1452) | An Android app's remote session runs: libghostty-vt built for `aarch64-linux-android` (Ghostty's build takes the NDK's sysroot, which `tools/libghostty` would download) goes into the APK's native libraries, and the Go process, which has no cgo on arm64, loads it: purego loads libraries on Android only through cgo, so this needs a loader for bionic without cgo, checked on a device | | iOS on a device | [#1453](https://github.com/nsgo-dev/nsgo/issues/1453) | The full-gallery `TestTerminalPhone` passes on a physical iPhone with its signed framework and software keyboard; device proof applies [#2119](https://github.com/nsgo-dev/nsgo/pull/2119)'s startup fix and omits widget/live-activity configuration because the available profile lacks App Groups | | Embedded Android terminal acceptance | [#1454](https://github.com/nsgo-dev/nsgo/issues/1454) | Windows/Linux sidecars and the complete companion XCFramework run natively, with iOS host acceptance using the safe-area fix from #1434; the arm64 AAR carries #1452’s prebuild, pending its loader and a real Android host. Android x86_64 has no prebuild | -| The web | [#1455](https://github.com/nsgo-dev/nsgo/issues/1455) | A page runs a remote session over a WebSocket with libghostty-vt built for WebAssembly, which the browser runs, through the binding's calls | | Mouse reports and the wheel on full-screen programs | `mouse-reporting`, `mouse-scroll-multiplier`, [#1456](https://github.com/nsgo-dev/nsgo/issues/1456) | Implemented in the shared view: requested button/motion/wheel protocols and alternate-scroll cursor keys, reactive capture preference and precision/discrete multipliers; native AppKit pointer/touchpad proof; native Windows/Linux runs and program-controlled Shift capture remain unverified or unexposed; Android/web runtimes above remain prerequisites | | Keybinds, zoom, the context menu and secondary clicks | `keybind`, `right-click-action`, [#1459](https://github.com/nsgo-dev/nsgo/issues/1459) | Shared view actions override defaults while focused and not composing, zoom resizes the grid in place, and secondary clicks offer Copy, Paste, Select All and Clear or a clipboard policy; headless and native macOS regressions cover them, with native Windows/Linux menu acceptance still to run | | Images relative to Unicode placements | Kitty graphics, [#1461](https://github.com/nsgo-dev/nsgo/issues/1461) | Resolve the viewport positions of relative placements rooted in virtual Unicode placements; search highlights, ordinary and Unicode image placements, and OSC 133 Option+click are implemented | +Browser terminal support does not yet extend to HarmonyOS or mini-program hosts; their module loading and input paths remain a goal. + ## Widgets What package `widget` lacks of WidgetKit and ActivityKit, and of widgets and Live Activities elsewhere ([tool](architecture/tool.md#widgets)). diff --git a/internal/testhost/testdata/terminalweb/nsgo.yaml b/internal/testhost/testdata/terminalweb/nsgo.yaml new file mode 100644 index 0000000000..517428a6ef --- /dev/null +++ b/internal/testhost/testdata/terminalweb/nsgo.yaml @@ -0,0 +1,2 @@ +name: NSGo Terminal Web +id: dev.nsgo.terminalweb1455 diff --git a/internal/testhost/testdata/terminalweb/socket_js_test.go b/internal/testhost/testdata/terminalweb/socket_js_test.go new file mode 100644 index 0000000000..811c6902c6 --- /dev/null +++ b/internal/testhost/testdata/terminalweb/socket_js_test.go @@ -0,0 +1,144 @@ +//go:build js + +package terminalweb + +import ( + "context" + "errors" + "io" + "sync" + "syscall/js" +) + +// socket is the app's byte-stream adapter. A WebSocket message boundary has no meaning to a terminal; reads may split or join messages. Resize/control messages are the app/server's protocol, independent of terminal.Options.Conn. +type socket struct { + ws js.Value + mu sync.Mutex + queue [][]byte + err error + wake chan struct{} + done chan struct{} + once sync.Once + listeners []js.Func +} + +func dialSocket(ctx context.Context, url string) (*socket, error) { + s := &socket{ws: js.Global().Get("WebSocket").New(url), wake: make(chan struct{}, 1), done: make(chan struct{})} + s.ws.Set("binaryType", "arraybuffer") + ready := make(chan error, 1) + bind := func(name string, fn func([]js.Value)) { + callback := js.FuncOf(func(_ js.Value, args []js.Value) any { fn(args); return nil }) + s.listeners = append(s.listeners, callback) + s.ws.Set(name, callback) + } + bind("onopen", func([]js.Value) { + select { + case ready <- nil: + default: + } + }) + bind("onmessage", func(args []js.Value) { + data := args[0].Get("data") + var bytes []byte + if data.Type() == js.TypeString { + bytes = []byte(data.String()) + } else { + array := js.Global().Get("Uint8Array").New(data) + bytes = make([]byte, array.Length()) + js.CopyBytesToGo(bytes, array) + } + s.mu.Lock() + if s.err == nil && len(bytes) > 0 { + s.queue = append(s.queue, bytes) + } + s.mu.Unlock() + select { + case s.wake <- struct{}{}: + default: + } + }) + bind("onerror", func([]js.Value) { + s.end(errors.New("WebSocket failed")) + select { + case ready <- errors.New("WebSocket failed"): + default: + } + }) + bind("onclose", func([]js.Value) { + s.end(io.EOF) + select { + case ready <- io.EOF: + default: + } + }) + select { + case err := <-ready: + if err != nil { + s.Close() + return nil, err + } + return s, nil + case <-ctx.Done(): + s.Close() + return nil, ctx.Err() + } +} + +func (s *socket) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + for { + s.mu.Lock() + if len(s.queue) > 0 { + n := copy(p, s.queue[0]) + s.queue[0] = s.queue[0][n:] + if len(s.queue[0]) == 0 { + s.queue = s.queue[1:] + } + s.mu.Unlock() + return n, nil + } + err := s.err + s.mu.Unlock() + if err != nil { + return 0, err + } + select { + case <-s.wake: + case <-s.done: + } + } +} + +func (s *socket) Write(p []byte) (int, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.err != nil { + return 0, s.err + } + if s.ws.Get("readyState").Int() != 1 { + return 0, io.ErrClosedPipe + } + array := js.Global().Get("Uint8Array").New(len(p)) + js.CopyBytesToJS(array, p) + s.ws.Call("send", array) + return len(p), nil +} + +func (s *socket) end(err error) { + s.once.Do(func() { s.mu.Lock(); s.err = err; s.mu.Unlock(); close(s.done) }) +} + +func (s *socket) Close() error { + s.end(io.ErrClosedPipe) + for _, name := range []string{"onopen", "onmessage", "onerror", "onclose"} { + s.ws.Set(name, js.Null()) + } + s.ws.Call("close") + for _, callback := range s.listeners { + callback.Release() + } + s.listeners = nil + return nil +} diff --git a/internal/testhost/testdata/terminalweb/terminal_js_test.go b/internal/testhost/testdata/terminalweb/terminal_js_test.go new file mode 100644 index 0000000000..b53bf902a8 --- /dev/null +++ b/internal/testhost/testdata/terminalweb/terminal_js_test.go @@ -0,0 +1,79 @@ +//go:build js + +package terminalweb + +import ( + "os" + "strings" + "testing" + "time" + + _ "github.com/nsgo-dev/nsgo" + "github.com/nsgo-dev/nsgo/base/terminal" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +func TestMain(m *testing.M) { nsgotest.Main(m) } + +func TestRemoteWebSocketSession(t *testing.T) { + url := os.Getenv("NSGO_TERMINAL_WS") + if url == "" { + t.Skip("the host test supplies a real local WebSocket PTY") + } + conn, err := dialSocket(t.Context(), url) + if err != nil { + t.Fatal(err) + } + term, err := terminal.New(terminal.Options{Conn: conn, ResizeByConn: true}) + if err != nil { + conn.Close() + t.Fatal(err) + } + t.Cleanup(func() { term.Close() }) + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + return terminal.View{Terminal: term, Label: "Remote terminal", AutoFocus: true, Font: core.Font{Size: 14}, + Style: core.Style{Width: core.Pct(100), Height: core.Pct(100)}} + }, nsgotest.Size(760, 520)) + app.WaitUntil(10*time.Second, func() bool { + return strings.Contains(term.Text(), "REMOTE_READY") && term.Title() == "WebSocket remote" + }) + pixels := func(color string) { + t.Helper() + img := app.Capture() + if img == nil { + t.Fatal("the browser did not capture the terminal canvas") + } + count := 0 + for y := range img.Bounds().Dy() { + for x := range img.Bounds().Dx() { + r, g, b, _ := img.At(x, y).RGBA() + if color == "green" && g > 20000 && g > r*3/2 && g > b*5/4 || color == "red" && r > 20000 && r > g*3/2 && r > b*3/2 { + count++ + } + } + } + if count < 10 { + t.Fatalf("only %d %s pixels: the browser did not draw the remote ANSI text", count, color) + } + } + pixels("green") + app.Type("label:Remote terminal", "printf '\\nREMOTE_%s\\n' REPLY") + app.Key("enter") + app.WaitUntil(10*time.Second, func() bool { return strings.Contains(term.Text(), "\nREMOTE_REPLY") }) + app.Screenshot("terminal-web-session") + app.Type("label:Remote terminal", "printf '\\033[?1049h\\033[H\\033[31mALT_%s\\033[0m' REMOTE") + app.Key("enter") + app.WaitUntil(10*time.Second, func() bool { return strings.Contains(term.Text(), "ALT_REMOTE") }) + pixels("red") + app.Screenshot("terminal-web-alternate") + app.Type("label:Remote terminal", "printf '\\033[?1049l'") + app.Key("enter") + app.WaitUntil(10*time.Second, func() bool { return strings.Contains(term.Text(), "REMOTE_REPLY") }) + term.Close() + select { + case <-term.Done(): + case <-time.After(5 * time.Second): + t.Fatal("closing the socket did not finish the remote session") + } +} diff --git a/skills/nsgo/references/components.md b/skills/nsgo/references/components.md index cd19e4e51b..5909134dd6 100644 --- a/skills/nsgo/references/components.md +++ b/skills/nsgo/references/components.md @@ -31,6 +31,7 @@ Use `ui`'s component whenever one exists: it is `base`'s control with NSGo's loo - `widget.Update` publishes the same timeline to Apple widgets and Android App Widgets. Android standalone APKs/AABs generate providers from `widgets` in YAML; use registered URL schemes for `Entry.URL` and `Style.Link`, `Image` for portable artwork, and allow background transitions to follow Android's inexact alarm schedule. [Widgets](https://nsgo.dev/docs/widgets.md). - `base/terminal` renders Kitty RGB/RGBA/PNG images with `Options.ImageLimit` (zero: 64 MiB; negative: disabled), search colors through `Theme.Search`, `SearchText`, `SearchSelected`, `SearchSelectedText`, and Alt/Option-click cursor movement in an active OSC 133 command input. Apps provide shell integration markers; NSGo installs no scripts. [Terminal](https://nsgo.dev/docs/components.md#terminal) - On Windows and Linux, `cx.AuthSession` with `AuthSessionOptions.Scheme` needs the same `url_schemes` declaration in `nsgo.yaml`; leave `Scheme` empty for loopback. Keep PKCE and state validation in the app, give browser sessions a timeout or cancel button, and use distinct callback paths for simultaneous sessions. +- `base/terminal` runs browser sessions through `Options.Conn` (`io.ReadWriteCloser`); adapt WebSocket messages to a continuous binary stream, own its server/control protocol, and close the session with the scope. Browser builds embed libghostty-vt Wasm and need no native library or Zig installation. [Terminal](https://nsgo.dev/docs/terminal.md). - Use `ui.ShellTab.TextFunc` and `ui.TabShell.LabelFunc` for a changing tab title and bar name, and set `Edge` (`mobile.TabBarLeading`, `mobile.TabBarTrailing` or `mobile.TabBarAutomatic`, reading `core.Env.VerticalBarEdge`) on `mobile.TabBar` or `ui.TabShell` to place the bar vertically along an edge. - Set `tabBarBackground`, `tabBarIdle`, `tabBarSelected` and `tabBarIndicator` as Android `mobile.TabBar` palette roles. A custom palette uses `Accent` for selected content by default. diff --git a/tools/libghostty/main.go b/tools/libghostty/main.go index 98af1e3466..3e60a3bd89 100644 --- a/tools/libghostty/main.go +++ b/tools/libghostty/main.go @@ -1,7 +1,4 @@ -// Command libghostty builds libghostty-vt, Ghostty's terminal emulator as -// a library, for every target base/terminal runs on, desktops and iOS, from -// Ghostty's sources at the commit it binds, and writes the themes that -// Ghostty ships. Run it on a Mac with Xcode, from the repository's root: +// Command libghostty builds libghostty-vt, Ghostty's terminal emulator as a library, for every target base/terminal runs on, desktops, iOS and the browser, from Ghostty's sources at the commit it binds, and writes the themes that Ghostty ships. Run it on a Mac with Xcode, from the repository's root: // // go run ./tools/libghostty // @@ -47,6 +44,7 @@ type libraryTarget struct { } var targets = []libraryTarget{ + {"js", "wasm", "wasm32-freestanding", "ghostty-vt.wasm", "bin/ghostty-vt.wasm"}, {"darwin", "arm64", "aarch64-macos", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, {"darwin", "amd64", "x86_64-macos", "libghostty-vt.dylib", "lib/libghostty-vt.dylib"}, // The glibc of Debian 10 and Ubuntu 20.04, and later. @@ -96,7 +94,18 @@ func buildLibraries(src, zig string, selected []libraryTarget) { } defer os.RemoveAll(prefix) log.Printf("building %s/%s", t.goos, t.goarch) - run(src, zig, "build", "-Demit-lib-vt", "-Dtarget="+t.zig, "-Doptimize=ReleaseFast", "-Dstrip=true", "--prefix", prefix) + optimize := "ReleaseFast" + buildSource := src + if t.goos == "js" { + optimize = "ReleaseSmall" + var cleanup func() + buildSource, cleanup, err = wasmSource(src) + if err != nil { + log.Fatal(err) + } + defer cleanup() + } + run(buildSource, zig, "build", "-Demit-lib-vt", "-Dtarget="+t.zig, "-Doptimize="+optimize, "-Dstrip=true", "--prefix", prefix) built := filepath.Join(prefix, t.built) if t.goos == "linux" { // The build keeps the debug information of ELF libraries, @@ -108,6 +117,11 @@ func buildLibraries(src, zig string, selected []libraryTarget) { log.Fatal(err) } log.Printf(" %s %s", dst, copyFile(built, dst)) + if t.goos == "js" { + if err := writeWasmLicense(buildSource, zig); err != nil { + log.Fatal(err) + } + } } } diff --git a/tools/libghostty/main_test.go b/tools/libghostty/main_test.go index d94cc0a5ee..886a4d75c8 100644 --- a/tools/libghostty/main_test.go +++ b/tools/libghostty/main_test.go @@ -7,12 +7,12 @@ import ( ) func TestSelectLibraryTargets(t *testing.T) { - selected, err := selectTargets("iossimulator-amd64,ioscatalyst-arm64,iossimulator-amd64") - if err != nil || len(selected) != 2 { + selected, err := selectTargets("js-wasm,iossimulator-amd64,ioscatalyst-arm64,js-wasm") + if err != nil || len(selected) != 3 { t.Fatalf("selected %v: %v", selected, err) } - if selected[0].zig != "x86_64-ios-simulator" || selected[1].zig != "aarch64-maccatalyst" { - t.Fatalf("wrong Apple targets: %+v", selected) + if selected[0].zig != "wasm32-freestanding" || selected[1].zig != "x86_64-ios-simulator" || selected[2].zig != "aarch64-maccatalyst" { + t.Fatalf("wrong browser/native targets: %+v", selected) } if _, err := selectTargets("missing-arm64"); err == nil { t.Error("unknown target accepted") diff --git a/tools/libghostty/wasm.go b/tools/libghostty/wasm.go new file mode 100644 index 0000000000..27d1b60fcb --- /dev/null +++ b/tools/libghostty/wasm.go @@ -0,0 +1,146 @@ +package main + +import ( + "archive/tar" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" +) + +// wasmSource prepares the pinned source in an independent temporary tree. The pinned release disables graphics on freestanding targets. The browser has the C API's PNG/entropy effects, but no files: enable graphics and reject file-based image media. Native builds and the checkout remain unchanged. +func wasmSource(src string) (string, func(), error) { + dir, err := os.MkdirTemp("", "libghostty-wasm-source-") + if err != nil { + return "", nil, err + } + cleanup := func() { os.RemoveAll(dir) } + fail := func(err error) (string, func(), error) { cleanup(); return "", nil, err } + cmd := exec.Command("git", "-C", src, "archive", "--format=tar", commit) + pipe, err := cmd.StdoutPipe() + if err != nil { + return fail(err) + } + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + return fail(err) + } + r := tar.NewReader(pipe) + var extractErr error + for { + h, err := r.Next() + if err == io.EOF { + break + } + if err != nil { + extractErr = err + break + } + if !filepath.IsLocal(h.Name) { + extractErr = fmt.Errorf("non-local source path %q", h.Name) + break + } + path := filepath.Join(dir, filepath.FromSlash(h.Name)) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + extractErr = err + break + } + switch h.Typeflag { + case tar.TypeXGlobalHeader, tar.TypeXHeader: + continue + case tar.TypeDir: + extractErr = os.MkdirAll(path, 0o755) + case tar.TypeReg: + var f *os.File + f, extractErr = os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_EXCL, os.FileMode(h.Mode)&0o777) + if extractErr == nil { + _, extractErr = io.Copy(f, r) + if err := f.Close(); extractErr == nil { + extractErr = err + } + } + case tar.TypeSymlink: + if !filepath.IsLocal(filepath.Join(filepath.Dir(h.Name), h.Linkname)) { + extractErr = fmt.Errorf("non-local source link %q", h.Linkname) + } else { + extractErr = os.Symlink(h.Linkname, path) + } + default: + extractErr = fmt.Errorf("unsupported source archive entry %q", h.Name) + } + if extractErr != nil { + break + } + } + if extractErr != nil { + cmd.Process.Kill() + } + waitErr := cmd.Wait() + if extractErr != nil { + return fail(extractErr) + } + if waitErr != nil { + return fail(waitErr) + } + patches := []struct{ path, before, after string }{ + {"src/terminal/build_options.zig", "if (target.os.tag == .freestanding) return false;", "if (target.os.tag == .freestanding and !target.cpu.arch.isWasm()) return false;"}, + {"src/terminal/kitty/graphics_image.zig", "else => @compileError(\"readFile only supports file and temporary_file\"),\n }", "else => @compileError(\"readFile only supports file and temporary_file\"),\n }\n if (comptime builtin.os.tag == .freestanding) return error.UnsupportedMedium;"}, + } + for _, patch := range patches { + path := filepath.Join(dir, patch.path) + data, err := os.ReadFile(path) + if err != nil { + return fail(err) + } + if strings.Count(string(data), patch.before) != 1 { + return fail(fmt.Errorf("pinned browser patch no longer applies to %s", patch.path)) + } + if err := os.WriteFile(path, []byte(strings.Replace(string(data), patch.before, patch.after, 1)), 0o644); err != nil { + return fail(err) + } + } + return dir, cleanup, nil +} + +// writeWasmLicense retains the notices of code linked into the browser module. +func writeWasmLicense(src, zig string) error { + wuffs, err := filepath.Glob(filepath.Join(src, "zig-pkg", "*", "release", "c", "wuffs-v0.4.c")) + if err != nil || len(wuffs) != 1 { + return fmt.Errorf("locate pinned Wuffs license: %v (%d matches)", err, len(wuffs)) + } + zigPath, err := exec.LookPath(zig) + if err != nil { + return err + } + zigPath, err = filepath.EvalSymlinks(zigPath) + if err != nil { + return err + } + zigNotice := "" + for dir, depth := filepath.Dir(zigPath), 0; depth < 3; dir, depth = filepath.Dir(dir), depth+1 { + path := filepath.Join(dir, "LICENSE") + if data, err := os.ReadFile(path); err == nil && strings.Contains(string(data), "Zig contributors") { + zigNotice = path + break + } + } + if zigNotice == "" { + return fmt.Errorf("cannot locate the Zig distribution's LICENSE beside %s", zigPath) + } + files := []struct{ name, path string }{ + {"Ghostty", filepath.Join(src, "LICENSE")}, + {"Zig standard library", zigNotice}, + {"Wuffs", filepath.Join(filepath.Dir(filepath.Dir(filepath.Dir(wuffs[0]))), "LICENSE-MIT")}, + } + var out strings.Builder + for _, file := range files { + data, err := os.ReadFile(file.path) + if err != nil { + return err + } + fmt.Fprintf(&out, "%s\n\n%s\n\n", file.name, strings.TrimSpace(string(data))) + } + return os.WriteFile(filepath.Join(filepath.Dir(libDir), "LICENSE"), []byte(strings.TrimSpace(out.String())+"\n"), 0o644) +} diff --git a/tsx/terminal/terminal.go b/tsx/terminal/terminal.go index fdbc3ad70e..5013e00636 100644 --- a/tsx/terminal/terminal.go +++ b/tsx/terminal/terminal.go @@ -29,8 +29,7 @@ type Terminal struct { OnTitle func(title string) OnExit func(code int) OnBell func() - // Unavailable renders where no terminal can run, as on the web, with - // why. + // Unavailable renders when its session cannot start, such as a browser session without Conn, with why. Unavailable func(message string) core.Node // The view, as terminal.View: Theme and DarkTheme name Ghostty's