From d70713d9ae372d1644e9cde0632793fcbd2ec795 Mon Sep 17 00:00:00 2001 From: dawn <90008@klbr.net> Date: Thu, 22 Oct 2026 02:00:16 +0300 Subject: [PATCH] tui: hold cell styles and links by reference through a patched ultraviolet cli/third_party/ultraviolet is the fork go.mod pinned plus ultraviolet.patch: a cell points at one shared record per distinct style and link instead of carrying them, 112 -> 40 bytes, so a 200x50 screen buffer goes 1.25 -> 0.43 MB. the bytes written to the terminal are unchanged (goldens from stock). Signed-off-by: dawn <90008@klbr.net> --- cli/go.mod | 3 +- .../testdata/ultraviolet_frames.golden | 22 + .../terminal/ultraviolet_render_test.go | 224 ++ cli/third_party/ultraviolet.patch | 427 ++++ cli/third_party/ultraviolet/LICENSE | 21 + cli/third_party/ultraviolet/README.md | 170 ++ cli/third_party/ultraviolet/TUTORIAL.md | 175 ++ cli/third_party/ultraviolet/border.go | 238 ++ cli/third_party/ultraviolet/buffer.go | 868 +++++++ .../ultraviolet/cancelreader_other.go | 16 + .../ultraviolet/cancelreader_windows.go | 139 ++ cli/third_party/ultraviolet/cell.go | 518 ++++ cli/third_party/ultraviolet/console.go | 219 ++ cli/third_party/ultraviolet/console_unix.go | 13 + .../ultraviolet/console_windows.go | 13 + cli/third_party/ultraviolet/cursor.go | 22 + cli/third_party/ultraviolet/decoder.go | 2117 +++++++++++++++++ cli/third_party/ultraviolet/doc.go | 46 + cli/third_party/ultraviolet/environ.go | 32 + cli/third_party/ultraviolet/event.go | 567 +++++ cli/third_party/ultraviolet/go.mod | 24 + cli/third_party/ultraviolet/go.sum | 30 + .../ultraviolet/internal/casso/math.go | 172 ++ .../ultraviolet/internal/casso/solver.go | 275 +++ .../ultraviolet/internal/lru/lru.go | 69 + cli/third_party/ultraviolet/key.go | 762 ++++++ cli/third_party/ultraviolet/key_table.go | 664 ++++++ cli/third_party/ultraviolet/layout/cache.go | 29 + .../ultraviolet/layout/constraint.go | 174 ++ cli/third_party/ultraviolet/layout/flex.go | 210 ++ cli/third_party/ultraviolet/layout/layout.go | 973 ++++++++ cli/third_party/ultraviolet/layout/padding.go | 66 + cli/third_party/ultraviolet/logger.go | 6 + cli/third_party/ultraviolet/mouse.go | 150 ++ cli/third_party/ultraviolet/poll.go | 38 + cli/third_party/ultraviolet/poll_bsd.go | 165 ++ cli/third_party/ultraviolet/poll_default.go | 12 + cli/third_party/ultraviolet/poll_fallback.go | 158 ++ cli/third_party/ultraviolet/poll_linux.go | 175 ++ cli/third_party/ultraviolet/poll_select.go | 156 ++ cli/third_party/ultraviolet/poll_solaris.go | 12 + cli/third_party/ultraviolet/poll_windows.go | 217 ++ cli/third_party/ultraviolet/screen/context.go | 381 +++ cli/third_party/ultraviolet/screen/screen.go | 117 + cli/third_party/ultraviolet/styled.go | 498 ++++ cli/third_party/ultraviolet/tabstop.go | 142 ++ cli/third_party/ultraviolet/terminal.go | 408 ++++ cli/third_party/ultraviolet/terminal_bsdly.go | 10 + .../ultraviolet/terminal_bsdly_other.go | 8 + cli/third_party/ultraviolet/terminal_other.go | 22 + .../ultraviolet/terminal_reader.go | 526 ++++ .../ultraviolet/terminal_reader_other.go | 13 + .../ultraviolet/terminal_reader_windows.go | 336 +++ .../ultraviolet/terminal_renderer.go | 1917 +++++++++++++++ .../terminal_renderer_hardscroll.go | 229 ++ .../ultraviolet/terminal_renderer_hashmap.go | 298 +++ .../ultraviolet/terminal_screen.go | 836 +++++++ .../ultraviolet/terminal_tabdly.go | 10 + .../ultraviolet/terminal_tabdly_other.go | 8 + cli/third_party/ultraviolet/terminal_unix.go | 56 + .../ultraviolet/terminal_windows.go | 77 + cli/third_party/ultraviolet/tty.go | 42 + cli/third_party/ultraviolet/tty_other.go | 26 + cli/third_party/ultraviolet/tty_unix.go | 39 + cli/third_party/ultraviolet/tty_windows.go | 39 + cli/third_party/ultraviolet/utils.go | 15 + cli/third_party/ultraviolet/uv.go | 406 ++++ cli/third_party/ultraviolet/winch.go | 62 + cli/third_party/ultraviolet/winch_other.go | 17 + cli/third_party/ultraviolet/winch_unix.go | 50 + cli/third_party/ultraviolet/window.go | 147 ++ 71 files changed, 17121 insertions(+), 1 deletion(-) create mode 100644 cli/internal/terminal/testdata/ultraviolet_frames.golden create mode 100644 cli/internal/terminal/ultraviolet_render_test.go create mode 100644 cli/third_party/ultraviolet.patch create mode 100644 cli/third_party/ultraviolet/LICENSE create mode 100644 cli/third_party/ultraviolet/README.md create mode 100644 cli/third_party/ultraviolet/TUTORIAL.md create mode 100644 cli/third_party/ultraviolet/border.go create mode 100644 cli/third_party/ultraviolet/buffer.go create mode 100644 cli/third_party/ultraviolet/cancelreader_other.go create mode 100644 cli/third_party/ultraviolet/cancelreader_windows.go create mode 100644 cli/third_party/ultraviolet/cell.go create mode 100644 cli/third_party/ultraviolet/console.go create mode 100644 cli/third_party/ultraviolet/console_unix.go create mode 100644 cli/third_party/ultraviolet/console_windows.go create mode 100644 cli/third_party/ultraviolet/cursor.go create mode 100644 cli/third_party/ultraviolet/decoder.go create mode 100644 cli/third_party/ultraviolet/doc.go create mode 100644 cli/third_party/ultraviolet/environ.go create mode 100644 cli/third_party/ultraviolet/event.go create mode 100644 cli/third_party/ultraviolet/go.mod create mode 100644 cli/third_party/ultraviolet/go.sum create mode 100644 cli/third_party/ultraviolet/internal/casso/math.go create mode 100644 cli/third_party/ultraviolet/internal/casso/solver.go create mode 100644 cli/third_party/ultraviolet/internal/lru/lru.go create mode 100644 cli/third_party/ultraviolet/key.go create mode 100644 cli/third_party/ultraviolet/key_table.go create mode 100644 cli/third_party/ultraviolet/layout/cache.go create mode 100644 cli/third_party/ultraviolet/layout/constraint.go create mode 100644 cli/third_party/ultraviolet/layout/flex.go create mode 100644 cli/third_party/ultraviolet/layout/layout.go create mode 100644 cli/third_party/ultraviolet/layout/padding.go create mode 100644 cli/third_party/ultraviolet/logger.go create mode 100644 cli/third_party/ultraviolet/mouse.go create mode 100644 cli/third_party/ultraviolet/poll.go create mode 100644 cli/third_party/ultraviolet/poll_bsd.go create mode 100644 cli/third_party/ultraviolet/poll_default.go create mode 100644 cli/third_party/ultraviolet/poll_fallback.go create mode 100644 cli/third_party/ultraviolet/poll_linux.go create mode 100644 cli/third_party/ultraviolet/poll_select.go create mode 100644 cli/third_party/ultraviolet/poll_solaris.go create mode 100644 cli/third_party/ultraviolet/poll_windows.go create mode 100644 cli/third_party/ultraviolet/screen/context.go create mode 100644 cli/third_party/ultraviolet/screen/screen.go create mode 100644 cli/third_party/ultraviolet/styled.go create mode 100644 cli/third_party/ultraviolet/tabstop.go create mode 100644 cli/third_party/ultraviolet/terminal.go create mode 100644 cli/third_party/ultraviolet/terminal_bsdly.go create mode 100644 cli/third_party/ultraviolet/terminal_bsdly_other.go create mode 100644 cli/third_party/ultraviolet/terminal_other.go create mode 100644 cli/third_party/ultraviolet/terminal_reader.go create mode 100644 cli/third_party/ultraviolet/terminal_reader_other.go create mode 100644 cli/third_party/ultraviolet/terminal_reader_windows.go create mode 100644 cli/third_party/ultraviolet/terminal_renderer.go create mode 100644 cli/third_party/ultraviolet/terminal_renderer_hardscroll.go create mode 100644 cli/third_party/ultraviolet/terminal_renderer_hashmap.go create mode 100644 cli/third_party/ultraviolet/terminal_screen.go create mode 100644 cli/third_party/ultraviolet/terminal_tabdly.go create mode 100644 cli/third_party/ultraviolet/terminal_tabdly_other.go create mode 100644 cli/third_party/ultraviolet/terminal_unix.go create mode 100644 cli/third_party/ultraviolet/terminal_windows.go create mode 100644 cli/third_party/ultraviolet/tty.go create mode 100644 cli/third_party/ultraviolet/tty_other.go create mode 100644 cli/third_party/ultraviolet/tty_unix.go create mode 100644 cli/third_party/ultraviolet/tty_windows.go create mode 100644 cli/third_party/ultraviolet/utils.go create mode 100644 cli/third_party/ultraviolet/uv.go create mode 100644 cli/third_party/ultraviolet/winch.go create mode 100644 cli/third_party/ultraviolet/winch_other.go create mode 100644 cli/third_party/ultraviolet/winch_unix.go create mode 100644 cli/third_party/ultraviolet/window.go diff --git a/cli/go.mod b/cli/go.mod index 9f3b8576a..234737a1a 100644 --- a/cli/go.mod +++ b/cli/go.mod @@ -50,9 +50,10 @@ require ( golang.org/x/sync v0.23.0 // indirect ) -replace github.com/charmbracelet/ultraviolet => tangled.org/okami.mom/ultraviolet v0.0.0-20261007174847-7bfbaab9c98a +replace github.com/charmbracelet/ultraviolet => ./third_party/ultraviolet replace charm.land/glamour/v2 => tangled.org/okami.mom/glamour.git/v2 v2.0.0-20261013013552-052c391d9e1d // demand-driven painting, see third_party/bubbletea.patch replace charm.land/bubbletea/v2 => ./third_party/bubbletea + diff --git a/cli/internal/terminal/testdata/ultraviolet_frames.golden b/cli/internal/terminal/testdata/ultraviolet_frames.golden new file mode 100644 index 000000000..3e7deb283 --- /dev/null +++ b/cli/internal/terminal/testdata/ultraviolet_frames.golden @@ -0,0 +1,22 @@ +"\r\x1b[Jhello world\r\nsecond line|render|hello world \nsecond line \n |lines|hello world\nsecond line\n" +"\r\x1b[A\x1b[31mred\x1b[m \x1b[38;5;208morange\x1b[m \x1b[38;2;12;34;56mtruecolor\x1b[m\r\n\x1b[44mblue bg\x1b[m \x1b[48;5;236mdark bg\x1b[m \x1b[48;2;1;2;3mrgb bg\x1b[m|render|\x1b[31mred\x1b[m \x1b[38;5;208morange\x1b[m \x1b[38;2;12;34;56mtruecolor\x1b[m \n\x1b[44mblue bg\x1b[m \x1b[48;5;236mdark bg\x1b[m \x1b[48;2;1;2;3mrgb bg\x1b[m \n |lines|red orange truecolor\nblue bg dark bg rgb bg\n" +"\r\x1b[A\x1b[J\x1b[1mbold\x1b[m \x1b[2mfaint\x1b[m \x1b[3mitalic\x1b[m \x1b[7mreverse\x1b[m \x1b[9mstruck\x1b[m\r\n\x1b[4munderline\x1b[m \x1b[4:2mdouble\x1b[m \x1b[4:3mcurly\x1b[m \x1b[4:4mdotted\x1b[m \x1b[4:5mdashed\x1b[m\r\n\x1b[58;5;93munderline color\x1b[m \x1b[31;1;3;4mmixed\x1b[m\r\n|render|\x1b[1mbold\x1b[m \x1b[2mfaint\x1b[m \x1b[3mitalic\x1b[m \x1b[7mreverse\x1b[m \x1b[9mstruck\x1b[m \n\x1b[4munderline\x1b[m \x1b[4:2mdouble\x1b[m \x1b[4:3mcurly\x1b[m \x1b[4:4mdotted\x1b[m \x1b[4:5mdashed\x1b[m \n\x1b[58;5;93munderline color\x1b[m \x1b[31;1;3;4mmixed\x1b[m \n |lines|bold faint italic reverse struck\nunderline double curly dotted dashed\nunderline color mixed\n" +"\x1b[3A\x1b]8;;https://example.com/a\alinked text\x1b]8;;\a plain\x1b[K\r\n\x1b[32m\x1b]8;id=42;https://example.com/b\agreen link\x1b[m still linked\x1b]8;;\a\x1b[K\r\n\x1b]8;;https://example.com/c\afirst\x1b]8;;https://example.com/d\asecond\x1b]8;;\a\x1b[K|render|\x1b]8;;https://example.com/a\alinked text\x1b]8;;\a plain \n\x1b[32m\x1b]8;id=42;https://example.com/b\agreen link\x1b[m still linked\x1b]8;;\a \n\x1b]8;;https://example.com/c\afirst\x1b]8;;\a\x1b]8;;https://example.com/d\asecond\x1b]8;;\a \n |lines|linked text plain\ngreen link still linked\nfirstsecond\n" +"\r\x1b[2A\x1b[J\x1b[?7l\x1b[K漢字とかな mixed ascii 漢\x1b[?7h\x1b[26G\x1b[?7l\r\n\x1b[Kemoji 🙂 👍🏽 done\x1b[?7h\x1b[19G\x1b[?7l\r\n\x1b[Kfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyph\x1b[?7h\x1b[32G\x1b[?7l\r\n\x1b[Kflags 🇯🇵 🇺🇸 pair\x1b[?7h\x1b[17G\r\ncombining á ë ñ\x1b[?7l\r\n\x1b[Kselector 漢️ text\x1b[?7h\x1b[17G\r\n|render|漢字とかな mixed ascii 漢 \nemoji 🙂 👍🏽 done \nfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyph \nflags 🇯🇵 🇺🇸 pair \ncombining á ë ñ \nselector 漢️ text \n |lines|漢字とかな mixed ascii 漢\nemoji 🙂 👍🏽 done\nfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyph\nflags 🇯🇵 🇺🇸 pair\ncombining á ë ñ\nselector 漢️ text\n" +"\x1b[6A\x1b[Jwide line: abcdefghijabcdefghijabcdefghijabcdefghijabcdefghi\r\n|render|wide line: abcdefghijabcdefghijabcdefghijabcdefghijabcdefghi\n |lines|wide line: abcdefghijabcdefghijabcdefghijabcdefghijabcdefghi\n" +"\x1b[A\x1b[J╭─────┬─────╮\r\n│ one │ two │\r\n╰─────┴─────╯\r\n────────────────────────────────────────────────────────────\r\n|render|╭─────┬─────╮ \n│ one │ two │ \n╰─────┴─────╯ \n────────────────────────────────────────────────────────────\n |lines|╭─────┬─────╮\n│ one │ two │\n╰─────┴─────╯\n────────────────────────────────────────────────────────────\n" +"\x1b[4Apadded\x1b[K\r\n\x1b[K\n\x1b[K\n\x1b[4C\x1b[1K indented\x1b[K|render|padded \n \n \n indented \n |lines|padded\n\n\n indented\n" +"\r\x1b[3A\x1b[Jhello world\r\nsecond line\r\n|render|hello world \nsecond line \n |lines|hello world\nsecond line\n" +"\x1b[2A\x1b[31mred\x1b[m \x1b[38;5;208morange\x1b[m \x1b[38;2;12;34;56mtruecolor\x1b[m\r\n\x1b[44mblue bg\x1b[m \x1b[48;5;236mdark bg\x1b[m \x1b[48;2;1;2;3mrgb bg\x1b[m|render|\x1b[31mred\x1b[m \x1b[38;5;208morange\x1b[m \x1b[38;2;12;34;56mtruecolor\x1b[m \n\x1b[44mblue bg\x1b[m \x1b[48;5;236mdark bg\x1b[m \x1b[48;2;1;2;3mrgb bg\x1b[m \n |lines|red orange truecolor\nblue bg dark bg rgb bg\n" +"\r\x1b[A\x1b[J\x1b]8;;https://example.com/a\alinked text\x1b]8;;\a plain\r\n\x1b[32m\x1b]8;id=42;https://example.com/b\agreen link\x1b[m still linked\x1b]8;;\a\r\n\x1b]8;;https://example.com/c\afirst\x1b]8;;https://example.com/d\asecond\x1b]8;;\a\r\n|render|\x1b]8;;https://example.com/a\alinked text\x1b]8;;\a plain \n\x1b[32m\x1b]8;id=42;https://example.com/b\agreen link\x1b[m still linked\x1b]8;;\a \n\x1b]8;;https://example.com/c\afirst\x1b]8;;\a\x1b]8;;https://example.com/d\asecond\x1b]8;;\a \n |lines|linked text plain\ngreen link still linked\nfirstsecond\n" +"" +"\x1b[3A\x1b[Jhello world\r\nsecond line\r\n|render|hello world \nsecond line \n |lines|hello world\nsecond line\n" +"\x1b[2A\x1b[J\x1b[?7l\x1b[K漢字とかな mixed ascii 漢\x1b[?7h\x1b[26G\x1b[?7l\r\n\x1b[Kemoji 🙂 👍🏽 done\x1b[?7h\x1b[19G\x1b[?7l\r\n\x1b[Kfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyp\x1b[?7h\x1b[?7l\r\n\x1b[Kflags 🇯🇵 🇺🇸 pair\x1b[?7h\x1b[17G\r\n|render|漢字とかな mixed ascii 漢 \nemoji 🙂 👍🏽 done \nfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyp\nflags 🇯🇵 🇺🇸 pair \n |lines|漢字とかな mixed ascii 漢\nemoji 🙂 👍🏽 done\nfamily 👨\u200d👩\u200d👧\u200d👦 stays one glyp\nflags 🇯🇵 🇺🇸 pair\n" +"\x1b[4A\x1b[Jwide line: abcdefghijabcdefghi\r\n|render|wide line: abcdefghijabcdefghi\n |lines|wide line: abcdefghijabcdefghi\n" +"" +"\x1b[A\x1b[J╭─────┬─────╮\r\n│ one │ two │\r\n╰─────┴─────╯\r\n────────────────────────────────────────────────────────────\r\n|render|╭─────┬─────╮ \n│ one │ two │ \n╰─────┴─────╯ \n──────────────────────────────────────────────────────────── \n |lines|╭─────┬─────╮\n│ one │ two │\n╰─────┴─────╯\n────────────────────────────────────────────────────────────\n" +"\x1b[4A\x1b[J\x1b[1mbold\x1b[m \x1b[2mfaint\x1b[m \x1b[3mitalic\x1b[m \x1b[7mreverse\x1b[m \x1b[9mstruck\x1b[m\r\n\x1b[4munderline\x1b[m \x1b[4:2mdouble\x1b[m \x1b[4:3mcurly\x1b[m \x1b[4:4mdotted\x1b[m \x1b[4:5mdashed\x1b[m\r\n\x1b[58;5;93munderline color\x1b[m \x1b[31;1;3;4mmixed\x1b[m\r\n|render|\x1b[1mbold\x1b[m \x1b[2mfaint\x1b[m \x1b[3mitalic\x1b[m \x1b[7mreverse\x1b[m \x1b[9mstruck\x1b[m \n\x1b[4munderline\x1b[m \x1b[4:2mdouble\x1b[m \x1b[4:3mcurly\x1b[m \x1b[4:4mdotted\x1b[m \x1b[4:5mdashed\x1b[m \n\x1b[58;5;93munderline color\x1b[m \x1b[31;1;3;4mmixed\x1b[m \n |lines|bold faint italic reverse struck\nunderline double curly dotted dashed\nunderline color mixed\n" +"" +"\x1b[3A\x1b[J\x1b[35mrow 21\x1b[m with \x1b]8;;https://example.com/21\aa link\x1b]8;;\a\r\n\x1b[36mrow 22\x1b[m with \x1b]8;;https://example.com/22\aa link\x1b]8;;\a\r\n\x1b[37mrow 23\x1b[m with \x1b]8;;https://example.com/23\aa link\x1b]8;;\a\r\n\x1b[30mrow 24\x1b[m with \x1b]8;;https://example.com/24\aa link\x1b]8;;\a\r\n\x1b[31mrow 25\x1b[m with \x1b]8;;https://example.com/25\aa link\x1b]8;;\a\r\n\x1b[32mrow 26\x1b[m with \x1b]8;;https://example.com/26\aa link\x1b]8;;\a\r\n\x1b[33mrow 27\x1b[m with \x1b]8;;https://example.com/27\aa link\x1b]8;;\a\r\n\x1b[34mrow 28\x1b[m with \x1b]8;;https://example.com/28\aa link\x1b]8;;\a\r\n\x1b[35mrow 29\x1b[m with \x1b]8;;https://example.com/29\aa link\x1b]8;;\a\r\n|render|\x1b[35mrow 21\x1b[m with \x1b]8;;https://example.com/21\aa link\x1b]8;;\a \n\x1b[36mrow 22\x1b[m with \x1b]8;;https://example.com/22\aa link\x1b]8;;\a \n\x1b[37mrow 23\x1b[m with \x1b]8;;https://example.com/23\aa link\x1b]8;;\a \n\x1b[30mrow 24\x1b[m with \x1b]8;;https://example.com/24\aa link\x1b]8;;\a \n\x1b[31mrow 25\x1b[m with \x1b]8;;https://example.com/25\aa link\x1b]8;;\a \n\x1b[32mrow 26\x1b[m with \x1b]8;;https://example.com/26\aa link\x1b]8;;\a \n\x1b[33mrow 27\x1b[m with \x1b]8;;https://example.com/27\aa link\x1b]8;;\a \n\x1b[34mrow 28\x1b[m with \x1b]8;;https://example.com/28\aa link\x1b]8;;\a \n\x1b[35mrow 29\x1b[m with \x1b]8;;https://example.com/29\aa link\x1b]8;;\a \n |lines|row 21 with a link\nrow 22 with a link\nrow 23 with a link\nrow 24 with a link\nrow 25 with a link\nrow 26 with a link\nrow 27 with a link\nrow 28 with a link\nrow 29 with a link\n" +"\x1b[9A\x1b[J|render| |lines|" +"\x1b[Jhello world\r\nsecond line\r\n|render|hello world \nsecond line \n |lines|hello world\nsecond line\n" diff --git a/cli/internal/terminal/ultraviolet_render_test.go b/cli/internal/terminal/ultraviolet_render_test.go new file mode 100644 index 000000000..0232d5490 --- /dev/null +++ b/cli/internal/terminal/ultraviolet_render_test.go @@ -0,0 +1,224 @@ +package terminal + +import ( + "fmt" + "os" + "regexp" + "strconv" + "strings" + "testing" + + uv "github.com/charmbracelet/ultraviolet" +) + +// the TUI's renderer diffs frames through ultraviolet, and cli/third_party +// replaces it with a copy whose cells are 40 bytes instead of 112 (see +// third_party/ultraviolet.patch). what a terminal receives must not change, +// so the copy is only worth keeping while it renders the same bytes: the +// goldens in testdata/ultraviolet_frames.golden were taken from the unpatched +// module, and every step of this script is compared against them byte for +// byte. +func TestUltravioletRendersLikeStock(t *testing.T) { + golden, err := os.ReadFile("testdata/ultraviolet_frames.golden") + if err != nil { + t.Fatal(err) + } + want := strings.Split(strings.TrimSuffix(string(golden), "\n"), "\n") + if len(want) != len(uvSteps) { + t.Fatalf("golden has %d steps, the script has %d", len(want), len(uvSteps)) + } + + term := newFrameTerminal(60, 20) + for i, step := range uvSteps { + quoted, err := strconv.Unquote(strings.TrimSpace(want[i])) + if err != nil { + t.Fatalf("golden step %d (%s): %v", i, step.name, err) + } + if step.width > 0 { + term.resize(step.width, step.height) + } + if step.flush { + term.flush(step.frame) + } + got := term.take() + if got != quoted { + t.Fatalf("step %d (%s) wrote\n got: %q\nwant: %q", i, step.name, got, quoted) + } + } +} + +// TestUltravioletIsThePatchedCopy catches a dependency bump that drops the +// replace and quietly restores 112-byte cells. +func TestUltravioletIsThePatchedCopy(t *testing.T) { + mod, err := os.ReadFile("../../go.mod") + if err != nil { + t.Fatal(err) + } + replace := regexp.MustCompile(`(?m)^replace github\.com/charmbracelet/ultraviolet => \./third_party/ultraviolet$`) + if !replace.Match(mod) { + t.Fatal("cli/go.mod no longer replaces ultraviolet with third_party/ultraviolet (see third_party/ultraviolet.patch)") + } +} + +// uvStep is one thing a renderer is asked to do: resize the terminal, draw a +// frame, or both, in the order the client does them. +type uvStep struct { + name string + width, height int // a resize, when width is set + flush bool + frame string +} + +// uvSteps is a script that covers what a frame can hold: colors in all three +// encodings, every attribute and underline style, hyperlinks (including one +// that spans a style change and one that changes mid-line), wide graphemes +// (CJK, emoji, ZWJ sequences, flags, combining marks, variation selectors), +// a line wider than the screen, box drawing, trailing spaces and blank lines, +// a restart of the same frames, two resizes, a frame taller than the screen +// and an empty frame. +var uvSteps = []uvStep{ + {name: "plain", flush: true, frame: "hello world\nsecond line\n"}, + {name: "colors", flush: true, frame: "\x1b[31mred\x1b[0m \x1b[38;5;208morange\x1b[0m \x1b[38;2;12;34;56mtruecolor\x1b[0m\n" + + "\x1b[44mblue bg\x1b[0m \x1b[48;5;236mdark bg\x1b[0m \x1b[48;2;1;2;3mrgb bg\x1b[0m\n"}, + {name: "attributes", flush: true, frame: "\x1b[1mbold\x1b[22m \x1b[2mfaint\x1b[22m \x1b[3mitalic\x1b[23m \x1b[7mreverse\x1b[27m \x1b[9mstruck\x1b[29m\n" + + "\x1b[4munderline\x1b[24m \x1b[4:2mdouble\x1b[24m \x1b[4:3mcurly\x1b[24m \x1b[4:4mdotted\x1b[24m \x1b[4:5mdashed\x1b[24m\n" + + "\x1b[58;5;93munderline color\x1b[59m \x1b[1;3;4;31mmixed\x1b[0m\n"}, + {name: "links", flush: true, frame: "\x1b]8;;https://example.com/a\x1b\\linked text\x1b]8;;\x1b\\ plain\n" + + "\x1b]8;id=42;https://example.com/b\x1b\\\x1b[32mgreen link\x1b[0m still linked\x1b]8;;\x1b\\\n" + + "\x1b]8;;https://example.com/c\x1b\\first\x1b]8;;https://example.com/d\x1b\\second\x1b]8;;\x1b\\\n"}, + {name: "wide graphemes", flush: true, frame: "漢字とかな mixed ascii 漢\n" + + "emoji 🙂 👍🏽 done\n" + + "family 👨\u200d👩\u200d👧\u200d👦 stays one glyph\n" + + "flags 🇯🇵 🇺🇸 pair\n" + + "combining a\u0301 e\u0308 n\u0303\n" + + "selector 漢\uFE0F text\n"}, + {name: "wide line", flush: true, frame: "wide line: " + strings.Repeat("abcdefghij", 12) + "\n"}, + {name: "box drawing", flush: true, frame: "╭─────┬─────╮\n│ one │ two │\n╰─────┴─────╯\n" + strings.Repeat("─", 60) + "\n"}, + {name: "padding", flush: true, frame: "padded \n\n\n indented\n"}, + {name: "repeat plain", flush: true, frame: "hello world\nsecond line\n"}, + {name: "repeat colors", flush: true, frame: "\x1b[31mred\x1b[0m \x1b[38;5;208morange\x1b[0m \x1b[38;2;12;34;56mtruecolor\x1b[0m\n" + + "\x1b[44mblue bg\x1b[0m \x1b[48;5;236mdark bg\x1b[0m \x1b[48;2;1;2;3mrgb bg\x1b[0m\n"}, + {name: "repeat links", flush: true, frame: "\x1b]8;;https://example.com/a\x1b\\linked text\x1b]8;;\x1b\\ plain\n" + + "\x1b]8;id=42;https://example.com/b\x1b\\\x1b[32mgreen link\x1b[0m still linked\x1b]8;;\x1b\\\n" + + "\x1b]8;;https://example.com/c\x1b\\first\x1b]8;;https://example.com/d\x1b\\second\x1b]8;;\x1b\\\n"}, + {name: "narrow resize", width: 30, height: 20}, + {name: "narrow plain", flush: true, frame: "hello world\nsecond line\n"}, + {name: "narrow wide graphemes", flush: true, frame: "漢字とかな mixed ascii 漢\n" + + "emoji 🙂 👍🏽 done\n" + + "family 👨\u200d👩\u200d👧\u200d👦 stays one glyph\n" + + "flags 🇯🇵 🇺🇸 pair\n"}, + {name: "narrow wide line", flush: true, frame: "wide line: " + strings.Repeat("abcdefghij", 12) + "\n"}, + {name: "wide resize", width: 80, height: 24}, + {name: "wide box drawing", flush: true, frame: "╭─────┬─────╮\n│ one │ two │\n╰─────┴─────╯\n" + strings.Repeat("─", 60) + "\n"}, + {name: "wide attributes", flush: true, frame: "\x1b[1mbold\x1b[22m \x1b[2mfaint\x1b[22m \x1b[3mitalic\x1b[23m \x1b[7mreverse\x1b[27m \x1b[9mstruck\x1b[29m\n" + + "\x1b[4munderline\x1b[24m \x1b[4:2mdouble\x1b[24m \x1b[4:3mcurly\x1b[24m \x1b[4:4mdotted\x1b[24m \x1b[4:5mdashed\x1b[24m\n" + + "\x1b[58;5;93munderline color\x1b[59m \x1b[1;3;4;31mmixed\x1b[0m\n"}, + {name: "short resize", width: 40, height: 10}, + {name: "tall frame", flush: true, frame: tallFrame()}, + {name: "empty frame", flush: true}, + {name: "plain again", flush: true, frame: "hello world\nsecond line\n"}, +} + +// tallFrame is 30 rows on a 10 row screen: the inline renderer draws the whole +// frame and shows its last rows. +func tallFrame() string { + var b strings.Builder + for i := range 30 { + fmt.Fprintf(&b, "\x1b[3%dmrow %d\x1b[0m with \x1b]8;;https://example.com/%d\x1b\\a link\x1b]8;;\x1b\\\n", i%8, i, i) + } + return b.String() +} + +// frameTerminal draws frames the way bubbletea v2's cursedRenderer.flush does +// and keeps every byte the renderer wrote, for the test to compare. +type frameTerminal struct { + width, height int + screen uv.ScreenBuffer + renderer *uv.TerminalRenderer + out strings.Builder +} + +func newFrameTerminal(width, height int) *frameTerminal { + // The environment a real client runs in: a 256-color terminal that reports + // true color. Detection reads it because the writer is not a tty. + env := []string{"TERM=xterm-256color", "COLORTERM=truecolor", "CLICOLOR_FORCE=1"} + t := &frameTerminal{width: width, height: height} + t.renderer = uv.NewTerminalRenderer(&t.out, env) + t.renderer.SetRelativeCursor(true) + t.renderer.SetFullscreen(false) + t.renderer.SetTabStops(-1) + t.renderer.SetScrollOptim(true) + t.renderer.Resize(width, height) + t.screen = uv.NewScreenBuffer(width, height) + return t +} + +func (t *frameTerminal) take() string { + got := t.out.String() + t.out.Reset() + return got +} + +func (t *frameTerminal) resize(width, height int) { + t.renderer.Erase() + t.width, t.height = width, height + t.renderer.Resize(width, height) + t.screen.Resize(width, height) +} + +// flush mirrors cursedRenderer.flush: an inline frame is as tall as its own +// content, so the screen buffer follows the frame height, and the rows above +// the terminal are dropped after drawing. +func (t *frameTerminal) flush(content string) { + styled := uv.NewStyledString(content) + frameHeight := t.height + if height := styled.Height(); height != frameHeight { + frameHeight = height + } + if t.screen.Width() != t.width || t.screen.Height() != frameHeight { + // A frame whose shape changed forces a full redraw, as the renderer + // does when its buffer no longer matches the frame area. + t.renderer.Erase() + t.screen.Touched = nil + t.screen.Resize(t.width, frameHeight) + } + t.screen.Clear() + styled.Draw(t.screen, t.screen.Bounds()) + if frameHeight > t.height { + drop := frameHeight - t.height + t.screen.Lines = t.screen.Lines[drop:] + t.screen.Touched = t.screen.Touched[drop:] + } + t.renderer.Render(t.screen.RenderBuffer) + _ = t.renderer.Flush() + // the renderer's own diff is not the only way a buffer reaches a string: + // lipgloss composes frames through Buffer.Render, so the line renderer is + // part of what a terminal receives. + fmt.Fprintf(&t.out, "|render|%s|lines|%s", t.screen.Render(), t.screen.String()) +} + +// TestUpdateUltravioletGoldens rewrites the goldens the comparison uses: one +// quoted line per step. It skips itself unless frameGolden is set, so the file +// can be regenerated from an unpatched build by dropping the replace, running +// that test, and putting the replace back. +const frameGolden = "UPDATE_UV_FRAMES" + +func TestUpdateUltravioletGoldens(t *testing.T) { + if os.Getenv(frameGolden) == "" { + t.Skip("set " + frameGolden + "=1 to rewrite testdata/ultraviolet_frames.golden") + } + var b strings.Builder + term := newFrameTerminal(60, 20) + for _, step := range uvSteps { + if step.width > 0 { + term.resize(step.width, step.height) + } + if step.flush { + term.flush(step.frame) + } + fmt.Fprintf(&b, "%s\n", strconv.Quote(term.take())) + } + if err := os.WriteFile("testdata/ultraviolet_frames.golden", []byte(b.String()), 0o644); err != nil { + t.Fatal(err) + } +} diff --git a/cli/third_party/ultraviolet.patch b/cli/third_party/ultraviolet.patch new file mode 100644 index 000000000..03d048456 --- /dev/null +++ b/cli/third_party/ultraviolet.patch @@ -0,0 +1,427 @@ +ultraviolet v0.0.0-20261007174847 (tangled.org/okami.mom/ultraviolet), with +40-byte cells instead of 112-byte ones. + +a cell was a 16-byte content string, a 56-byte Style holding three color +interfaces, a 32-byte Link holding two strings, and the width. the screen is a +cell per column and row, so at 200x50 the screen is 10000 cells: 1.1MB while +only a handful of styles appear on it, and bubbletea's frame buffer (sized to +the content, not the screen) was 3.1MB by itself. + +a cell now holds its style and link by pointer, one record per distinct style: +a parse interns one record per distinct style, a border shares one per side, and a +nil pointer is the zero style, so a cell with no style is still the zero Cell. +cells are 40 bytes: the 200x50 screen is 400KB. + +a parse interns the records it hands out, so a frame allocates one small +record per distinct style it uses (about ten for a chat frame, 1.2KB) where it +allocated none before: that is the price of the 72 bytes it saves per cell. + +what a renderer writes is unchanged. the pen in renderLine and in +TerminalRenderer is still a value, and a zero style is still written as the +reset it always was. cli/internal/terminal/ultraviolet_render_test.go renders a +scripted sequence of frames through this build and compares the bytes with +goldens taken from the unpatched one. one thing to know when reading the code: +`Cell == Cell` compares the style pointers, so compare cells with Cell.Equal; +Style.IsZero and Link.IsZero take a nil pointer as the zero value. + +to bump ultraviolet: copy the new version over third_party/ultraviolet, drop +its tests and CI files, and apply this patch (patch -p1 -d third_party/ultraviolet +< third_party/ultraviolet.patch). the fork's own tests need a `&` on any cell +literal that sets Style or Link; they were run that way against this diff. + +--- a/border.go ++++ b/border.go +@@ -190,26 +190,33 @@ + + // Draw draws the border around the given component. + func (b *Border) Draw(scr Screen, area Rectangle) { ++ // A side is the same cell along its whole run, and a screen copies the ++ // cells it is given, so one cell per side is enough. ++ top, bottom := borderCell(scr, &b.Top), borderCell(scr, &b.Bottom) ++ left, right := borderCell(scr, &b.Left), borderCell(scr, &b.Right) ++ topLeft, topRight := borderCell(scr, &b.TopLeft), borderCell(scr, &b.TopRight) ++ bottomLeft, bottomRight := borderCell(scr, &b.BottomLeft), borderCell(scr, &b.BottomRight) ++ + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x++ { + var cell *Cell + switch { + case y == area.Min.Y && x == area.Min.X: +- cell = borderCell(scr, &b.TopLeft) ++ cell = topLeft + case y == area.Min.Y && x == area.Max.X-1: +- cell = borderCell(scr, &b.TopRight) ++ cell = topRight + case y == area.Max.Y-1 && x == area.Min.X: +- cell = borderCell(scr, &b.BottomLeft) ++ cell = bottomLeft + case y == area.Max.Y-1 && x == area.Max.X-1: +- cell = borderCell(scr, &b.BottomRight) ++ cell = bottomRight + case y == area.Min.Y: +- cell = borderCell(scr, &b.Top) ++ cell = top + case y == area.Max.Y-1: +- cell = borderCell(scr, &b.Bottom) ++ cell = bottom + case x == area.Min.X: +- cell = borderCell(scr, &b.Left) ++ cell = left + case x == area.Max.X-1: +- cell = borderCell(scr, &b.Right) ++ cell = right + default: + continue + } +@@ -224,8 +231,8 @@ + func borderCell(scr Screen, b *Side) *Cell { + c := NewCell(scr.WidthMethod(), b.Content) + if c != nil { +- c.Style = b.Style +- c.Link = b.Link ++ c.Style = StyleRef(b.Style) ++ c.Link = LinkRef(b.Link) + } + return c + } +--- a/buffer.go ++++ b/buffer.go +@@ -164,24 +164,30 @@ + pending.Reset() + } + +- if c.Style.IsZero() && !pen.IsZero() { ++ // A cell shares its style and link records with every cell that has ++ // the same ones, so render from a copy: the pen is a value, and the ++ // sequence written is the one a cell's own style and link always were. ++ style := styleValue(c.Style) ++ cellLink := linkValue(c.Link) ++ ++ if style.IsZero() && !pen.IsZero() { + _, _ = buf.WriteString(ansi.ResetStyle) + pen = Style{} + } +- if !c.Style.Equal(&pen) { +- seq := c.Style.Diff(&pen) ++ if !style.Equal(&pen) { ++ seq := style.Diff(&pen) + _, _ = buf.WriteString(seq) +- pen = c.Style ++ pen = style + } + + // Write the URL escape sequence +- if c.Link != link && link.URL != "" { ++ if cellLink != link && link.URL != "" { + _, _ = buf.WriteString(ansi.ResetHyperlink()) + link = Link{} + } +- if c.Link != link { +- _, _ = buf.WriteString(ansi.SetHyperlink(c.Link.URL, c.Link.Params)) +- link = c.Link ++ if cellLink != link { ++ _, _ = buf.WriteString(ansi.SetHyperlink(cellLink.URL, cellLink.Params)) ++ link = cellLink + } + + _, _ = buf.WriteString(c.String()) +--- a/cell.go ++++ b/cell.go +@@ -12,23 +12,62 @@ + var EmptyCell = Cell{Content: " ", Width: 1} + + // Cell represents a single cell in the terminal screen. ++// ++// A screen is a cell per column and row, so what a cell costs is what a screen ++// costs. Style and Link are therefore shared records rather than values: every ++// cell that has the same style points at the same one, and a nil pointer is ++// the zero style or link, which is what most cells have. + type Cell struct { + // Content is the [Cell]'s content, which consists of a single grapheme + // cluster. Most of the time, this will be a single rune as well, but it + // can also be a combination of runes that form a grapheme cluster. + Content string + +- // The style of the cell. Nil style means no style. Zero value prints a +- // reset sequence. +- Style Style ++ // The style of the cell, shared with every cell that has the same one. A ++ // nil style means no style. Zero value prints a reset sequence. ++ Style *Style + +- // Link is the hyperlink of the cell. +- Link Link ++ // Link is the hyperlink of the cell, shared like [Cell.Style]. ++ Link *Link + + // Width is the mono-spaced width of the grapheme cluster. + Width int + } + ++// StyleRef returns the style record for a cell: nil for the zero style, so a ++// cell with no style stays the zero [Cell], and a fresh record otherwise. ++// Cells that have the same style can share one record. ++func StyleRef(style Style) *Style { ++ if style.IsZero() { ++ return nil ++ } ++ return &style ++} ++ ++// LinkRef returns the link record for a cell, like [StyleRef]. ++func LinkRef(link Link) *Link { ++ if link.IsZero() { ++ return nil ++ } ++ return &link ++} ++ ++// styleValue is the style a cell holds, with a nil style as the zero one. ++func styleValue(style *Style) Style { ++ if style == nil { ++ return Style{} ++ } ++ return *style ++} ++ ++// linkValue is the link a cell holds, with a nil link as the zero one. ++func linkValue(link *Link) Link { ++ if link == nil { ++ return Link{} ++ } ++ return *link ++} ++ + // NewCell creates a new cell from the given string grapheme. It will only use + // the first grapheme in the string and ignore the rest. The width of the cell + // is determined using the given width method. +@@ -56,13 +95,13 @@ + return o != nil && + c.Width == o.Width && + c.Content == o.Content && +- c.Style.Equal(&o.Style) && +- c.Link.Equal(&o.Link) ++ c.Style.Equal(o.Style) && ++ c.Link.Equal(o.Link) + } + + // IsZero returns whether the cell is an empty cell. + func (c *Cell) IsZero() bool { +- return *c == Cell{} ++ return c.Width == 0 && c.Content == "" && c.Style.IsZero() && c.Link.IsZero() + } + + // isWidePlaceholder reports whether the cell is the continuation column of a +@@ -101,17 +140,27 @@ + + // String returns a string representation of the hyperlink. + func (h *Link) String() string { ++ if h == nil { ++ return "" ++ } + return h.URL + } + +-// Equal returns whether the hyperlink is equal to the other hyperlink. ++// Equal returns whether the hyperlink is equal to the other hyperlink. A nil ++// link is the zero link. + func (h *Link) Equal(o *Link) bool { +- return o != nil && *h == *o ++ if h == o { ++ return true ++ } ++ if h == nil || o == nil { ++ return h.IsZero() && o.IsZero() ++ } ++ return *h == *o + } + +-// IsZero returns whether the hyperlink is empty. ++// IsZero returns whether the hyperlink is empty. A nil link is empty. + func (h *Link) IsZero() bool { +- return *h == Link{} ++ return h == nil || *h == Link{} + } + + // These are the available text attributes that can be combined to create +@@ -175,8 +224,12 @@ + Attrs uint8 + } + +-// Equal returns true if the style is equal to the other style. ++// Equal returns true if the style is equal to the other style. A nil style is ++// the zero style. + func (s *Style) Equal(o *Style) bool { ++ if s == nil || o == nil { ++ return s.IsZero() && o.IsZero() ++ } + return s.Attrs == o.Attrs && + s.Underline == o.Underline && + colorEqual(s.Fg, o.Fg) && +@@ -425,9 +478,9 @@ + return cr == or && cg == og && cb == ob && ca == oa + } + +-// IsZero returns true if the style is empty. ++// IsZero returns true if the style is empty. A nil style is empty. + func (s *Style) IsZero() bool { +- return *s == Style{} ++ return s == nil || *s == Style{} + } + + // ConvertStyle converts a style to respect the given color profile. +--- a/screen/context.go ++++ b/screen/context.go +@@ -336,6 +336,8 @@ + return x, y + } + ++ // The cells share one style and one link record for the whole draw. ++ stylep, linkp := uv.StyleRef(style), uv.LinkRef(link) + wm := scr.WidthMethod() + for grs.Next() { + gr := string(grs.Value()) +@@ -364,8 +366,8 @@ + scr.SetCell(x, y, &uv.Cell{ + Content: gr, + Width: w, +- Style: style, +- Link: link, ++ Style: stylep, ++ Link: linkp, + }) + + x += w +--- a/styled.go ++++ b/styled.go +@@ -145,6 +145,48 @@ + return n >= 2 && seq[n-1] == '\\' && seq[n-2] == ansi.ESC + } + ++// cellAttrs shares the style and link records a parse hands out. A string ++// repeats the same few styles across its cells, so a parse allocates one ++// record per style rather than per cell, and a string with no escapes ++// allocates none at all. ++type cellAttrs struct { ++ styles map[Style]*Style ++ links map[Link]*Link ++} ++ ++// style returns the shared record for style, creating it the first time this ++// parse sees it. ++func (a *cellAttrs) style(style Style) *Style { ++ if style.IsZero() { ++ return nil ++ } ++ if a.styles == nil { ++ a.styles = make(map[Style]*Style) ++ } ++ if shared, ok := a.styles[style]; ok { ++ return shared ++ } ++ shared := StyleRef(style) ++ a.styles[style] = shared ++ return shared ++} ++ ++// link returns the shared record for link, like [cellAttrs.style]. ++func (a *cellAttrs) link(link Link) *Link { ++ if link.IsZero() { ++ return nil ++ } ++ if a.links == nil { ++ a.links = make(map[Link]*Link) ++ } ++ if shared, ok := a.links[link]; ok { ++ return shared ++ } ++ shared := LinkRef(link) ++ a.links[link] = shared ++ return shared ++} ++ + func printString[T []byte | string]( + s Screen, + m WidthMethod, +@@ -174,6 +216,9 @@ + var cell Cell + var style Style + var link Link ++ var attrs cellAttrs ++ var stylep *Style ++ var linkp *Link + var state byte + lastX, lastY := -1, -1 // last cell written, for folding in combining marks + var pending []byte // pass-through sequences awaiting a cell to ride on +@@ -205,8 +250,8 @@ + cell.Content = string(pending) + pending = pending[:0] + } +- cell.Style = style +- cell.Link = link ++ cell.Style = stylep ++ cell.Link = linkp + + if s == nil { + // Building lines: unwrapped, no bounds +@@ -229,8 +274,8 @@ + if truncate && tailc.Width > 0 && x+cell.Width > bounds.Max.X-tailc.Width { + // Truncate the string and append the tail if any. + cell = tailc +- cell.Style = style +- cell.Link = link ++ cell.Style = stylep ++ cell.Link = linkp + s.SetCell(x, y, &cell) + lastX, lastY = x, y + x += tailc.Width +@@ -252,9 +297,11 @@ + case ansi.HasCsiPrefix(seq) && p.Command() == 'm': + // SGR - Select Graphic Rendition + ReadStyle(p.Params(), &style) ++ stylep = attrs.style(style) + case ansi.HasOscPrefix(seq) && p.Command() == 8: + // Hyperlinks + ReadLink(p.Data(), &link) ++ linkp = attrs.link(link) + case ansi.Equal(seq, T("\n")): + if s == nil { + // When building lines, we need to ensure empty lines are represented. +--- a/terminal_renderer.go ++++ b/terminal_renderer.go +@@ -601,10 +601,10 @@ + + // Downsample pen when we don't have a [colorprofile.TrueColor], + // otherwise, use the original style. +- newStyle := ConvertStyle(cell.Style, s.profile) +- newLink := ConvertLink(cell.Link, s.profile) +- oldStyle := ConvertStyle(s.cur.Style, s.profile) +- oldLink := ConvertLink(s.cur.Link, s.profile) ++ newStyle := ConvertStyle(styleValue(cell.Style), s.profile) ++ newLink := ConvertLink(linkValue(cell.Link), s.profile) ++ oldStyle := ConvertStyle(styleValue(s.cur.Style), s.profile) ++ oldLink := ConvertLink(linkValue(s.cur.Link), s.profile) + + if !newStyle.Equal(&oldStyle) { + seq := newStyle.Diff(&oldStyle) +@@ -633,8 +633,9 @@ + // NOTE: This assumes that the terminal supports bce terminfo capability + // which all xterm-compatible terminals and terminals that use xterm* + // terminal types do. +- return c.Style.Underline == UnderlineNone && +- c.Style.Attrs&^(AttrBold|AttrFaint|AttrItalic|AttrBlink|AttrRapidBlink) == 0 && ++ style := styleValue(c.Style) ++ return style.Underline == UnderlineNone && ++ style.Attrs&^(AttrBold|AttrFaint|AttrItalic|AttrBlink|AttrRapidBlink) == 0 && + c.Link.IsZero() + } + +@@ -1713,7 +1714,7 @@ + cell := newbuf.CellAt(fx+i, ty) + if cell != nil && cell.Width > 0 { + i += cell.Width - 1 +- if !cell.Style.Equal(&s.cur.Style) || !cell.Link.Equal(&s.cur.Link) { ++ if !cell.Style.Equal(s.cur.Style) || !cell.Link.Equal(s.cur.Link) { + overwrite = false + break + } diff --git a/cli/third_party/ultraviolet/LICENSE b/cli/third_party/ultraviolet/LICENSE new file mode 100644 index 000000000..3217a2fb7 --- /dev/null +++ b/cli/third_party/ultraviolet/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Charmbracelet, Inc + +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/cli/third_party/ultraviolet/README.md b/cli/third_party/ultraviolet/README.md new file mode 100644 index 000000000..91b4ab3b4 --- /dev/null +++ b/cli/third_party/ultraviolet/README.md @@ -0,0 +1,170 @@ +# Ultraviolet + +> [!NOTE] +> This is a fork of [charmbracelet/ultraviolet](https://github.com/charmbracelet/ultraviolet) +> used by [albedo](https://tangled.org/okami.mom/albedo). `main` is upstream +> (the `upstream` branch) plus one patch: the input reader keeps OSC, DCS and +> other ST-terminated replies whole when a read ends between the ESC and +> backslash of the terminator, and holds a partial OSC 5522 clipboard reply up +> to 5 seconds instead of flushing it at the 50 ms escape timeout. Use it with +> `replace github.com/charmbracelet/ultraviolet => tangled.org/okami.mom/ultraviolet `. + +Charm Ultraviolet + +

+ GoDoc + Build Status +

+ +Ultraviolet is a set of primitives for building terminal user interfaces in Go. +It provides cell-based rendering, cross-platform input handling, and a diffing +renderer inspired by [ncurses](https://invisible-island.net/ncurses/)—without +the need for `terminfo` or `termcap` databases. + +Ultraviolet powers [Bubble Tea v2][bbt] and [Lip Gloss v2][lg]. It replaces the +ad-hoc terminal primitives from earlier versions with a cohesive, imperative API +that can also be used standalone. + +[bbt]: https://github.com/charmbracelet/bubbletea +[lg]: https://github.com/charmbracelet/lipgloss + +## Install + +```bash +go get github.com/charmbracelet/ultraviolet@latest +``` + +## Quick Start + +```go +package main + +import ( + "log" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/ultraviolet/screen" +) + +func main() { + t := uv.DefaultTerminal() + scr := t.Screen() + + scr.EnterAltScreen() + + if err := t.Start(); err != nil { + log.Fatalf("failed to start terminal: %v", err) + } + defer t.Stop() + + ctx := screen.NewContext(scr) + text := "Hello, World!" + textWidth := scr.StringWidth(text) + + display := func() { + screen.Clear(scr) + bounds := scr.Bounds() + x := (bounds.Dx() - textWidth) / 2 + y := bounds.Dy() / 2 + ctx.DrawString(text, x, y) + scr.Render() + scr.Flush() + } + + for ev := range t.Events() { + switch ev := ev.(type) { + case uv.WindowSizeEvent: + scr.Resize(ev.Width, ev.Height) + display() + case uv.KeyPressEvent: + if ev.MatchString("q", "ctrl+c") { + return + } + } + } +} +``` + +## Architecture + +Ultraviolet is organized as a set of layered primitives: + +- **Terminal** — manages the application lifecycle: raw mode, input event loop, + start/stop. Create one with `DefaultTerminal()` or `NewTerminal(console, opts)`. + +- **TerminalScreen** — the screen state manager. Handles rendering, alternate + screen buffer, cursor, mouse modes, keyboard enhancements, bracketed paste, + window title, and more. Access it via `terminal.Screen()`. + +- **Screen** — a minimal interface (`Bounds`, `CellAt`, `SetCell`, + `WidthMethod`) implemented by `TerminalScreen`, `Buffer`, `Window`, and + `ScreenBuffer`. Write code against `Screen` to stay decoupled from the + terminal. + +- **Buffer / Window** — off-screen cell buffers. `Buffer` is a flat grid of + cells. `Window` adds parent/child relationships and shared-buffer views. + Both implement `Screen` and `Drawable`. + +- **screen package** — drawing helpers that operate on any `Screen`: a + `Context` for styled text rendering (`Print`, `DrawString`, etc.) and + utility functions like `Clear`, `Fill`, `Clone`. + +- **layout package** — a constraint-based layout solver built on the + [Cassowary algorithm][casso]. Partition screen space with `Len`, `Min`, + `Max`, `Percent`, `Ratio`, and `Fill` constraints. + +[casso]: https://en.wikipedia.org/wiki/Cassowary_(software) + +## Features + +- **Cell-based diffing renderer** — only redraws what changed. Optimizes + cursor movement, uses ECH/REP/ICH/DCH when available, and supports scroll + optimizations. Minimal bandwidth, critical for SSH. + +- **Universal input** — unified keyboard and mouse event handling across + platforms. Supports legacy encodings, Kitty keyboard protocol, SGR mouse, + and Windows Console input. + +- **Inline and fullscreen** — works in both alternate screen (fullscreen) and + inline mode. Inline TUIs preserve terminal context and scrollback. + +- **Cross-platform** — first-class support for Unix (termios + ANSI) and + Windows (Console API). Consistent behavior across terminal emulators. + +- **Suspend/resume** — `Stop()` and `Start()` can be called repeatedly for + suspend/resume cycles, shelling out to editors, or process suspension + via `uv.Suspend()`. + +## Examples + +See the [`examples/`](./examples/) directory for core examples and +[`examples/advanced/`](./examples/advanced/) for more complex demos. + +## Tutorial + +See [TUTORIAL.md](./TUTORIAL.md) for a step-by-step guide to building your +first Ultraviolet application. + +> [!NOTE] +> Ultraviolet is in active development. The API may change. + +## Feedback + +We'd love to hear your thoughts on this project. Feel free to drop us a note! + +- [Twitter](https://twitter.com/charmcli) +- [Discord](https://charm.land/discord) +- [Slack](https://charm.land/slack) +- [The Fediverse](https://mastodon.social/@charmcli) + +## License + +[MIT](./LICENSE) + +--- + +Part of [Charm](https://charm.land). + +The Charm logo + +Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة diff --git a/cli/third_party/ultraviolet/TUTORIAL.md b/cli/third_party/ultraviolet/TUTORIAL.md new file mode 100644 index 000000000..d456d5a49 --- /dev/null +++ b/cli/third_party/ultraviolet/TUTORIAL.md @@ -0,0 +1,175 @@ +# Tutorial: Hello World + +This tutorial walks through building a simple Ultraviolet application that +displays centered "Hello, World!" text. You'll learn the core concepts: +creating a terminal, managing a screen, handling input events, and rendering. + +## Creating a Terminal + +A `Terminal` manages the console, input event loop, and screen state. + +```go +t := uv.DefaultTerminal() +``` + +You can also create a terminal with a custom console and options: + +```go +con := uv.NewConsole(os.Stdin, os.Stdout, os.Environ()) +t := uv.NewTerminal(con, &uv.Options{ + Logger: myLogger, // optional, for debugging I/O +}) +``` + +## Getting the Screen + +The terminal's screen is where you draw content, manage the alternate screen +buffer, and set cells. + +```go +scr := t.Screen() +``` + +## Alternate Screen + +The alternate screen buffer lets your application display content without +affecting the user's scrollback. Most fullscreen TUIs use it. + +```go +scr.EnterAltScreen() +``` + +## Starting the Terminal + +Starting puts the console into raw mode (disabling echoing and line buffering +so we receive individual keypresses like ctrl+c), initializes the +input event loop, and prepares the screen for rendering. + +```go +if err := t.Start(); err != nil { + log.Fatalf("failed to start terminal: %v", err) +} +defer t.Stop() +``` + +`Stop()` restores the console, exits the alternate screen, and cleans up. It +is safe to call multiple times and supports suspend/resume cycles. + +## Drawing Text + +You can set individual cells directly: + +```go +for i, r := range "Hello, World!" { + scr.SetCell(i, 0, &uv.Cell{Content: string(r), Width: 1}) +} +``` + +Or use the `screen` helper package for convenience: + +```go +ctx := screen.NewContext(scr) +ctx.DrawString("Hello, World!", 0, 0) +``` + +The `Context` supports styled text, links, and wrapping. It implements +`io.Writer`, so you can use `fmt.Fprint` and friends. + +## Rendering + +Drawing to the screen is a two-step process: + +1. **Render** — computes the minimal diff between the current and new screen + state, writing ANSI escape sequences to an internal buffer. +2. **Flush** — writes the buffer to the terminal. This is the only step that + performs real I/O and can return an error. + +```go +scr.Render() +if err := scr.Flush(); err != nil { + log.Fatalf("flush failed: %v", err) +} +``` + +## Handling Events + +The terminal provides a channel of input events. Range over it to process +keyboard, mouse, and resize events: + +```go +for ev := range t.Events() { + switch ev := ev.(type) { + case uv.WindowSizeEvent: + scr.Resize(ev.Width, ev.Height) + case uv.KeyPressEvent: + if ev.MatchString("q", "ctrl+c") { + return + } + } +} +``` + +`MatchString` accepts key names and modifier combinations like `"ctrl+a"`, +`"shift+enter"`, or `"alt+tab"`. + +## Putting It Together + +Here's the complete program—centered "Hello, World!" that redraws on resize +and exits on `q` or `ctrl+c`: + +```go +package main + +import ( + "log" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/ultraviolet/screen" +) + +func main() { + t := uv.DefaultTerminal() + scr := t.Screen() + + scr.EnterAltScreen() + + if err := t.Start(); err != nil { + log.Fatalf("failed to start terminal: %v", err) + } + defer t.Stop() + + ctx := screen.NewContext(scr) + text := "Hello, World!" + textWidth := scr.StringWidth(text) + + display := func() { + screen.Clear(scr) + bounds := scr.Bounds() + x := (bounds.Dx() - textWidth) / 2 + y := bounds.Dy() / 2 + ctx.DrawString(text, x, y) + scr.Render() + scr.Flush() + } + + for ev := range t.Events() { + switch ev := ev.(type) { + case uv.WindowSizeEvent: + scr.Resize(ev.Width, ev.Height) + display() + case uv.KeyPressEvent: + if ev.MatchString("q", "ctrl+c") { + return + } + } + } +} +``` + +--- + +Part of [Charm](https://charm.sh). + +The Charm logo + +Charm热爱开源 • Charm loves open source • نحنُ نحب المصادر المفتوحة diff --git a/cli/third_party/ultraviolet/border.go b/cli/third_party/ultraviolet/border.go new file mode 100644 index 000000000..d8ef477b4 --- /dev/null +++ b/cli/third_party/ultraviolet/border.go @@ -0,0 +1,238 @@ +package uv + +// NormalBorder returns a standard-type border with a normal weight and 90 +// degree corners. +func NormalBorder() Border { + return Border{ + Top: Side{Content: "─"}, + Bottom: Side{Content: "─"}, + Left: Side{Content: "│"}, + Right: Side{Content: "│"}, + TopLeft: Side{Content: "┌"}, + TopRight: Side{Content: "┐"}, + BottomLeft: Side{Content: "└"}, + BottomRight: Side{Content: "┘"}, + } +} + +// RoundedBorder returns a border with rounded corners. +func RoundedBorder() Border { + return Border{ + Top: Side{Content: "─"}, + Bottom: Side{Content: "─"}, + Left: Side{Content: "│"}, + Right: Side{Content: "│"}, + TopLeft: Side{Content: "╭"}, + TopRight: Side{Content: "╮"}, + BottomLeft: Side{Content: "╰"}, + BottomRight: Side{Content: "╯"}, + } +} + +// BlockBorder returns a border that takes the whole block. +func BlockBorder() Border { + return Border{ + Top: Side{Content: "█"}, + Bottom: Side{Content: "█"}, + Left: Side{Content: "█"}, + Right: Side{Content: "█"}, + TopLeft: Side{Content: "█"}, + TopRight: Side{Content: "█"}, + BottomLeft: Side{Content: "█"}, + BottomRight: Side{Content: "█"}, + } +} + +// OuterHalfBlockBorder returns a half-block border that sits outside the frame. +func OuterHalfBlockBorder() Border { + return Border{ + Top: Side{Content: "▀"}, + Bottom: Side{Content: "▄"}, + Left: Side{Content: "▌"}, + Right: Side{Content: "▐"}, + TopLeft: Side{Content: "▛"}, + TopRight: Side{Content: "▜"}, + BottomLeft: Side{Content: "▙"}, + BottomRight: Side{Content: "▟"}, + } +} + +// InnerHalfBlockBorder returns a half-block border that sits inside the frame. +func InnerHalfBlockBorder() Border { + return Border{ + Top: Side{Content: "▄"}, + Bottom: Side{Content: "▀"}, + Left: Side{Content: "▐"}, + Right: Side{Content: "▌"}, + TopLeft: Side{Content: "▗"}, + TopRight: Side{Content: "▖"}, + BottomLeft: Side{Content: "▝"}, + BottomRight: Side{Content: "▘"}, + } +} + +// ThickBorder returns a border that's thicker than the one returned by +// NormalBorder. +func ThickBorder() Border { + return Border{ + Top: Side{Content: "━"}, + Bottom: Side{Content: "━"}, + Left: Side{Content: "┃"}, + Right: Side{Content: "┃"}, + TopLeft: Side{Content: "┏"}, + TopRight: Side{Content: "┓"}, + BottomLeft: Side{Content: "┗"}, + BottomRight: Side{Content: "┛"}, + } +} + +// DoubleBorder returns a border comprised of two thin strokes. +func DoubleBorder() Border { + return Border{ + Top: Side{Content: "═"}, + Bottom: Side{Content: "═"}, + Left: Side{Content: "║"}, + Right: Side{Content: "║"}, + TopLeft: Side{Content: "╔"}, + TopRight: Side{Content: "╗"}, + BottomLeft: Side{Content: "╚"}, + BottomRight: Side{Content: "╝"}, + } +} + +// HiddenBorder returns a border that renders as a series of single-cell +// spaces. It's useful for cases when you want to remove a standard border but +// maintain layout positioning. This said, you can still apply a background +// color to a hidden border. +func HiddenBorder() Border { + return Border{ + Top: Side{Content: " "}, + Bottom: Side{Content: " "}, + Left: Side{Content: " "}, + Right: Side{Content: " "}, + TopLeft: Side{Content: " "}, + TopRight: Side{Content: " "}, + BottomLeft: Side{Content: " "}, + BottomRight: Side{Content: " "}, + } +} + +// MarkdownBorder return a table border in markdown style. +func MarkdownBorder() Border { + return Border{ + Left: Side{Content: "|"}, + Right: Side{Content: "|"}, + TopLeft: Side{Content: "|"}, + TopRight: Side{Content: "|"}, + BottomLeft: Side{Content: "|"}, + BottomRight: Side{Content: "|"}, + } +} + +// ASCIIBorder returns a table border with ASCII characters. +func ASCIIBorder() Border { + return Border{ + Top: Side{Content: "-"}, + Bottom: Side{Content: "-"}, + Left: Side{Content: "|"}, + Right: Side{Content: "|"}, + TopLeft: Side{Content: "+"}, + TopRight: Side{Content: "+"}, + BottomLeft: Side{Content: "+"}, + BottomRight: Side{Content: "+"}, + } +} + +// Side represents a single border side with its properties. +type Side struct { + Content string + Style + Link +} + +// Border represents a border with its properties. +type Border struct { + Top Side + Bottom Side + Left Side + Right Side + TopLeft Side + TopRight Side + BottomLeft Side + BottomRight Side +} + +// Style returns a new [Border] with the given style applied to all [Side]s. +func (b Border) Style(style Style) Border { + b.Top.Style = style + b.Bottom.Style = style + b.Left.Style = style + b.Right.Style = style + b.TopLeft.Style = style + b.TopRight.Style = style + b.BottomLeft.Style = style + b.BottomRight.Style = style + return b +} + +// Link returns a new [Border] with the given link applied to all [Side]s. +func (b Border) Link(link Link) Border { + b.Top.Link = link + b.Bottom.Link = link + b.Left.Link = link + b.Right.Link = link + b.TopLeft.Link = link + b.TopRight.Link = link + b.BottomLeft.Link = link + b.BottomRight.Link = link + return b +} + +// Draw draws the border around the given component. +func (b *Border) Draw(scr Screen, area Rectangle) { + // A side is the same cell along its whole run, and a screen copies the + // cells it is given, so one cell per side is enough. + top, bottom := borderCell(scr, &b.Top), borderCell(scr, &b.Bottom) + left, right := borderCell(scr, &b.Left), borderCell(scr, &b.Right) + topLeft, topRight := borderCell(scr, &b.TopLeft), borderCell(scr, &b.TopRight) + bottomLeft, bottomRight := borderCell(scr, &b.BottomLeft), borderCell(scr, &b.BottomRight) + + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x++ { + var cell *Cell + switch { + case y == area.Min.Y && x == area.Min.X: + cell = topLeft + case y == area.Min.Y && x == area.Max.X-1: + cell = topRight + case y == area.Max.Y-1 && x == area.Min.X: + cell = bottomLeft + case y == area.Max.Y-1 && x == area.Max.X-1: + cell = bottomRight + case y == area.Min.Y: + cell = top + case y == area.Max.Y-1: + cell = bottom + case x == area.Min.X: + cell = left + case x == area.Max.X-1: + cell = right + default: + continue + } + if cell == nil { + continue + } + scr.SetCell(x, y, cell) + } + } +} + +func borderCell(scr Screen, b *Side) *Cell { + c := NewCell(scr.WidthMethod(), b.Content) + if c != nil { + c.Style = StyleRef(b.Style) + c.Link = LinkRef(b.Link) + } + return c +} diff --git a/cli/third_party/ultraviolet/buffer.go b/cli/third_party/ultraviolet/buffer.go new file mode 100644 index 000000000..49b995ea9 --- /dev/null +++ b/cli/third_party/ultraviolet/buffer.go @@ -0,0 +1,868 @@ +package uv + +import ( + "bytes" + "image" + "io" + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// Position represents a position in a coordinate system. +type Position = image.Point + +// Pos is a shorthand for creating a new [Position]. +func Pos(x, y int) Position { + return Position{X: x, Y: y} +} + +// Rectangle represents a rectangular area. +type Rectangle = image.Rectangle + +// Rect is a shorthand for creating a new [Rectangle]. +func Rect(x, y, w, h int) Rectangle { + return Rectangle{Min: image.Point{X: x, Y: y}, Max: image.Point{X: x + w, Y: y + h}} +} + +// Line represents cells in a line. +type Line []Cell + +// NewLine creates a new line with the given width, filled with empty cells. +func NewLine(width int) Line { + l := make(Line, width) + for i := range l { + l[i] = EmptyCell + } + return l +} + +// Set sets the cell at the given x position. +func (l Line) Set(x int, c *Cell) { + lineWidth := len(l) + if x < 0 || x >= lineWidth { + return + } + + // When a wide cell is partially overwritten, we need + // to fill the rest of the cell with space cells to + // avoid rendering issues. + var prev *Cell + if prev = l.At(x); prev != nil { //nolint:nestif + if pw := prev.Width; pw > 1 { + // Writing to the first wide cell + for j := 0; j < pw && x+j < lineWidth; j++ { + l[x+j] = *prev + l[x+j].Empty() + } + } else if pw == 0 { + // Writing to wide cell placeholders + for j := 1; x-j >= 0; j++ { + if wide := l.At(x - j); wide != nil { + if ww := wide.Width; ww > 1 && j < ww { + for k := range ww { + l[x-j+k] = *wide + l[x-j+k].Empty() + } + break + } + } + } + } + } + + if c == nil { + // Nil cells are treated as blank empty cells. + l[x] = EmptyCell + return + } + + l[x] = *c + cw := c.Width + if x+cw > lineWidth { + // If the cell is too wide, we write blanks with the same style. + for i := 0; i < cw && x+i < lineWidth; i++ { + l[x+i] = *c + l[x+i].Empty() + } + return + } + + if cw > 1 { + // Mark wide cells with zero-width placeholder cells. + for j := 1; j < cw && x+j < lineWidth; j++ { + l[x+j] = Cell{} + } + } +} + +// At returns the cell at the given x position. +// If the cell does not exist, it returns nil. +func (l Line) At(x int) *Cell { + if x < 0 || x >= len(l) { + return nil + } + + return &l[x] +} + +// String returns the string representation of the line. Any trailing spaces +// are removed. +func (l Line) String() string { + var buf strings.Builder + var pending bytes.Buffer + for _, c := range l { + if c.IsZero() { + continue + } + if c.Equal(&EmptyCell) { + pending.WriteByte(' ') + continue + } + if pending.Len() > 0 { + buf.WriteString(pending.String()) + pending.Reset() + } + buf.WriteString(c.String()) + } + + return buf.String() +} + +// Render renders the line to a string with all the required attributes and +// styles. +func (l Line) Render() string { + var buf strings.Builder + renderLine(&buf, l) + return buf.String() +} + +func renderLine(buf io.StringWriter, l Line) { + var pen Style + var link Link + var pending bytes.Buffer + + for _, c := range l { + if c.IsZero() { + continue + } + if c.Equal(&EmptyCell) { + if !pen.IsZero() { + _, _ = buf.WriteString(ansi.ResetStyle) + pen = Style{} + } + if !link.IsZero() { + _, _ = buf.WriteString(ansi.ResetHyperlink()) + link = Link{} + } + pending.WriteByte(' ') + continue + } + + if pending.Len() > 0 { + _, _ = buf.WriteString(pending.String()) + pending.Reset() + } + + // A cell shares its style and link records with every cell that has + // the same ones, so render from a copy: the pen is a value, and the + // sequence written is the one a cell's own style and link always were. + style := styleValue(c.Style) + cellLink := linkValue(c.Link) + + if style.IsZero() && !pen.IsZero() { + _, _ = buf.WriteString(ansi.ResetStyle) + pen = Style{} + } + if !style.Equal(&pen) { + seq := style.Diff(&pen) + _, _ = buf.WriteString(seq) + pen = style + } + + // Write the URL escape sequence + if cellLink != link && link.URL != "" { + _, _ = buf.WriteString(ansi.ResetHyperlink()) + link = Link{} + } + if cellLink != link { + _, _ = buf.WriteString(ansi.SetHyperlink(cellLink.URL, cellLink.Params)) + link = cellLink + } + + _, _ = buf.WriteString(c.String()) + } + + if pending.Len() > 0 { + _, _ = buf.WriteString(pending.String()) + } + if link.URL != "" { + _, _ = buf.WriteString(ansi.ResetHyperlink()) + } + if !pen.IsZero() { + _, _ = buf.WriteString(ansi.ResetStyle) + } +} + +// Lines represents a slice of lines. +type Lines []Line + +// Height returns the height of the lines. +func (ls Lines) Height() int { + return len(ls) +} + +// Width returns the width of the widest line. +func (ls Lines) Width() int { + maxWidth := 0 + for _, l := range ls { + maxWidth = max(maxWidth, len(l)) + } + return maxWidth +} + +// String returns the string representation of the lines. +func (ls Lines) String() string { + var buf strings.Builder + for i, l := range ls { + buf.WriteString(l.String()) + if i < len(ls)-1 { + _ = buf.WriteByte('\n') + } + } + return buf.String() +} + +// Render renders the lines to a styled string with all the required attributes +// and styles. +func (ls Lines) Render() string { + var buf strings.Builder + for i, l := range ls { + renderLine(&buf, l) + if i < len(ls)-1 { + _ = buf.WriteByte('\n') + } + } + return buf.String() +} + +// Buffer represents a cell buffer that contains the contents of a screen. +type Buffer struct { + // Lines is a slice of lines that make up the cells of the buffer. + Lines []Line +} + +var _ Drawable = (*Buffer)(nil) + +// NewBuffer creates a new buffer with the given width and height. +// This is a convenience function that initializes a new buffer and resizes it. +func NewBuffer(width int, height int) *Buffer { + b := new(Buffer) + b.Lines = make([]Line, height) + for i := range b.Lines { + b.Lines[i] = make(Line, width) + for j := range b.Lines[i] { + b.Lines[i][j] = EmptyCell + } + } + b.Resize(width, height) + return b +} + +// String returns the string representation of the buffer. +func (b *Buffer) String() string { + return Lines(b.Lines).String() +} + +// Render renders the buffer to a styled string with all the required +// attributes and styles. +func (b *Buffer) Render() string { + return Lines(b.Lines).Render() +} + +// Line returns a pointer to the line at the given y position. +// If the line does not exist, it returns nil. +func (b *Buffer) Line(y int) Line { + if y < 0 || y >= len(b.Lines) { + return nil + } + return b.Lines[y] +} + +// CellAt returns the cell at the given position. It returns nil if the +// position is out of bounds. +func (b *Buffer) CellAt(x int, y int) *Cell { + if y < 0 || y >= len(b.Lines) { + return nil + } + return b.Lines[y].At(x) +} + +// SetCell sets the cell at the given x, y position. +func (b *Buffer) SetCell(x, y int, c *Cell) { + if y < 0 || y >= len(b.Lines) { + return + } + + b.Lines[y].Set(x, c) +} + +// Height implements Screen. +func (b *Buffer) Height() int { + return len(b.Lines) +} + +// Width implements Screen. +func (b *Buffer) Width() int { + if len(b.Lines) == 0 { + return 0 + } + return len(b.Lines[0]) +} + +// Bounds returns the bounds of the buffer. +// The origin is always at (0, 0) and the maximum coordinates are determined by +// the width and height of the buffer. +func (b *Buffer) Bounds() Rectangle { + return Rect(0, 0, b.Width(), b.Height()) +} + +// Resize resizes the buffer to the given width and height. +func (b *Buffer) Resize(width int, height int) { + curWidth, curHeight := b.Width(), b.Height() + if curWidth == width && curHeight == height { + // No need to resize if the dimensions are the same. + return + } + + if width > curWidth { + line := make(Line, width-curWidth) + for i := range line { + line[i] = EmptyCell + } + for i := range b.Lines { + b.Lines[i] = append(b.Lines[i], line...) + } + } else if width < curWidth { + for i := range b.Lines { + b.Lines[i] = b.Lines[i][:width] + } + } + + if height > len(b.Lines) { + for i := len(b.Lines); i < height; i++ { + line := make(Line, width) + for j := range line { + line[j] = EmptyCell + } + b.Lines = append(b.Lines, line) + } + } else if height < len(b.Lines) { + b.Lines = b.Lines[:height] + } +} + +// Fill fills the buffer with the given cell and rectangle. +func (b *Buffer) Fill(c *Cell) { + b.FillArea(c, b.Bounds()) +} + +// FillArea fills the buffer with the given cell and rectangle. +func (b *Buffer) FillArea(c *Cell, area Rectangle) { + cellWidth := 1 + if c != nil && c.Width > 1 { + cellWidth = c.Width + } + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x += cellWidth { + b.SetCell(x, y, c) + } + } +} + +// Clear clears the buffer with space cells and rectangle. +func (b *Buffer) Clear() { + area := b.Bounds() + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x++ { + b.Lines[y][x] = EmptyCell + } + } +} + +// ClearArea clears the buffer with space cells within the specified +// rectangles. Only cells within the rectangle's bounds are affected. +func (b *Buffer) ClearArea(area Rectangle) { + b.FillArea(nil, area) +} + +// CloneArea clones the area of the buffer within the specified rectangle. If +// the area is out of bounds, it returns nil. +func (b *Buffer) CloneArea(area Rectangle) *Buffer { + bounds := b.Bounds() + if !area.In(bounds) { + return nil + } + n := NewBuffer(area.Dx(), area.Dy()) + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; { + c := b.CellAt(x, y) + if c == nil || c.IsZero() { + x++ + continue + } + n.SetCell(x-area.Min.X, y-area.Min.Y, c) + x += max(c.Width, 1) + } + } + return n +} + +// Clone clones the entire buffer into a new buffer. +func (b *Buffer) Clone() *Buffer { + return b.CloneArea(b.Bounds()) +} + +// Draw draws the buffer to the given screen at the specified area. +// It implements the [Drawable] interface. +func (b *Buffer) Draw(scr Screen, area Rectangle) { + if area.Empty() { + return + } + + // Ensure the area is within the bounds of the screen. + bounds := scr.Bounds() + if !area.Overlaps(bounds) { + return + } + + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; { + c := b.CellAt(x-area.Min.X, y-area.Min.Y) + if c == nil || c.IsZero() { + x++ + continue + } + scr.SetCell(x, y, c) + width := c.Width + if width <= 0 { + width = 1 + } + x += width + } + } +} + +// InsertLine inserts n lines at the given line position, with the given +// optional cell, within the specified rectangles. If no rectangles are +// specified, it inserts lines in the entire buffer. Only cells within the +// rectangle's horizontal bounds are affected. Lines are pushed out of the +// rectangle bounds and lost. This follows terminal [ansi.IL] behavior. +// It returns the pushed out lines. +func (b *Buffer) InsertLine(y, n int, c *Cell) { + b.InsertLineArea(y, n, c, b.Bounds()) +} + +// InsertLineArea inserts new lines at the given line position, with the +// given optional cell, within the rectangle bounds. Only cells within the +// rectangle's horizontal bounds are affected. Lines are pushed out of the +// rectangle bounds and lost. This follows terminal [ansi.IL] behavior. +func (b *Buffer) InsertLineArea(y, n int, c *Cell, area Rectangle) { + if n <= 0 || y < area.Min.Y || y >= area.Max.Y || y >= b.Height() { + return + } + + // Limit number of lines to insert to available space + if y+n > area.Max.Y { + n = area.Max.Y - y + } + + // Move existing lines down within the bounds + for i := area.Max.Y - 1; i >= y+n; i-- { + for x := area.Min.X; x < area.Max.X; x++ { + // We don't need to clone c here because we're just moving lines down. + b.Lines[i][x] = b.Lines[i-n][x] + } + } + + // Clear the newly inserted lines within bounds + for i := y; i < y+n; i++ { + for x := area.Min.X; x < area.Max.X; x++ { + b.SetCell(x, i, c) + } + } +} + +// DeleteLineArea deletes lines at the given line position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected. Lines are shifted up within the bounds and +// new blank lines are created at the bottom. This follows terminal [ansi.DL] +// behavior. +func (b *Buffer) DeleteLineArea(y, n int, c *Cell, area Rectangle) { + if n <= 0 || y < area.Min.Y || y >= area.Max.Y || y >= b.Height() { + return + } + + // Limit deletion count to available space in scroll region + if n > area.Max.Y-y { + n = area.Max.Y - y + } + + // Shift cells up within the bounds + for dst := y; dst < area.Max.Y-n; dst++ { + src := dst + n + for x := area.Min.X; x < area.Max.X; x++ { + // We don't need to clone c here because we're just moving cells up. + b.Lines[dst][x] = b.Lines[src][x] + } + } + + // Fill the bottom n lines with blank cells + for i := area.Max.Y - n; i < area.Max.Y; i++ { + for x := area.Min.X; x < area.Max.X; x++ { + b.SetCell(x, i, c) + } + } +} + +// DeleteLine deletes n lines at the given line position, with the given +// optional cell, within the specified rectangles. If no rectangles are +// specified, it deletes lines in the entire buffer. +func (b *Buffer) DeleteLine(y, n int, c *Cell) { + b.DeleteLineArea(y, n, c, b.Bounds()) +} + +// InsertCell inserts new cells at the given position, with the given optional +// cell, within the specified rectangles. If no rectangles are specified, it +// inserts cells in the entire buffer. This follows terminal [ansi.ICH] +// behavior. +func (b *Buffer) InsertCell(x, y, n int, c *Cell) { + b.InsertCellArea(x, y, n, c, b.Bounds()) +} + +// InsertCellArea inserts new cells at the given position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected, following terminal [ansi.ICH] behavior. +func (b *Buffer) InsertCellArea(x, y, n int, c *Cell, area Rectangle) { + if n <= 0 || y < area.Min.Y || y >= area.Max.Y || y >= b.Height() || + x < area.Min.X || x >= area.Max.X || x >= b.Width() { + return + } + + // Limit number of cells to insert to available space + if x+n > area.Max.X { + n = area.Max.X - x + } + + // Move existing cells within rectangle bounds to the right + for i := area.Max.X - 1; i >= x+n && i-n >= area.Min.X; i-- { + // We don't need to clone c here because we're just moving cells to the + // right. + b.Lines[y][i] = b.Lines[y][i-n] + } + + // Clear the newly inserted cells within rectangle bounds + for i := x; i < x+n && i < area.Max.X; i++ { + b.SetCell(i, y, c) + } +} + +// DeleteCell deletes cells at the given position, with the given optional +// cell, within the specified rectangles. If no rectangles are specified, it +// deletes cells in the entire buffer. This follows terminal [ansi.DCH] +// behavior. +func (b *Buffer) DeleteCell(x, y, n int, c *Cell) { + b.DeleteCellArea(x, y, n, c, b.Bounds()) +} + +// DeleteCellArea deletes cells at the given position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected, following terminal [ansi.DCH] behavior. +func (b *Buffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle) { + if n <= 0 || y < area.Min.Y || y >= area.Max.Y || y >= b.Height() || + x < area.Min.X || x >= area.Max.X || x >= b.Width() { + return + } + + // Calculate how many positions we can actually delete + remainingCells := area.Max.X - x + if n > remainingCells { + n = remainingCells + } + + // Shift the remaining cells to the left + for i := x; i < area.Max.X-n; i++ { + if i+n < area.Max.X { + // We need to use SetCell here to ensure we blank out any wide + // cells we encounter. + b.SetCell(i, y, b.CellAt(i+n, y)) + } + } + + // Fill the vacated positions with the given cell + for i := area.Max.X - n; i < area.Max.X; i++ { + b.SetCell(i, y, c) + } +} + +// ScreenBuffer is a buffer that can be used as a [Screen]. +type ScreenBuffer struct { + *RenderBuffer + Method ansi.Method +} + +var ( + _ Screen = ScreenBuffer{} + _ Drawable = ScreenBuffer{} +) + +// NewScreenBuffer creates a new ScreenBuffer with the given width and height. +func NewScreenBuffer(width, height int) ScreenBuffer { + return ScreenBuffer{ + RenderBuffer: NewRenderBuffer(width, height), + Method: ansi.WcWidth, + } +} + +// WidthMethod returns the width method used by the screen. +// It defaults to [ansi.WcWidth]. +func (s ScreenBuffer) WidthMethod() WidthMethod { + return s.Method +} + +// TrimSpace trims trailing spaces from the end of each line in the given +// string. +func TrimSpace(s string) string { + lines := strings.Split(s, "\n") + for i, line := range lines { + // Check if we have a trailing '\r' and preserve it + hasCR := strings.HasSuffix(line, "\r") + if hasCR { + line = strings.TrimSuffix(line, "\r") + } + line = strings.TrimRight(line, " ") + if hasCR { + line = line + "\r" + } + lines[i] = line + } + return strings.Join(lines, "\n") +} + +// RenderBuffer represents a buffer that keeps track of the current and new +// state of the screen, allowing for efficient rendering by only updating the +// parts of the screen that have changed. +type RenderBuffer struct { + *Buffer + + // Touched records which lines changed since the last render. It holds at + // least one entry per screen row, and a nil entry means that row is + // unchanged. Shortening it is not meaningful, since the rows still exist, so + // the renderer restores the length rather than checking it at every read. + Touched []*LineData +} + +// NewRenderBuffer creates a new [RenderBuffer] with the given width and height. +func NewRenderBuffer(width, height int) *RenderBuffer { + return &RenderBuffer{ + Buffer: NewBuffer(width, height), + Touched: make([]*LineData, height), + } +} + +// TouchLine marks a line n times starting at the given x position as touched. +func (b *RenderBuffer) TouchLine(x, y, n int) { + if y < 0 || y >= len(b.Lines) { + return + } + + b.growTouched() + + ch := b.Touched[y] + if ch == nil { + ch = &LineData{FirstCell: x, LastCell: x + n} + } else { + ch.FirstCell = min(ch.FirstCell, x) + ch.LastCell = max(ch.LastCell, x+n) + } + b.Touched[y] = ch +} + +// Touch marks the cell at the given x, y position as touched. +func (b *RenderBuffer) Touch(x, y int) { + b.TouchLine(x, y, 0) +} + +// TouchedLines returns the number of touched lines in the buffer. +func (b *RenderBuffer) TouchedLines() int { + count := 0 + for _, t := range b.Touched { + if t != nil { + count++ + } + } + return count +} + +// SetCell sets the cell at the given x, y position and marks the line as +// touched. +func (b *RenderBuffer) SetCell(x, y int, c *Cell) { + if p := b.CellAt(x, y); !cellEqual(p, c) { + width := 1 + if c != nil && c.Width > 0 { + width = c.Width + } + if p != nil && p.Width > 0 { + width = max(width, p.Width) + } + b.TouchLine(x, y, width) + } + b.Buffer.SetCell(x, y, c) +} + +// InsertLine inserts n lines at the given line position, with the given +// optional cell, within the specified rectangles. If no rectangles are +// specified, it inserts lines in the entire buffer. Only cells within the +// rectangle's horizontal bounds are affected. Lines are pushed out of the +// rectangle bounds and lost. This follows terminal [ansi.IL] behavior. +func (b *RenderBuffer) InsertLine(y, n int, c *Cell) { + b.InsertLineArea(y, n, c, b.Bounds()) +} + +// InsertLineArea inserts new lines at the given line position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's horizontal bounds are affected. Lines are pushed out of the +// rectangle bounds and lost. This follows terminal [ansi.IL] behavior. +func (b *RenderBuffer) InsertLineArea(y, n int, c *Cell, area Rectangle) { + b.Buffer.InsertLineArea(y, n, c, area) + for i := area.Min.Y; i < area.Max.Y; i++ { + b.TouchLine(area.Min.X, i, area.Max.X-area.Min.X) + b.TouchLine(area.Min.X, i-n, area.Max.X-area.Min.X) + } +} + +// DeleteLine deletes n lines at the given line position, with the given +// optional cell, within the specified rectangles. If no rectangles are +// specified, it deletes lines in the entire buffer. +func (b *RenderBuffer) DeleteLine(y, n int, c *Cell) { + b.DeleteLineArea(y, n, c, b.Bounds()) +} + +// DeleteLineArea deletes lines at the given line position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected. Lines are shifted up within the bounds and +// new blank lines are created at the bottom. This follows terminal [ansi.DL] +// behavior. +func (b *RenderBuffer) DeleteLineArea(y, n int, c *Cell, area Rectangle) { + b.Buffer.DeleteLineArea(y, n, c, area) + for i := area.Min.Y; i < area.Max.Y; i++ { + b.TouchLine(area.Min.X, i, area.Max.X-area.Min.X) + b.TouchLine(area.Min.X, i+n, area.Max.X-area.Min.X) + } +} + +// InsertCell inserts new cells at the given position, with the given optional +// cell, within the specified rectangles. If no rectangles are specified, it +// inserts cells in the entire buffer. This follows terminal [ansi.ICH] +// behavior. +func (b *RenderBuffer) InsertCell(x, y, n int, c *Cell) { + b.InsertCellArea(x, y, n, c, b.Bounds()) +} + +// InsertCellArea inserts new cells at the given position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected, following terminal [ansi.ICH] behavior. +func (b *RenderBuffer) InsertCellArea(x, y, n int, c *Cell, area Rectangle) { + b.Buffer.InsertCellArea(x, y, n, c, area) + if x+n > area.Max.X { + n = area.Max.X - x + } + b.TouchLine(x, y, n) +} + +// DeleteCell deletes cells at the given position, with the given optional +// cell, within the specified rectangles. If no rectangles are specified, it +// deletes cells in the entire buffer. This follows terminal [ansi.DCH] +// behavior. +func (b *RenderBuffer) DeleteCell(x, y, n int, c *Cell) { + b.DeleteCellArea(x, y, n, c, b.Bounds()) +} + +// DeleteCellArea deletes cells at the given position, with the given +// optional cell, within the rectangle bounds. Only cells within the +// rectangle's bounds are affected, following terminal [ansi.DCH] behavior. +func (b *RenderBuffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle) { + b.Buffer.DeleteCellArea(x, y, n, c, area) + remainingCells := area.Max.X - x + if n > remainingCells { + n = remainingCells + } + b.TouchLine(x, y, n) +} + +// Resize resizes the buffer and touches every cell it creates, since the +// screen there still shows whatever the last render left. +func (b *RenderBuffer) Resize(width, height int) { + curWidth, curHeight := b.Width(), b.Height() + b.Buffer.Resize(width, height) + + if width > curWidth { + for y := range min(curHeight, height) { + b.TouchLine(curWidth, y, width-curWidth) + } + } + for y := curHeight; y < height; y++ { + b.TouchLine(0, y, width) + } +} + +// Clear clears the buffer with space cells and marks all lines as touched. +func (b *RenderBuffer) Clear() { + b.Buffer.Clear() + w := b.Width() + for y := range b.Lines { + b.TouchLine(0, y, w) + } +} + +// ClearArea clears the buffer with space cells within the specified rectangle +// and marks the affected lines as touched. +func (b *RenderBuffer) ClearArea(area Rectangle) { + b.Buffer.ClearArea(area) + w := area.Max.X - area.Min.X + for y := area.Min.Y; y < area.Max.Y; y++ { + b.TouchLine(area.Min.X, y, w) + } +} + +// Fill fills the buffer with the given cell and marks all lines as touched. +func (b *RenderBuffer) Fill(c *Cell) { + b.FillArea(c, b.Bounds()) +} + +// FillArea fills the buffer with the given cell within the specified rectangle +// and marks the affected lines as touched. +func (b *RenderBuffer) FillArea(c *Cell, area Rectangle) { + b.Buffer.FillArea(c, area) + w := area.Max.X - area.Min.X + for y := area.Min.Y; y < area.Max.Y; y++ { + b.TouchLine(area.Min.X, y, w) + } +} + +// growTouched restores the one-entry-per-row invariant, which an application is +// free to break by shortening or dropping the list. +// +// Only ever grows. Truncating to the screen would be the tidier rule, but +// [RenderBuffer.TouchedLines] counts non-nil records rather than touched ones, +// so discarding the entries of a frame that collapsed makes it look untouched +// and skips the erase that clears the rows it gave up. Growing is enough: every +// reader indexes by screen row, and a longer list has an entry for each. +func (b *RenderBuffer) growTouched() { + if len(b.Touched) >= len(b.Lines) { + return + } + touched := make([]*LineData, len(b.Lines)) + copy(touched, b.Touched) + b.Touched = touched +} diff --git a/cli/third_party/ultraviolet/cancelreader_other.go b/cli/third_party/ultraviolet/cancelreader_other.go new file mode 100644 index 000000000..3fb3c95ce --- /dev/null +++ b/cli/third_party/ultraviolet/cancelreader_other.go @@ -0,0 +1,16 @@ +//go:build !windows +// +build !windows + +package uv + +import ( + "io" + + "github.com/muesli/cancelreader" +) + +// NewCancelReader creates a new [cancelreader.CancelReader] that provides a +// cancelable reader interface that can be used to cancel reads. +func NewCancelReader(r io.Reader) (cancelreader.CancelReader, error) { + return cancelreader.NewReader(r) //nolint:wrapcheck +} diff --git a/cli/third_party/ultraviolet/cancelreader_windows.go b/cli/third_party/ultraviolet/cancelreader_windows.go new file mode 100644 index 000000000..fdc2db584 --- /dev/null +++ b/cli/third_party/ultraviolet/cancelreader_windows.go @@ -0,0 +1,139 @@ +//go:build windows +// +build windows + +package uv + +import ( + "fmt" + "io" + "os" + "sync" + + xwindows "github.com/charmbracelet/x/windows" + "github.com/muesli/cancelreader" + "golang.org/x/sys/windows" +) + +type conInputReader struct { + cancelMixin + conin windows.Handle + originalMode uint32 + newMode uint32 +} + +var _ cancelreader.CancelReader = &conInputReader{} + +// NewCancelReader creates a new [cancelreader.CancelReader] that provides a +// cancelable reader interface that can be used to cancel reads. +func NewCancelReader(r io.Reader) (cancelreader.CancelReader, error) { + fallback := func(io.Reader) (cancelreader.CancelReader, error) { + return cancelreader.NewReader(r) + } + + var dummy uint32 + if f, ok := r.(cancelreader.File); !ok || f.Fd() != os.Stdin.Fd() || + // If data was piped to the standard input, it does not emit events + // anymore. We can detect this if the console mode cannot be set anymore, + // in this case, we fallback to the default cancelreader implementation. + windows.GetConsoleMode(windows.Handle(f.Fd()), &dummy) != nil { + return fallback(r) + } + + conin, err := windows.GetStdHandle(windows.STD_INPUT_HANDLE) + if err != nil { + return fallback(r) + } + + // Discard any pending input events. + if err := xwindows.FlushConsoleInputBuffer(conin); err != nil { + return fallback(r) + } + + modes := []uint32{ + windows.ENABLE_VIRTUAL_TERMINAL_INPUT, + windows.ENABLE_WINDOW_INPUT, + windows.ENABLE_EXTENDED_FLAGS, + } + + originalMode, newMode, err := prepareConsole(conin, modes...) + if err != nil { + return nil, fmt.Errorf("failed to prepare console input: %w", err) + } + + return &conInputReader{ + conin: conin, + originalMode: originalMode, + newMode: newMode, + }, nil +} + +// Cancel implements cancelreader.CancelReader. +func (r *conInputReader) Cancel() bool { + r.setCanceled() + + return windows.CancelIoEx(r.conin, nil) == nil || windows.CancelIo(r.conin) == nil +} + +// Close implements cancelreader.CancelReader. +func (r *conInputReader) Close() error { + if r.originalMode != 0 { + err := windows.SetConsoleMode(r.conin, r.originalMode) + if err != nil { + return fmt.Errorf("reset console mode: %w", err) + } + } + + return nil +} + +// Read implements cancelreader.CancelReader. +func (r *conInputReader) Read(data []byte) (int, error) { + if r.isCanceled() { + return 0, cancelreader.ErrCanceled + } + + var n uint32 + if err := windows.ReadFile(r.conin, data, &n, nil); err != nil { + return int(n), fmt.Errorf("read console input: %w", err) + } + + return int(n), nil +} + +func prepareConsole(input windows.Handle, modes ...uint32) (originalMode, newMode uint32, err error) { + err = windows.GetConsoleMode(input, &originalMode) + if err != nil { + return 0, 0, fmt.Errorf("get console mode: %w", err) + } + + for _, mode := range modes { + newMode |= mode + } + + err = windows.SetConsoleMode(input, newMode) + if err != nil { + return 0, 0, fmt.Errorf("set console mode: %w", err) + } + + return originalMode, newMode, nil +} + +// cancelMixin represents a goroutine-safe cancelation status. +type cancelMixin struct { + unsafeCanceled bool + lock sync.Mutex +} + +func (c *cancelMixin) setCanceled() { + c.lock.Lock() + defer c.lock.Unlock() + + c.unsafeCanceled = true +} + +func (c *cancelMixin) isCanceled() bool { + c.lock.Lock() + defer c.lock.Unlock() + + return c.unsafeCanceled +} diff --git a/cli/third_party/ultraviolet/cell.go b/cli/third_party/ultraviolet/cell.go new file mode 100644 index 000000000..0ee8ae21e --- /dev/null +++ b/cli/third_party/ultraviolet/cell.go @@ -0,0 +1,518 @@ +package uv + +import ( + "image/color" + "strings" + + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/x/ansi" +) + +// EmptyCell is a cell with a single space, width of 1, and no style or link. +var EmptyCell = Cell{Content: " ", Width: 1} + +// Cell represents a single cell in the terminal screen. +// +// A screen is a cell per column and row, so what a cell costs is what a screen +// costs. Style and Link are therefore shared records rather than values: every +// cell that has the same style points at the same one, and a nil pointer is +// the zero style or link, which is what most cells have. +type Cell struct { + // Content is the [Cell]'s content, which consists of a single grapheme + // cluster. Most of the time, this will be a single rune as well, but it + // can also be a combination of runes that form a grapheme cluster. + Content string + + // The style of the cell, shared with every cell that has the same one. A + // nil style means no style. Zero value prints a reset sequence. + Style *Style + + // Link is the hyperlink of the cell, shared like [Cell.Style]. + Link *Link + + // Width is the mono-spaced width of the grapheme cluster. + Width int +} + +// StyleRef returns the style record for a cell: nil for the zero style, so a +// cell with no style stays the zero [Cell], and a fresh record otherwise. +// Cells that have the same style can share one record. +func StyleRef(style Style) *Style { + if style.IsZero() { + return nil + } + return &style +} + +// LinkRef returns the link record for a cell, like [StyleRef]. +func LinkRef(link Link) *Link { + if link.IsZero() { + return nil + } + return &link +} + +// styleValue is the style a cell holds, with a nil style as the zero one. +func styleValue(style *Style) Style { + if style == nil { + return Style{} + } + return *style +} + +// linkValue is the link a cell holds, with a nil link as the zero one. +func linkValue(link *Link) Link { + if link == nil { + return Link{} + } + return *link +} + +// NewCell creates a new cell from the given string grapheme. It will only use +// the first grapheme in the string and ignore the rest. The width of the cell +// is determined using the given width method. +func NewCell(method WidthMethod, gr string) *Cell { + if len(gr) == 0 { + return &Cell{} + } + if gr == " " { + return EmptyCell.Clone() + } + return &Cell{ + Content: gr, + Width: method.StringWidth(gr), + } +} + +// String returns the string content of the cell excluding any styles, links, +// and escape sequences. +func (c *Cell) String() string { + return c.Content +} + +// Equal returns whether the cell is equal to the other cell. +func (c *Cell) Equal(o *Cell) bool { + return o != nil && + c.Width == o.Width && + c.Content == o.Content && + c.Style.Equal(o.Style) && + c.Link.Equal(o.Link) +} + +// IsZero returns whether the cell is an empty cell. +func (c *Cell) IsZero() bool { + return c.Width == 0 && c.Content == "" && c.Style.IsZero() && c.Link.IsZero() +} + +// isWidePlaceholder reports whether the cell is the continuation column of a +// wide cell, marked with a zero display width. +func (c *Cell) isWidePlaceholder() bool { + return c != nil && c.Width == 0 +} + +// Clone returns a copy of the cell. +func (c *Cell) Clone() (n *Cell) { + n = new(Cell) + *n = *c + return +} + +// Empty makes the cell an empty cell by setting its content to a single space +// and width to 1. +func (c *Cell) Empty() { + c.Content = " " + c.Width = 1 +} + +// NewLink creates a new hyperlink with the given URL and parameters. +func NewLink(url string, params ...string) Link { + return Link{ + URL: url, + Params: strings.Join(params, ":"), + } +} + +// Link represents a hyperlink in the terminal screen. +type Link struct { + URL string + Params string +} + +// String returns a string representation of the hyperlink. +func (h *Link) String() string { + if h == nil { + return "" + } + return h.URL +} + +// Equal returns whether the hyperlink is equal to the other hyperlink. A nil +// link is the zero link. +func (h *Link) Equal(o *Link) bool { + if h == o { + return true + } + if h == nil || o == nil { + return h.IsZero() && o.IsZero() + } + return *h == *o +} + +// IsZero returns whether the hyperlink is empty. A nil link is empty. +func (h *Link) IsZero() bool { + return h == nil || *h == Link{} +} + +// These are the available text attributes that can be combined to create +// different styles. +const ( + AttrBold = 1 << iota + AttrFaint + AttrItalic + AttrBlink + AttrRapidBlink // Not widely supported + AttrReverse + AttrConceal + AttrStrikethrough + + AttrReset = 0 +) + +// AttrSlowBlink is an alias for AttrBlink. +// +// Deprecated: Use [AttrBlink] instead. +const ( + AttrSlowBlink = AttrBlink +) + +// Underline is the style of underline to use for text. +type Underline = ansi.Underline + +// UnderlineStyle is the style of underline to use for text. +// +// Deprecated: Use [Underline] instead. +type UnderlineStyle = ansi.Underline + +// These are the available underline styles. +const ( + UnderlineNone = ansi.UnderlineNone + UnderlineSingle = ansi.UnderlineSingle + UnderlineDouble = ansi.UnderlineDouble + UnderlineCurly = ansi.UnderlineCurly + UnderlineDotted = ansi.UnderlineDotted + UnderlineDashed = ansi.UnderlineDashed +) + +// These are the available underline styles. +// +// Deprecated: Use the constants from [Underline] instead. +const ( + UnderlineStyleNone = ansi.UnderlineNone + UnderlineStyleSingle = ansi.UnderlineSingle + UnderlineStyleDouble = ansi.UnderlineDouble + UnderlineStyleCurly = ansi.UnderlineCurly + UnderlineStyleDotted = ansi.UnderlineDotted + UnderlineStyleDashed = ansi.UnderlineDashed +) + +// Style represents the style of a cell. +type Style struct { + Fg color.Color + Bg color.Color + UnderlineColor color.Color + Underline Underline + Attrs uint8 +} + +// Equal returns true if the style is equal to the other style. A nil style is +// the zero style. +func (s *Style) Equal(o *Style) bool { + if s == nil || o == nil { + return s.IsZero() && o.IsZero() + } + return s.Attrs == o.Attrs && + s.Underline == o.Underline && + colorEqual(s.Fg, o.Fg) && + colorEqual(s.Bg, o.Bg) && + colorEqual(s.UnderlineColor, o.UnderlineColor) +} + +// Styled wraps the given string with the style's ANSI sequences and resets. +func (s *Style) Styled(str string) string { + if s.IsZero() { + return str + } + return s.String() + str + ansi.ResetStyle +} + +// String returns the ANSI SGR sequence for the style. +func (s *Style) String() string { + if s.IsZero() { + return ansi.ResetStyle + } + + var b ansi.Style + + if s.Attrs != 0 { //nolint:nestif + if s.Attrs&AttrBold != 0 { + b = b.Bold() + } + if s.Attrs&AttrFaint != 0 { + b = b.Faint() + } + if s.Attrs&AttrItalic != 0 { + b = b.Italic(true) + } + if s.Attrs&AttrBlink != 0 { + b = b.Blink(true) + } + if s.Attrs&AttrRapidBlink != 0 { + b = b.RapidBlink(true) + } + if s.Attrs&AttrReverse != 0 { + b = b.Reverse(true) + } + if s.Attrs&AttrConceal != 0 { + b = b.Conceal(true) + } + if s.Attrs&AttrStrikethrough != 0 { + b = b.Strikethrough(true) + } + } + if s.Underline != UnderlineStyleNone { + switch s.Underline { + case UnderlineStyleSingle: + b = b.Underline(true) + case UnderlineStyleDouble: + b = b.UnderlineStyle(UnderlineStyleDouble) + case UnderlineStyleCurly: + b = b.UnderlineStyle(UnderlineStyleCurly) + case UnderlineStyleDotted: + b = b.UnderlineStyle(UnderlineStyleDotted) + case UnderlineStyleDashed: + b = b.UnderlineStyle(UnderlineStyleDashed) + } + } + if s.Fg != nil { + b = b.ForegroundColor(s.Fg) + } + if s.Bg != nil { + b = b.BackgroundColor(s.Bg) + } + if s.UnderlineColor != nil { + b = b.UnderlineColor(s.UnderlineColor) + } + + return b.String() +} + +// Diff returns the ANSI sequence that sets the style as a diff from +// another style. +func (s *Style) Diff(from *Style) string { + return StyleDiff(from, s) +} + +// StyleDiff returns the SGR ANSI sequence necessary to transition from the +// "from" style to the "to" style. +func StyleDiff(from, to *Style) string { + if from == nil && to == nil { + return "" + } + if from != nil && to != nil && from.Equal(to) { + return "" + } + if from == nil { + return to.String() + } + if to == nil || to.IsZero() { + // Resetting all styles is cheaper than calculating diffs. + // "\x1b[m" is 3 bytes vs potentially much longer sequences. + return ansi.ResetStyle + } + + // TODO: Optimize further by checking if a full reset is cheaper than + // calculating diffs. Often, it might be cheaper to reset everything and + // then set the desired styles rather than calculating diffs. Also more + // compatible with terminals that have buggy SGR implementations. + + var b ansi.Style + + if !colorEqual(from.Fg, to.Fg) { + b = b.ForegroundColor(to.Fg) + } + + if !colorEqual(from.Bg, to.Bg) { + b = b.BackgroundColor(to.Bg) + } + + if !colorEqual(from.UnderlineColor, to.UnderlineColor) { + // TODO: Investigate this. For backward compatibility, we might want to + // set this at the end instead. Because on terminals that don't support + // underline color, this might mess up some other attributes if set in + // the middle. + b = b.UnderlineColor(to.UnderlineColor) + } + + fromBold := from.Attrs&AttrBold != 0 + fromFaint := from.Attrs&AttrFaint != 0 + fromItalic := from.Attrs&AttrItalic != 0 + fromUnderline := from.Underline != UnderlineStyleNone + fromBlink := from.Attrs&AttrBlink != 0 + fromRapidBlink := from.Attrs&AttrRapidBlink != 0 + fromReverse := from.Attrs&AttrReverse != 0 + fromConceal := from.Attrs&AttrConceal != 0 + fromStrikethrough := from.Attrs&AttrStrikethrough != 0 + toBold := to.Attrs&AttrBold != 0 + toFaint := to.Attrs&AttrFaint != 0 + toItalic := to.Attrs&AttrItalic != 0 + toUnderline := to.Underline != UnderlineStyleNone + toBlink := to.Attrs&AttrBlink != 0 + toRapidBlink := to.Attrs&AttrRapidBlink != 0 + toReverse := to.Attrs&AttrReverse != 0 + toConceal := to.Attrs&AttrConceal != 0 + toStrikethrough := to.Attrs&AttrStrikethrough != 0 + + // We perform the resets first since they are single attributes and + // shouldn't interfere with others being set. + + boldChanged := fromBold != toBold + faintChanged := fromFaint != toFaint + if boldChanged || faintChanged { + if fromBold && !toBold || fromFaint && !toFaint { + b = b.Normal() + boldChanged = true + faintChanged = true + } + } + + italicChanged := fromItalic != toItalic + if italicChanged && !toItalic { + b = b.Italic(false) + } + + underlineChanged := fromUnderline != toUnderline || from.Underline != to.Underline + if underlineChanged && !toUnderline { + b = b.Underline(false) + } + + blinkChanged := fromBlink != toBlink + rapidBlinkChanged := fromRapidBlink != toRapidBlink + if blinkChanged || rapidBlinkChanged { + if fromBlink && !toBlink || fromRapidBlink && !toRapidBlink { + b = b.Blink(false) + blinkChanged = true + rapidBlinkChanged = true + } + } + + reverseChanged := fromReverse != toReverse + if reverseChanged && !toReverse { + b = b.Reverse(false) + } + + concealChanged := fromConceal != toConceal + if concealChanged && !toConceal { + b = b.Conceal(false) + } + + strikethroughChanged := fromStrikethrough != toStrikethrough + if strikethroughChanged && !toStrikethrough { + b = b.Strikethrough(false) + } + + if boldChanged && toBold { + b = b.Bold() + } + + if faintChanged && toFaint { + b = b.Faint() + } + + if italicChanged && toItalic { + b = b.Italic(true) + } + + if underlineChanged && toUnderline && to.Underline == UnderlineStyleSingle { + // We only handle single underline here since others require more + // specific handling at the end. + b = b.Underline(true) + } + + if blinkChanged && toBlink { + b = b.Blink(true) + } + + if rapidBlinkChanged && toRapidBlink { + b = b.RapidBlink(true) + } + + if reverseChanged && toReverse { + b = b.Reverse(true) + } + + if concealChanged && toConceal { + b = b.Conceal(true) + } + + if strikethroughChanged && toStrikethrough { + b = b.Strikethrough(true) + } + + // Handle special underline styles. + if underlineChanged && toUnderline && to.Underline > UnderlineStyleSingle { + b = b.UnderlineStyle(to.Underline) + } + + return b.String() +} + +func colorEqual(c, o color.Color) bool { + if c == nil && o == nil { + return true + } + if c == nil || o == nil { + return false + } + cr, cg, cb, ca := c.RGBA() + or, og, ob, oa := o.RGBA() + return cr == or && cg == og && cb == ob && ca == oa +} + +// IsZero returns true if the style is empty. A nil style is empty. +func (s *Style) IsZero() bool { + return s == nil || *s == Style{} +} + +// ConvertStyle converts a style to respect the given color profile. +func ConvertStyle(s Style, p colorprofile.Profile) Style { + switch p { + case colorprofile.TrueColor: + return s + case colorprofile.ANSI, colorprofile.ANSI256: + case colorprofile.Ascii: + s.Fg = nil + s.Bg = nil + s.UnderlineColor = nil + case colorprofile.NoTTY: + return Style{} + } + + if s.Fg != nil { + s.Fg = p.Convert(s.Fg) + } + if s.Bg != nil { + s.Bg = p.Convert(s.Bg) + } + if s.UnderlineColor != nil { + s.UnderlineColor = p.Convert(s.UnderlineColor) + } + return s +} + +// ConvertLink converts a hyperlink to respect the given color profile. +func ConvertLink(h Link, p colorprofile.Profile) Link { + if p == colorprofile.NoTTY { + return Link{} + } + return h +} diff --git a/cli/third_party/ultraviolet/console.go b/cli/third_party/ultraviolet/console.go new file mode 100644 index 000000000..7ef37fd60 --- /dev/null +++ b/cli/third_party/ultraviolet/console.go @@ -0,0 +1,219 @@ +package uv + +import ( + "io" + "os" + "runtime" + + "github.com/charmbracelet/x/term" +) + +var isWindows = runtime.GOOS == "windows" + +// File is an interface that represents a file with a file descriptor. +// +// This is typically an [os.File] like [os.Stdin] and [os.Stdout]. +type File interface { + io.ReadWriteCloser + term.File + + // Name returns the name of the file. + Name() string +} + +// Winsize represents the size of a terminal in cells and pixels. +// +// This is the same as [unix.Winsize], but defined here for cross-platform compatibility. +type Winsize struct { + Row uint16 + Col uint16 + Xpixel uint16 + Ypixel uint16 +} + +// Console represents a cross-platform console I/O interface. +type Console interface { + io.ReadWriteCloser + + // Environ returns the console's environment variables. + Environ() []string + + // Getenv retrieves the value of the environment variable named by the key. + Getenv(key string) string + + // LookupEnv retrieves the value of the environment variable named by the key + // and a boolean indicating whether the variable is present. + LookupEnv(key string) (string, bool) + + // Reader returns the input reader of the console. + Reader() io.Reader + + // Writer returns the output writer of the console. + Writer() io.Writer + + // MakeRaw puts the console input side into raw mode. + MakeRaw() (state *term.State, err error) + + // Restore restores the console to its previous state. + Restore() error + + // GetSize returns the current size of the console. + GetSize() (width, height int, err error) + + // GetWinsize returns the current size of the console in cells and pixels. + GetWinsize() (*Winsize, error) +} + +// TTY represents a Unix TTY device. It implements the [Console] interface. +type TTY struct { + *console +} + +var _ Console = (*TTY)(nil) + +// WinCon represents a Windows Console. It implements the [Console] interface. +type WinCon struct { + *console +} + +var _ Console = (*WinCon)(nil) + +// Console is a cross-platform console I/O. +type console struct { + input File + inputState *term.State + output File + outputState *term.State + environ Environ +} + +// DefaultConsole returns a new default console instance that uses standard I/O +// [os.Stdin], [os.Stdout], and [os.Environ]. +// +// To use [os.Stderr] as the output, you can create a new console with +// [NewConsole] and pass [os.Stderr] as the output parameter. +func DefaultConsole() Console { + return NewConsole(os.Stdin, os.Stdout, os.Environ()) +} + +// ControllingConsole returns a new console instance that uses the current +// controlling terminal's input and output file descriptors. +func ControllingConsole() (Console, error) { + inTty, outTty, err := OpenTTY() + if err != nil { + return nil, err + } + return NewConsole(inTty, outTty, os.Environ()), nil +} + +// NewConsole creates a new [Console] with the given input, output, and +// environment variables. +// +// You can use [OpenTTY] to open the current controlling console files and pass +// them to this function. Use [ControllingConsole] for a convenience function +// that does this for you. +// +// Use this to create a new terminal for PTY processes by passing the PTY slave +// file as the input and output and any environment variables the process +// needs. +func NewConsole(input, output File, environ []string) Console { + if input == nil { + input = os.Stdin + } + if output == nil { + output = os.Stdout + } + if environ == nil { + environ = os.Environ() + } + return newConsole(input, output, environ) +} + +// Environ returns the console's environment variables. +func (t *console) Environ() []string { + return t.environ +} + +// Writer returns the output writer of the console. +func (t *console) Writer() io.Writer { + return t.output +} + +// Reader returns the input reader of the console. +func (t *console) Reader() io.Reader { + return t.input +} + +// Write writes data to the console's output. +func (t *console) Write(p []byte) (n int, err error) { + return t.output.Write(p) +} + +// Read reads data from the console's input. +func (t *console) Read(p []byte) (n int, err error) { + return t.input.Read(p) +} + +// Getenv retrieves the value of the environment variable named by the key. +func (t *console) Getenv(key string) string { + return t.environ.Getenv(key) +} + +// LookupEnv retrieves the value of the environment variable named by the key +// and a boolean indicating whether the variable is present. +func (t *console) LookupEnv(key string) (string, bool) { + return t.environ.LookupEnv(key) +} + +// MakeRaw puts the console input side into raw mode. +func (t *console) MakeRaw() (state *term.State, err error) { + inState, outState, err := makeRaw(t.input, t.output) + if err != nil { + return nil, err + } + t.inputState = inState + t.outputState = outState + if inState != nil { + return inState, nil + } + return outState, nil +} + +// Restore restores the console to its previous state. +func (t *console) Restore() error { + if t.inputState != nil { + if err := term.Restore(t.input.Fd(), t.inputState); err != nil { + return err + } + t.inputState = nil + } + if t.outputState != nil { + if err := term.Restore(t.output.Fd(), t.outputState); err != nil { + return err + } + t.outputState = nil + } + return nil +} + +// Close restores the console to its previous state and releases resources. +func (t *console) Close() error { + if err := t.Restore(); err != nil { + return err + } + return nil +} + +// GetSize returns the current size of the console. +func (t *console) GetSize() (width, height int, err error) { + return getSize(t.input, t.output) +} + +// GetWinsize returns the current size of the console in cells and pixels. +func (t *console) GetWinsize() (*Winsize, error) { + ws, err := getWinsize(t.input, t.output) + if err != nil { + return nil, err + } + return &ws, nil +} diff --git a/cli/third_party/ultraviolet/console_unix.go b/cli/third_party/ultraviolet/console_unix.go new file mode 100644 index 000000000..5460effff --- /dev/null +++ b/cli/third_party/ultraviolet/console_unix.go @@ -0,0 +1,13 @@ +//go:build !windows +// +build !windows + +package uv + +func newConsole(in File, out File, env Environ) *TTY { + c := &console{ + input: in, + output: out, + environ: env, + } + return &TTY{console: c} +} diff --git a/cli/third_party/ultraviolet/console_windows.go b/cli/third_party/ultraviolet/console_windows.go new file mode 100644 index 000000000..0836f1c38 --- /dev/null +++ b/cli/third_party/ultraviolet/console_windows.go @@ -0,0 +1,13 @@ +//go:build windows +// +build windows + +package uv + +func newConsole(in File, out File, env Environ) *WinCon { + c := &console{ + input: in, + output: out, + environ: env, + } + return &WinCon{console: c} +} diff --git a/cli/third_party/ultraviolet/cursor.go b/cli/third_party/ultraviolet/cursor.go new file mode 100644 index 000000000..33a3843a8 --- /dev/null +++ b/cli/third_party/ultraviolet/cursor.go @@ -0,0 +1,22 @@ +package uv + +// CursorShape represents a terminal cursor shape. +type CursorShape int + +// Cursor shapes. +const ( + CursorBlock CursorShape = iota + CursorUnderline + CursorBar +) + +// Encode returns the encoded value for the cursor shape. +func (s CursorShape) Encode(blink bool) int { + // We're using the ANSI escape sequence values for cursor styles. + // We need to map both [style] and [steady] to the correct value. + s = (s * 2) + 1 //nolint:mnd + if !blink { + s++ + } + return int(s) +} diff --git a/cli/third_party/ultraviolet/decoder.go b/cli/third_party/ultraviolet/decoder.go new file mode 100644 index 000000000..d76cdf77e --- /dev/null +++ b/cli/third_party/ultraviolet/decoder.go @@ -0,0 +1,2117 @@ +package uv + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "fmt" + "image/color" + "math" + "slices" + "strings" + "unicode" + "unicode/utf8" + + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/ansi/parser" + xwindows "github.com/charmbracelet/x/windows" + "github.com/rivo/uniseg" +) + +// Flags to control the behavior of the parser. +const ( + // When this flag is set, the driver will treat both Ctrl+Space and Ctrl+@ + // as the same key sequence. + // + // Historically, the ANSI specs generate NUL (0x00) on both the Ctrl+Space + // and Ctrl+@ key sequences. This flag allows the driver to treat both as + // the same key sequence. + flagCtrlAt = 1 << iota + + // When this flag is set, the driver will treat the Tab key and Ctrl+I as + // the same key sequence. + // + // Historically, the ANSI specs generate HT (0x09) on both the Tab key and + // Ctrl+I. This flag allows the driver to treat both as the same key + // sequence. + flagCtrlI + + // When this flag is set, the driver will treat the Enter key and Ctrl+M as + // the same key sequence. + // + // Historically, the ANSI specs generate CR (0x0D) on both the Enter key + // and Ctrl+M. This flag allows the driver to treat both as the same key. + flagCtrlM + + // When this flag is set, the driver will treat Escape and Ctrl+[ as + // the same key sequence. + // + // Historically, the ANSI specs generate ESC (0x1B) on both the Escape key + // and Ctrl+[. This flag allows the driver to treat both as the same key + // sequence. + flagCtrlOpenBracket + + // When this flag is set, the driver will send a BS (0x08 byte) character + // instead of a DEL (0x7F byte) character when the Backspace key is + // pressed. + // + // The VT100 terminal has both a Backspace and a Delete key. The VT220 + // terminal dropped the Backspace key and replaced it with the Delete key. + // Both terminals send a DEL character when the Delete key is pressed. + // Modern terminals and PCs later readded the Delete key but used a + // different key sequence, and the Backspace key was standardized to send a + // DEL character. + flagBackspace + + // When this flag is set, the driver will recognize the Find key instead of + // treating it as a Home key. + // + // The Find key was part of the VT220 keyboard, and is no longer used in + // modern day PCs. + flagFind + + // When this flag is set, the driver will recognize the Select key instead + // of treating it as a End key. + // + // The Symbol key was part of the VT220 keyboard, and is no longer used in + // modern day PCs. + flagSelect + + // When this flag is set, the driver will preserve function keys (F13-F63) + // as symbols. + // + // Since these keys are not part of today's standard 20th century keyboard, + // we treat them as F1-F12 modifier keys i.e. ctrl/shift/alt + Fn combos. + // Key definitions come from Terminfo, this flag is only useful when + // FlagTerminfo is not set. + flagFKeys +) + +// LegacyKeyEncoding is a set of flags that control the behavior of legacy +// terminal key encodings. Historically, ctrl+ input events produce +// control characters (0x00-0x1F) that collide with some special keys like Tab, +// Enter, and Escape. This controls the expected behavior of encoding these +// keys. +// +// This type has the following default values: +// - CtrlAt maps 0x00 [ansi.NUL] to ctrl+space instead of ctrl+@. +// - CtrlI maps 0x09 [ansi.HT] to the tab key instead of ctrl+i. +// - CtrlM maps 0x0D [ansi.CR] to the enter key instead of ctrl+m. +// - CtrlOpenBracket maps 0x1B [ansi.ESC] to the escape key instead of ctrl+[. +// - Backspace maps the backspace key to 0x08 [ansi.BS] instead of 0x7F [ansi.DEL]. +// - Find maps the legacy find key to the home key. +// - Select maps the legacy select key to the end key. +// - FKeys maps high function keys instead of treating them as Function+. +type LegacyKeyEncoding uint32 + +// CtrlAt returns a [LegacyKeyEncoding] with whether [ansi.NUL] (0x00) +// is mapped to ctrl+at instead of ctrl+space. +func (l LegacyKeyEncoding) CtrlAt(v bool) LegacyKeyEncoding { + if v { + l |= flagCtrlAt + } else { + l &^= flagCtrlAt + } + return l +} + +// CtrlI returns a [LegacyKeyEncoding] with whether [ansi.HT] (0x09) +// is mapped to ctrl+i instead of the tab key. +func (l LegacyKeyEncoding) CtrlI(v bool) LegacyKeyEncoding { + if v { + l |= flagCtrlI + } else { + l &^= flagCtrlI + } + return l +} + +// CtrlM returns a [LegacyKeyEncoding] with whether [ansi.CR] (0x0D) +// is mapped to ctrl+m instead of the enter key. +func (l LegacyKeyEncoding) CtrlM(v bool) LegacyKeyEncoding { + if v { + l |= flagCtrlM + } else { + l &^= flagCtrlM + } + return l +} + +// CtrlOpenBracket returns a [LegacyKeyEncoding] with whether [ansi.ESC] (0x1B) +// is mapped to ctrl+[ instead of the escape key. +func (l LegacyKeyEncoding) CtrlOpenBracket(v bool) LegacyKeyEncoding { + if v { + l |= flagCtrlOpenBracket + } else { + l &^= flagCtrlOpenBracket + } + return l +} + +// Backspace returns a [LegacyKeyEncoding] with whether the backspace key is +// mapped to [ansi.BS] (0x08) instead of [ansi.DEL] (0x7F). +func (l LegacyKeyEncoding) Backspace(v bool) LegacyKeyEncoding { + if v { + l |= flagBackspace + } else { + l &^= flagBackspace + } + return l +} + +// Find returns a [LegacyKeyEncoding] with whether the legacy find key +// is mapped to the home key. +func (l LegacyKeyEncoding) Find(v bool) LegacyKeyEncoding { + if v { + l |= flagFind + } else { + l &^= flagFind + } + return l +} + +// Select returns a [LegacyKeyEncoding] with whether the legacy select key +// is mapped to the end key. +func (l LegacyKeyEncoding) Select(v bool) LegacyKeyEncoding { + if v { + l |= flagSelect + } else { + l &^= flagSelect + } + return l +} + +// FKeys returns a [LegacyKeyEncoding] with whether high function keys are +// mapped to high function keys (beyond F20) instead of treating them as +// Function+ keys. +func (l LegacyKeyEncoding) FKeys(v bool) LegacyKeyEncoding { + if v { + l |= flagFKeys + } else { + l &^= flagFKeys + } + return l +} + +// EventDecoder decodes terminal input events from a byte buffer. Terminal +// input events are typically encoded as Unicode or ASCII characters, control +// codes, or ANSI escape sequences. +type EventDecoder struct { + // Legacy is the legacy key encoding flags. These flags control the + // behavior of legacy terminal key encodings. See [LegacyKeyEncoding] for + // more details. + Legacy LegacyKeyEncoding + // UseTerminfo is a flag that controls whether to use the terminal type + // Terminfo database to map escape sequences to key events. This will + // override the default key sequences handled by the parser. + UseTerminfo bool + + lastCks uint32 // the last control key state for the previous key event record. +} + +// Decode finds the first recognized event sequence and returns it along +// with its length. +// +// It will return zero and nil no sequence is recognized or when the buffer is +// empty. If a sequence is not supported, an [UnknownEvent] is returned. +// +// Example: +// +// ```go +// var decoder EventDecoder +// var events []Event +// buf := []byte("\x00" + // Ctrl+Space +// "\x1b[A" + // Up arrow +// "Hello") // Text input +// for len(buf) > 0 { +// n, ev := decoder.Decode(buf) +// if ev != nil { +// events = append(events, ev) +// } +// buf = buf[n:] +// } +// ``` +func (p *EventDecoder) Decode(buf []byte) (n int, Event Event) { + if len(buf) == 0 { + return 0, nil + } + + switch b := buf[0]; b { + case ansi.ESC: + if len(buf) == 1 { + // Escape key + return 1, KeyPressEvent{Code: KeyEscape} + } + + switch bPrime := buf[1]; bPrime { + case 'O': // Esc-prefixed SS3 + return p.parseSs3(buf) + case 'P': // Esc-prefixed DCS + return p.parseDcs(buf) + case '[': // Esc-prefixed CSI + return p.parseCsi(buf) + case ']': // Esc-prefixed OSC + return p.parseOsc(buf) + case '_': // Esc-prefixed APC + return p.parseApc(buf) + case '^': // Esc-prefixed PM + return p.parseStTerminated(ansi.PM, '^', nil)(buf) + case 'X': // Esc-prefixed SOS + return p.parseStTerminated(ansi.SOS, 'X', nil)(buf) + default: + n, e := p.Decode(buf[1:]) + if k, ok := e.(KeyPressEvent); ok { + k.Text = "" + k.Mod |= ModAlt + return n + 1, k + } + + // Not a key sequence, nor an alt modified key sequence. In that + // case, just report a single escape key. + return 1, KeyPressEvent{Code: KeyEscape} + } + case ansi.SS3: + return p.parseSs3(buf) + case ansi.DCS: + return p.parseDcs(buf) + case ansi.CSI: + return p.parseCsi(buf) + case ansi.OSC: + return p.parseOsc(buf) + case ansi.APC: + return p.parseApc(buf) + case ansi.PM: + return p.parseStTerminated(ansi.PM, '^', nil)(buf) + case ansi.SOS: + return p.parseStTerminated(ansi.SOS, 'X', nil)(buf) + default: + if b <= ansi.US || b == ansi.DEL || b == ansi.SP { + return 1, p.parseControl(b) + } else if b >= ansi.PAD && b <= ansi.APC { + // C1 control code + // UTF-8 never starts with a C1 control code + // Encode these as Ctrl+Alt+ + code := rune(b) - 0x40 + return 1, KeyPressEvent{Code: code, Mod: ModCtrl | ModAlt} + } + return p.parseUtf8(buf) + } +} + +func (p *EventDecoder) parseCsi(b []byte) (int, Event) { + if len(b) == 2 && b[0] == ansi.ESC { + // short cut if this is an alt+[ key + return 2, KeyPressEvent{Code: rune(b[1]), Mod: ModAlt} + } + + var cmd ansi.Cmd + var params [parser.MaxParamsSize]ansi.Param + var paramsLen int + + var i int + if b[i] == ansi.CSI || b[i] == ansi.ESC { + i++ + } + if i < len(b) && b[i-1] == ansi.ESC && b[i] == '[' { + i++ + } + + // Initial CSI byte + if i < len(b) && b[i] >= '<' && b[i] <= '?' { + cmd |= ansi.Cmd(b[i]) << parser.PrefixShift + } + + // Scan parameter bytes in the range 0x30-0x3F + var j int + for j = 0; i < len(b) && paramsLen < len(params) && b[i] >= 0x30 && b[i] <= 0x3F; i, j = i+1, j+1 { + if b[i] >= '0' && b[i] <= '9' { + if params[paramsLen] == parser.MissingParam { + params[paramsLen] = 0 + } + params[paramsLen] *= 10 + params[paramsLen] += ansi.Param(b[i]) - '0' + } + if b[i] == ':' { + params[paramsLen] |= parser.HasMoreFlag + } + if b[i] == ';' || b[i] == ':' { + paramsLen++ + if paramsLen < len(params) { + // Don't overflow the params slice + params[paramsLen] = parser.MissingParam + } + } + } + + if j > 0 && paramsLen < len(params) { + // has parameters + paramsLen++ + } + + // Scan intermediate bytes in the range 0x20-0x2F + var intermed byte + for ; i < len(b) && b[i] >= 0x20 && b[i] <= 0x2F; i++ { + intermed = b[i] + } + + // Set the intermediate byte + cmd |= ansi.Cmd(intermed) << parser.IntermedShift + + // Scan final byte in the range 0x40-0x7E + if i >= len(b) || b[i] < 0x40 || b[i] > 0x7E { + // Special case for URxvt keys + // CSI $ is an invalid sequence, but URxvt uses it for + // shift modified keys. + if intermed == '$' && b[i-1] == '$' { + buf := slices.Clone(b[:i-1]) + n, ev := p.parseCsi(append(buf, '~')) + if k, ok := ev.(KeyPressEvent); ok { + k.Mod |= ModShift + return n, k + } + } + return i, UnknownEvent(b[:i]) + } + + // Add the final byte + cmd |= ansi.Cmd(b[i]) + i++ + + pa := ansi.Params(params[:paramsLen]) + switch cmd { + case 'y' | '?'<'<'< R (which is modified F3) when the cursor is at the + // row 1. In this case, we report both messages. + // + // For a non ambiguous cursor position report, use + // [ansi.RequestExtendedCursorPosition] (DECXCPR) instead. + return i, MultiEvent{KeyPressEvent{Code: KeyF3, Mod: KeyMod(col - 1)}, m} + } + + return i, m + } + + if paramsLen != 0 { + break + } + + // Unmodified key F3 (CSI R) + fallthrough + case 'a', 'b', 'c', 'd', 'A', 'B', 'C', 'D', 'E', 'F', 'H', 'P', 'Q', 'S', 'Z': + var k KeyPressEvent + switch cmd { + case 'a', 'b', 'c', 'd': + k = KeyPressEvent{Code: KeyUp + rune(cmd-'a'), Mod: ModShift} + case 'A', 'B', 'C', 'D': + k = KeyPressEvent{Code: KeyUp + rune(cmd-'A')} + case 'E': + k = KeyPressEvent{Code: KeyBegin} + case 'F': + k = KeyPressEvent{Code: KeyEnd} + case 'H': + k = KeyPressEvent{Code: KeyHome} + case 'P', 'Q', 'R', 'S': + k = KeyPressEvent{Code: KeyF1 + rune(cmd-'P')} + case 'Z': + k = KeyPressEvent{Code: KeyTab, Mod: ModShift} + } + id, _, _ := pa.Param(0, 1) + mod, _, _ := pa.Param(1, 1) + if paramsLen > 2 && !pa[1].HasMore() || id != 1 { + break + } + if paramsLen > 1 && id == 1 && mod != -1 { + // CSI 1 ; A + k.Mod |= KeyMod(mod - 1) + } + // Don't forget to handle Kitty keyboard protocol + return i, parseKittyKeyboardExt(pa, k) + case 'M': + // Handle X10 mouse + if i+3 > len(b) { + return i, UnknownCsiEvent(b[:i]) + } + return i + 3, parseX10MouseEvent(append(b[:i], b[i:i+3]...)) + case 'y' | '$'< 1 && mod != -1 { + k.Mod |= KeyMod(mod - 1) + } + + // Handle URxvt weird keys + switch cmd { + case '~': + // Don't forget to handle Kitty keyboard protocol + return i, parseKittyKeyboardExt(pa, k) + case '^': + k.Mod |= ModCtrl + case '@': + k.Mod |= ModCtrl | ModShift + } + + return i, k + } + + case 't': + param, _, ok := pa.Param(0, 0) + if !ok { + break + } + + switch param { + case 4: // Report Terminal window size in pixels. + if paramsLen == 3 { + height, _, hOk := pa.Param(1, 0) + width, _, wOk := pa.Param(2, 0) + if !hOk || !wOk { + break + } + return i, PixelSizeEvent{Width: width, Height: height} + } + case 6: // Report Terminal character cell size. + if paramsLen == 3 { + height, _, hOk := pa.Param(1, 0) + width, _, wOk := pa.Param(2, 0) + if !hOk || !wOk { + break + } + return i, CellSizeEvent{Width: width, Height: height} + } + case 8: // Report Terminal Window size in cells. + if paramsLen == 3 { + height, _, hOk := pa.Param(1, 0) + width, _, wOk := pa.Param(2, 0) + if !hOk || !wOk { + break + } + return i, WindowSizeEvent{Width: width, Height: height} + } + case 48: // In band terminal size report. + if paramsLen == 5 { + cellHeight, _, chOk := pa.Param(1, 0) + cellWidth, _, cwOk := pa.Param(2, 0) + pixelHeight, _, phOk := pa.Param(3, 0) + pixelWidth, _, pwOk := pa.Param(4, 0) + if !chOk || !cwOk || !phOk || !pwOk { + break + } + return i, MultiEvent{ + WindowSizeEvent{Width: cellWidth, Height: cellHeight}, + PixelSizeEvent{Width: pixelWidth, Height: pixelHeight}, + } + } + } + + // Any other window operation event. + + var winop WindowOpEvent + winop.Op = param + for j := 1; j < paramsLen; j++ { + val, _, ok := pa.Param(j, 0) + if ok { + winop.Args = append(winop.Args, val) + } + } + + return i, winop + } + return i, UnknownCsiEvent(b[:i]) +} + +// parseSs3 parses a SS3 sequence. +// See https://vt100.net/docs/vt220-rm/chapter4.html#S4.4.4.2 +func (p *EventDecoder) parseSs3(b []byte) (int, Event) { + if len(b) == 2 && b[0] == ansi.ESC { + // short cut if this is an alt+O key + return 2, KeyPressEvent{Code: unicode.ToLower(rune(b[1])), Mod: ModShift | ModAlt} + } + + var i int + if b[i] == ansi.SS3 || b[i] == ansi.ESC { + i++ + } + if i < len(b) && b[i-1] == ansi.ESC && b[i] == 'O' { + i++ + } + + // Scan numbers from 0-9 + var mod int + for ; i < len(b) && b[i] >= '0' && b[i] <= '9'; i++ { + mod *= 10 + mod += int(b[i]) - '0' + } + + // Scan a GL character + // A GL character is a single byte in the range 0x21-0x7E + // See https://vt100.net/docs/vt220-rm/chapter2.html#S2.3.2 + if i >= len(b) || b[i] < 0x21 || b[i] > 0x7E { + return i, UnknownEvent(b[:i]) + } + + // GL character(s) + gl := b[i] + i++ + + var k KeyPressEvent + switch gl { + case 'a', 'b', 'c', 'd': + k = KeyPressEvent{Code: KeyUp + rune(gl-'a'), Mod: ModCtrl} + case 'A', 'B', 'C', 'D': + k = KeyPressEvent{Code: KeyUp + rune(gl-'A')} + case 'E': + k = KeyPressEvent{Code: KeyBegin} + case 'F': + k = KeyPressEvent{Code: KeyEnd} + case 'H': + k = KeyPressEvent{Code: KeyHome} + case 'P', 'Q', 'R', 'S': + k = KeyPressEvent{Code: KeyF1 + rune(gl-'P')} + case 'M': + k = KeyPressEvent{Code: KeyKpEnter} + case 'X': + k = KeyPressEvent{Code: KeyKpEqual} + case 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y': + k = KeyPressEvent{Code: KeyKpMultiply + rune(gl-'j')} + default: + return i, UnknownSs3Event(b[:i]) + } + + // Handle weird SS3 Func + if mod > 0 { + k.Mod |= KeyMod(mod - 1) + } + + return i, k +} + +func (p *EventDecoder) parseOsc(b []byte) (int, Event) { + defaultKey := func() KeyPressEvent { + return KeyPressEvent{Code: rune(b[1]), Mod: ModAlt} + } + if len(b) == 2 && b[0] == ansi.ESC { + // short cut if this is an alt+] key + return 2, defaultKey() + } + + var i int + if b[i] == ansi.OSC || b[i] == ansi.ESC { + i++ + } + if i < len(b) && b[i-1] == ansi.ESC && b[i] == ']' { + i++ + } + + // Parse OSC command + // An OSC sequence is terminated by a BEL, ESC, or ST character + var start, end int + cmd := -1 + for ; i < len(b) && b[i] >= '0' && b[i] <= '9'; i++ { + if cmd == -1 { + cmd = 0 + } else { + cmd *= 10 + } + cmd += int(b[i]) - '0' + } + + if i < len(b) && b[i] == ';' { + // mark the start of the sequence data + i++ + start = i + } + + for ; i < len(b); i++ { + // advance to the end of the sequence + if slices.Contains([]byte{ansi.BEL, ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, b[i]) { + break + } + } + + if i >= len(b) { + return i, UnknownEvent(b[:i]) + } + + end = i // end of the sequence data + i++ + + // Check 7-bit ST (string terminator) character + switch b[i-1] { + case ansi.CAN, ansi.SUB: + return i, ignoredEvent(b[:i]) + case ansi.ESC: + if i >= len(b) || b[i] != '\\' { + if cmd == -1 || (start == 0 && end == 2) { + return 2, defaultKey() + } + if i >= len(b) { + // The read ended between ESC and the backslash of ST: wait + // for it instead of dropping the sequence and typing a \. + return i, UnknownEvent(b[:i]) + } + + // If we don't have a valid ST terminator, then this is a + // cancelled sequence and should be ignored. + return i, ignoredEvent(b[:i]) + } + + i++ + } + + if end <= start { + return i, UnknownEvent(b[:i]) + } + + data := string(b[start:end]) + switch cmd { + case 10: + return i, ForegroundColorEvent{ansi.XParseColor(data)} + case 11: + return i, BackgroundColorEvent{ansi.XParseColor(data)} + case 12: + return i, CursorColorEvent{ansi.XParseColor(data)} + case 52: + parts := strings.Split(data, ";") + if len(parts) != 2 || len(parts[0]) < 1 { + return i, ClipboardEvent{} + } + + b64 := parts[1] + bts, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + return i, ClipboardEvent{Content: parts[1]} + } + + sel := ClipboardSelection(parts[0][0]) //nolint:unconvert + return i, ClipboardEvent{Selection: sel, Content: string(bts)} + } + + return i, UnknownOscEvent(b[:i]) +} + +// parseStTerminated parses a control sequence that gets terminated by a ST character. +func (p *EventDecoder) parseStTerminated(intro8, intro7 byte, fn func([]byte) Event) func([]byte) (int, Event) { + defaultKey := func(b []byte) (int, Event) { + switch intro8 { + case ansi.SOS: + return 2, KeyPressEvent{Code: unicode.ToLower(rune(b[1])), Mod: ModShift | ModAlt} + case ansi.PM, ansi.APC: + return 2, KeyPressEvent{Code: rune(b[1]), Mod: ModAlt} + } + return 0, nil + } + return func(b []byte) (int, Event) { + if len(b) == 2 && b[0] == ansi.ESC { + return defaultKey(b) + } + + var i int + if b[i] == intro8 || b[i] == ansi.ESC { + i++ + } + if i < len(b) && b[i-1] == ansi.ESC && b[i] == intro7 { + i++ + } + + // Scan control sequence + // Most common control sequence is terminated by a ST character + // ST is a 7-bit string terminator character is (ESC \) + start := i + for ; i < len(b); i++ { + if slices.Contains([]byte{ansi.ESC, ansi.ST, ansi.CAN, ansi.SUB}, b[i]) { + break + } + } + + if i >= len(b) { + return i, UnknownEvent(b[:i]) + } + + end := i // end of the sequence data + i++ + + // Check 7-bit ST (string terminator) character + switch b[i-1] { + case ansi.CAN, ansi.SUB: + return i, ignoredEvent(b[:i]) + case ansi.ESC: + if i >= len(b) || b[i] != '\\' { + if start == end { + return defaultKey(b) + } + if i >= len(b) { + // ST may still be arriving; see parseOsc. + return i, UnknownEvent(b[:i]) + } + + // If we don't have a valid ST terminator, then this is a + // cancelled sequence and should be ignored. + return i, ignoredEvent(b[:i]) + } + + i++ + } + + // Call the function to parse the sequence and return the result + if fn != nil { + if e := fn(b[start:end]); e != nil { + return i, e + } + } + + switch intro8 { + case ansi.PM: + return i, UnknownPmEvent(b[:i]) + case ansi.SOS: + return i, UnknownSosEvent(b[:i]) + case ansi.APC: + return i, UnknownApcEvent(b[:i]) + default: + return i, UnknownEvent(b[:i]) + } + } +} + +func (p *EventDecoder) parseDcs(b []byte) (int, Event) { + if len(b) == 2 && b[0] == ansi.ESC { + // short cut if this is an alt+P key + return 2, KeyPressEvent{Code: unicode.ToLower(rune(b[1])), Mod: ModShift | ModAlt} + } + + var params [16]ansi.Param + var paramsLen int + var cmd ansi.Cmd + + // DCS sequences are introduced by DCS (0x90) or ESC P (0x1b 0x50) + var i int + if b[i] == ansi.DCS || b[i] == ansi.ESC { + i++ + } + if i < len(b) && b[i-1] == ansi.ESC && b[i] == 'P' { + i++ + } + + // initial DCS byte + if i < len(b) && b[i] >= '<' && b[i] <= '?' { + cmd |= ansi.Cmd(b[i]) << parser.PrefixShift + } + + // Scan parameter bytes in the range 0x30-0x3F + var j int + for j = 0; i < len(b) && paramsLen < len(params) && b[i] >= 0x30 && b[i] <= 0x3F; i, j = i+1, j+1 { + if b[i] >= '0' && b[i] <= '9' { + if params[paramsLen] == parser.MissingParam { + params[paramsLen] = 0 + } + params[paramsLen] *= 10 + params[paramsLen] += ansi.Param(b[i]) - '0' + } + if b[i] == ':' { + params[paramsLen] |= parser.HasMoreFlag + } + if b[i] == ';' || b[i] == ':' { + paramsLen++ + if paramsLen < len(params) { + // Don't overflow the params slice + params[paramsLen] = parser.MissingParam + } + } + } + + if j > 0 && paramsLen < len(params) { + // has parameters + paramsLen++ + } + + // Scan intermediate bytes in the range 0x20-0x2F + var intermed byte + for j := 0; i < len(b) && b[i] >= 0x20 && b[i] <= 0x2F; i, j = i+1, j+1 { + intermed = b[i] + } + + // set intermediate byte + cmd |= ansi.Cmd(intermed) << parser.IntermedShift + + // Scan final byte in the range 0x40-0x7E + if i >= len(b) || b[i] < 0x40 || b[i] > 0x7E { + return i, UnknownEvent(b[:i]) + } + + // Add the final byte + cmd |= ansi.Cmd(b[i]) + i++ + + start := i // start of the sequence data + for ; i < len(b); i++ { + if b[i] == ansi.ST || b[i] == ansi.ESC { + break + } + } + + if i >= len(b) { + return i, UnknownEvent(b[:i]) + } + + end := i // end of the sequence data + i++ + + // Check 7-bit ST (string terminator) character + if b[i-1] == ansi.ESC { + if i >= len(b) { + // ST may still be arriving; see parseOsc. + return i, UnknownEvent(b[:i]) + } + if b[i] == '\\' { + i++ + } + } + + pa := ansi.Params(params[:paramsLen]) + switch cmd { + case 'r' | '+'<'< 1 { + g.Payload = parts[1] + } + return g + } + + return nil + })(b) +} + +func (p *EventDecoder) parseUtf8(b []byte) (int, Event) { + if len(b) == 0 { + return 0, nil + } + + c := b[0] + if c <= ansi.US || c == ansi.DEL { + // Control codes get handled by parseControl + return 1, p.parseControl(c) + } else if c > ansi.US && c < ansi.DEL { + // ASCII printable characters + code := rune(c) + k := KeyPressEvent{Code: code, Text: string(code)} + if unicode.IsUpper(code) { + // Convert upper case letters to lower case + shift modifier + k.Code = unicode.ToLower(code) + k.ShiftedCode = code + k.Mod |= ModShift + } + + return 1, k + } + + code, _ := utf8.DecodeRune(b) + if code == utf8.RuneError { + return 1, UnknownEvent(b[0]) + } + + cluster, _, _, _ := uniseg.FirstGraphemeCluster(b, -1) + text := string(cluster) + for i := range text { + if i > 0 { + // Use [KeyExtended] for multi-rune graphemes + code = KeyExtended + break + } + } + + return len(cluster), KeyPressEvent{Code: code, Text: text} +} + +func (p *EventDecoder) parseControl(b byte) Event { + switch b { + case ansi.NUL: + if p.Legacy&flagCtrlAt != 0 { + return KeyPressEvent{Code: '@', Mod: ModCtrl} + } + return KeyPressEvent{Code: KeySpace, Mod: ModCtrl} + case ansi.BS: + return KeyPressEvent{Code: 'h', Mod: ModCtrl} + case ansi.HT: + if p.Legacy&flagCtrlI != 0 { + return KeyPressEvent{Code: 'i', Mod: ModCtrl} + } + return KeyPressEvent{Code: KeyTab} + case ansi.CR: + if p.Legacy&flagCtrlM != 0 { + return KeyPressEvent{Code: 'm', Mod: ModCtrl} + } + return KeyPressEvent{Code: KeyEnter} + case ansi.ESC: + if p.Legacy&flagCtrlOpenBracket != 0 { + return KeyPressEvent{Code: '[', Mod: ModCtrl} + } + return KeyPressEvent{Code: KeyEscape} + case ansi.DEL: + if p.Legacy&flagBackspace != 0 { + return KeyPressEvent{Code: KeyDelete} + } + return KeyPressEvent{Code: KeyBackspace} + case ansi.SP: + return KeyPressEvent{Code: KeySpace, Text: " "} + default: + if b >= ansi.SOH && b <= ansi.SUB { + // Use lower case letters for control codes + code := rune(b + 0x60) + return KeyPressEvent{Code: code, Mod: ModCtrl} + } else if b >= ansi.FS && b <= ansi.US { + code := rune(b + 0x40) + return KeyPressEvent{Code: code, Mod: ModCtrl} + } + return UnknownEvent(b) + } +} + +func parseXTermModifyOtherKeys(params ansi.Params) Event { + // XTerm modify other keys starts with ESC [ 27 ; ; ~ + xmod, _, _ := params.Param(1, 1) + xrune, _, _ := params.Param(2, 1) + mod := KeyMod(xmod - 1) + r := rune(xrune) + + switch r { + case ansi.BS: + return KeyPressEvent{Mod: mod, Code: KeyBackspace} + case ansi.HT: + return KeyPressEvent{Mod: mod, Code: KeyTab} + case ansi.CR: + return KeyPressEvent{Mod: mod, Code: KeyEnter} + case ansi.ESC: + return KeyPressEvent{Mod: mod, Code: KeyEscape} + case ansi.DEL: + return KeyPressEvent{Mod: mod, Code: KeyBackspace} + } + + // CSI 27 ; ; ~ keys defined in XTerm modifyOtherKeys + k := KeyPressEvent{Code: r, Mod: mod} + if k.Mod <= ModShift { + k.Text = string(r) + } + + return k +} + +// Kitty Clipboard Control Sequences. +var kittyKeyMap = map[int]Key{ + ansi.BS: {Code: KeyBackspace}, + ansi.HT: {Code: KeyTab}, + ansi.CR: {Code: KeyEnter}, + ansi.ESC: {Code: KeyEscape}, + ansi.DEL: {Code: KeyBackspace}, + + 57344: {Code: KeyEscape}, + 57345: {Code: KeyEnter}, + 57346: {Code: KeyTab}, + 57347: {Code: KeyBackspace}, + 57348: {Code: KeyInsert}, + 57349: {Code: KeyDelete}, + 57350: {Code: KeyLeft}, + 57351: {Code: KeyRight}, + 57352: {Code: KeyUp}, + 57353: {Code: KeyDown}, + 57354: {Code: KeyPgUp}, + 57355: {Code: KeyPgDown}, + 57356: {Code: KeyHome}, + 57357: {Code: KeyEnd}, + 57358: {Code: KeyCapsLock}, + 57359: {Code: KeyScrollLock}, + 57360: {Code: KeyNumLock}, + 57361: {Code: KeyPrintScreen}, + 57362: {Code: KeyPause}, + 57363: {Code: KeyMenu}, + 57364: {Code: KeyF1}, + 57365: {Code: KeyF2}, + 57366: {Code: KeyF3}, + 57367: {Code: KeyF4}, + 57368: {Code: KeyF5}, + 57369: {Code: KeyF6}, + 57370: {Code: KeyF7}, + 57371: {Code: KeyF8}, + 57372: {Code: KeyF9}, + 57373: {Code: KeyF10}, + 57374: {Code: KeyF11}, + 57375: {Code: KeyF12}, + 57376: {Code: KeyF13}, + 57377: {Code: KeyF14}, + 57378: {Code: KeyF15}, + 57379: {Code: KeyF16}, + 57380: {Code: KeyF17}, + 57381: {Code: KeyF18}, + 57382: {Code: KeyF19}, + 57383: {Code: KeyF20}, + 57384: {Code: KeyF21}, + 57385: {Code: KeyF22}, + 57386: {Code: KeyF23}, + 57387: {Code: KeyF24}, + 57388: {Code: KeyF25}, + 57389: {Code: KeyF26}, + 57390: {Code: KeyF27}, + 57391: {Code: KeyF28}, + 57392: {Code: KeyF29}, + 57393: {Code: KeyF30}, + 57394: {Code: KeyF31}, + 57395: {Code: KeyF32}, + 57396: {Code: KeyF33}, + 57397: {Code: KeyF34}, + 57398: {Code: KeyF35}, + 57399: {Code: KeyKp0}, + 57400: {Code: KeyKp1}, + 57401: {Code: KeyKp2}, + 57402: {Code: KeyKp3}, + 57403: {Code: KeyKp4}, + 57404: {Code: KeyKp5}, + 57405: {Code: KeyKp6}, + 57406: {Code: KeyKp7}, + 57407: {Code: KeyKp8}, + 57408: {Code: KeyKp9}, + 57409: {Code: KeyKpDecimal}, + 57410: {Code: KeyKpDivide}, + 57411: {Code: KeyKpMultiply}, + 57412: {Code: KeyKpMinus}, + 57413: {Code: KeyKpPlus}, + 57414: {Code: KeyKpEnter}, + 57415: {Code: KeyKpEqual}, + 57416: {Code: KeyKpSep}, + 57417: {Code: KeyKpLeft}, + 57418: {Code: KeyKpRight}, + 57419: {Code: KeyKpUp}, + 57420: {Code: KeyKpDown}, + 57421: {Code: KeyKpPgUp}, + 57422: {Code: KeyKpPgDown}, + 57423: {Code: KeyKpHome}, + 57424: {Code: KeyKpEnd}, + 57425: {Code: KeyKpInsert}, + 57426: {Code: KeyKpDelete}, + 57427: {Code: KeyKpBegin}, + 57428: {Code: KeyMediaPlay}, + 57429: {Code: KeyMediaPause}, + 57430: {Code: KeyMediaPlayPause}, + 57431: {Code: KeyMediaReverse}, + 57432: {Code: KeyMediaStop}, + 57433: {Code: KeyMediaFastForward}, + 57434: {Code: KeyMediaRewind}, + 57435: {Code: KeyMediaNext}, + 57436: {Code: KeyMediaPrev}, + 57437: {Code: KeyMediaRecord}, + 57438: {Code: KeyLowerVol}, + 57439: {Code: KeyRaiseVol}, + 57440: {Code: KeyMute}, + 57441: {Code: KeyLeftShift}, + 57442: {Code: KeyLeftCtrl}, + 57443: {Code: KeyLeftAlt}, + 57444: {Code: KeyLeftSuper}, + 57445: {Code: KeyLeftHyper}, + 57446: {Code: KeyLeftMeta}, + 57447: {Code: KeyRightShift}, + 57448: {Code: KeyRightCtrl}, + 57449: {Code: KeyRightAlt}, + 57450: {Code: KeyRightSuper}, + 57451: {Code: KeyRightHyper}, + 57452: {Code: KeyRightMeta}, + 57453: {Code: KeyIsoLevel3Shift}, + 57454: {Code: KeyIsoLevel5Shift}, +} + +func init() { + // These are some faulty C0 mappings some terminals such as WezTerm have + // and doesn't follow the specs. + kittyKeyMap[ansi.NUL] = Key{Code: KeySpace, Mod: ModCtrl} + for i := ansi.SOH; i <= ansi.SUB; i++ { + if _, ok := kittyKeyMap[i]; !ok { + kittyKeyMap[i] = Key{Code: rune(i + 0x60), Mod: ModCtrl} + } + } + for i := ansi.FS; i <= ansi.US; i++ { + if _, ok := kittyKeyMap[i]; !ok { + kittyKeyMap[i] = Key{Code: rune(i + 0x40), Mod: ModCtrl} + } + } +} + +const ( + kittyShift = 1 << iota + kittyAlt + kittyCtrl + kittySuper + kittyHyper + kittyMeta + kittyCapsLock + kittyNumLock +) + +func fromKittyMod(mod int) KeyMod { + var m KeyMod + if mod&kittyShift != 0 { + m |= ModShift + } + if mod&kittyAlt != 0 { + m |= ModAlt + } + if mod&kittyCtrl != 0 { + m |= ModCtrl + } + if mod&kittySuper != 0 { + m |= ModSuper + } + if mod&kittyHyper != 0 { + m |= ModHyper + } + if mod&kittyMeta != 0 { + m |= ModMeta + } + if mod&kittyCapsLock != 0 { + m |= ModCapsLock + } + if mod&kittyNumLock != 0 { + m |= ModNumLock + } + return m +} + +// parseKittyKeyboard parses a Kitty Keyboard Protocol sequence. +// +// In `CSI u`, this is parsed as: +// +// CSI codepoint ; modifiers u +// codepoint: ASCII Dec value +// +// The Kitty Keyboard Protocol extends this with optional components that can be +// enabled progressively. The full sequence is parsed as: +// +// CSI unicode-key-code:alternate-key-codes ; modifiers:event-type ; text-as-codepoints u +// +// See https://sw.kovidgoyal.net/kitty/keyboard-protocol/ +func parseKittyKeyboard(params ansi.Params) (Event Event) { + var isRelease bool + var key Key + + // The index of parameters separated by semicolons ';'. Sub parameters are + // separated by colons ':'. + var paramIdx int + var sudIdx int // The sub parameter index + for _, p := range params { + // Kitty Keyboard Protocol has 3 optional components. + switch paramIdx { + case 0: + switch sudIdx { + case 0: + var foundKey bool + code := p.Param(1) // CSI u has a default value of 1 + key, foundKey = kittyKeyMap[code] + if !foundKey { + r := rune(code) + if !utf8.ValidRune(r) { + r = utf8.RuneError + } + + key.Code = r + } + + case 2: + // shifted key + base key + if b := rune(p.Param(1)); unicode.IsPrint(b) { + // XXX: When alternate key reporting is enabled, the protocol + // can return 3 things, the unicode codepoint of the key, + // the shifted codepoint of the key, and the standard + // PC-101 key layout codepoint. + // This is useful to create an unambiguous mapping of keys + // when using a different language layout. + key.BaseCode = b + } + fallthrough + + case 1: + // shifted key + if s := rune(p.Param(1)); unicode.IsPrint(s) { + // XXX: We swap keys here because we want the shifted key + // to be the Rune that is returned by the event. + // For example, shift+a should produce "A" not "a". + // In such a case, we set AltRune to the original key "a" + // and Rune to "A". + key.ShiftedCode = s + } + } + case 1: + switch sudIdx { + case 0: + mod := p.Param(1) + if mod > 1 { + key.Mod = fromKittyMod(mod - 1) + if key.Mod > ModShift { + // XXX: We need to clear the text if we have a modifier key + // other than a [ModShift] key. + key.Text = "" + } + } + + case 1: + switch p.Param(1) { + case 2: + key.IsRepeat = true + case 3: + isRelease = true + } + case 2: + } + case 2: + if code := p.Param(0); code != 0 { + key.Text += string(rune(code)) + } + } + + sudIdx++ + if !p.HasMore() { + paramIdx++ + sudIdx = 0 + } + } + + keyMod := key.Mod + + // Remove these lock modifiers from now on since they don't affect the text. + keyMod &^= ModNumLock + // keyMod &^= ModScrollLock // Kitty doesn't support scroll lock + + printMod := keyMod <= ModShift || keyMod == ModCapsLock || keyMod == (ModShift|ModCapsLock) + printKeyPad := key.Code >= KeyKpEqual && key.Code <= KeyKpSep + if len(key.Text) == 0 && printKeyPad && printMod { + switch { + case key.Code >= KeyKp0 && key.Code <= KeyKp9: + key.Text = string('0' + key.Code - KeyKp0) + case key.Code == KeyKpEqual: + key.Text = "=" + case key.Code == KeyKpMultiply: + key.Text = "*" + case key.Code == KeyKpPlus: + key.Text = "+" + case key.Code == KeyKpMinus: + key.Text = "-" + case key.Code == KeyKpDecimal: + key.Text = "." + case key.Code == KeyKpDivide: + key.Text = "/" + case key.Code == KeyKpSep: + key.Text = "," + } + } + + //nolint:nestif + if len(key.Text) == 0 && unicode.IsPrint(key.Code) && printMod { + if keyMod == 0 { + key.Text = string(key.Code) + } else { + desiredCase := unicode.ToLower + if keyMod.Contains(ModShift) || keyMod.Contains(ModCapsLock) { + desiredCase = unicode.ToUpper + } + if key.ShiftedCode != 0 { + key.Text = string(key.ShiftedCode) + } else { + key.Text = string(desiredCase(key.Code)) + } + } + } + + if isRelease { + return KeyReleaseEvent(key) + } + + return KeyPressEvent(key) +} + +// parseKittyKeyboardExt parses a Kitty Keyboard Protocol sequence extensions +// for non CSI u sequences. This includes things like CSI A, SS3 A and others, +// and CSI ~. +func parseKittyKeyboardExt(params ansi.Params, k KeyPressEvent) Event { + // Handle Kitty keyboard protocol + if len(params) > 2 && // We have at least 3 parameters + params[1].HasMore() { // The second parameter is a subparameter (separated by a ":") + switch params[2].Param(1) { // The third parameter is the event type (defaults to 1) + case 2: + k.IsRepeat = true + case 3: + return KeyReleaseEvent(k) + } + } + return k +} + +func parsePrimaryDevAttrs(params ansi.Params) Event { + // Primary Device Attributes + da1 := make(PrimaryDeviceAttributesEvent, len(params)) + for i, p := range params { + if !p.HasMore() { + da1[i] = p.Param(0) + } + } + return da1 +} + +func parseSecondaryDevAttrs(params ansi.Params) Event { + // Secondary Device Attributes + da2 := make(SecondaryDeviceAttributesEvent, len(params)) + for i, p := range params { + if !p.HasMore() { + da2[i] = p.Param(0) + } + } + return da2 +} + +func parseTertiaryDevAttrs(b []byte) Event { + // Tertiary Device Attributes + // The response is a 4-digit hexadecimal number. + bts, err := hex.DecodeString(string(b)) + if err != nil { + return UnknownDcsEvent(fmt.Sprintf("\x1bP!|%s\x1b\\", b)) + } + return TertiaryDeviceAttributesEvent(bts) +} + +// Parse SGR-encoded mouse events; SGR extended mouse events. SGR mouse events +// look like: +// +// ESC [ < Cb ; Cx ; Cy (M or m) +// +// where: +// +// Cb is the encoded button code +// Cx is the x-coordinate of the mouse +// Cy is the y-coordinate of the mouse +// M is for button press, m is for button release +// +// https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates +func parseSGRMouseEvent(cmd ansi.Cmd, params ansi.Params) Event { + x, _, ok := params.Param(1, 1) + if !ok { + x = 1 + } + y, _, ok := params.Param(2, 1) + if !ok { + y = 1 + } + release := cmd.Final() == 'm' + b, _, _ := params.Param(0, 0) + mod, btn, _, isMotion := parseMouseButton(b) + + // (1,1) is the upper left. We subtract 1 to normalize it to (0,0). + x-- + y-- + + m := Mouse{X: x, Y: y, Button: btn, Mod: mod} + + // Wheel buttons don't have release events + // Motion can be reported as a release event in some terminals (Windows Terminal) + if isWheel(m.Button) { + return MouseWheelEvent(m) + } else if !isMotion && release { + return MouseReleaseEvent(m) + } else if isMotion { + return MouseMotionEvent(m) + } + return MouseClickEvent(m) +} + +const x10MouseByteOffset = 32 + +// Parse X10-encoded mouse events; the simplest kind. The last release of X10 +// was December 1986, by the way. The original X10 mouse protocol limits the Cx +// and Cy coordinates to 223 (=255-032). +// +// X10 mouse events look like: +// +// ESC [M Cb Cx Cy +// +// See: http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking +func parseX10MouseEvent(buf []byte) Event { + v := buf[3:6] + b := int(v[0]) + if b >= x10MouseByteOffset { + // XXX: b < 32 should be impossible, but we're being defensive. + b -= x10MouseByteOffset + } + + mod, btn, isRelease, isMotion := parseMouseButton(b) + + // (1,1) is the upper left. We subtract 1 to normalize it to (0,0). + x := int(v[1]) - x10MouseByteOffset - 1 + y := int(v[2]) - x10MouseByteOffset - 1 + + m := Mouse{X: x, Y: y, Button: btn, Mod: mod} + if isWheel(m.Button) { + return MouseWheelEvent(m) + } else if isMotion { + return MouseMotionEvent(m) + } else if isRelease { + return MouseReleaseEvent(m) + } + return MouseClickEvent(m) +} + +// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Extended-coordinates +func parseMouseButton(b int) (mod KeyMod, btn MouseButton, isRelease bool, isMotion bool) { + // mouse bit shifts + const ( + bitShift = 0b0000_0100 + bitAlt = 0b0000_1000 + bitCtrl = 0b0001_0000 + bitMotion = 0b0010_0000 + bitWheel = 0b0100_0000 + bitAdd = 0b1000_0000 // additional buttons 8-11 + + bitsMask = 0b0000_0011 + ) + + // Modifiers + if b&bitAlt != 0 { + mod |= ModAlt + } + if b&bitCtrl != 0 { + mod |= ModCtrl + } + if b&bitShift != 0 { + mod |= ModShift + } + + if b&bitAdd != 0 { + btn = MouseBackward + MouseButton(b&bitsMask) + } else if b&bitWheel != 0 { + btn = MouseWheelUp + MouseButton(b&bitsMask) + } else { + btn = MouseLeft + MouseButton(b&bitsMask) + // X10 reports a button release as 0b0000_0011 (3) + if b&bitsMask == bitsMask { + btn = MouseNone + isRelease = true + } + } + + // Motion bit doesn't get reported for wheel events. + if b&bitMotion != 0 && !isWheel(btn) { + isMotion = true + } + + return //nolint:nakedret +} + +// isWheel returns true if the mouse event is a wheel event. +func isWheel(btn MouseButton) bool { + return btn >= MouseWheelUp && btn <= MouseWheelRight +} + +type shiftable interface { + ~uint | ~uint16 | ~uint32 | ~uint64 +} + +func shift[T shiftable](x T) T { + if x > 0xff { + x >>= 8 + } + return x +} + +func colorToHex(c color.Color) string { + if c == nil { + return "" + } + r, g, b, _ := c.RGBA() + return fmt.Sprintf("#%02x%02x%02x", shift(r), shift(g), shift(b)) +} + +func getMaxMin(a, b, c float64) (ma, mi float64) { + if a > b { + ma = a + mi = b + } else { + ma = b + mi = a + } + if c > ma { + ma = c + } else if c < mi { + mi = c + } + return ma, mi +} + +func round(x float64) float64 { + return math.Round(x*1000) / 1000 +} + +// rgbToHSL converts an RGB triple to an HSL triple. +func rgbToHSL(r, g, b uint8) (h, s, l float64) { + // convert uint32 pre-multiplied value to uint8 + // The r,g,b values are divided by 255 to change the range from 0..255 to 0..1: + Rnot := float64(r) / 255 + Gnot := float64(g) / 255 + Bnot := float64(b) / 255 + Cmax, Cmin := getMaxMin(Rnot, Gnot, Bnot) + Δ := Cmax - Cmin + // Lightness calculation: + l = (Cmax + Cmin) / 2 + // Hue and Saturation Calculation: + if Δ == 0 { + h = 0 + s = 0 + } else { + switch Cmax { + case Rnot: + h = 60 * math.Mod((Gnot-Bnot)/Δ, 6) + case Gnot: + h = 60 * (((Bnot - Rnot) / Δ) + 2) + case Bnot: + h = 60 * (((Rnot - Gnot) / Δ) + 4) + } + if h < 0 { + h += 360 + } + + s = Δ / (1 - math.Abs((2*l)-1)) + } + + return h, round(s), round(l) +} + +// isDarkColor returns whether the given color is dark. +func isDarkColor(c color.Color) bool { + if c == nil { + return true + } + + r, g, b, _ := c.RGBA() + _, _, l := rgbToHSL(uint8(r>>8), uint8(g>>8), uint8(b>>8)) //nolint:gosec + return l < 0.5 +} + +func parseTermcap(data []byte) CapabilityEvent { + // XTGETTCAP + if len(data) == 0 { + return CapabilityEvent{""} + } + + var tc strings.Builder + split := bytes.Split(data, []byte{';'}) + for _, s := range split { + parts := bytes.SplitN(s, []byte{'='}, 2) + if len(parts) == 0 { + return CapabilityEvent{""} + } + + name, err := hex.DecodeString(string(parts[0])) + if err != nil || len(name) == 0 { + continue + } + + var value []byte + if len(parts) > 1 { + value, err = hex.DecodeString(string(parts[1])) + if err != nil { + continue + } + } + + if tc.Len() > 0 { + tc.WriteByte(';') + } + tc.WriteString(string(name)) + if len(value) > 0 { + tc.WriteByte('=') + tc.WriteString(string(value)) + } + } + + return CapabilityEvent{tc.String()} +} + +// parseWin32InputKeyEvent converts a Windows Input Record Key Event into a +// KeyPressEvent, KeyReleaseEvent, or MultiEvent including multiple of the +// former type. +// A special case is when the key is either part of VtInputMode which produces +// vkc == 0, or when a key is a UTF-16 surrogate pair. In both of these cases, +// we need to handle key encoding and properly parse the key event. +func (p *EventDecoder) parseWin32InputKeyEvent(vkc uint16, _ uint16, r rune, keyDown bool, cks uint32, repeatCount uint16) (event Event) { + defer func() { + // Respect the repeat count. + if repeatCount > 1 { + var multi MultiEvent + for i := 0; i < int(repeatCount); i++ { + multi = append(multi, event) + } + event = multi + } + }() + defer func() { + if vkc != 0 { + p.lastCks = cks + } + }() + + var key Key + switch { + case vkc == 0: + // This is either a UTF-16 encoded pair, or an escape sequence waiting + // to be decoded. + if keyDown { + return KeyPressEvent{Code: 0, BaseCode: r, Mod: translateControlKeyState(cks)} + } + return KeyReleaseEvent{Code: 0, BaseCode: r, Mod: translateControlKeyState(cks)} + case vkc == xwindows.VK_BACK: + key.BaseCode = KeyBackspace + case vkc == xwindows.VK_TAB: + key.BaseCode = KeyTab + case vkc == xwindows.VK_RETURN: + key.BaseCode = KeyEnter + case vkc == xwindows.VK_SHIFT: + //nolint:nestif + if cks&xwindows.SHIFT_PRESSED != 0 { + if cks&xwindows.ENHANCED_KEY != 0 { + key.BaseCode = KeyRightShift + } else { + key.BaseCode = KeyLeftShift + } + } else if p.lastCks&xwindows.SHIFT_PRESSED != 0 { + if p.lastCks&xwindows.ENHANCED_KEY != 0 { + key.BaseCode = KeyRightShift + } else { + key.BaseCode = KeyLeftShift + } + } + case vkc == xwindows.VK_CONTROL: + if cks&xwindows.LEFT_CTRL_PRESSED != 0 { + key.BaseCode = KeyLeftCtrl + } else if cks&xwindows.RIGHT_CTRL_PRESSED != 0 { + key.BaseCode = KeyRightCtrl + } else if p.lastCks&xwindows.LEFT_CTRL_PRESSED != 0 { + key.BaseCode = KeyLeftCtrl + } else if p.lastCks&xwindows.RIGHT_CTRL_PRESSED != 0 { + key.BaseCode = KeyRightCtrl + } + case vkc == xwindows.VK_MENU: + if cks&xwindows.LEFT_ALT_PRESSED != 0 { + key.BaseCode = KeyLeftAlt + } else if cks&xwindows.RIGHT_ALT_PRESSED != 0 { + key.BaseCode = KeyRightAlt + } else if p.lastCks&xwindows.LEFT_ALT_PRESSED != 0 { + key.BaseCode = KeyLeftAlt + } else if p.lastCks&xwindows.RIGHT_ALT_PRESSED != 0 { + key.BaseCode = KeyRightAlt + } + case vkc == xwindows.VK_PAUSE: + key.BaseCode = KeyPause + case vkc == xwindows.VK_CAPITAL: + key.BaseCode = KeyCapsLock + case vkc == xwindows.VK_ESCAPE: + key.BaseCode = KeyEscape + case vkc == xwindows.VK_SPACE: + key.BaseCode = KeySpace + case vkc == xwindows.VK_PRIOR: + key.BaseCode = KeyPgUp + case vkc == xwindows.VK_NEXT: + key.BaseCode = KeyPgDown + case vkc == xwindows.VK_END: + key.BaseCode = KeyEnd + case vkc == xwindows.VK_HOME: + key.BaseCode = KeyHome + case vkc == xwindows.VK_LEFT: + key.BaseCode = KeyLeft + case vkc == xwindows.VK_UP: + key.BaseCode = KeyUp + case vkc == xwindows.VK_RIGHT: + key.BaseCode = KeyRight + case vkc == xwindows.VK_DOWN: + key.BaseCode = KeyDown + case vkc == xwindows.VK_SELECT: + key.BaseCode = KeySelect + case vkc == xwindows.VK_SNAPSHOT: + key.BaseCode = KeyPrintScreen + case vkc == xwindows.VK_INSERT: + key.BaseCode = KeyInsert + case vkc == xwindows.VK_DELETE: + key.BaseCode = KeyDelete + case vkc >= '0' && vkc <= '9': + key.BaseCode = rune(vkc) + case vkc >= 'A' && vkc <= 'Z': + // Convert to lowercase. + key.BaseCode = rune(vkc) + 32 + case vkc == xwindows.VK_LWIN: + key.BaseCode = KeyLeftSuper + case vkc == xwindows.VK_RWIN: + key.BaseCode = KeyRightSuper + case vkc == xwindows.VK_APPS: + key.BaseCode = KeyMenu + case vkc >= xwindows.VK_NUMPAD0 && vkc <= xwindows.VK_NUMPAD9: + key.BaseCode = rune(vkc-xwindows.VK_NUMPAD0) + KeyKp0 + key.Text = string('0' + (rune(vkc) - xwindows.VK_NUMPAD0)) + case vkc == xwindows.VK_MULTIPLY: + key.BaseCode = KeyKpMultiply + key.Text = "*" + case vkc == xwindows.VK_ADD: + key.BaseCode = KeyKpPlus + key.Text = "+" + case vkc == xwindows.VK_SEPARATOR: + key.BaseCode = KeyKpComma + key.Text = "," + case vkc == xwindows.VK_SUBTRACT: + key.BaseCode = KeyKpMinus + key.Text = "-" + case vkc == xwindows.VK_DECIMAL: + key.BaseCode = KeyKpDecimal + key.Text = "." + case vkc == xwindows.VK_DIVIDE: + key.BaseCode = KeyKpDivide + key.Text = "/" + case vkc >= xwindows.VK_F1 && vkc <= xwindows.VK_F24: + key.BaseCode = rune(vkc-xwindows.VK_F1) + KeyF1 + case vkc == xwindows.VK_NUMLOCK: + key.BaseCode = KeyNumLock + case vkc == xwindows.VK_SCROLL: + key.BaseCode = KeyScrollLock + case vkc == xwindows.VK_LSHIFT: + key.BaseCode = KeyLeftShift + case vkc == xwindows.VK_RSHIFT: + key.BaseCode = KeyRightShift + case vkc == xwindows.VK_LCONTROL: + key.BaseCode = KeyLeftCtrl + case vkc == xwindows.VK_RCONTROL: + key.BaseCode = KeyRightCtrl + case vkc == xwindows.VK_LMENU: + key.BaseCode = KeyLeftAlt + case vkc == xwindows.VK_RMENU: + key.BaseCode = KeyRightAlt + case vkc == xwindows.VK_VOLUME_MUTE: + key.BaseCode = KeyMute + case vkc == xwindows.VK_VOLUME_DOWN: + key.BaseCode = KeyLowerVol + case vkc == xwindows.VK_VOLUME_UP: + key.BaseCode = KeyRaiseVol + case vkc == xwindows.VK_MEDIA_NEXT_TRACK: + key.BaseCode = KeyMediaNext + case vkc == xwindows.VK_MEDIA_PREV_TRACK: + key.BaseCode = KeyMediaPrev + case vkc == xwindows.VK_MEDIA_STOP: + key.BaseCode = KeyMediaStop + case vkc == xwindows.VK_MEDIA_PLAY_PAUSE: + key.BaseCode = KeyMediaPlayPause + case vkc == xwindows.VK_OEM_1: + key.BaseCode = ';' + case vkc == xwindows.VK_OEM_PLUS: + key.BaseCode = '+' + case vkc == xwindows.VK_OEM_COMMA: + key.BaseCode = ',' + case vkc == xwindows.VK_OEM_MINUS: + key.BaseCode = '-' + case vkc == xwindows.VK_OEM_PERIOD: + key.BaseCode = '.' + case vkc == xwindows.VK_OEM_2: + key.BaseCode = '/' + case vkc == xwindows.VK_OEM_3: + key.BaseCode = '`' + case vkc == xwindows.VK_OEM_4: + key.BaseCode = '[' + case vkc == xwindows.VK_OEM_5: + key.BaseCode = '\\' + case vkc == xwindows.VK_OEM_6: + key.BaseCode = ']' + case vkc == xwindows.VK_OEM_7: + key.BaseCode = '\'' + } + + // AltGr is left ctrl + right alt. On non-US keyboards, this is used to type + // special characters and produce printable events. + // XXX: Should this be a KeyMod? + const altGrPressed = xwindows.LEFT_CTRL_PRESSED | xwindows.RIGHT_ALT_PRESSED + altGr := cks&altGrPressed == altGrPressed + + // Remove these lock keys from the control key state from now on. + cks &^= xwindows.NUMLOCK_ON + cks &^= xwindows.SCROLLLOCK_ON + key.Code = key.BaseCode + if !unicode.IsControl(r) { + key.Code = r + if unicode.IsPrint(key.Code) && (cks == 0 || // no modifiers pressed + cks == xwindows.SHIFT_PRESSED || // shift pressed + cks == xwindows.CAPSLOCK_ON || // caps lock on + cks == (xwindows.SHIFT_PRESSED|xwindows.CAPSLOCK_ON) || // Shift + caps lock pressed + altGr) { // AltGr pressed + // If the control key state is 0, shift is pressed, or caps lock + // then the key event is a printable event i.e. [text] is not empty. + key.Text = string(key.Code) + } + } + + key.Mod = translateControlKeyState(cks) + key = ensureKeyCase(key, cks) + if keyDown { + return KeyPressEvent(key) + } + + return KeyReleaseEvent(key) +} + +// ensureKeyCase ensures that the key's text is in the correct case based on the +// control key state. +func ensureKeyCase(key Key, cks uint32) Key { + if len(key.Text) == 0 { + return key + } + + hasShift := cks&xwindows.SHIFT_PRESSED != 0 + hasCaps := cks&xwindows.CAPSLOCK_ON != 0 + if hasShift || hasCaps { + if unicode.IsLower(key.Code) { + key.ShiftedCode = unicode.ToUpper(key.Code) + key.Text = string(key.ShiftedCode) + } + } else { + if unicode.IsUpper(key.Code) { + key.ShiftedCode = unicode.ToLower(key.Code) + key.Text = string(key.ShiftedCode) + } + } + + return key +} + +// translateControlKeyState translates the control key state from the Windows +// Console API into a Mod bitmask. +func translateControlKeyState(cks uint32) (m KeyMod) { + if cks&xwindows.LEFT_CTRL_PRESSED != 0 || cks&xwindows.RIGHT_CTRL_PRESSED != 0 { + m |= ModCtrl + } + if cks&xwindows.LEFT_ALT_PRESSED != 0 || cks&xwindows.RIGHT_ALT_PRESSED != 0 { + m |= ModAlt + } + if cks&xwindows.SHIFT_PRESSED != 0 { + m |= ModShift + } + if cks&xwindows.CAPSLOCK_ON != 0 { + m |= ModCapsLock + } + if cks&xwindows.NUMLOCK_ON != 0 { + m |= ModNumLock + } + if cks&xwindows.SCROLLLOCK_ON != 0 { + m |= ModScrollLock + } + return +} diff --git a/cli/third_party/ultraviolet/doc.go b/cli/third_party/ultraviolet/doc.go new file mode 100644 index 000000000..27b8a25c3 --- /dev/null +++ b/cli/third_party/ultraviolet/doc.go @@ -0,0 +1,46 @@ +// Package uv (Ultraviolet) provides primitives for building terminal user +// interfaces in Go. +// +// It offers cell-based screen buffers, a diffing terminal renderer, cross-platform +// input decoding (keyboard, mouse, paste, focus, resize), and a windowing model +// with off-screen buffers. Ultraviolet powers Bubble Tea v2 and Lip Gloss v2. +// +// # Getting Started +// +// Create a terminal, get its screen, and run an event loop: +// +// t := uv.DefaultTerminal() +// scr := t.Screen() +// scr.EnterAltScreen() +// +// if err := t.Start(); err != nil { +// log.Fatal(err) +// } +// defer t.Stop() +// +// for ev := range t.Events() { +// switch ev := ev.(type) { +// case uv.WindowSizeEvent: +// scr.Resize(ev.Width, ev.Height) +// case uv.KeyPressEvent: +// if ev.MatchString("q") { return } +// } +// } +// +// # Rendering +// +// Drawing is a two-step process. [TerminalScreen.Render] diffs the screen and +// writes escape sequences to an internal buffer. [TerminalScreen.Flush] sends +// the buffer to the terminal—this is the only method that performs real I/O. +// +// scr.Render() +// scr.Flush() +// +// Use the screen package for high-level drawing helpers like +// [screen.Context.DrawString] and [screen.Clear]. +// +// # Packages +// +// - screen — drawing context and screen manipulation helpers +// - layout — constraint-based layout solver (Cassowary algorithm) +package uv diff --git a/cli/third_party/ultraviolet/environ.go b/cli/third_party/ultraviolet/environ.go new file mode 100644 index 000000000..9622b607a --- /dev/null +++ b/cli/third_party/ultraviolet/environ.go @@ -0,0 +1,32 @@ +package uv + +import ( + "strings" +) + +// Environ is a slice of strings that represents the environment variables of +// the program. +type Environ []string + +// Getenv returns the value of the environment variable named by the key. If +// the variable is not present in the environment, the value returned will be +// the empty string. +func (p Environ) Getenv(key string) (v string) { + v, _ = p.LookupEnv(key) + return +} + +// LookupEnv retrieves the value of the environment variable named by the key. +// If the variable is present in the environment the value (which may be empty) +// is returned and the boolean is true. Otherwise the returned value will be +// empty and the boolean will be false. +func (p Environ) LookupEnv(key string) (s string, v bool) { + for i := len(p) - 1; i >= 0; i-- { + if strings.HasPrefix(p[i], key+"=") { + s = strings.TrimPrefix(p[i], key+"=") + v = true + break + } + } + return +} diff --git a/cli/third_party/ultraviolet/event.go b/cli/third_party/ultraviolet/event.go new file mode 100644 index 000000000..2d0d8cf20 --- /dev/null +++ b/cli/third_party/ultraviolet/event.go @@ -0,0 +1,567 @@ +package uv + +import ( + "context" + "fmt" + "image" + "image/color" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/ansi/kitty" +) + +// Event represents an input event that can be received from an input source. +type Event interface{} + +// EventStreamer is an interface that defines a method to stream events from an +// input source. It takes a context and a channel to send events to. The +// streamer should block until the context is done or an error occurs. The +// channel should never be closed by the streamer, as it is the responsibility +// of the consumer to close it when done. +type EventStreamer interface { + StreamEvents(ctx context.Context, ch chan<- Event) error +} + +// UnknownEvent represents an unknown event. +type UnknownEvent string + +// String returns a string representation of the unknown event. +func (e UnknownEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownCsiEvent represents an unknown CSI (Control Sequence Introducer) event. +type UnknownCsiEvent string + +// String returns a string representation of the unknown CSI event. +func (e UnknownCsiEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownSs3Event represents an unknown SS3 (Single Shift 3) event. +type UnknownSs3Event string + +// String returns a string representation of the unknown SS3 event. +func (e UnknownSs3Event) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownOscEvent represents an unknown OSC (Operating System Command) event. +type UnknownOscEvent string + +// String returns a string representation of the unknown OSC event. +func (e UnknownOscEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownDcsEvent represents an unknown DCS (Device Control String) event. +type UnknownDcsEvent string + +// String returns a string representation of the unknown DCS event. +func (e UnknownDcsEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownSosEvent represents an unknown SOS (Start of String) event. +type UnknownSosEvent string + +// String returns a string representation of the unknown SOS event. +func (e UnknownSosEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownPmEvent represents an unknown PM (Privacy Message) event. +type UnknownPmEvent string + +// String returns a string representation of the unknown PM event. +func (e UnknownPmEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// UnknownApcEvent represents an unknown APC (Application Program Command) event. +type UnknownApcEvent string + +// String returns a string representation of the unknown APC event. +func (e UnknownApcEvent) String() string { + return fmt.Sprintf("%q", string(e)) +} + +// MultiEvent represents multiple messages event. +type MultiEvent []Event + +// String returns a string representation of the multiple messages event. +func (e MultiEvent) String() string { + var sb strings.Builder + for _, ev := range e { + fmt.Fprintf(&sb, "%v\n", ev) + } + return sb.String() +} + +// Size represents the size of the terminal window. +type Size struct { + Width int + Height int +} + +// Bounds returns the bounds corresponding to the size. +func (s Size) Bounds() Rectangle { + return Rectangle{ + Min: image.Point{X: 0, Y: 0}, + Max: image.Point{X: s.Width, Y: s.Height}, + } +} + +// WindowSizeEvent represents the window size in cells. +type WindowSizeEvent Size + +// Bounds returns the bounds corresponding to the size. +func (s WindowSizeEvent) Bounds() Rectangle { + return Size(s).Bounds() +} + +// PixelSizeEvent represents the window size in pixels. +type PixelSizeEvent Size + +// Bounds returns the bounds corresponding to the size. +func (s PixelSizeEvent) Bounds() Rectangle { + return Size(s).Bounds() +} + +// CellSizeEvent represents the cell size in pixels. +type CellSizeEvent Size + +// Bounds returns the bounds corresponding to the size. +func (s CellSizeEvent) Bounds() Rectangle { + return Size(s).Bounds() +} + +// KeyPressEvent represents a key press event. +type KeyPressEvent Key + +// MatchString returns true if the [Key] matches one of the given strings. +// +// A string can be a key name like "enter", "tab", "a", or a printable +// character like "1" or " ". It can also have combinations of modifiers like +// "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. +func (k KeyPressEvent) MatchString(s ...string) bool { + return Key(k).MatchString(s...) +} + +// String implements [fmt.Stringer] and is quite useful for matching key +// events. For details, on what this returns see [Key.String]. +func (k KeyPressEvent) String() string { + return Key(k).String() +} + +// Keystroke returns the keystroke representation of the [Key]. While less type +// safe than looking at the individual fields, it will usually be more +// convenient and readable to use this method when matching against keys. +// +// Note that modifier keys are always printed in the following order: +// - ctrl +// - alt +// - shift +// - meta +// - hyper +// - super +// +// For example, you'll always see "ctrl+shift+alt+a" and never +// "shift+ctrl+alt+a". +func (k KeyPressEvent) Keystroke() string { + return Key(k).Keystroke() +} + +// Key returns the underlying key event. This is a syntactic sugar for casting +// the key event to a [Key]. +func (k KeyPressEvent) Key() Key { + return Key(k) +} + +// KeyReleaseEvent represents a key release event. +type KeyReleaseEvent Key + +// MatchString returns true if the [Key] matches one of the given strings. +// +// A string can be a key name like "enter", "tab", "a", or a printable +// character like "1" or " ". It can also have combinations of modifiers like +// "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. +func (k KeyReleaseEvent) MatchString(s ...string) bool { + return Key(k).MatchString(s...) +} + +// String implements [fmt.Stringer] and is quite useful for matching key +// events. For details, on what this returns see [Key.String]. +func (k KeyReleaseEvent) String() string { + return Key(k).String() +} + +// Keystroke returns the keystroke representation of the [Key]. While less type +// safe than looking at the individual fields, it will usually be more +// convenient and readable to use this method when matching against keys. +// +// Note that modifier keys are always printed in the following order: +// - ctrl +// - alt +// - shift +// - meta +// - hyper +// - super +// +// For example, you'll always see "ctrl+shift+alt+a" and never +// "shift+ctrl+alt+a". +func (k KeyReleaseEvent) Keystroke() string { + return Key(k).Keystroke() +} + +// Key returns the underlying key event. This is a convenience method and +// syntactic sugar to satisfy the [KeyEvent] interface, and cast the key event to +// [Key]. +func (k KeyReleaseEvent) Key() Key { + return Key(k) +} + +// KeyEvent represents a key event. This can be either a key press or a key +// release event. +type KeyEvent interface { + fmt.Stringer + + // Key returns the underlying key event. + Key() Key +} + +// MouseEvent represents a mouse message. This is a generic mouse message that +// can represent any kind of mouse event. +type MouseEvent interface { + fmt.Stringer + + // Mouse returns the underlying mouse event. + Mouse() Mouse +} + +// MouseClickEvent represents a mouse button click event. +type MouseClickEvent Mouse + +// String returns a string representation of the mouse click event. +func (e MouseClickEvent) String() string { + return Mouse(e).String() +} + +// Mouse returns the underlying mouse event. This is a convenience method and +// syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse +// event to [Mouse]. +func (e MouseClickEvent) Mouse() Mouse { + return Mouse(e) +} + +// MouseReleaseEvent represents a mouse button release event. +type MouseReleaseEvent Mouse + +// String returns a string representation of the mouse release event. +func (e MouseReleaseEvent) String() string { + return Mouse(e).String() +} + +// Mouse returns the underlying mouse event. This is a convenience method and +// syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse +// event to [Mouse]. +func (e MouseReleaseEvent) Mouse() Mouse { + return Mouse(e) +} + +// MouseWheelEvent represents a mouse wheel message event. +type MouseWheelEvent Mouse + +// String returns a string representation of the mouse wheel event. +func (e MouseWheelEvent) String() string { + return Mouse(e).String() +} + +// Mouse returns the underlying mouse event. This is a convenience method and +// syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse +// event to [Mouse]. +func (e MouseWheelEvent) Mouse() Mouse { + return Mouse(e) +} + +// MouseMotionEvent represents a mouse motion event. +type MouseMotionEvent Mouse + +// String returns a string representation of the mouse motion event. +func (e MouseMotionEvent) String() string { + m := Mouse(e) + if m.Button != 0 { + return m.String() + "+motion" + } + return m.String() + "motion" +} + +// Mouse returns the underlying mouse event. This is a convenience method and +// syntactic sugar to satisfy the [MouseEvent] interface, and cast the mouse +// event to [Mouse]. +func (e MouseMotionEvent) Mouse() Mouse { + return Mouse(e) +} + +// CursorPositionEvent represents a cursor position event. Where X is the +// zero-based column and Y is the zero-based row. +type CursorPositionEvent struct { + X, Y int +} + +// FocusEvent represents a terminal focus event. +// This occurs when the terminal gains focus. +type FocusEvent struct{} + +// BlurEvent represents a terminal blur event. +// This occurs when the terminal loses focus. +type BlurEvent struct{} + +// DarkColorSchemeEvent is sent when the operating system is using a dark color +// scheme. This is typically used to notify applications of the current or new +// system color scheme. +type DarkColorSchemeEvent struct{} + +// LightColorSchemeEvent is sent when the operating system is using a light color +// scheme. This is typically used to notify applications of the current or new +// system color scheme. +type LightColorSchemeEvent struct{} + +// PasteEvent is an message that is emitted when a terminal receives pasted text +// using bracketed-paste. +type PasteEvent struct { + // Content is the pasted text content. + Content string +} + +// String returns the pasted content as a string. +func (e PasteEvent) String() string { + return e.Content +} + +// PasteStartEvent is an message that is emitted when the terminal starts the +// bracketed-paste text. +type PasteStartEvent struct{} + +// PasteEndEvent is an message that is emitted when the terminal ends the +// bracketed-paste text. +type PasteEndEvent struct{} + +// TerminalVersionEvent is a message that represents the terminal version. +type TerminalVersionEvent struct { + Name string +} + +// String returns the terminal version as a string. +func (e TerminalVersionEvent) String() string { + return e.Name +} + +// ModifyOtherKeysEvent represents a modifyOtherKeys event. +// +// 0: disable +// 1: enable mode 1 +// 2: enable mode 2 +// +// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Functions-using-CSI-_-ordered-by-the-final-character_s_ +// See: https://invisible-island.net/xterm/manpage/xterm.html#VT100-Widget-Resources:modifyOtherKeys +type ModifyOtherKeysEvent struct { + Mode int +} + +// KittyGraphicsEvent represents a Kitty Graphics response event. +// +// See https://sw.kovidgoyal.net/kitty/graphics-protocol/ +type KittyGraphicsEvent struct { + Options kitty.Options + Payload []byte +} + +// KeyboardEnhancementsEvent represents a keyboard enhancements report event. +type KeyboardEnhancementsEvent struct { + // Flags are the Kitty Keyboard Enhancement flags. + // + // Bit values: + // + // 00000001: Disambiguate escape codes + // 00000010: Report event types + // 00000100: Report alternate keys + // 00001000: Report all keys as escape codes + // 00010000: Report associated text + // + // See: https://sw.kovidgoyal.net/kitty/keyboard-protocol/#keyboard-enhancements + Flags int +} + +// Contains reports whether m contains the given enhancements. +func (e KeyboardEnhancementsEvent) Contains(enhancements int) bool { + return e.Flags&enhancements == enhancements +} + +// SupportsKeyDisambiguation returns whether the terminal supports reporting +// disambiguous keys as escape codes. +func (e KeyboardEnhancementsEvent) SupportsKeyDisambiguation() bool { + return e.Flags&ansi.KittyDisambiguateEscapeCodes != 0 +} + +// SupportsKeyReleases returns whether the terminal supports key release +// events. +func (e KeyboardEnhancementsEvent) SupportsKeyReleases() bool { + return e.Flags&ansi.KittyReportEventTypes != 0 +} + +// SupportsUniformKeyLayout returns whether the terminal supports reporting key +// events as though they were on a PC-101 layout. +func (e KeyboardEnhancementsEvent) SupportsUniformKeyLayout() bool { + return e.SupportsKeyDisambiguation() && + e.Flags&ansi.KittyReportAlternateKeys != 0 && + e.Flags&ansi.KittyReportAllKeysAsEscapeCodes != 0 +} + +// PrimaryDeviceAttributesEvent is an event that represents the terminal +// primary device attributes. +// +// Common attributes include: +// - 1 132 columns +// - 2 Printer port +// - 4 Sixel +// - 6 Selective erase +// - 7 Soft character set (DRCS) +// - 8 User-defined keys (UDKs) +// - 9 National replacement character sets (NRCS) (International terminal only) +// - 12 Yugoslavian (SCS) +// - 15 Technical character set +// - 18 Windowing capability +// - 21 Horizontal scrolling +// - 23 Greek +// - 24 Turkish +// - 42 ISO Latin-2 character set +// - 44 PCTerm +// - 45 Soft key map +// - 46 ASCII emulation +// +// See [ansi.PrimaryDeviceAttributes] for more details. +type PrimaryDeviceAttributesEvent []int + +// SecondaryDeviceAttributesEvent is an event that represents the terminal +// secondary device attributes. +// +// See [ansi.SecondaryDeviceAttributes] for more details. +type SecondaryDeviceAttributesEvent []int + +// TertiaryDeviceAttributesEvent is an event that represents the terminal +// tertiary device attributes. +// +// See [ansi.TertiaryDeviceAttributes] for more details. +type TertiaryDeviceAttributesEvent string + +// ModeReportEvent is a message that represents a mode report event (DECRPM). +// +// See: https://vt100.net/docs/vt510-rm/DECRPM.html +type ModeReportEvent struct { + // Mode is the mode number. + Mode ansi.Mode + + // Value is the mode value. + Value ansi.ModeSetting +} + +// ForegroundColorEvent represents a foreground color event. This event is +// emitted when the terminal requests the terminal foreground color using +// [ansi.RequestForegroundColor]. +type ForegroundColorEvent struct{ color.Color } + +// String returns the hex representation of the color. +func (e ForegroundColorEvent) String() string { + return colorToHex(e.Color) +} + +// IsDark returns whether the color is dark. +func (e ForegroundColorEvent) IsDark() bool { + return isDarkColor(e.Color) +} + +// BackgroundColorEvent represents a background color event. This event is +// emitted when the terminal requests the terminal background color using +// [ansi.RequestBackgroundColor]. +type BackgroundColorEvent struct{ color.Color } + +// String returns the hex representation of the color. +func (e BackgroundColorEvent) String() string { + return colorToHex(e) +} + +// IsDark returns whether the color is dark. +func (e BackgroundColorEvent) IsDark() bool { + return isDarkColor(e.Color) +} + +// CursorColorEvent represents a cursor color change event. This event is +// emitted when the program requests the terminal cursor color using +// [ansi.RequestCursorColor]. +type CursorColorEvent struct{ color.Color } + +// String returns the hex representation of the color. +func (e CursorColorEvent) String() string { + return colorToHex(e) +} + +// IsDark returns whether the color is dark. +func (e CursorColorEvent) IsDark() bool { + return isDarkColor(e) +} + +// WindowOpEvent is a window operation (XTWINOPS) report event. This is used to +// report various window operations such as reporting the window size or cell +// size. +type WindowOpEvent struct { + Op int + Args []int +} + +// CapabilityEvent represents a Termcap/Terminfo response event. Termcap +// responses are generated by the terminal in response to RequestTermcap +// (XTGETTCAP) requests. +// +// See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands +type CapabilityEvent struct { + Content string +} + +// String returns the capability content. +func (e CapabilityEvent) String() string { + return e.Content +} + +// ClipboardSelection represents a clipboard selection. The most common +// clipboard selections are "system" and "primary" and selections. +type ClipboardSelection = byte + +// Clipboard selections. +const ( + SystemClipboard ClipboardSelection = ansi.SystemClipboard + PrimaryClipboard ClipboardSelection = ansi.PrimaryClipboard +) + +// ClipboardEvent is a clipboard read message event. This message is emitted when +// a terminal receives an OSC52 clipboard read message event. +type ClipboardEvent struct { + Content string + Selection ClipboardSelection +} + +// String returns the string representation of the clipboard message. +func (e ClipboardEvent) String() string { + return e.Content +} + +// Clipboard returns the clipboard selection. This can be either +// [SystemClipboard] 'c' or [PrimaryClipboard] 'p'. +func (e ClipboardEvent) Clipboard() ClipboardSelection { + return e.Selection +} + +// ignoredEvent represents a sequence event that is ignored by the terminal +// reader. This is used to ignore certain sequences that can be canceled. +type ignoredEvent string diff --git a/cli/third_party/ultraviolet/go.mod b/cli/third_party/ultraviolet/go.mod new file mode 100644 index 000000000..b086a8d86 --- /dev/null +++ b/cli/third_party/ultraviolet/go.mod @@ -0,0 +1,24 @@ +module github.com/charmbracelet/ultraviolet + +go 1.26.0 + +require ( + github.com/charmbracelet/colorprofile v0.4.3 + github.com/charmbracelet/x/ansi v0.11.8 + github.com/charmbracelet/x/term v0.2.2 + github.com/charmbracelet/x/termios v0.1.1 + github.com/charmbracelet/x/windows v0.2.2 + github.com/clipperhouse/uax29/v2 v2.7.0 + github.com/muesli/cancelreader v0.2.2 + github.com/rivo/uniseg v0.4.7 + github.com/xo/terminfo v1.0.0 + golang.org/x/sync v0.22.0 + golang.org/x/sys v0.47.0 +) + +require ( + github.com/clipperhouse/displaywidth v0.11.0 // indirect + github.com/mattn/go-runewidth v0.0.30 // indirect +) + +require github.com/lucasb-eyer/go-colorful v1.4.1 diff --git a/cli/third_party/ultraviolet/go.sum b/cli/third_party/ultraviolet/go.sum new file mode 100644 index 000000000..659fab66b --- /dev/null +++ b/cli/third_party/ultraviolet/go.sum @@ -0,0 +1,30 @@ +github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q= +github.com/charmbracelet/colorprofile v0.4.3/go.mod h1:/zT4BhpD5aGFpqQQqw7a+VtHCzu+zrQtt1zhMt9mR4Q= +github.com/charmbracelet/x/ansi v0.11.8 h1:JMFwp0CgDC2+jcOB162HH5k7I3FVbgFSMMYg7dSPBQQ= +github.com/charmbracelet/x/ansi v0.11.8/go.mod h1:ZNN+3mXny/516oTQPLMPIBeSINvNJJQ8uQXDgbeJxY0= +github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk= +github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI= +github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY= +github.com/charmbracelet/x/termios v0.1.1/go.mod h1:rB7fnv1TgOPOyyKRJ9o+AsTU/vK5WHJ2ivHeut/Pcwo= +github.com/charmbracelet/x/windows v0.2.2 h1:IofanmuvaxnKHuV04sC0eBy/smG6kIKrWG2/jYn2GuM= +github.com/charmbracelet/x/windows v0.2.2/go.mod h1:/8XtdKZzedat74NQFn0NGlGL4soHB0YQZrETF96h75k= +github.com/clipperhouse/displaywidth v0.11.0 h1:lBc6kY44VFw+TDx4I8opi/EtL9m20WSEFgwIwO+UVM8= +github.com/clipperhouse/displaywidth v0.11.0/go.mod h1:bkrFNkf81G8HyVqmKGxsPufD3JhNl3dSqnGhOoSD/o0= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBqlTf+2hNss= +github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk= +github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= +github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA= +github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= +github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E= +golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= diff --git a/cli/third_party/ultraviolet/internal/casso/math.go b/cli/third_party/ultraviolet/internal/casso/math.go new file mode 100644 index 000000000..dc1da7ef7 --- /dev/null +++ b/cli/third_party/ultraviolet/internal/casso/math.go @@ -0,0 +1,172 @@ +// Package casso implements a Cassowary constraint solver. +// +// Ported from github.com/lithdew/casso with unused API removed. +package casso + +import "sync/atomic" + +type symbolKind uint8 + +const ( + external symbolKind = iota + slack + errorSym + dummy +) + +func (s symbolKind) restricted() bool { return s == slack || s == errorSym } + +// Symbol is an opaque identifier for a variable in the solver. +type Symbol uint64 + +var ( + count uint64 + zero Symbol +) + +// New creates a new external symbol. +func New() Symbol { return next(external) } + +func next(typ symbolKind) Symbol { + return Symbol((atomic.AddUint64(&count, 1) & 0x3fffffffffffffff) | (uint64(typ) << 62)) +} + +func (sym Symbol) kind() symbolKind { return symbolKind(sym >> 62) } +func (sym Symbol) isZero() bool { return sym == zero } +func (sym Symbol) restricted() bool { return !sym.isZero() && sym.kind().restricted() } +func (sym Symbol) external() bool { return !sym.isZero() && sym.kind() == external } +func (sym Symbol) isDummy() bool { return !sym.isZero() && sym.kind() == dummy } + +// T creates a Term with the given coefficient. +func (sym Symbol) T(coeff float64) Term { return Term{coeff: coeff, id: sym} } + +// Priority represents the strength of a constraint. +type Priority float64 + +// Op represents a constraint operator. +type Op uint8 + +const ( + EQ Op = iota + GTE + LTE +) + +// Constraint represents a linear constraint. +type Constraint struct { + op Op + expr expr +} + +// NewConstraint creates a new constraint. +func NewConstraint(op Op, constant float64, terms ...Term) Constraint { + return Constraint{op: op, expr: newExpr(constant, terms...)} +} + +func (c Constraint) clone() Constraint { + return Constraint{op: c.op, expr: c.expr.clone()} +} + +// Term represents a variable with a coefficient. +type Term struct { + coeff float64 + id Symbol +} + +type expr struct { + constant float64 + terms []Term +} + +func newExpr(constant float64, terms ...Term) expr { + return expr{constant: constant, terms: terms} +} + +func (c expr) clone() expr { + res := expr{constant: c.constant, terms: make([]Term, len(c.terms))} + copy(res.terms, c.terms) + return res +} + +func (c expr) find(id Symbol) int { + for i := 0; i < len(c.terms); i++ { + if c.terms[i].id == id { + return i + } + } + return -1 +} + +func (c *expr) delete(idx int) { + copy(c.terms[idx:], c.terms[idx+1:]) + c.terms = c.terms[:len(c.terms)-1] +} + +func (c *expr) addSymbol(coeff float64, id Symbol) { + idx := c.find(id) + if idx == -1 { + if !eqz(coeff) { + c.terms = append(c.terms, Term{coeff: coeff, id: id}) + } + return + } + c.terms[idx].coeff += coeff + if eqz(c.terms[idx].coeff) { + c.delete(idx) + } +} + +func (c *expr) addExpr(coeff float64, other expr) { + c.constant += coeff * other.constant + for i := 0; i < len(other.terms); i++ { + c.addSymbol(coeff*other.terms[i].coeff, other.terms[i].id) + } +} + +func (c *expr) negate() { + c.constant = -c.constant + for i := 0; i < len(c.terms); i++ { + c.terms[i].coeff = -c.terms[i].coeff + } +} + +func (c *expr) solveFor(id Symbol) { + idx := c.find(id) + if idx == -1 { + return + } + + coeff := -1.0 / c.terms[idx].coeff + c.delete(idx) + + if coeff == 1.0 { + return + } + + c.constant *= coeff + for i := 0; i < len(c.terms); i++ { + c.terms[i].coeff *= coeff + } +} + +func (c *expr) solveForSymbols(lhs, rhs Symbol) { + c.addSymbol(-1.0, lhs) + c.solveFor(rhs) +} + +func (c *expr) substitute(id Symbol, other expr) { + idx := c.find(id) + if idx == -1 { + return + } + coeff := c.terms[idx].coeff + c.delete(idx) + c.addExpr(coeff, other) +} + +func eqz(val float64) bool { + if val < 0 { + return -val < 1.0e-8 + } + return val < 1.0e-8 +} diff --git a/cli/third_party/ultraviolet/internal/casso/solver.go b/cli/third_party/ultraviolet/internal/casso/solver.go new file mode 100644 index 000000000..b099d3c19 --- /dev/null +++ b/cli/third_party/ultraviolet/internal/casso/solver.go @@ -0,0 +1,275 @@ +package casso + +import ( + "errors" + "math" +) + +type tag struct { + priority Priority + marker Symbol + other Symbol +} + +// Solver implements the Cassowary constraint solving algorithm. +type Solver struct { + tabs map[Symbol]Constraint + tags map[Symbol]tag + + infeasible []Symbol + + objective expr + artificial expr +} + +// NewSolver creates a new constraint solver. +func NewSolver() *Solver { + return &Solver{ + tabs: make(map[Symbol]Constraint), + tags: make(map[Symbol]tag), + } +} + +// Val returns the current value of a symbol. +func (s *Solver) Val(id Symbol) float64 { + row, ok := s.tabs[id] + if !ok { + return 0 + } + return row.expr.constant +} + +// Add adds a constraint to the solver with the given priority. +func (s *Solver) Add(priority Priority, cell Constraint) (Symbol, error) { + t := tag{priority: priority} + + c := cell + c.expr.terms = make([]Term, 0, len(c.expr.terms)) + + for _, term := range cell.expr.terms { + if eqz(term.coeff) { + continue + } + if term.id.isZero() { + return zero, errBadTerm + } + resolved, exists := s.tabs[term.id] + if !exists { + c.expr.addSymbol(term.coeff, term.id) + continue + } + c.expr.addExpr(term.coeff, resolved.expr) + } + + switch c.op { + case LTE, GTE: + coeff := 1.0 + if c.op == GTE { + coeff = -1.0 + } + + t.marker = next(slack) + c.expr.addSymbol(coeff, t.marker) + + if priority < required { + t.other = next(errorSym) + c.expr.addSymbol(-coeff, t.other) + s.objective.addSymbol(float64(priority), t.other) + } + case EQ: + if priority < required { + t.marker = next(errorSym) + t.other = next(errorSym) + + c.expr.addSymbol(-1.0, t.marker) + c.expr.addSymbol(1.0, t.other) + + s.objective.addSymbol(float64(priority), t.marker) + s.objective.addSymbol(float64(priority), t.other) + } else { + t.marker = next(dummy) + c.expr.addSymbol(1.0, t.marker) + } + } + + if c.expr.constant < 0.0 { + c.expr.negate() + } + + subject, err := s.findSubject(c, t) + if err != nil { + return zero, err + } + + if subject.isZero() { + if err := s.augmentArtificialVariable(c); err != nil { + return t.marker, err + } + } else { + c.expr.solveFor(subject) + s.substitute(subject, c.expr) + s.tabs[subject] = c + } + + s.tags[t.marker] = t + + return t.marker, s.optimizeAgainst(&s.objective) +} + +const required Priority = 1e9 + +func (s *Solver) findSubject(cell Constraint, t tag) (Symbol, error) { + for _, term := range cell.expr.terms { + if term.id.external() { + return term.id, nil + } + } + + if t.marker.restricted() { + idx := cell.expr.find(t.marker) + if idx != -1 && cell.expr.terms[idx].coeff < 0.0 { + return t.marker, nil + } + } + + if t.other.restricted() { + idx := cell.expr.find(t.other) + if idx != -1 && cell.expr.terms[idx].coeff < 0.0 { + return t.other, nil + } + } + + for _, term := range cell.expr.terms { + if !term.id.isDummy() { + return zero, nil + } + } + + if !eqz(cell.expr.constant) { + return zero, errUnsatisfiable + } + + return t.marker, nil +} + +func (s *Solver) substitute(id Symbol, e expr) { + for symbol := range s.tabs { + row := s.tabs[symbol] + row.expr.substitute(id, e) + s.tabs[symbol] = row + if symbol.external() || row.expr.constant >= 0.0 { + continue + } + s.infeasible = append(s.infeasible, symbol) + } + s.objective.substitute(id, e) + s.artificial.substitute(id, e) +} + +func (s *Solver) optimizeAgainst(objective *expr) error { + for { + entry := zero + exit := zero + + for _, term := range objective.terms { + if !term.id.isDummy() && term.coeff < 0.0 { + entry = term.id + break + } + } + if entry.isZero() { + return nil + } + + ratio := math.MaxFloat64 + + for symbol := range s.tabs { + if symbol.external() { + continue + } + idx := s.tabs[symbol].expr.find(entry) + if idx == -1 { + continue + } + coeff := s.tabs[symbol].expr.terms[idx].coeff + if coeff >= 0.0 { + continue + } + r := -s.tabs[symbol].expr.constant / coeff + if r < ratio { + ratio, exit = r, symbol + } + } + + row := s.tabs[exit] + delete(s.tabs, exit) + + row.expr.solveForSymbols(exit, entry) + + s.substitute(entry, row.expr) + s.tabs[entry] = row + } +} + +func (s *Solver) augmentArtificialVariable(row Constraint) error { + art := next(slack) + + s.tabs[art] = row.clone() + s.artificial = row.expr.clone() + + if err := s.optimizeAgainst(&s.artificial); err != nil { + return err + } + + success := eqz(s.artificial.constant) + s.artificial = newExpr(0.0) + + artificial, ok := s.tabs[art] + if ok { + delete(s.tabs, art) + + if len(artificial.expr.terms) == 0 { + return nil + } + + entry := zero + for _, term := range artificial.expr.terms { + if term.id.restricted() { + entry = term.id + break + } + } + if entry.isZero() { + return errUnsatisfiable + } + + artificial.expr.solveForSymbols(art, entry) + + s.substitute(entry, artificial.expr) + s.tabs[entry] = artificial + } + + for symbol, row := range s.tabs { + idx := row.expr.find(art) + if idx == -1 { + continue + } + row.expr.delete(idx) + s.tabs[symbol] = row + } + + idx := s.objective.find(art) + if idx != -1 { + s.objective.delete(idx) + } + + if !success { + return errUnsatisfiable + } + return nil +} + +var ( + errUnsatisfiable = errors.New("casso: constraint is unsatisfiable") + errBadTerm = errors.New("casso: term references a nil symbol") +) diff --git a/cli/third_party/ultraviolet/internal/lru/lru.go b/cli/third_party/ultraviolet/internal/lru/lru.go new file mode 100644 index 000000000..5ceabb60a --- /dev/null +++ b/cli/third_party/ultraviolet/internal/lru/lru.go @@ -0,0 +1,69 @@ +package lru + +import ( + "container/list" + "fmt" +) + +type LRU[K comparable, V any] struct { + size int + + items map[K]*list.Element + evict *list.List +} + +type entry[K comparable, T any] struct { + Key K + Value T +} + +func New[K comparable, V any](size int) *LRU[K, V] { + if size < 0 { + panic(fmt.Sprintf("lru: negative size given: %d", size)) + } + + return &LRU[K, V]{ + size: size, + items: make(map[K]*list.Element), + evict: list.New(), + } +} + +func (c *LRU[K, V]) Get(key K) (V, bool) { + e, ok := c.items[key] + if !ok { + var zero V + + return zero, false + } + + c.evict.MoveToFront(e) + + return e.Value.(entry[K, V]).Value, true +} + +func (c *LRU[K, V]) Add(key K, value V) (evicted bool) { + if e, ok := c.items[key]; ok { + c.evict.MoveToFront(e) + e.Value = value + + return false + } + + e := c.evict.PushFront(key) + + e.Value = entry[K, V]{Key: key, Value: value} + + c.items[key] = e + + if c.evict.Len() <= c.size { + return false + } + + if oldest := c.evict.Back(); oldest != nil { + c.evict.Remove(oldest) + delete(c.items, oldest.Value.(entry[K, V]).Key) + } + + return true +} diff --git a/cli/third_party/ultraviolet/key.go b/cli/third_party/ultraviolet/key.go new file mode 100644 index 000000000..f3b5f6a57 --- /dev/null +++ b/cli/third_party/ultraviolet/key.go @@ -0,0 +1,762 @@ +package uv + +import ( + "strings" + "unicode" + "unicode/utf8" + + "github.com/charmbracelet/x/ansi" +) + +// KeyMod represents modifier keys. +type KeyMod int + +// Modifier keys. +const ( + ModShift KeyMod = 1 << iota + ModAlt + ModCtrl + ModMeta + + // These modifiers are used with the Kitty protocol. + // XXX: Meta and Super are swapped in the Kitty protocol, + // this is to preserve compatibility with XTerm modifiers. + + ModHyper + ModSuper // Windows/Command keys + + // These are key lock states. + + ModCapsLock + ModNumLock + ModScrollLock // Defined in Windows API only +) + +// Contains reports whether m contains the given modifiers. +// +// Example: +// +// m := ModAlt | ModCtrl +// m.Contains(ModCtrl) // true +// m.Contains(ModAlt | ModCtrl) // true +// m.Contains(ModAlt | ModCtrl | ModShift) // false +func (m KeyMod) Contains(mods KeyMod) bool { + return m&mods == mods +} + +const ( + // KeyExtended is a special key code used to signify that a key event + // contains multiple runes. + KeyExtended = unicode.MaxRune + 1 +) + +// Special key symbols. +const ( + + // Special keys. + + KeyUp rune = KeyExtended + iota + 1 + KeyDown + KeyRight + KeyLeft + KeyBegin + KeyFind + KeyInsert + KeyDelete + KeySelect + KeyPgUp + KeyPgDown + KeyHome + KeyEnd + + // Keypad keys. + + KeyKpEnter + KeyKpEqual + KeyKpMultiply + KeyKpPlus + KeyKpComma + KeyKpMinus + KeyKpDecimal + KeyKpDivide + KeyKp0 + KeyKp1 + KeyKp2 + KeyKp3 + KeyKp4 + KeyKp5 + KeyKp6 + KeyKp7 + KeyKp8 + KeyKp9 + + //nolint:godox + // The following are keys defined in the Kitty keyboard protocol. + // TODO: Investigate the names of these keys. + + KeyKpSep + KeyKpUp + KeyKpDown + KeyKpLeft + KeyKpRight + KeyKpPgUp + KeyKpPgDown + KeyKpHome + KeyKpEnd + KeyKpInsert + KeyKpDelete + KeyKpBegin + + // Function keys. + + KeyF1 + KeyF2 + KeyF3 + KeyF4 + KeyF5 + KeyF6 + KeyF7 + KeyF8 + KeyF9 + KeyF10 + KeyF11 + KeyF12 + KeyF13 + KeyF14 + KeyF15 + KeyF16 + KeyF17 + KeyF18 + KeyF19 + KeyF20 + KeyF21 + KeyF22 + KeyF23 + KeyF24 + KeyF25 + KeyF26 + KeyF27 + KeyF28 + KeyF29 + KeyF30 + KeyF31 + KeyF32 + KeyF33 + KeyF34 + KeyF35 + KeyF36 + KeyF37 + KeyF38 + KeyF39 + KeyF40 + KeyF41 + KeyF42 + KeyF43 + KeyF44 + KeyF45 + KeyF46 + KeyF47 + KeyF48 + KeyF49 + KeyF50 + KeyF51 + KeyF52 + KeyF53 + KeyF54 + KeyF55 + KeyF56 + KeyF57 + KeyF58 + KeyF59 + KeyF60 + KeyF61 + KeyF62 + KeyF63 + + //nolint:godox + // The following are keys defined in the Kitty keyboard protocol. + // TODO: Investigate the names of these keys. + + KeyCapsLock + KeyScrollLock + KeyNumLock + KeyPrintScreen + KeyPause + KeyMenu + + KeyMediaPlay + KeyMediaPause + KeyMediaPlayPause + KeyMediaReverse + KeyMediaStop + KeyMediaFastForward + KeyMediaRewind + KeyMediaNext + KeyMediaPrev + KeyMediaRecord + + KeyLowerVol + KeyRaiseVol + KeyMute + + KeyLeftShift + KeyLeftAlt + KeyLeftCtrl + KeyLeftSuper + KeyLeftHyper + KeyLeftMeta + KeyRightShift + KeyRightAlt + KeyRightCtrl + KeyRightSuper + KeyRightHyper + KeyRightMeta + KeyIsoLevel3Shift + KeyIsoLevel5Shift + + // Special names in C0. + + KeyBackspace = rune(ansi.DEL) + KeyTab = rune(ansi.HT) + KeyEnter = rune(ansi.CR) + KeyReturn = KeyEnter + KeyEscape = rune(ansi.ESC) + KeyEsc = KeyEscape + + // Special names in G0. + + KeySpace = rune(ansi.SP) +) + +// Key represents a Key press or release event. It contains information about +// the Key pressed, like the runes, the type of Key, and the modifiers pressed. +// There are a couple general patterns you could use to check for key presses +// or releases: +// +// // Switch on the string representation of the key (shorter) +// switch ev := ev.(type) { +// case KeyPressEvent: +// switch ev.String() { +// case "enter": +// fmt.Println("you pressed enter!") +// case "a": +// fmt.Println("you pressed a!") +// } +// } +// +// // Switch on the key type (more foolproof) +// switch ev := ev.(type) { +// case KeyEvent: +// // catch both KeyPressEvent and KeyReleaseEvent +// switch key := ev.Key(); key.Code { +// case KeyEnter: +// fmt.Println("you pressed enter!") +// default: +// switch key.Text { +// case "a": +// fmt.Println("you pressed a!") +// } +// } +// } +// +// Note that [Key.Text] will be empty for special keys like [KeyEnter], +// [KeyTab], and for keys that don't represent printable characters like key +// combos with modifier keys. In other words, [Key.Text] is populated only for +// keys that represent printable characters shifted or unshifted (like 'a', +// 'A', '1', '!', etc.). +type Key struct { + // Text contains the actual characters received. This usually the same as + // [Key.Code]. When [Key.Text] is non-empty, it indicates that the key + // pressed represents printable character(s). + Text string + + // Mod represents modifier keys, like [ModCtrl], [ModAlt], and so on. + Mod KeyMod + + // Code represents the key pressed. This is usually a special key like + // [KeyTab], [KeyEnter], [KeyF1], or a printable character like 'a'. + Code rune + + // ShiftedCode is the actual, shifted key pressed by the user. For example, + // if the user presses shift+a, or caps lock is on, [Key.ShiftedCode] will + // be 'A' and [Key.Code] will be 'a'. + // + // In the case of non-latin keyboards, like Arabic, [Key.ShiftedCode] is the + // unshifted key on the keyboard. + // + // This is only available with the Kitty Keyboard Protocol or the Windows + // Console API. + ShiftedCode rune + + // BaseCode is the key pressed according to the standard PC-101 key layout. + // On international keyboards, this is the key that would be pressed if the + // keyboard was set to US PC-101 layout. + // + // For example, if the user presses 'q' on a French AZERTY keyboard, + // [Key.BaseCode] will be 'q'. + // + // This is only available with the Kitty Keyboard Protocol or the Windows + // Console API. + BaseCode rune + + // IsRepeat indicates whether the key is being held down and sending events + // repeatedly. + // + // This is only available with the Kitty Keyboard Protocol or the Windows + // Console API. + IsRepeat bool +} + +// MatchString returns true if the [Key] matches one of the given strings. +// +// A string can be a key name like "enter", "tab", "a", or a printable +// character like "1" or " ". It can also have combinations of modifiers like +// "ctrl+a", "shift+enter", "alt+tab", "ctrl+shift+enter", etc. +func (k Key) MatchString(s ...string) bool { + for _, s := range s { + if keyMatchString(k, s) { + return true + } + } + return false +} + +func keyMatchString(k Key, s string) bool { + var ( + mod KeyMod + code rune + text string + ) + parts := strings.Split(s, "+") + for _, part := range parts { + switch part { + case "ctrl": + mod |= ModCtrl + case "alt": + mod |= ModAlt + case "shift": + mod |= ModShift + case "meta": + mod |= ModMeta + case "hyper": + mod |= ModHyper + case "super": + mod |= ModSuper + case "capslock": + mod |= ModCapsLock + case "scrolllock": + mod |= ModScrollLock + case "numlock": + mod |= ModNumLock + default: + // Check if the part is a key name. + if k, ok := stringKeyType[part]; ok { + code = k + } else { + // Check if the part is a printable character. + if utf8.RuneCountInString(part) == 1 { + code, _ = utf8.DecodeRuneInString(part) + } else { + // Multi-rune key. + code = KeyExtended + text = part + } + } + } + } + + // Check if we have a printable character. + smod := mod &^ (ModShift | ModCapsLock) + if smod == 0 && text == "" && unicode.IsPrint(code) { + if mod&ModShift != 0 || mod&ModCapsLock != 0 { + // Shifted code we need to use uppercase. + text = string(unicode.ToUpper(code)) + } else { + // Otherwise, use the code as is. + text = string(code) + } + } + + // Check if we have a match. + return (k.Mod == mod && k.Code == code) || + (k.Text != "" && k.Text == text) +} + +// String implements [fmt.Stringer] and is quite useful for matching key +// events. It will return the textual representation of the [Key] if there is +// one, otherwise, it will fallback to [Key.Keystroke]. +// +// For example, you'll always get "?" and instead of "shift+/" on a US ANSI +// keyboard. +func (k Key) String() string { + if len(k.Text) > 0 && k.Text != " " { + return k.Text + } + return k.Keystroke() +} + +// Keystroke returns the keystroke representation of the [Key]. While less type +// safe than looking at the individual fields, it will usually be more +// convenient and readable to use this method when matching against keys. +// +// Note that modifier keys are always printed in the following order: +// - ctrl +// - alt +// - shift +// - meta +// - hyper +// - super +// +// For example, you'll always see "ctrl+shift+alt+a" and never +// "shift+ctrl+alt+a". +func (k Key) Keystroke() string { + var sb strings.Builder + if k.Mod.Contains(ModCtrl) && k.Code != KeyLeftCtrl && k.Code != KeyRightCtrl { + sb.WriteString("ctrl+") + } + if k.Mod.Contains(ModAlt) && k.Code != KeyLeftAlt && k.Code != KeyRightAlt { + sb.WriteString("alt+") + } + if k.Mod.Contains(ModShift) && k.Code != KeyLeftShift && k.Code != KeyRightShift { + sb.WriteString("shift+") + } + if k.Mod.Contains(ModMeta) && k.Code != KeyLeftMeta && k.Code != KeyRightMeta { + sb.WriteString("meta+") + } + if k.Mod.Contains(ModHyper) && k.Code != KeyLeftHyper && k.Code != KeyRightHyper { + sb.WriteString("hyper+") + } + if k.Mod.Contains(ModSuper) && k.Code != KeyLeftSuper && k.Code != KeyRightSuper { + sb.WriteString("super+") + } + + if kt, ok := keyTypeString[k.Code]; ok { + sb.WriteString(kt) + } else { + code := k.Code + if k.BaseCode != 0 { + // If a [Key.BaseCode] is present, use it to represent a key using the standard + // PC-101 key layout. + code = k.BaseCode + } + + switch code { + case KeySpace: + // Space is the only invisible printable character. + sb.WriteString("space") + case KeyExtended: + // Write the actual text of the key when the key contains multiple + // runes. + sb.WriteString(k.Text) + default: + sb.WriteRune(code) + } + } + + return sb.String() +} + +var keyTypeString = map[rune]string{ + KeyEnter: "enter", + KeyTab: "tab", + KeyBackspace: "backspace", + KeyEscape: "esc", + KeySpace: "space", + KeyUp: "up", + KeyDown: "down", + KeyLeft: "left", + KeyRight: "right", + KeyBegin: "begin", + KeyFind: "find", + KeyInsert: "insert", + KeyDelete: "delete", + KeySelect: "select", + KeyPgUp: "pgup", + KeyPgDown: "pgdown", + KeyHome: "home", + KeyEnd: "end", + KeyKpEnter: "enter", + KeyKpEqual: "equal", + KeyKpMultiply: "mul", + KeyKpPlus: "plus", + KeyKpComma: "comma", + KeyKpMinus: "minus", + KeyKpDecimal: "period", + KeyKpDivide: "div", + KeyKp0: "0", + KeyKp1: "1", + KeyKp2: "2", + KeyKp3: "3", + KeyKp4: "4", + KeyKp5: "5", + KeyKp6: "6", + KeyKp7: "7", + KeyKp8: "8", + KeyKp9: "9", + + // Kitty keyboard extension + KeyKpSep: "sep", + KeyKpUp: "up", + KeyKpDown: "down", + KeyKpLeft: "left", + KeyKpRight: "right", + KeyKpPgUp: "pgup", + KeyKpPgDown: "pgdown", + KeyKpHome: "home", + KeyKpEnd: "end", + KeyKpInsert: "insert", + KeyKpDelete: "delete", + KeyKpBegin: "begin", + + KeyF1: "f1", + KeyF2: "f2", + KeyF3: "f3", + KeyF4: "f4", + KeyF5: "f5", + KeyF6: "f6", + KeyF7: "f7", + KeyF8: "f8", + KeyF9: "f9", + KeyF10: "f10", + KeyF11: "f11", + KeyF12: "f12", + KeyF13: "f13", + KeyF14: "f14", + KeyF15: "f15", + KeyF16: "f16", + KeyF17: "f17", + KeyF18: "f18", + KeyF19: "f19", + KeyF20: "f20", + KeyF21: "f21", + KeyF22: "f22", + KeyF23: "f23", + KeyF24: "f24", + KeyF25: "f25", + KeyF26: "f26", + KeyF27: "f27", + KeyF28: "f28", + KeyF29: "f29", + KeyF30: "f30", + KeyF31: "f31", + KeyF32: "f32", + KeyF33: "f33", + KeyF34: "f34", + KeyF35: "f35", + KeyF36: "f36", + KeyF37: "f37", + KeyF38: "f38", + KeyF39: "f39", + KeyF40: "f40", + KeyF41: "f41", + KeyF42: "f42", + KeyF43: "f43", + KeyF44: "f44", + KeyF45: "f45", + KeyF46: "f46", + KeyF47: "f47", + KeyF48: "f48", + KeyF49: "f49", + KeyF50: "f50", + KeyF51: "f51", + KeyF52: "f52", + KeyF53: "f53", + KeyF54: "f54", + KeyF55: "f55", + KeyF56: "f56", + KeyF57: "f57", + KeyF58: "f58", + KeyF59: "f59", + KeyF60: "f60", + KeyF61: "f61", + KeyF62: "f62", + KeyF63: "f63", + + // Kitty keyboard extension + KeyCapsLock: "capslock", + KeyScrollLock: "scrolllock", + KeyNumLock: "numlock", + KeyPrintScreen: "printscreen", + KeyPause: "pause", + KeyMenu: "menu", + KeyMediaPlay: "mediaplay", + KeyMediaPause: "mediapause", + KeyMediaPlayPause: "mediaplaypause", + KeyMediaReverse: "mediareverse", + KeyMediaStop: "mediastop", + KeyMediaFastForward: "mediafastforward", + KeyMediaRewind: "mediarewind", + KeyMediaNext: "medianext", + KeyMediaPrev: "mediaprev", + KeyMediaRecord: "mediarecord", + KeyLowerVol: "lowervol", + KeyRaiseVol: "raisevol", + KeyMute: "mute", + KeyLeftShift: "leftshift", + KeyLeftAlt: "leftalt", + KeyLeftCtrl: "leftctrl", + KeyLeftSuper: "leftsuper", + KeyLeftHyper: "lefthyper", + KeyLeftMeta: "leftmeta", + KeyRightShift: "rightshift", + KeyRightAlt: "rightalt", + KeyRightCtrl: "rightctrl", + KeyRightSuper: "rightsuper", + KeyRightHyper: "righthyper", + KeyRightMeta: "rightmeta", + KeyIsoLevel3Shift: "isolevel3shift", + KeyIsoLevel5Shift: "isolevel5shift", +} + +var stringKeyType = map[string]rune{ + "enter": KeyEnter, + "tab": KeyTab, + "backspace": KeyBackspace, + "escape": KeyEscape, + "esc": KeyEscape, + "space": KeySpace, + "up": KeyUp, + "down": KeyDown, + "left": KeyLeft, + "right": KeyRight, + "begin": KeyBegin, + "find": KeyFind, + "insert": KeyInsert, + "delete": KeyDelete, + "select": KeySelect, + "pgup": KeyPgUp, + "pgdown": KeyPgDown, + "home": KeyHome, + "end": KeyEnd, + "kpenter": KeyKpEnter, + "kpequal": KeyKpEqual, + "kpmul": KeyKpMultiply, + "kpplus": KeyKpPlus, + "kpcomma": KeyKpComma, + "kpminus": KeyKpMinus, + "kpperiod": KeyKpDecimal, + "kpdiv": KeyKpDivide, + "kp0": KeyKp0, + "kp1": KeyKp1, + "kp2": KeyKp2, + "kp3": KeyKp3, + "kp4": KeyKp4, + "kp5": KeyKp5, + "kp6": KeyKp6, + "kp7": KeyKp7, + "kp8": KeyKp8, + "kp9": KeyKp9, + + // Kitty keyboard extension + "kpsep": KeyKpSep, + "kpup": KeyKpUp, + "kpdown": KeyKpDown, + "kpleft": KeyKpLeft, + "kpright": KeyKpRight, + "kppgup": KeyKpPgUp, + "kppgdown": KeyKpPgDown, + "kphome": KeyKpHome, + "kpend": KeyKpEnd, + "kpinsert": KeyKpInsert, + "kpdelete": KeyKpDelete, + "kpbegin": KeyKpBegin, + + "f1": KeyF1, + "f2": KeyF2, + "f3": KeyF3, + "f4": KeyF4, + "f5": KeyF5, + "f6": KeyF6, + "f7": KeyF7, + "f8": KeyF8, + "f9": KeyF9, + "f10": KeyF10, + "f11": KeyF11, + "f12": KeyF12, + "f13": KeyF13, + "f14": KeyF14, + "f15": KeyF15, + "f16": KeyF16, + "f17": KeyF17, + "f18": KeyF18, + "f19": KeyF19, + "f20": KeyF20, + "f21": KeyF21, + "f22": KeyF22, + "f23": KeyF23, + "f24": KeyF24, + "f25": KeyF25, + "f26": KeyF26, + "f27": KeyF27, + "f28": KeyF28, + "f29": KeyF29, + "f30": KeyF30, + "f31": KeyF31, + "f32": KeyF32, + "f33": KeyF33, + "f34": KeyF34, + "f35": KeyF35, + "f36": KeyF36, + "f37": KeyF37, + "f38": KeyF38, + "f39": KeyF39, + "f40": KeyF40, + "f41": KeyF41, + "f42": KeyF42, + "f43": KeyF43, + "f44": KeyF44, + "f45": KeyF45, + "f46": KeyF46, + "f47": KeyF47, + "f48": KeyF48, + "f49": KeyF49, + "f50": KeyF50, + "f51": KeyF51, + "f52": KeyF52, + "f53": KeyF53, + "f54": KeyF54, + "f55": KeyF55, + "f56": KeyF56, + "f57": KeyF57, + "f58": KeyF58, + "f59": KeyF59, + "f60": KeyF60, + "f61": KeyF61, + "f62": KeyF62, + "f63": KeyF63, + + // Kitty keyboard extension + "capslock": KeyCapsLock, + "scrolllock": KeyScrollLock, + "numlock": KeyNumLock, + "printscreen": KeyPrintScreen, + "pause": KeyPause, + "menu": KeyMenu, + "mediaplay": KeyMediaPlay, + "mediapause": KeyMediaPause, + "mediaplaypause": KeyMediaPlayPause, + "mediareverse": KeyMediaReverse, + "mediastop": KeyMediaStop, + "mediafastforward": KeyMediaFastForward, + "mediarewind": KeyMediaRewind, + "medianext": KeyMediaNext, + "mediaprev": KeyMediaPrev, + "mediarecord": KeyMediaRecord, + "lowervol": KeyLowerVol, + "raisevol": KeyRaiseVol, + "mute": KeyMute, + "leftshift": KeyLeftShift, + "leftalt": KeyLeftAlt, + "leftctrl": KeyLeftCtrl, + "leftsuper": KeyLeftSuper, + "lefthyper": KeyLeftHyper, + "leftmeta": KeyLeftMeta, + "rightshift": KeyRightShift, + "rightalt": KeyRightAlt, + "rightctrl": KeyRightCtrl, + "rightsuper": KeyRightSuper, + "righthyper": KeyRightHyper, + "rightmeta": KeyRightMeta, + "isolevel3shift": KeyIsoLevel3Shift, + "isolevel5shift": KeyIsoLevel5Shift, +} diff --git a/cli/third_party/ultraviolet/key_table.go b/cli/third_party/ultraviolet/key_table.go new file mode 100644 index 000000000..285ed70fa --- /dev/null +++ b/cli/third_party/ultraviolet/key_table.go @@ -0,0 +1,664 @@ +package uv + +import ( + "strconv" + "strings" + + "github.com/charmbracelet/x/ansi" + "github.com/xo/terminfo" +) + +// buildKeysTable builds a table of key sequences and their corresponding key +// events based on the VT100/VT200, XTerm, and Urxvt terminal specs. +func buildKeysTable(flags LegacyKeyEncoding, term string, useTerminfo bool) map[string]Key { + nul := Key{Code: KeySpace, Mod: ModCtrl} // ctrl+@ or ctrl+space + if flags&flagCtrlAt != 0 { + nul = Key{Code: '@', Mod: ModCtrl} + } + + tab := Key{Code: KeyTab} // ctrl+i or tab + if flags&flagCtrlI != 0 { + tab = Key{Code: 'i', Mod: ModCtrl} + } + + enter := Key{Code: KeyEnter} // ctrl+m or enter + if flags&flagCtrlM != 0 { + enter = Key{Code: 'm', Mod: ModCtrl} + } + + esc := Key{Code: KeyEscape} // ctrl+[ or escape + if flags&flagCtrlOpenBracket != 0 { + esc = Key{Code: '[', Mod: ModCtrl} // ctrl+[ or escape + } + + del := Key{Code: KeyBackspace} + if flags&flagBackspace != 0 { + del.Code = KeyDelete + } + + find := Key{Code: KeyHome} + if flags&flagFind != 0 { + find.Code = KeyFind + } + + sel := Key{Code: KeyEnd} + if flags&flagSelect != 0 { + sel.Code = KeySelect + } + + // The following is a table of key sequences and their corresponding key + // events based on the VT100/VT200 terminal specs. + // + // See: https://vt100.net/docs/vt100-ug/chapter3.html#S3.2 + // See: https://vt100.net/docs/vt220-rm/chapter3.html + // + // XXX: These keys may be overwritten by other options like XTerm or + // Terminfo. + table := map[string]Key{ + // C0 control characters + string(byte(ansi.NUL)): nul, + string(byte(ansi.SOH)): {Code: 'a', Mod: ModCtrl}, + string(byte(ansi.STX)): {Code: 'b', Mod: ModCtrl}, + string(byte(ansi.ETX)): {Code: 'c', Mod: ModCtrl}, + string(byte(ansi.EOT)): {Code: 'd', Mod: ModCtrl}, + string(byte(ansi.ENQ)): {Code: 'e', Mod: ModCtrl}, + string(byte(ansi.ACK)): {Code: 'f', Mod: ModCtrl}, + string(byte(ansi.BEL)): {Code: 'g', Mod: ModCtrl}, + string(byte(ansi.BS)): {Code: 'h', Mod: ModCtrl}, + string(byte(ansi.HT)): tab, + string(byte(ansi.LF)): {Code: 'j', Mod: ModCtrl}, + string(byte(ansi.VT)): {Code: 'k', Mod: ModCtrl}, + string(byte(ansi.FF)): {Code: 'l', Mod: ModCtrl}, + string(byte(ansi.CR)): enter, + string(byte(ansi.SO)): {Code: 'n', Mod: ModCtrl}, + string(byte(ansi.SI)): {Code: 'o', Mod: ModCtrl}, + string(byte(ansi.DLE)): {Code: 'p', Mod: ModCtrl}, + string(byte(ansi.DC1)): {Code: 'q', Mod: ModCtrl}, + string(byte(ansi.DC2)): {Code: 'r', Mod: ModCtrl}, + string(byte(ansi.DC3)): {Code: 's', Mod: ModCtrl}, + string(byte(ansi.DC4)): {Code: 't', Mod: ModCtrl}, + string(byte(ansi.NAK)): {Code: 'u', Mod: ModCtrl}, + string(byte(ansi.SYN)): {Code: 'v', Mod: ModCtrl}, + string(byte(ansi.ETB)): {Code: 'w', Mod: ModCtrl}, + string(byte(ansi.CAN)): {Code: 'x', Mod: ModCtrl}, + string(byte(ansi.EM)): {Code: 'y', Mod: ModCtrl}, + string(byte(ansi.SUB)): {Code: 'z', Mod: ModCtrl}, + string(byte(ansi.ESC)): esc, + string(byte(ansi.FS)): {Code: '\\', Mod: ModCtrl}, + string(byte(ansi.GS)): {Code: ']', Mod: ModCtrl}, + string(byte(ansi.RS)): {Code: '^', Mod: ModCtrl}, + string(byte(ansi.US)): {Code: '_', Mod: ModCtrl}, + + // Special keys in G0 + string(byte(ansi.SP)): {Code: KeySpace, Text: " "}, + string(byte(ansi.DEL)): del, + + // Special keys + + "\x1b[Z": {Code: KeyTab, Mod: ModShift}, + + "\x1b[1~": find, + "\x1b[2~": {Code: KeyInsert}, + "\x1b[3~": {Code: KeyDelete}, + "\x1b[4~": sel, + "\x1b[5~": {Code: KeyPgUp}, + "\x1b[6~": {Code: KeyPgDown}, + "\x1b[7~": {Code: KeyHome}, + "\x1b[8~": {Code: KeyEnd}, + + // Normal mode + "\x1b[A": {Code: KeyUp}, + "\x1b[B": {Code: KeyDown}, + "\x1b[C": {Code: KeyRight}, + "\x1b[D": {Code: KeyLeft}, + "\x1b[E": {Code: KeyBegin}, + "\x1b[F": {Code: KeyEnd}, + "\x1b[H": {Code: KeyHome}, + "\x1b[P": {Code: KeyF1}, + "\x1b[Q": {Code: KeyF2}, + "\x1b[R": {Code: KeyF3}, + "\x1b[S": {Code: KeyF4}, + + // Application Cursor Key Mode (DECCKM) + "\x1bOA": {Code: KeyUp}, + "\x1bOB": {Code: KeyDown}, + "\x1bOC": {Code: KeyRight}, + "\x1bOD": {Code: KeyLeft}, + "\x1bOE": {Code: KeyBegin}, + "\x1bOF": {Code: KeyEnd}, + "\x1bOH": {Code: KeyHome}, + "\x1bOP": {Code: KeyF1}, + "\x1bOQ": {Code: KeyF2}, + "\x1bOR": {Code: KeyF3}, + "\x1bOS": {Code: KeyF4}, + + // Keypad Application Mode (DECKPAM) + + "\x1bOM": {Code: KeyKpEnter}, + "\x1bOX": {Code: KeyKpEqual}, + "\x1bOj": {Code: KeyKpMultiply}, + "\x1bOk": {Code: KeyKpPlus}, + "\x1bOl": {Code: KeyKpComma}, + "\x1bOm": {Code: KeyKpMinus}, + "\x1bOn": {Code: KeyKpDecimal}, + "\x1bOo": {Code: KeyKpDivide}, + "\x1bOp": {Code: KeyKp0}, + "\x1bOq": {Code: KeyKp1}, + "\x1bOr": {Code: KeyKp2}, + "\x1bOs": {Code: KeyKp3}, + "\x1bOt": {Code: KeyKp4}, + "\x1bOu": {Code: KeyKp5}, + "\x1bOv": {Code: KeyKp6}, + "\x1bOw": {Code: KeyKp7}, + "\x1bOx": {Code: KeyKp8}, + "\x1bOy": {Code: KeyKp9}, + + // Function keys + + "\x1b[11~": {Code: KeyF1}, + "\x1b[12~": {Code: KeyF2}, + "\x1b[13~": {Code: KeyF3}, + "\x1b[14~": {Code: KeyF4}, + "\x1b[15~": {Code: KeyF5}, + "\x1b[17~": {Code: KeyF6}, + "\x1b[18~": {Code: KeyF7}, + "\x1b[19~": {Code: KeyF8}, + "\x1b[20~": {Code: KeyF9}, + "\x1b[21~": {Code: KeyF10}, + "\x1b[23~": {Code: KeyF11}, + "\x1b[24~": {Code: KeyF12}, + "\x1b[25~": {Code: KeyF13}, + "\x1b[26~": {Code: KeyF14}, + "\x1b[28~": {Code: KeyF15}, + "\x1b[29~": {Code: KeyF16}, + "\x1b[31~": {Code: KeyF17}, + "\x1b[32~": {Code: KeyF18}, + "\x1b[33~": {Code: KeyF19}, + "\x1b[34~": {Code: KeyF20}, + } + + // CSI ~ sequence keys + csiTildeKeys := map[string]Key{ + "1": find, "2": {Code: KeyInsert}, + "3": {Code: KeyDelete}, "4": sel, + "5": {Code: KeyPgUp}, "6": {Code: KeyPgDown}, + "7": {Code: KeyHome}, "8": {Code: KeyEnd}, + // There are no 9 and 10 keys + "11": {Code: KeyF1}, "12": {Code: KeyF2}, + "13": {Code: KeyF3}, "14": {Code: KeyF4}, + "15": {Code: KeyF5}, "17": {Code: KeyF6}, + "18": {Code: KeyF7}, "19": {Code: KeyF8}, + "20": {Code: KeyF9}, "21": {Code: KeyF10}, + "23": {Code: KeyF11}, "24": {Code: KeyF12}, + "25": {Code: KeyF13}, "26": {Code: KeyF14}, + "28": {Code: KeyF15}, "29": {Code: KeyF16}, + "31": {Code: KeyF17}, "32": {Code: KeyF18}, + "33": {Code: KeyF19}, "34": {Code: KeyF20}, + } + + // URxvt keys + // See https://manpages.ubuntu.com/manpages/trusty/man7/urxvt.7.html#key%20codes + table["\x1b[a"] = Key{Code: KeyUp, Mod: ModShift} + table["\x1b[b"] = Key{Code: KeyDown, Mod: ModShift} + table["\x1b[c"] = Key{Code: KeyRight, Mod: ModShift} + table["\x1b[d"] = Key{Code: KeyLeft, Mod: ModShift} + table["\x1bOa"] = Key{Code: KeyUp, Mod: ModCtrl} + table["\x1bOb"] = Key{Code: KeyDown, Mod: ModCtrl} + table["\x1bOc"] = Key{Code: KeyRight, Mod: ModCtrl} + table["\x1bOd"] = Key{Code: KeyLeft, Mod: ModCtrl} + //nolint:godox + // TODO: invistigate if shift-ctrl arrow keys collide with DECCKM keys i.e. + // "\x1bOA", "\x1bOB", "\x1bOC", "\x1bOD" + + // URxvt modifier CSI ~ keys + for k, v := range csiTildeKeys { + key := v + // Normal (no modifier) already defined part of VT100/VT200 + // Shift modifier + key.Mod = ModShift + table["\x1b["+k+"$"] = key + // Ctrl modifier + key.Mod = ModCtrl + table["\x1b["+k+"^"] = key + // Shift-Ctrl modifier + key.Mod = ModShift | ModCtrl + table["\x1b["+k+"@"] = key + } + + // URxvt F keys + // Note: Shift + F1-F10 generates F11-F20. + // This means Shift + F1 and Shift + F2 will generate F11 and F12, the same + // applies to Ctrl + Shift F1 & F2. + // + // P.S. Don't like this? Blame URxvt, configure your terminal to use + // different escapes like XTerm, or switch to a better terminal ¯\_(ツ)_/¯ + // + // See https://manpages.ubuntu.com/manpages/trusty/man7/urxvt.7.html#key%20codes + table["\x1b[23$"] = Key{Code: KeyF11, Mod: ModShift} + table["\x1b[24$"] = Key{Code: KeyF12, Mod: ModShift} + table["\x1b[25$"] = Key{Code: KeyF13, Mod: ModShift} + table["\x1b[26$"] = Key{Code: KeyF14, Mod: ModShift} + table["\x1b[28$"] = Key{Code: KeyF15, Mod: ModShift} + table["\x1b[29$"] = Key{Code: KeyF16, Mod: ModShift} + table["\x1b[31$"] = Key{Code: KeyF17, Mod: ModShift} + table["\x1b[32$"] = Key{Code: KeyF18, Mod: ModShift} + table["\x1b[33$"] = Key{Code: KeyF19, Mod: ModShift} + table["\x1b[34$"] = Key{Code: KeyF20, Mod: ModShift} + table["\x1b[11^"] = Key{Code: KeyF1, Mod: ModCtrl} + table["\x1b[12^"] = Key{Code: KeyF2, Mod: ModCtrl} + table["\x1b[13^"] = Key{Code: KeyF3, Mod: ModCtrl} + table["\x1b[14^"] = Key{Code: KeyF4, Mod: ModCtrl} + table["\x1b[15^"] = Key{Code: KeyF5, Mod: ModCtrl} + table["\x1b[17^"] = Key{Code: KeyF6, Mod: ModCtrl} + table["\x1b[18^"] = Key{Code: KeyF7, Mod: ModCtrl} + table["\x1b[19^"] = Key{Code: KeyF8, Mod: ModCtrl} + table["\x1b[20^"] = Key{Code: KeyF9, Mod: ModCtrl} + table["\x1b[21^"] = Key{Code: KeyF10, Mod: ModCtrl} + table["\x1b[23^"] = Key{Code: KeyF11, Mod: ModCtrl} + table["\x1b[24^"] = Key{Code: KeyF12, Mod: ModCtrl} + table["\x1b[25^"] = Key{Code: KeyF13, Mod: ModCtrl} + table["\x1b[26^"] = Key{Code: KeyF14, Mod: ModCtrl} + table["\x1b[28^"] = Key{Code: KeyF15, Mod: ModCtrl} + table["\x1b[29^"] = Key{Code: KeyF16, Mod: ModCtrl} + table["\x1b[31^"] = Key{Code: KeyF17, Mod: ModCtrl} + table["\x1b[32^"] = Key{Code: KeyF18, Mod: ModCtrl} + table["\x1b[33^"] = Key{Code: KeyF19, Mod: ModCtrl} + table["\x1b[34^"] = Key{Code: KeyF20, Mod: ModCtrl} + table["\x1b[23@"] = Key{Code: KeyF11, Mod: ModShift | ModCtrl} + table["\x1b[24@"] = Key{Code: KeyF12, Mod: ModShift | ModCtrl} + table["\x1b[25@"] = Key{Code: KeyF13, Mod: ModShift | ModCtrl} + table["\x1b[26@"] = Key{Code: KeyF14, Mod: ModShift | ModCtrl} + table["\x1b[28@"] = Key{Code: KeyF15, Mod: ModShift | ModCtrl} + table["\x1b[29@"] = Key{Code: KeyF16, Mod: ModShift | ModCtrl} + table["\x1b[31@"] = Key{Code: KeyF17, Mod: ModShift | ModCtrl} + table["\x1b[32@"] = Key{Code: KeyF18, Mod: ModShift | ModCtrl} + table["\x1b[33@"] = Key{Code: KeyF19, Mod: ModShift | ModCtrl} + table["\x1b[34@"] = Key{Code: KeyF20, Mod: ModShift | ModCtrl} + + // Register Alt + combinations + // XXX: this must come after URxvt but before XTerm keys to register URxvt + // keys with alt modifier + tmap := map[string]Key{} + for seq, key := range table { + key := key + key.Mod |= ModAlt + key.Text = "" // Clear runes + tmap["\x1b"+seq] = key + } + for seq, key := range tmap { + table[seq] = key + } + + // XTerm modifiers + // These are offset by 1 to be compatible with our Mod type. + // See https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-PC-Style-Function-Keys + modifiers := []KeyMod{ + ModShift, // 1 + ModAlt, // 2 + ModShift | ModAlt, // 3 + ModCtrl, // 4 + ModShift | ModCtrl, // 5 + ModAlt | ModCtrl, // 6 + ModShift | ModAlt | ModCtrl, // 7 + ModMeta, // 8 + ModMeta | ModShift, // 9 + ModMeta | ModAlt, // 10 + ModMeta | ModShift | ModAlt, // 11 + ModMeta | ModCtrl, // 12 + ModMeta | ModShift | ModCtrl, // 13 + ModMeta | ModAlt | ModCtrl, // 14 + ModMeta | ModShift | ModAlt | ModCtrl, // 15 + } + + // SS3 keypad function keys + ss3FuncKeys := map[string]Key{ + // These are defined in XTerm + // Taken from Foot keymap.h and XTerm modifyOtherKeys + // https://codeberg.org/dnkl/foot/src/branch/master/keymap.h + "M": {Code: KeyKpEnter}, "X": {Code: KeyKpEqual}, + "j": {Code: KeyKpMultiply}, "k": {Code: KeyKpPlus}, + "l": {Code: KeyKpComma}, "m": {Code: KeyKpMinus}, + "n": {Code: KeyKpDecimal}, "o": {Code: KeyKpDivide}, + "p": {Code: KeyKp0}, "q": {Code: KeyKp1}, + "r": {Code: KeyKp2}, "s": {Code: KeyKp3}, + "t": {Code: KeyKp4}, "u": {Code: KeyKp5}, + "v": {Code: KeyKp6}, "w": {Code: KeyKp7}, + "x": {Code: KeyKp8}, "y": {Code: KeyKp9}, + } + + // XTerm keys + csiFuncKeys := map[string]Key{ + "A": {Code: KeyUp}, "B": {Code: KeyDown}, + "C": {Code: KeyRight}, "D": {Code: KeyLeft}, + "E": {Code: KeyBegin}, "F": {Code: KeyEnd}, + "H": {Code: KeyHome}, "P": {Code: KeyF1}, + "Q": {Code: KeyF2}, "R": {Code: KeyF3}, + "S": {Code: KeyF4}, + } + + // CSI 27 ; ; ~ keys defined in XTerm modifyOtherKeys + modifyOtherKeys := map[int]Key{ + ansi.BS: {Code: KeyBackspace}, + ansi.HT: {Code: KeyTab}, + ansi.CR: {Code: KeyEnter}, + ansi.ESC: {Code: KeyEscape}, + ansi.DEL: {Code: KeyBackspace}, + } + + for _, m := range modifiers { + // XTerm modifier offset +1 + xtermMod := strconv.Itoa(int(m) + 1) + + // CSI 1 ; + for k, v := range csiFuncKeys { + // Functions always have a leading 1 param + seq := "\x1b[1;" + xtermMod + k + key := v + key.Mod = m + table[seq] = key + } + // SS3 + for k, v := range ss3FuncKeys { + seq := "\x1bO" + xtermMod + k + key := v + key.Mod = m + table[seq] = key + } + // CSI ; ~ + for k, v := range csiTildeKeys { + seq := "\x1b[" + k + ";" + xtermMod + "~" + key := v + key.Mod = m + table[seq] = key + } + // CSI 27 ; ; ~ + for k, v := range modifyOtherKeys { + code := strconv.Itoa(k) + seq := "\x1b[27;" + xtermMod + ";" + code + "~" + key := v + key.Mod = m + table[seq] = key + } + } + + // Register terminfo keys + // XXX: this might override keys already registered in table + if useTerminfo { + titable := buildTerminfoKeys(flags, term) + for seq, key := range titable { + table[seq] = key + } + } + + return table +} + +func buildTerminfoKeys(flags LegacyKeyEncoding, term string) map[string]Key { + table := make(map[string]Key) + ti, _ := terminfo.Load(term) + if ti == nil { + return table + } + + tiTable := defaultTerminfoKeys(flags) + + // Default keys + for name, seq := range ti.StringCapsShort() { + if !strings.HasPrefix(name, "k") || len(seq) == 0 { + continue + } + + if k, ok := tiTable[name]; ok { + table[string(seq)] = k + } + } + + // Extended keys + for name, seq := range ti.ExtStringCapsShort() { + if !strings.HasPrefix(name, "k") || len(seq) == 0 { + continue + } + + if k, ok := tiTable[name]; ok { + table[string(seq)] = k + } + } + + return table +} + +// This returns a map of terminfo keys to key events. It's a mix of ncurses +// terminfo default and user-defined key capabilities. +// Upper-case caps that are defined in the default terminfo database are +// - kNXT +// - kPRV +// - kHOM +// - kEND +// - kDC +// - kIC +// - kLFT +// - kRIT +// +// See https://man7.org/linux/man-pages/man5/terminfo.5.html +// See https://github.com/mirror/ncurses/blob/master/include/Caps-ncurses +func defaultTerminfoKeys(flags LegacyKeyEncoding) map[string]Key { + keys := map[string]Key{ + "kcuu1": {Code: KeyUp}, + "kUP": {Code: KeyUp, Mod: ModShift}, + "kUP3": {Code: KeyUp, Mod: ModAlt}, + "kUP4": {Code: KeyUp, Mod: ModShift | ModAlt}, + "kUP5": {Code: KeyUp, Mod: ModCtrl}, + "kUP6": {Code: KeyUp, Mod: ModShift | ModCtrl}, + "kUP7": {Code: KeyUp, Mod: ModAlt | ModCtrl}, + "kUP8": {Code: KeyUp, Mod: ModShift | ModAlt | ModCtrl}, + "kcud1": {Code: KeyDown}, + "kDN": {Code: KeyDown, Mod: ModShift}, + "kDN3": {Code: KeyDown, Mod: ModAlt}, + "kDN4": {Code: KeyDown, Mod: ModShift | ModAlt}, + "kDN5": {Code: KeyDown, Mod: ModCtrl}, + "kDN7": {Code: KeyDown, Mod: ModAlt | ModCtrl}, + "kDN6": {Code: KeyDown, Mod: ModShift | ModCtrl}, + "kDN8": {Code: KeyDown, Mod: ModShift | ModAlt | ModCtrl}, + "kcub1": {Code: KeyLeft}, + "kLFT": {Code: KeyLeft, Mod: ModShift}, + "kLFT3": {Code: KeyLeft, Mod: ModAlt}, + "kLFT4": {Code: KeyLeft, Mod: ModShift | ModAlt}, + "kLFT5": {Code: KeyLeft, Mod: ModCtrl}, + "kLFT6": {Code: KeyLeft, Mod: ModShift | ModCtrl}, + "kLFT7": {Code: KeyLeft, Mod: ModAlt | ModCtrl}, + "kLFT8": {Code: KeyLeft, Mod: ModShift | ModAlt | ModCtrl}, + "kcuf1": {Code: KeyRight}, + "kRIT": {Code: KeyRight, Mod: ModShift}, + "kRIT3": {Code: KeyRight, Mod: ModAlt}, + "kRIT4": {Code: KeyRight, Mod: ModShift | ModAlt}, + "kRIT5": {Code: KeyRight, Mod: ModCtrl}, + "kRIT6": {Code: KeyRight, Mod: ModShift | ModCtrl}, + "kRIT7": {Code: KeyRight, Mod: ModAlt | ModCtrl}, + "kRIT8": {Code: KeyRight, Mod: ModShift | ModAlt | ModCtrl}, + "kich1": {Code: KeyInsert}, + "kIC": {Code: KeyInsert, Mod: ModShift}, + "kIC3": {Code: KeyInsert, Mod: ModAlt}, + "kIC4": {Code: KeyInsert, Mod: ModShift | ModAlt}, + "kIC5": {Code: KeyInsert, Mod: ModCtrl}, + "kIC6": {Code: KeyInsert, Mod: ModShift | ModCtrl}, + "kIC7": {Code: KeyInsert, Mod: ModAlt | ModCtrl}, + "kIC8": {Code: KeyInsert, Mod: ModShift | ModAlt | ModCtrl}, + "kdch1": {Code: KeyDelete}, + "kDC": {Code: KeyDelete, Mod: ModShift}, + "kDC3": {Code: KeyDelete, Mod: ModAlt}, + "kDC4": {Code: KeyDelete, Mod: ModShift | ModAlt}, + "kDC5": {Code: KeyDelete, Mod: ModCtrl}, + "kDC6": {Code: KeyDelete, Mod: ModShift | ModCtrl}, + "kDC7": {Code: KeyDelete, Mod: ModAlt | ModCtrl}, + "kDC8": {Code: KeyDelete, Mod: ModShift | ModAlt | ModCtrl}, + "khome": {Code: KeyHome}, + "kHOM": {Code: KeyHome, Mod: ModShift}, + "kHOM3": {Code: KeyHome, Mod: ModAlt}, + "kHOM4": {Code: KeyHome, Mod: ModShift | ModAlt}, + "kHOM5": {Code: KeyHome, Mod: ModCtrl}, + "kHOM6": {Code: KeyHome, Mod: ModShift | ModCtrl}, + "kHOM7": {Code: KeyHome, Mod: ModAlt | ModCtrl}, + "kHOM8": {Code: KeyHome, Mod: ModShift | ModAlt | ModCtrl}, + "kend": {Code: KeyEnd}, + "kEND": {Code: KeyEnd, Mod: ModShift}, + "kEND3": {Code: KeyEnd, Mod: ModAlt}, + "kEND4": {Code: KeyEnd, Mod: ModShift | ModAlt}, + "kEND5": {Code: KeyEnd, Mod: ModCtrl}, + "kEND6": {Code: KeyEnd, Mod: ModShift | ModCtrl}, + "kEND7": {Code: KeyEnd, Mod: ModAlt | ModCtrl}, + "kEND8": {Code: KeyEnd, Mod: ModShift | ModAlt | ModCtrl}, + "kpp": {Code: KeyPgUp}, + "kprv": {Code: KeyPgUp}, + "kPRV": {Code: KeyPgUp, Mod: ModShift}, + "kPRV3": {Code: KeyPgUp, Mod: ModAlt}, + "kPRV4": {Code: KeyPgUp, Mod: ModShift | ModAlt}, + "kPRV5": {Code: KeyPgUp, Mod: ModCtrl}, + "kPRV6": {Code: KeyPgUp, Mod: ModShift | ModCtrl}, + "kPRV7": {Code: KeyPgUp, Mod: ModAlt | ModCtrl}, + "kPRV8": {Code: KeyPgUp, Mod: ModShift | ModAlt | ModCtrl}, + "knp": {Code: KeyPgDown}, + "knxt": {Code: KeyPgDown}, + "kNXT": {Code: KeyPgDown, Mod: ModShift}, + "kNXT3": {Code: KeyPgDown, Mod: ModAlt}, + "kNXT4": {Code: KeyPgDown, Mod: ModShift | ModAlt}, + "kNXT5": {Code: KeyPgDown, Mod: ModCtrl}, + "kNXT6": {Code: KeyPgDown, Mod: ModShift | ModCtrl}, + "kNXT7": {Code: KeyPgDown, Mod: ModAlt | ModCtrl}, + "kNXT8": {Code: KeyPgDown, Mod: ModShift | ModAlt | ModCtrl}, + + "kbs": {Code: KeyBackspace}, + "kcbt": {Code: KeyTab, Mod: ModShift}, + + // Function keys + // This only includes the first 12 function keys. The rest are treated + // as modifiers of the first 12. + // Take a look at XTerm modifyFunctionKeys + // + // XXX: To use unambiguous function keys, use fixterms or kitty clipboard. + // + // See https://invisible-island.net/xterm/manpage/xterm.html#VT100-Widget-Resources:modifyFunctionKeys + // See https://invisible-island.net/xterm/terminfo.html + + "kf1": {Code: KeyF1}, + "kf2": {Code: KeyF2}, + "kf3": {Code: KeyF3}, + "kf4": {Code: KeyF4}, + "kf5": {Code: KeyF5}, + "kf6": {Code: KeyF6}, + "kf7": {Code: KeyF7}, + "kf8": {Code: KeyF8}, + "kf9": {Code: KeyF9}, + "kf10": {Code: KeyF10}, + "kf11": {Code: KeyF11}, + "kf12": {Code: KeyF12}, + "kf13": {Code: KeyF1, Mod: ModShift}, + "kf14": {Code: KeyF2, Mod: ModShift}, + "kf15": {Code: KeyF3, Mod: ModShift}, + "kf16": {Code: KeyF4, Mod: ModShift}, + "kf17": {Code: KeyF5, Mod: ModShift}, + "kf18": {Code: KeyF6, Mod: ModShift}, + "kf19": {Code: KeyF7, Mod: ModShift}, + "kf20": {Code: KeyF8, Mod: ModShift}, + "kf21": {Code: KeyF9, Mod: ModShift}, + "kf22": {Code: KeyF10, Mod: ModShift}, + "kf23": {Code: KeyF11, Mod: ModShift}, + "kf24": {Code: KeyF12, Mod: ModShift}, + "kf25": {Code: KeyF1, Mod: ModCtrl}, + "kf26": {Code: KeyF2, Mod: ModCtrl}, + "kf27": {Code: KeyF3, Mod: ModCtrl}, + "kf28": {Code: KeyF4, Mod: ModCtrl}, + "kf29": {Code: KeyF5, Mod: ModCtrl}, + "kf30": {Code: KeyF6, Mod: ModCtrl}, + "kf31": {Code: KeyF7, Mod: ModCtrl}, + "kf32": {Code: KeyF8, Mod: ModCtrl}, + "kf33": {Code: KeyF9, Mod: ModCtrl}, + "kf34": {Code: KeyF10, Mod: ModCtrl}, + "kf35": {Code: KeyF11, Mod: ModCtrl}, + "kf36": {Code: KeyF12, Mod: ModCtrl}, + "kf37": {Code: KeyF1, Mod: ModShift | ModCtrl}, + "kf38": {Code: KeyF2, Mod: ModShift | ModCtrl}, + "kf39": {Code: KeyF3, Mod: ModShift | ModCtrl}, + "kf40": {Code: KeyF4, Mod: ModShift | ModCtrl}, + "kf41": {Code: KeyF5, Mod: ModShift | ModCtrl}, + "kf42": {Code: KeyF6, Mod: ModShift | ModCtrl}, + "kf43": {Code: KeyF7, Mod: ModShift | ModCtrl}, + "kf44": {Code: KeyF8, Mod: ModShift | ModCtrl}, + "kf45": {Code: KeyF9, Mod: ModShift | ModCtrl}, + "kf46": {Code: KeyF10, Mod: ModShift | ModCtrl}, + "kf47": {Code: KeyF11, Mod: ModShift | ModCtrl}, + "kf48": {Code: KeyF12, Mod: ModShift | ModCtrl}, + "kf49": {Code: KeyF1, Mod: ModAlt}, + "kf50": {Code: KeyF2, Mod: ModAlt}, + "kf51": {Code: KeyF3, Mod: ModAlt}, + "kf52": {Code: KeyF4, Mod: ModAlt}, + "kf53": {Code: KeyF5, Mod: ModAlt}, + "kf54": {Code: KeyF6, Mod: ModAlt}, + "kf55": {Code: KeyF7, Mod: ModAlt}, + "kf56": {Code: KeyF8, Mod: ModAlt}, + "kf57": {Code: KeyF9, Mod: ModAlt}, + "kf58": {Code: KeyF10, Mod: ModAlt}, + "kf59": {Code: KeyF11, Mod: ModAlt}, + "kf60": {Code: KeyF12, Mod: ModAlt}, + "kf61": {Code: KeyF1, Mod: ModShift | ModAlt}, + "kf62": {Code: KeyF2, Mod: ModShift | ModAlt}, + "kf63": {Code: KeyF3, Mod: ModShift | ModAlt}, + } + + // Preserve F keys from F13 to F63 instead of using them for F-keys + // modifiers. + if flags&flagFKeys != 0 { + keys["kf13"] = Key{Code: KeyF13} + keys["kf14"] = Key{Code: KeyF14} + keys["kf15"] = Key{Code: KeyF15} + keys["kf16"] = Key{Code: KeyF16} + keys["kf17"] = Key{Code: KeyF17} + keys["kf18"] = Key{Code: KeyF18} + keys["kf19"] = Key{Code: KeyF19} + keys["kf20"] = Key{Code: KeyF20} + keys["kf21"] = Key{Code: KeyF21} + keys["kf22"] = Key{Code: KeyF22} + keys["kf23"] = Key{Code: KeyF23} + keys["kf24"] = Key{Code: KeyF24} + keys["kf25"] = Key{Code: KeyF25} + keys["kf26"] = Key{Code: KeyF26} + keys["kf27"] = Key{Code: KeyF27} + keys["kf28"] = Key{Code: KeyF28} + keys["kf29"] = Key{Code: KeyF29} + keys["kf30"] = Key{Code: KeyF30} + keys["kf31"] = Key{Code: KeyF31} + keys["kf32"] = Key{Code: KeyF32} + keys["kf33"] = Key{Code: KeyF33} + keys["kf34"] = Key{Code: KeyF34} + keys["kf35"] = Key{Code: KeyF35} + keys["kf36"] = Key{Code: KeyF36} + keys["kf37"] = Key{Code: KeyF37} + keys["kf38"] = Key{Code: KeyF38} + keys["kf39"] = Key{Code: KeyF39} + keys["kf40"] = Key{Code: KeyF40} + keys["kf41"] = Key{Code: KeyF41} + keys["kf42"] = Key{Code: KeyF42} + keys["kf43"] = Key{Code: KeyF43} + keys["kf44"] = Key{Code: KeyF44} + keys["kf45"] = Key{Code: KeyF45} + keys["kf46"] = Key{Code: KeyF46} + keys["kf47"] = Key{Code: KeyF47} + keys["kf48"] = Key{Code: KeyF48} + keys["kf49"] = Key{Code: KeyF49} + keys["kf50"] = Key{Code: KeyF50} + keys["kf51"] = Key{Code: KeyF51} + keys["kf52"] = Key{Code: KeyF52} + keys["kf53"] = Key{Code: KeyF53} + keys["kf54"] = Key{Code: KeyF54} + keys["kf55"] = Key{Code: KeyF55} + keys["kf56"] = Key{Code: KeyF56} + keys["kf57"] = Key{Code: KeyF57} + keys["kf58"] = Key{Code: KeyF58} + keys["kf59"] = Key{Code: KeyF59} + keys["kf60"] = Key{Code: KeyF60} + keys["kf61"] = Key{Code: KeyF61} + keys["kf62"] = Key{Code: KeyF62} + keys["kf63"] = Key{Code: KeyF63} + } + + return keys +} diff --git a/cli/third_party/ultraviolet/layout/cache.go b/cli/third_party/ultraviolet/layout/cache.go new file mode 100644 index 000000000..6874cfc46 --- /dev/null +++ b/cli/third_party/ultraviolet/layout/cache.go @@ -0,0 +1,29 @@ +package layout + +import ( + "sync" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/ultraviolet/internal/lru" +) + +// globalCacheSize is chosen to comfortably hold one entry per row and column +// of a typical terminal, with headroom to spare. A 171-column x 51-row +// display yields 222 unique keys; doubling and rounding up gives 500. +const globalCacheSize = 500 + +var ( + globalCache = lru.New[cacheKey, cacheValue](globalCacheSize) + globalCacheMu sync.Mutex +) + +type cacheKey struct { + Area uv.Rectangle + Direction Direction + ConstraintsHash uint64 + Padding Padding + Spacing int + Flex Flex +} + +type cacheValue struct{ Segments, Spacers Splitted } diff --git a/cli/third_party/ultraviolet/layout/constraint.go b/cli/third_party/ultraviolet/layout/constraint.go new file mode 100644 index 000000000..c66c4d73c --- /dev/null +++ b/cli/third_party/ultraviolet/layout/constraint.go @@ -0,0 +1,174 @@ +package layout + +import ( + "fmt" + "io" +) + +// Constraint describes how a single segment of a [Layout] should be sized. +// +// Each constraint type expresses a different kind of sizing rule: +// fixed ([Len]), proportional ([Percent], [Ratio]), bounded ([Min], [Max]), +// or greedy ([Fill]). Proportional constraints are evaluated against the +// full area being split rather than the remaining space after fixed +// constraints have been applied. +// +// When the solver cannot satisfy every constraint, it resolves conflicts +// according to the following priority order (highest first): +// +// - [Min] +// - [Max] +// - [Len] +// - [Percent] +// - [Ratio] +// - [Fill] +type Constraint interface { + hash(w io.Writer) + + // isConstraint is a private method to prevent users implementing the + // interface making it a sealed enum. + isConstraint() +} + +type ( + // Min ensures the segment is no smaller than the given number of cells. + // + // # Examples + // + // [Percent(100), Min(20)] + // + // ┌────────────────────────────┐┌──────────────────┐ + // │ 30 px ││ 20 px │ + // └────────────────────────────┘└──────────────────┘ + // + // [Percent(100), Min(10)] + // + // ┌──────────────────────────────────────┐┌────────┐ + // │ 40 px ││ 10 px │ + // └──────────────────────────────────────┘└────────┘ + Min int + + // Max caps the segment at the given number of cells. + // + // # Examples + // + // [Percent(0), Max(20)] + // + // ┌────────────────────────────┐┌──────────────────┐ + // │ 30 px ││ 20 px │ + // └────────────────────────────┘└──────────────────┘ + // + // [Percent(0), Max(10)] + // + // ┌──────────────────────────────────────┐┌────────┐ + // │ 40 px ││ 10 px │ + // └──────────────────────────────────────┘└────────┘ + Max int + + // Len fixes the segment to exactly the given number of cells. + // + // # Examples + // + // [Len(20), Len(20)] + // + // ┌──────────────────┐┌──────────────────┐ + // │ 20 px ││ 20 px │ + // └──────────────────┘└──────────────────┘ + // + // [Len(20), Len(30)] + // + // ┌──────────────────┐┌────────────────────────────┐ + // │ 20 px ││ 30 px │ + // └──────────────────┘└────────────────────────────┘ + Len int + + // Percent sizes the segment as a fraction of the total area. + // + // The integer value is treated as a percentage (0-100+) and multiplied + // by the total area; the result is rounded to the nearest cell. + // + // Because only whole integers are accepted, some fractions (e.g. 1/3) + // cannot be represented exactly. Consider [Ratio] or [Fill] instead. + // + // # Examples + // + // [Percent(75), Fill(1)] + // + // ┌────────────────────────────────────┐┌──────────┐ + // │ 38 px ││ 12 px │ + // └────────────────────────────────────┘└──────────┘ + // + // [Percent(50), Fill(1)] + // + // ┌───────────────────────┐┌───────────────────────┐ + // │ 25 px ││ 25 px │ + // └───────────────────────┘└───────────────────────┘ + Percent int + + // Ratio sizes the segment as a numerator/denominator fraction of the total area. + // + // The fraction is converted to a float, multiplied by the area, and + // rounded to the nearest cell. + // + // # Examples + // + // [Ratio(1, 2) ; 2] + // + // ┌───────────────────────┐┌───────────────────────┐ + // │ 25 px ││ 25 px │ + // └───────────────────────┘└───────────────────────┘ + // + // [Ratio(1, 4) ; 4] + // + // ┌───────────┐┌──────────┐┌───────────┐┌──────────┐ + // │ 13 px ││ 12 px ││ 13 px ││ 12 px │ + // └───────────┘└──────────┘└───────────┘└──────────┘ + Ratio struct{ Num, Den int } + + // Fill distributes remaining space proportionally among all Fill segments + // according to their respective weights. + // + // A Fill segment only expands into space left over after higher-priority + // constraints have been satisfied. Multiple Fill segments share that + // leftover in proportion to their integer values. + // + // # Examples + // + // + // [Fill(1), Fill(2), Fill(3)] + // + // ┌──────┐┌───────────────┐┌───────────────────────┐ + // │ 8 px ││ 17 px ││ 25 px │ + // └──────┘└───────────────┘└───────────────────────┘ + // + // [Fill(1), Percent(50), Fill(1)] + // + // ┌───────────┐┌───────────────────────┐┌──────────┐ + // │ 13 px ││ 25 px ││ 12 px │ + // └───────────┘└───────────────────────┘└──────────┘ + Fill int +) + +func (m Min) String() string { return fmt.Sprintf("Min(%d)", m) } +func (m Min) hash(w io.Writer) { fmt.Fprint(w, "min", m) } +func (Min) isConstraint() {} + +func (m Max) String() string { return fmt.Sprintf("Max(%d)", m) } +func (m Max) hash(w io.Writer) { fmt.Fprint(w, "max", m) } +func (Max) isConstraint() {} + +func (l Len) String() string { return fmt.Sprintf("Len(%d)", l) } +func (l Len) hash(w io.Writer) { fmt.Fprint(w, "len", l) } +func (Len) isConstraint() {} + +func (p Percent) String() string { return fmt.Sprintf("Percent(%d)", p) } +func (p Percent) hash(w io.Writer) { fmt.Fprint(w, "percent", p) } +func (Percent) isConstraint() {} + +func (r Ratio) String() string { return fmt.Sprintf("Ratio(%d / %d)", r.Num, r.Den) } +func (r Ratio) hash(w io.Writer) { fmt.Fprint(w, "ratio", r.Num, r.Den) } +func (Ratio) isConstraint() {} + +func (f Fill) String() string { return fmt.Sprintf("Fill(%d)", f) } +func (f Fill) hash(w io.Writer) { fmt.Fprint(w, "fill", f) } +func (Fill) isConstraint() {} diff --git a/cli/third_party/ultraviolet/layout/flex.go b/cli/third_party/ultraviolet/layout/flex.go new file mode 100644 index 000000000..0327c31b1 --- /dev/null +++ b/cli/third_party/ultraviolet/layout/flex.go @@ -0,0 +1,210 @@ +package layout + +import ( + "fmt" +) + +// Flex controls how leftover space is distributed once every segment's +// constraint has been resolved. It is analogous to the CSS +// justify-content property and is used together with [Layout]. +type Flex int + +const ( + + // FlexStart pushes segments to the leading edge of the area, leaving + // any surplus space at the trailing edge. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ + // │ Percent(20) ││ Length(20) ││ Fixed(20) │ + // └──────────────┘└──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐┌──────20 px───────┐ + // │ Max(20) ││ Max(20) │ + // └──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ + // │ Max(20) │ + // └──────────────────┘ + FlexStart Flex = iota + + // FlexLegacy fills the entire area by assigning surplus space to the + // lowest-priority trailing segment. This reproduces the original + // Ratatui/tui-rs layout behaviour. + // + // The examples below show how surplus space is allocated for different + // constraint combinations. Recall the priority order (highest first): + // + // - [Min] + // - [Max] + // - [Len] + // - [Percent] + // - [Ratio] + // - [Fill] + // + // With all-[Len] constraints the surplus goes to the final segment. + // + // <----------------------------------- 80 px ------------------------------------> + // ┌──────20 px───────┐┌──────20 px───────┐┌────────────────40 px─────────────────┐ + // │ Length(20) ││ Length(20) ││ Length(20) │ + // └──────────────────┘└──────────────────┘└──────────────────────────────────────┘ + // ^^^^^^^^^^^^^^^^ EXCESS ^^^^^^^^^^^^^^^^ + // + // [Fill] has the lowest priority, so it always absorbs surplus. + // + // <----------------------------------- 80 px ------------------------------------> + // ┌──────20 px───────┐┌──────20 px───────┐┌──────20 px───────┐┌──────20 px───────┐ + // │ Fill(0) ││ Max(20) ││ Length(20) ││ Length(20) │ + // └──────────────────┘└──────────────────┘└──────────────────┘└──────────────────┘ + // ^^^^^^ EXCESS ^^^^^^ + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌──────────────────────────60 px───────────────────────────┐┌──────20 px───────┐ + // │ Min(20) ││ Max(20) │ + // └──────────────────────────────────────────────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌────────────────────────────────────80 px─────────────────────────────────────┐ + // │ Max(20) │ + // └──────────────────────────────────────────────────────────────────────────────┘ + FlexLegacy + + // FlexEnd pushes segments to the trailing edge of the area, leaving + // surplus space at the leading edge. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ + // │ Percent(20) ││ Length(20) ││ Length(20) │ + // └──────────────┘└──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐┌──────20 px───────┐ + // │ Max(20) ││ Max(20) │ + // └──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ + // │ Max(20) │ + // └──────────────────┘ + FlexEnd + + // FlexCenter places segments in the middle of the area, distributing + // surplus space equally before the first and after the last segment. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐┌──────20 px───────┐┌──────20 px───────┐ + // │ Percent(20) ││ Length(20) ││ Length(20) │ + // └──────────────┘└──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐┌──────20 px───────┐ + // │ Max(20) ││ Max(20) │ + // └──────────────────┘└──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ + // │ Max(20) │ + // └──────────────────┘ + FlexCenter + + // FlexSpaceBetween distributes surplus space equally between adjacent + // segments, with no space before the first or after the last. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐ ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Percent(20) │ │ Length(20) │ │ Length(20) │ + // └──────────────┘ └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Max(20) │ │ Max(20) │ + // └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌────────────────────────────────────80 px─────────────────────────────────────┐ + // │ Max(20) │ + // └──────────────────────────────────────────────────────────────────────────────┘ + FlexSpaceBetween + + // FlexSpaceEvenly distributes surplus space so that every gap + // (including before the first and after the last segment) is the same width. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐ ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Percent(20) │ │ Length(20) │ │ Length(20) │ + // └──────────────┘ └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Max(20) │ │ Max(20) │ + // └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ + // │ Max(20) │ + // └──────────────────┘ + FlexSpaceEvenly + + // FlexSpaceAround places equal space on both sides of each segment. + // Adjacent segments therefore have twice the gap of the outer edges. + // + // # Examples + // + // <------------------------------------80 px-------------------------------------> + // ┌────16 px─────┐ ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Percent(20) │ │ Length(20) │ │ Length(20) │ + // └──────────────┘ └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ ┌──────20 px───────┐ + // │ Max(20) │ │ Max(20) │ + // └──────────────────┘ └──────────────────┘ + // + // <------------------------------------80 px-------------------------------------> + // ┌──────20 px───────┐ + // │ Max(20) │ + // └──────────────────┘ + FlexSpaceAround +) + +func (f Flex) String() string { + switch f { + case FlexCenter: + return "Center" + + case FlexEnd: + return "End" + + case FlexLegacy: + return "Legacy" + + case FlexSpaceAround: + return "Space Around" + + case FlexSpaceBetween: + return "Space Between" + + case FlexSpaceEvenly: + return "Space Evenly" + + case FlexStart: + return "Start" + + default: + return fmt.Sprintf("Flex(%d)", f) + } +} diff --git a/cli/third_party/ultraviolet/layout/layout.go b/cli/third_party/ultraviolet/layout/layout.go new file mode 100644 index 000000000..b5748c5c8 --- /dev/null +++ b/cli/third_party/ultraviolet/layout/layout.go @@ -0,0 +1,973 @@ +// Package layout partitions terminal screen space into rectangular regions +// using a constraint-based solver. +// +// Under the hood, it relies on the [Cassowary constraint solver algorithm] to +// resolve competing size requirements. Each constraint carries a priority, so +// the solver can pick the best trade-off when not every requirement fits. +// +// # How It Works +// +// A [Layout] takes the available area and a list of constraints ([Len], [Ratio], +// [Percent], [Fill], [Min], [Max]) and produces a set of non-overlapping rectangles. +// The solver tries to honour every constraint; when that is impossible it +// relaxes lower-priority ones first. +// +// You are not required to use [Layout] at all. If you prefer manual control, +// you can compute [uv.Rectangle] values yourself with plain arithmetic. +// +// # Acknowledgements +// +// This implementation is heavily based on [Ratatui] source code and +// is roughly 1:1 translation from Rust with some minor API adjustments. +// +// [Cassowary constraint solver algorithm]: https://en.wikipedia.org/wiki/Cassowary_(software) +// [Ratatui]: https://ratatui.rs/ +package layout + +import ( + "fmt" + "hash/fnv" + "math" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/ultraviolet/internal/casso" +) + +// floatPrecisionMultiplier scales cell positions into a higher-precision +// floating-point domain before handing them to the constraint solver. +// The number of trailing zeros determines the decimal precision kept +// during rounding. +const floatPrecisionMultiplier float64 = 100.0 + +const ( + required casso.Priority = 1_001_001_000 + strong casso.Priority = 1_000_000 + medium casso.Priority = 1_000 + weak casso.Priority = 1 +) + +const ( + // spacerSizeEq enforces equal sizing across spacers. + // + // ┌ ┐┌───┐┌ ┐┌───┐┌ ┐ + // ==x │ │ ==x │ │ ==x + // └ ┘└───┘└ ┘└───┘└ ┘ + spacerSizeEq = required / 10.0 + + // minSizeGTE enforces the lower-bound inequality for [Min] constraints. + // + // ┌────────┐ + // │Min(>=x)│ + // └────────┘ + minSizeGTE = strong * 100.0 + + // maxSizeLTE enforces the upper-bound inequality for [Max] constraints. + // + // ┌────────┐ + // │Max(<=x)│ + // └────────┘ + maxSizeLTE = strong * 100.0 + + // lengthSizeEq pins the segment to the exact size requested by a [Len] constraint. + // + // ┌────────┐ + // │Len(==x)│ + // └────────┘ + lengthSizeEq = strong * 10.0 + + // percentSizeEq tries to make the segment match its [Percent] target. + // + // ┌────────────┐ + // │Percent(==x)│ + // └────────────┘ + percentSizeEq = strong + + // ratioSizeEq tries to make the segment match its [Ratio] target. + // + // ┌────────────┐ + // │Ratio(==x,y)│ + // └────────────┘ + ratioSizeEq = strong / 10.0 + + // minSizeEq is an equality companion for the [Min] lower-bound; it + // nudges the segment toward the minimum value when room is tight. + // + // ┌────────┐ + // │Min(==x)│ + // └────────┘ + minSizeEq = medium * 10.0 + + // maxSizeEq is an equality companion for the [Max] upper-bound; + // it nudges the segment toward the maximum value. + // + // ┌────────┐ + // │Max(==x)│ + // └────────┘ + maxSizeEq = medium * 10.0 + + // fillGrow lets [Fill] segments expand into available space. + // + // ┌─────────────────────┐ + // │<= Fill(x) =>│ + // └─────────────────────┘ + fillGrow = medium + + // grow is a general expansion priority (used by [Min] in non-legacy flex). + // + // ┌────────────┐ + // │<= Min(x) =>│ + // └────────────┘ + grow casso.Priority = 100.0 + + // spaceGrow allows spacers to expand and absorb remaining room. + // + // ┌ ┐ + // <= x => + // └ ┘ + spaceGrow = weak * 10.0 + + // allSegmentGrow encourages all segments to share the same size. + // + // ┌───────┐ + // │<= x =>│ + // └───────┘ + allSegmentGrow = weak +) + +// Splitted holds the rectangles produced by a [Layout.Split] call. +type Splitted []uv.Rectangle + +// Assign stores each resulting rectangle into the corresponding pointer. +// +// Nil pointers are silently skipped. +// +// Panics when len(areas) exceeds the number of rectangles in [Splitted]. +// +// # Examples +// +// var top, bottom uv.Rectangle +// +// layout.New(layout.Fill(1), layout.Len(1)). +// Split(area). +// Assign(&top, &bottom) +func (s Splitted) Assign(areas ...*uv.Rectangle) { + for i := range areas { + if areas[i] != nil { + *areas[i] = s[i] + } + } +} + +// Direction controls whether a [Layout] arranges its segments +// horizontally (left to right) or vertically (top to bottom). +type Direction int + +const ( + // DirectionVertical - layout segments are arranged top to bottom (default). + DirectionVertical Direction = iota + // DirectionHorizontal - layout segments are arranged side by side (left to right). + DirectionHorizontal +) + +// New returns a [Layout] configured with the given direction and constraints. +func New(direction Direction, constraints ...Constraint) Layout { + return Layout{ + Direction: direction, + Constraints: constraints, + } +} + +// Vertical is shorthand for New(DirectionVertical, constraints...). +func Vertical(constraints ...Constraint) Layout { + return New(DirectionVertical, constraints...) +} + +// Horizontal is shorthand for New(DirectionHorizontal, constraints...). +func Horizontal(constraints ...Constraint) Layout { + return New(DirectionHorizontal, constraints...) +} + +// Layout splits a rectangular area into smaller rectangles using a set of constraints. +// It is the primary building block for structuring terminal user interfaces. +// +// Fields: +// - Direction: whether segments flow vertically or horizontally. +// - Constraints: the sizing rules ([Len], [Ratio], [Percent], [Fill], [Min], [Max]). +// - Padding: inset applied to the outer area before solving. +// - Flex: strategy for distributing leftover space among segments. +// - Spacing: gap (or overlap, if negative) between adjacent segments. +// +// Internally, sizes are resolved by a Cassowary linear-constraint solver that +// satisfies as many rules as it can, preferring higher-priority constraints +// when trade-offs are necessary. +type Layout struct { + Direction Direction + Constraints []Constraint + Padding Padding + // Spacing is the gap between adjacent segments, measured in cells. + // A negative value causes segments to overlap by that many cells. + Spacing int + Flex Flex +} + +// WithDirection returns a shallow copy of the layout using the specified direction. +func (l Layout) WithDirection(direction Direction) Layout { + l.Direction = direction + + return l +} + +// WithPadding returns a shallow copy of the layout using the specified padding. +func (l Layout) WithPadding(padding Padding) Layout { + l.Padding = padding + return l +} + +// WithFlex returns a shallow copy of the layout using the specified flex strategy. +func (l Layout) WithFlex(flex Flex) Layout { + l.Flex = flex + + return l +} + +// WithSpacing returns a shallow copy of the layout using the specified spacing value. +func (l Layout) WithSpacing(spacing int) Layout { + l.Spacing = spacing + + return l +} + +// WithConstraints returns a shallow copy of the layout with the given +// constraints appended to its existing list. +func (l Layout) WithConstraints(constraints ...Constraint) Layout { + l.Constraints = append(l.Constraints, constraints...) + + return l +} + +// SplitWithSpacers divides the given area into content segments and the +// gaps (spacers) between them. It returns both slices; use [Layout.Split] +// if you only need the content rectangles. +func (l Layout) SplitWithSpacers(area uv.Rectangle) (segments, spacers Splitted) { + segments, spacers, err := l.splitCached(area) + if err != nil { + panic(err) + } + + return segments, spacers +} + +// Split partitions the area into content rectangles according to the +// layout's direction and constraints. +// +// Because every constraint is evaluated against the total area, mixing +// relative constraints (Percent, Ratio) with absolute ones (Min, Max, Len) +// can produce ambiguous results. For example, splitting 100 cells as +// [Min(20), Percent(50), Percent(50)] will not necessarily yield [20, 40, 40]. +func (l Layout) Split(area uv.Rectangle) Splitted { + segments, _ := l.SplitWithSpacers(area) + + return segments +} + +func (l Layout) splitCached(area uv.Rectangle) (segments, spacers []uv.Rectangle, err error) { + globalCacheMu.Lock() + defer globalCacheMu.Unlock() + + key := l.cacheKey(area) + + if v, ok := globalCache.Get(key); ok { + return v.Segments, v.Spacers, nil + } + + segments, spacers, err = l.split(area) + if err != nil { + return nil, nil, err + } + + globalCache.Add(key, cacheValue{Segments: segments, Spacers: spacers}) + + return segments, spacers, nil +} + +func (l Layout) split(area uv.Rectangle) (segments, spacers []uv.Rectangle, err error) { + s := casso.NewSolver() + + innerArea := l.Padding.apply(area) + + var areaStart, areaEnd float64 + + switch l.Direction { + case DirectionHorizontal: + areaStart = float64(innerArea.Min.X) * floatPrecisionMultiplier + areaEnd = float64(innerArea.Max.X) * floatPrecisionMultiplier + + case DirectionVertical: + areaStart = float64(innerArea.Min.Y) * floatPrecisionMultiplier + areaEnd = float64(innerArea.Max.Y) * floatPrecisionMultiplier + } + + // <───────────────────────────────────area_size──────────────────────────────────> + // ┌─area_start area_end─┐ + // V V + // ┌────┬───────────────────┬────┬─────variables─────┬────┬───────────────────┬────┐ + // │ │ │ │ │ │ │ │ + // V V V V V V V V + // ┌ ┐┌──────────────────┐┌ ┐┌──────────────────┐┌ ┐┌──────────────────┐┌ ┐ + // │ Max(20) │ │ Max(20) │ │ Max(20) │ + // └ ┘└──────────────────┘└ ┘└──────────────────┘└ ┘└──────────────────┘└ ┘ + // ^ ^ ^ ^ ^ ^ ^ ^ + // │ │ │ │ │ │ │ │ + // └─┬──┶━━━━━━━━━┳━━━━━━━━━┵─┬──┶━━━━━━━━━┳━━━━━━━━━┵─┬──┶━━━━━━━━━┳━━━━━━━━━┵─┬──┘ + // │ ┃ │ ┃ │ ┃ │ + // └────────────╂───────────┴────────────╂───────────┴────────────╂──Spacers──┘ + // ┃ ┃ ┃ + // ┗━━━━━━━━━━━━━━━━━━━━━━━━┻━━━━━━━━Segments━━━━━━━━┛ + + variableCount := len(l.Constraints)*2 + 2 + + variables := make([]casso.Symbol, variableCount) + for i := range variableCount { + variables[i] = casso.New() + } + + spacerElements := newElements(variables) + segmentElements := newElements(variables[1:]) + + spacing := l.Spacing + + areaEl := element{ + start: variables[0], + end: variables[len(variables)-1], + } + + if err := configureArea(s, areaEl, areaStart, areaEnd); err != nil { + return nil, nil, fmt.Errorf("configure area: %w", err) + } + + if err := configureVariableInAreaConstraints(s, variables, areaEl); err != nil { + return nil, nil, fmt.Errorf("configure variable in area constraints: %w", err) + } + + if err := configureVariableConstraints(s, variables); err != nil { + return nil, nil, fmt.Errorf("configure variable constraints: %w", err) + } + + if err := configureFlexConstraints(s, areaEl, spacerElements, l.Flex, spacing); err != nil { + return nil, nil, fmt.Errorf("configure flex constraints: %w", err) + } + + if err := configureConstraints(s, areaEl, segmentElements, l.Constraints, l.Flex); err != nil { + return nil, nil, fmt.Errorf("configure constraints: %w", err) + } + + if err := configureFillConstraints(s, segmentElements, l.Constraints, l.Flex); err != nil { + return nil, nil, fmt.Errorf("configure fill constraints: %w", err) + } + + if l.Flex != FlexLegacy { + for i := 0; i < len(segmentElements)-1; i++ { + left := segmentElements[i] + right := segmentElements[i+1] + + if _, err := s.Add(allSegmentGrow, left.sizeEqSize(right)); err != nil { + return nil, nil, fmt.Errorf("add has size constraint: %w", err) + } + } + } + + changes := make(map[casso.Symbol]float64, variableCount) + + for _, v := range variables { + changes[v] = s.Val(v) + } + + segments = changesToRects(changes, segmentElements, innerArea, l.Direction) + spacers = changesToRects(changes, spacerElements, innerArea, l.Direction) + + return segments, spacers, nil +} + +func (l Layout) cacheKey(area uv.Rectangle) cacheKey { + h := fnv.New64a() + + for _, c := range l.Constraints { + c.hash(h) + } + + return cacheKey{ + Area: area, + Direction: l.Direction, + ConstraintsHash: h.Sum64(), + Padding: l.Padding, + Spacing: l.Spacing, + Flex: l.Flex, + } +} + +func changesToRects( + changes map[casso.Symbol]float64, + elements []element, + area uv.Rectangle, + direction Direction, +) []uv.Rectangle { + var rects []uv.Rectangle + + for _, e := range elements { + startVal := changes[e.start] + endVal := changes[e.end] + + startRounded := int(math.Round(math.Round(startVal) / floatPrecisionMultiplier)) + endRounded := int(math.Round(math.Round(endVal) / floatPrecisionMultiplier)) + + size := max(0, endRounded-startRounded) + + switch direction { + case DirectionHorizontal: + rect := uv.Rect(startRounded, area.Min.Y, size, area.Dy()) + + rects = append(rects, rect) + + case DirectionVertical: + rect := uv.Rect(area.Min.X, startRounded, area.Dx(), size) + + rects = append(rects, rect) + } + } + + return rects +} + +// configureFillConstraints ensures that every [Fill] (and, outside legacy mode, +// every [Min]) segment grows proportionally to its scaling factor, so that +// remaining space is shared according to the declared weights. +// +// [Fill(1), Fill(1)] +// ┌──────┐┌──────┐ +// │abcdef││abcdef│ +// └──────┘└──────┘ +// +// [Fill(1), Fill(2)] +// ┌──────┐┌────────────┐ +// │abcdef││abcdefabcdef│ +// └──────┘└────────────┘ +// +// size == base_element * scaling_factor +func configureFillConstraints( + s *casso.Solver, + segments []element, + constraints []Constraint, + flex Flex, +) error { + var ( + validConstraints []Constraint + validSegments []element + ) + + for i := 0; i < min(len(constraints), len(segments)); i++ { + c := constraints[i] + seg := segments[i] + + switch c.(type) { + case Fill, Min: + if _, ok := c.(Min); ok && flex == FlexLegacy { + continue + } + + validConstraints = append(validConstraints, c) + validSegments = append(validSegments, seg) + } + } + + for _, indices := range combinations(len(validConstraints), 2) { + i, j := indices[0], indices[1] + + leftConstraint := validConstraints[i] + leftSegment := validSegments[i] + + rightConstraint := validConstraints[j] + rightSegment := validSegments[j] + + getScalingFactor := func(c Constraint) float64 { + var scalingFactor float64 + + switch c := c.(type) { + case Fill: + scale := float64(c) + + scalingFactor = 1e-6 + scalingFactor = max(scalingFactor, scale) + + case Min: + scalingFactor = 1 + } + + return scalingFactor + } + + leftScalingFactor := getScalingFactor(leftConstraint) + rightScalingFactor := getScalingFactor(rightConstraint) + + c := casso.NewConstraint(casso.EQ, 0, + leftSegment.end.T(rightScalingFactor), + leftSegment.start.T(-rightScalingFactor), + rightSegment.end.T(-leftScalingFactor), + rightSegment.start.T(leftScalingFactor), + ) + + if _, err := s.Add(grow, c); err != nil { + return fmt.Errorf("add constraint: %w", err) + } + } + + return nil +} + +func configureConstraints( + s *casso.Solver, + area element, + segments []element, + constraints []Constraint, + flex Flex, +) error { + for i := 0; i < min(len(constraints), len(segments)); i++ { + constraint := constraints[i] + segment := segments[i] + + switch constraint := constraint.(type) { + case Max: + size := int(constraint) + + if _, err := s.Add(maxSizeLTE, segment.sizeLTE(size)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(maxSizeEq, segment.sizeEqConst(size)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + case Min: + size := int(constraint) + + if _, err := s.Add(minSizeGTE, segment.sizeGTE(size)); err != nil { + return fmt.Errorf("add has min size constraint: %w", err) + } + + if flex == FlexLegacy { + if _, err := s.Add(minSizeEq, segment.sizeEqConst(size)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } else { + if _, err := s.Add(fillGrow, segment.sizeEqSize(area)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + case Len: + length := int(constraint) + + if _, err := s.Add(lengthSizeEq, segment.sizeEqConst(length)); err != nil { + return fmt.Errorf("add has int size constraint: %w", err) + } + + case Percent: + f := float64(constraint) / 100 + + if _, err := s.Add(percentSizeEq, segment.sizeEqScaledSize(area, f)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + + case Ratio: + f := float64(constraint.Num) / float64(max(1, constraint.Den)) + + if _, err := s.Add(ratioSizeEq, segment.sizeEqScaledSize(area, f)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + + case Fill: + if _, err := s.Add(fillGrow, segment.sizeEqSize(area)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + } + + return nil +} + +func configureFlexConstraints( + s *casso.Solver, + area element, + spacers []element, + flex Flex, + spacing int, +) error { + var spacersExceptFirstAndLast []element + + if len(spacers) > 2 { + spacersExceptFirstAndLast = spacers[1 : len(spacers)-1] + } + + switch flex { + case FlexLegacy: + for _, sp := range spacersExceptFirstAndLast { + if _, err := s.Add(spacerSizeEq, sp.sizeEqConst(spacing)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + if len(spacers) >= 2 { + first, last := spacers[0], spacers[len(spacers)-1] + + if _, err := s.Add(required-weak, first.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(required-weak, last.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + case FlexSpaceEvenly: + for _, indices := range combinations(len(spacers), 2) { + i, j := indices[0], indices[1] + + left, right := spacers[i], spacers[j] + + if _, err := s.Add(spacerSizeEq, left.sizeEqSize(right)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + for _, sp := range spacers { + if _, err := s.Add(spacerSizeEq, sp.sizeGTE(spacing)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(spaceGrow, sp.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + case FlexSpaceAround: + if len(spacers) <= 2 { + for _, indices := range combinations(len(spacers), 2) { + i, j := indices[0], indices[1] + + left, right := spacers[i], spacers[j] + + if _, err := s.Add(spacerSizeEq, left.sizeEqSize(right)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + for _, sp := range spacers { + if _, err := s.Add(spacerSizeEq, sp.sizeGTE(spacing)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(spaceGrow, sp.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + } else { + first, rest := spacers[0], spacers[1:] + last, middle := rest[len(rest)-1], rest[:len(rest)-1] + + for _, indices := range combinations(len(middle), 2) { + i, j := indices[0], indices[1] + + left, right := middle[i], middle[j] + + if _, err := s.Add(spacerSizeEq, left.sizeEqSize(right)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + if len(middle) > 0 { + firstMiddle := middle[0] + + for _, e := range []element{first, last} { + if _, err := s.Add(spacerSizeEq, firstMiddle.sizeEqDouble(e)); err != nil { + return fmt.Errorf("add has double size constraint: %w", err) + } + } + } + + for _, sp := range spacers { + if _, err := s.Add(spacerSizeEq, sp.sizeGTE(spacing)); err != nil { + return fmt.Errorf("add has min size constraint: %w", err) + } + + if _, err := s.Add(spaceGrow, sp.sizeEqSize(area)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + } + + case FlexSpaceBetween: + for _, indices := range combinations(len(spacersExceptFirstAndLast), 2) { + i, j := indices[0], indices[1] + + left, right := spacersExceptFirstAndLast[i], spacersExceptFirstAndLast[j] + + if _, err := s.Add(spacerSizeEq, left.sizeEqSize(right)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + for _, sp := range spacersExceptFirstAndLast { + if _, err := s.Add(spacerSizeEq, sp.sizeGTE(spacing)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(spaceGrow, sp.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + if len(spacers) >= 2 { + first, last := spacers[0], spacers[len(spacers)-1] + + if _, err := s.Add(required-weak, first.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(required-weak, last.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + case FlexStart: + for _, sp := range spacersExceptFirstAndLast { + if _, err := s.Add(spacerSizeEq, sp.sizeEqConst(spacing)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + if len(spacers) >= 2 { + first := spacers[0] + last := spacers[len(spacers)-1] + + if _, err := s.Add(required-weak, first.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(grow, last.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + case FlexCenter: + for _, sp := range spacersExceptFirstAndLast { + if _, err := s.Add(spacerSizeEq, sp.sizeEqConst(spacing)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + if len(spacers) >= 2 { + first, last := spacers[0], spacers[len(spacers)-1] + + if _, err := s.Add(grow, first.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(grow, last.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(spacerSizeEq, first.sizeEqSize(last)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + + case FlexEnd: + for _, sp := range spacersExceptFirstAndLast { + if _, err := s.Add(spacerSizeEq, sp.sizeEqConst(spacing)); err != nil { + return fmt.Errorf("add has size constraint: %w", err) + } + } + + if len(spacers) >= 2 { + first := spacers[0] + last := spacers[len(spacers)-1] + + if _, err := s.Add(required-weak, last.empty()); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + + if _, err := s.Add(grow, first.sizeEqSize(area)); err != nil { + return fmt.Errorf("add constraints: %w", err) + } + } + } + + return nil +} + +func configureVariableConstraints( + s *casso.Solver, + variables []casso.Symbol, +) error { + // ┌────┬───────────────────┬────┬─────variables─────┬────┬───────────────────┬────┐ + // │ │ │ │ │ │ │ │ + // v v v v v v v v + // ┌ ┐┌──────────────────┐┌ ┐┌──────────────────┐┌ ┐┌──────────────────┐┌ ┐ + // │ Max(20) │ │ Max(20) │ │ Max(20) │ + // └ ┘└──────────────────┘└ ┘└──────────────────┘└ ┘└──────────────────┘└ ┘ + // ^ ^ ^ ^ ^ ^ ^ ^ + // └v0 └v1 └v2 └v3 └v4 └v5 └v6 └v7 + + variables = variables[1:] + + count := len(variables) + + for i := 0; i < count-count%2; i += 2 { + left, right := variables[i], variables[i+1] + + if _, err := s.Add(required, casso.NewConstraint(casso.LTE, 0, left.T(1), right.T(-1))); err != nil { + return fmt.Errorf("add constraint: %w", err) + } + } + + return nil +} + +func configureVariableInAreaConstraints( + s *casso.Solver, + variables []casso.Symbol, + area element, +) error { + for _, v := range variables { + if _, err := s.Add(required, casso.NewConstraint(casso.GTE, 0, v.T(1), area.start.T(-1))); err != nil { + return fmt.Errorf("add start constraint: %w", err) + } + + if _, err := s.Add(required, casso.NewConstraint(casso.LTE, 0, v.T(1), area.end.T(-1))); err != nil { + return fmt.Errorf("add end constraint: %w", err) + } + } + + return nil +} + +func configureArea( + s *casso.Solver, + area element, + areaStart, areaEnd float64, +) error { + if _, err := s.Add(required, casso.NewConstraint(casso.EQ, -areaStart, area.start.T(1))); err != nil { + return fmt.Errorf("add start constraint: %w", err) + } + + if _, err := s.Add(required, casso.NewConstraint(casso.EQ, -areaEnd, area.end.T(1))); err != nil { + return fmt.Errorf("add end constraint: %w", err) + } + + return nil +} + +func newElements(variables []casso.Symbol) []element { + count := len(variables) + + elements := make([]element, 0, count/2+1) + + for i := 0; i < count-count%2; i += 2 { + s, e := variables[i], variables[i+1] + + elements = append(elements, element{start: s, end: e}) + } + + return elements +} + +type element struct { + start, end casso.Symbol +} + +func (e element) empty() casso.Constraint { + return casso.NewConstraint(casso.EQ, 0, e.end.T(1), e.start.T(-1)) +} + +func (e element) sizeEqConst(size int) casso.Constraint { + return casso.NewConstraint(casso.EQ, -float64(size)*floatPrecisionMultiplier, e.end.T(1), e.start.T(-1)) +} + +func (e element) sizeLTE(size int) casso.Constraint { + return casso.NewConstraint(casso.LTE, -float64(size)*floatPrecisionMultiplier, e.end.T(1), e.start.T(-1)) +} + +func (e element) sizeGTE(size int) casso.Constraint { + return casso.NewConstraint(casso.GTE, -float64(size)*floatPrecisionMultiplier, e.end.T(1), e.start.T(-1)) +} + +func (e element) sizeEqSize(other element) casso.Constraint { + return casso.NewConstraint(casso.EQ, 0, e.end.T(1), e.start.T(-1), other.end.T(-1), other.start.T(1)) +} + +func (e element) sizeEqScaledSize(other element, f float64) casso.Constraint { + return casso.NewConstraint(casso.EQ, 0, e.end.T(1), e.start.T(-1), other.end.T(-f), other.start.T(f)) +} + +func (e element) sizeEqDouble(other element) casso.Constraint { + return casso.NewConstraint(casso.EQ, 0, e.end.T(1), e.start.T(-1), other.end.T(-2), other.start.T(2)) +} + +func combinations(n, k int) [][]int { + combs := binomial(n, k) + data := make([][]int, combs) + if len(data) == 0 { + return nil + } + + data[0] = make([]int, k) + for i := range data[0] { + data[0][i] = i + } + + for i := 1; i < combs; i++ { + next := make([]int, k) + copy(next, data[i-1]) + nextCombination(next, n, k) + data[i] = next + } + + return data +} + +func nextCombination(s []int, n, k int) { + for j := k - 1; j >= 0; j-- { + if s[j] == n+j-k { + continue + } + + s[j]++ + + for l := j + 1; l < k; l++ { + s[l] = s[j] + l - j + } + + break + } +} + +func binomial(n, k int) int { + if n < 0 || k < 0 { + panic("layout: binomial: negative input") + } + + if n < k { + return 0 + } + + // (n,k) = (n, n-k) + if k > n/2 { + k = n - k + } + + b := 1 + for i := 1; i <= k; i++ { + b = (n - k + i) * b / i + } + + return b +} diff --git a/cli/third_party/ultraviolet/layout/padding.go b/cli/third_party/ultraviolet/layout/padding.go new file mode 100644 index 000000000..4916eacc8 --- /dev/null +++ b/cli/third_party/ultraviolet/layout/padding.go @@ -0,0 +1,66 @@ +package layout + +import uv "github.com/charmbracelet/ultraviolet" + +// Padding defines the inset applied to a [Layout]'s outer area before solving. +type Padding struct { + Top, Right, Bottom, Left int +} + +func (p Padding) apply(area uv.Rectangle) uv.Rectangle { + horizontal := p.Right + p.Left + vertical := p.Top + p.Bottom + + if area.Dx() < horizontal || area.Dy() < vertical { + return uv.Rectangle{} + } + + return uv.Rect( + area.Min.X+p.Left, + area.Min.Y+p.Top, + max(0, area.Dx()-horizontal), + max(0, area.Dy()-vertical), + ) +} + +// Pad builds a [Padding] value from a variable number of sides, +// following the same shorthand convention as CSS: +// - 0 args: all sides zero. +// - 1 arg: uniform on every side. +// - 2 args: first is top/bottom, second is left/right. +// - 4 args: top, right, bottom, left. +// +// Any other count causes a panic. +func Pad(sides ...int) Padding { + switch len(sides) { + case 0: + return Padding{} + + case 1: + side := sides[0] + + return Padding{Top: side, Right: side, Bottom: side, Left: side} + + case 2: + vertical := sides[0] + horizontal := sides[1] + + return Padding{ + Top: vertical, + Right: horizontal, + Bottom: vertical, + Left: horizontal, + } + + case 4: + return Padding{ + Top: sides[0], + Right: sides[1], + Bottom: sides[2], + Left: sides[3], + } + + default: + panic("layout.Pad: unexpected sides count") + } +} diff --git a/cli/third_party/ultraviolet/logger.go b/cli/third_party/ultraviolet/logger.go new file mode 100644 index 000000000..abfd86e7a --- /dev/null +++ b/cli/third_party/ultraviolet/logger.go @@ -0,0 +1,6 @@ +package uv + +// Logger is a simple logger interface. +type Logger interface { + Printf(format string, v ...interface{}) +} diff --git a/cli/third_party/ultraviolet/mouse.go b/cli/third_party/ultraviolet/mouse.go new file mode 100644 index 000000000..a74cdf992 --- /dev/null +++ b/cli/third_party/ultraviolet/mouse.go @@ -0,0 +1,150 @@ +package uv + +import ( + "github.com/charmbracelet/x/ansi" +) + +// MouseMode represents the mouse tracking mode for the terminal. +type MouseMode uint8 + +// Mouse tracking modes. +// +// These determine which mouse events the terminal reports. +const ( + MouseModeNone MouseMode = iota // Disable mouse tracking. + MouseModePress // Press only (DEC mode 9). Reports button press events. + MouseModeClick // Click tracking (DEC mode 1000). Reports button press and release. + MouseModeDrag // Drag tracking (DEC mode 1002). Reports press, release, and drag. + MouseModeMotion // Motion tracking (DEC mode 1003). Reports all mouse events including motion. +) + +// MouseEncoding represents the encoding used for mouse events. +type MouseEncoding uint8 + +// Mouse encodings. +// +// These determine how mouse coordinates and buttons are encoded in the +// terminal's escape sequences. The encoding is only meaningful when mouse +// tracking is enabled via [MouseMode]. +const ( + MouseEncodingLegacy MouseEncoding = iota // Legacy X10-compatible encoding. Coordinates limited to 223. + MouseEncodingSGR // SGR encoding (DEC mode 1006). No coordinate limit, distinguishes press/release. + MouseEncodingSGRPixel // SGR-pixel encoding (DEC mode 1016). Reports pixel coordinates. + + // TODO: support these additional encodings in the future. + // MouseEncodingUTF8 // UTF-8 encoding (DEC mode 1005). Coordinates limited to 223. + // MouseEncodingUrxvt // urxvt encoding (DEC mode 1015). No coordinate limit. + // MouseEncodingSGRPixel // SGR-pixel encoding (DEC mode 1016). Reports pixel coordinates. +) + +// MouseButton represents the button that was pressed during a mouse message. +type MouseButton = ansi.MouseButton + +// Mouse event buttons +// +// This is based on X11 mouse button codes. +// +// 1 = left button +// 2 = middle button (pressing the scroll wheel) +// 3 = right button +// 4 = turn scroll wheel up +// 5 = turn scroll wheel down +// 6 = push scroll wheel left +// 7 = push scroll wheel right +// 8 = 4th button (aka browser backward button) +// 9 = 5th button (aka browser forward button) +// 10 +// 11 +// +// Other buttons are not supported. +const ( + MouseNone = ansi.MouseNone + MouseLeft = ansi.MouseLeft + MouseMiddle = ansi.MouseMiddle + MouseRight = ansi.MouseRight + MouseWheelUp = ansi.MouseWheelUp + MouseWheelDown = ansi.MouseWheelDown + MouseWheelLeft = ansi.MouseWheelLeft + MouseWheelRight = ansi.MouseWheelRight + MouseBackward = ansi.MouseBackward + MouseForward = ansi.MouseForward + MouseButton10 = ansi.MouseButton10 + MouseButton11 = ansi.MouseButton11 +) + +// Mouse represents a Mouse message. Use [MouseEvent] to represent all mouse +// messages. +// +// The X and Y coordinates are zero-based, with (0,0) being the upper left +// corner of the terminal. When using [MouseEncodingSGRPixel] (DEC mode 1016), +// X and Y are in pixel coordinates; otherwise they are in cell coordinates. +// +// // Catch all mouse events +// switch Event := Event.(type) { +// case MouseEvent: +// m := Event.Mouse() +// fmt.Println("Mouse event:", m.X, m.Y, m) +// } +// +// // Only catch mouse click events +// switch Event := Event.(type) { +// case MouseClickEvent: +// fmt.Println("Mouse click event:", Event.X, Event.Y, Event) +// } +type Mouse struct { + X, Y int + Button MouseButton + Mod KeyMod +} + +// String returns a string representation of the mouse message. +func (m Mouse) String() (s string) { + if m.Mod.Contains(ModCtrl) { + s += "ctrl+" + } + if m.Mod.Contains(ModAlt) { + s += "alt+" + } + if m.Mod.Contains(ModShift) { + s += "shift+" + } + + str := m.Button.String() + if str == "" { + s += "unknown" + } else if str != "none" { // motion events don't have a button + s += str + } + + return s +} + +// MousePixelToCell converts a mouse event with pixel coordinates to cell +// coordinates. +// +// This is only meaningful when using [MouseEncodingSGRPixel] encoding, which +// reports mouse coordinates in pixels rather than cell units. The conversion +// is based on the terminal's reported pixel dimensions and cell dimensions. +// +// On Windows, or other platforms where [Terminal.GetWinsize] doesn't report +// pixel dimensions, you can query for the terminal window pixel dimensions via +// [ansi.WindowOp](4) and get back a [PixelSizeEvent] with the pixel +// dimensions. You can then construct a [Winsize] struct with the pixel +// dimensions and the cell dimensions from [Terminal.GetWinsize] and pass it to +// this function. +func MousePixelToCell(m Mouse, ws *Winsize) Mouse { + var col, row int + if ws.Xpixel > 0 { + col = m.X * int(ws.Col) / int(ws.Xpixel) + } + if ws.Ypixel > 0 { + row = m.Y * int(ws.Row) / int(ws.Ypixel) + } + + return Mouse{ + X: col, + Y: row, + Button: m.Button, + Mod: m.Mod, + } +} diff --git a/cli/third_party/ultraviolet/poll.go b/cli/third_party/ultraviolet/poll.go new file mode 100644 index 000000000..209211f58 --- /dev/null +++ b/cli/third_party/ultraviolet/poll.go @@ -0,0 +1,38 @@ +package uv + +import ( + "fmt" + "time" +) + +// pollReader reads data from an [io.Reader] using different native poll APIs +// depending on the operating system. +// +// On Linux, it uses the epoll API. +// On Windows, it uses The Windows I/O and Console APIs. +// On macOS and other BSD-based systems, it will try to use the kqueue API and +// fall back to Unix select if kqueue is not available (e.g., on TTY). +// On other Unix-like systems, it uses the select API. +// On all other systems, it falls back to a simple read loop with a timeout. +type pollReader interface { + // Read reads data from the underlying [io.Reader]. It blocks until data is + // available or an error occurs. + // + // Use [pollReader] to check for data availability before calling Read to + // avoid blocking. + Read(p []byte) (n int, err error) + + // Poll notifies when data is available to read with the given timeout. Use + // a negative duration to wait indefinitely. + Poll(timeout time.Duration) (ready bool, err error) + + // Cancel cancels any ongoing poll or read operations. It returns true if + // an operation was canceled, false otherwise. + Cancel() bool + + // Close closes the reader and releases any resources associated with it. + Close() error +} + +// ErrCanceled is returned when a poll or read operation is canceled. +var ErrCanceled = fmt.Errorf("poll canceled") diff --git a/cli/third_party/ultraviolet/poll_bsd.go b/cli/third_party/ultraviolet/poll_bsd.go new file mode 100644 index 000000000..947448750 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_bsd.go @@ -0,0 +1,165 @@ +//go:build darwin || freebsd || netbsd || openbsd || dragonfly +// +build darwin freebsd netbsd openbsd dragonfly + +package uv + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +// newPollReader creates a new pollReader for the given io.Reader. +func newPollReader(reader io.Reader) (pollReader, error) { + file, ok := reader.(File) + if !ok { + return newFallbackReader(reader) + } + + // kqueue returns instantly when polling /dev/tty so fallback to select + if file.Name() == "/dev/tty" { + return newSelectPollReader(reader) + } + + kQueue, err := unix.Kqueue() + if err != nil { + return nil, fmt.Errorf("create kqueue: %w", err) + } + + r := &kqueueReader{ + reader: reader, + file: file, + kQueue: kQueue, + } + + r.cancelSignalReader, r.cancelSignalWriter, err = os.Pipe() + if err != nil { + _ = unix.Close(kQueue) + return nil, err + } + + unix.SetKevent(&r.kQueueEvents[0], int(file.Fd()), unix.EVFILT_READ, unix.EV_ADD) + unix.SetKevent(&r.kQueueEvents[1], int(r.cancelSignalReader.Fd()), unix.EVFILT_READ, unix.EV_ADD) + + return r, nil +} + +// kqueueReader implements pollReader using the BSD kqueue API. +type kqueueReader struct { + reader io.Reader + file File + cancelSignalReader *os.File + cancelSignalWriter *os.File + kQueue int + kQueueEvents [2]unix.Kevent_t + mu sync.Mutex + canceled bool +} + +// Read reads data from the underlying reader. +func (r *kqueueReader) Read(p []byte) (int, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + + return r.reader.Read(p) +} + +// Poll waits for data to be available to read with the given timeout. +func (r *kqueueReader) Poll(timeout time.Duration) (bool, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false, ErrCanceled + } + r.mu.Unlock() + + events := make([]unix.Kevent_t, 1) + + var ts *unix.Timespec + if timeout >= 0 { + t := unix.NsecToTimespec(timeout.Nanoseconds()) + ts = &t + } + + for { + n, err := unix.Kevent(r.kQueue, r.kQueueEvents[:], events, ts) + if errors.Is(err, unix.EINTR) { + continue // try again if the syscall was interrupted + } + + if err != nil { + return false, fmt.Errorf("kevent: %w", err) + } + + if n == 0 { + return false, nil // timeout + } + + break + } + + ident := uint64(events[0].Ident) + switch ident { + case uint64(r.file.Fd()): + return true, nil + case uint64(r.cancelSignalReader.Fd()): + // remove signal from pipe + var b [1]byte + _, errRead := r.cancelSignalReader.Read(b[:]) + if errRead != nil { + return false, fmt.Errorf("reading cancel signal: %w", errRead) + } + return false, ErrCanceled + } + + return false, fmt.Errorf("unknown error") +} + +// Cancel cancels any ongoing poll or read operations. +func (r *kqueueReader) Cancel() bool { + r.mu.Lock() + r.canceled = true + r.mu.Unlock() + + // send cancel signal + _, err := r.cancelSignalWriter.Write([]byte{'c'}) + return err == nil +} + +// Close closes the reader and releases any resources. +func (r *kqueueReader) Close() error { + var errMsgs []string + + // close kqueue + err := unix.Close(r.kQueue) + if err != nil { + errMsgs = append(errMsgs, fmt.Sprintf("closing kqueue: %v", err)) + } + + // close pipe + err = r.cancelSignalWriter.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Sprintf("closing cancel signal writer: %v", err)) + } + + err = r.cancelSignalReader.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Sprintf("closing cancel signal reader: %v", err)) + } + + if len(errMsgs) > 0 { + return fmt.Errorf("%s", strings.Join(errMsgs, ", ")) + } + + return nil +} diff --git a/cli/third_party/ultraviolet/poll_default.go b/cli/third_party/ultraviolet/poll_default.go new file mode 100644 index 000000000..464c70fb6 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_default.go @@ -0,0 +1,12 @@ +//go:build !linux && !windows && !darwin && !freebsd && !netbsd && !openbsd && !dragonfly && !solaris +// +build !linux,!windows,!darwin,!freebsd,!netbsd,!openbsd,!dragonfly,!solaris + +package uv + +import "io" + +// newPollReader creates a new pollReader for the given io.Reader. +// This is the default implementation for unsupported platforms. +func newPollReader(reader io.Reader) (pollReader, error) { + return newFallbackReader(reader) +} diff --git a/cli/third_party/ultraviolet/poll_fallback.go b/cli/third_party/ultraviolet/poll_fallback.go new file mode 100644 index 000000000..187a1ed85 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_fallback.go @@ -0,0 +1,158 @@ +package uv + +import ( + "bufio" + "io" + "sync" + "time" +) + +// newFallbackReader creates a new fallbackReader for the given io.Reader. +func newFallbackReader(reader io.Reader) (pollReader, error) { + return &fallbackReader{ + reader: bufio.NewReader(reader), + cancelChan: make(chan struct{}), + dataChan: make(chan struct{}, 1), + }, nil +} + +// fallbackReader implements pollReader using goroutines and buffered I/O. +// This is a fallback implementation that works on all platforms. +type fallbackReader struct { + reader *bufio.Reader + cancelChan chan struct{} + dataChan chan struct{} + mu sync.Mutex + canceled bool + started bool +} + +// Read reads data from the underlying reader. +func (r *fallbackReader) Read(p []byte) (int, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + + n, err := r.reader.Read(p) + // If we get an error during a concurrent cancel, prefer ErrCanceled + if err != nil { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + } + return n, err +} + +// Poll waits for data to be available to read with the given timeout. +// This implementation starts a background goroutine to check for buffered +// data availability. +func (r *fallbackReader) Poll(timeout time.Duration) (bool, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false, ErrCanceled + } + + // Start the background reader goroutine if not already started + if !r.started { + r.started = true + go r.checkBuffered() + } + r.mu.Unlock() + + if timeout < 0 { + // Wait indefinitely + select { + case <-r.dataChan: + // Put it back for next poll/read + select { + case r.dataChan <- struct{}{}: + default: + } + return true, nil + case <-r.cancelChan: + return false, ErrCanceled + } + } + + // Wait with timeout + timer := time.NewTimer(timeout) + defer timer.Stop() + + select { + case <-r.dataChan: + // Put it back for next poll/read + select { + case r.dataChan <- struct{}{}: + default: + } + return true, nil + case <-timer.C: + return false, nil + case <-r.cancelChan: + return false, ErrCanceled + } +} + +// checkBuffered runs in a background goroutine to signal when data is available. +func (r *fallbackReader) checkBuffered() { + for { + select { + case <-r.cancelChan: + return + default: + } + + // Check if data is buffered + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return + } + r.mu.Unlock() + + // Peek at one byte to check if data is available + // This will block until data arrives + _, err := r.reader.Peek(1) + if err != nil { + // If error (including EOF), stop the goroutine + return + } + + // Signal that data is available + select { + case r.dataChan <- struct{}{}: + case <-r.cancelChan: + return + } + + // Wait a bit before checking again to avoid busy loop + time.Sleep(10 * time.Millisecond) + } +} + +// Cancel cancels any ongoing poll or read operations. +func (r *fallbackReader) Cancel() bool { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false + } + r.canceled = true + r.mu.Unlock() + + close(r.cancelChan) + return true +} + +// Close closes the reader and releases any resources. +func (r *fallbackReader) Close() error { + r.Cancel() + return nil +} diff --git a/cli/third_party/ultraviolet/poll_linux.go b/cli/third_party/ultraviolet/poll_linux.go new file mode 100644 index 000000000..bbe2c9fa4 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_linux.go @@ -0,0 +1,175 @@ +//go:build linux +// +build linux + +package uv + +import ( + "errors" + "fmt" + "io" + "os" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +// newPollReader creates a new pollReader for the given io.Reader. +func newPollReader(reader io.Reader) (pollReader, error) { + file, ok := reader.(File) + if !ok { + return newFallbackReader(reader) + } + + epoll, err := unix.EpollCreate1(0) + if err != nil { + return nil, fmt.Errorf("create epoll: %w", err) + } + + r := &epollReader{ + reader: reader, + file: file, + epoll: epoll, + } + + r.cancelSignalReader, r.cancelSignalWriter, err = os.Pipe() + if err != nil { + _ = unix.Close(epoll) + return nil, err + } + + err = unix.EpollCtl(epoll, unix.EPOLL_CTL_ADD, int(file.Fd()), &unix.EpollEvent{ + Events: unix.EPOLLIN, + Fd: int32(file.Fd()), + }) + if err != nil { + _ = unix.Close(epoll) + _ = r.cancelSignalReader.Close() + _ = r.cancelSignalWriter.Close() + return nil, fmt.Errorf("add reader to epoll interest list: %w", err) + } + + err = unix.EpollCtl(epoll, unix.EPOLL_CTL_ADD, int(r.cancelSignalReader.Fd()), &unix.EpollEvent{ + Events: unix.EPOLLIN, + Fd: int32(r.cancelSignalReader.Fd()), + }) + if err != nil { + _ = unix.Close(epoll) + _ = r.cancelSignalReader.Close() + _ = r.cancelSignalWriter.Close() + return nil, fmt.Errorf("add cancel signal to epoll interest list: %w", err) + } + + return r, nil +} + +// epollReader implements pollReader using the Linux epoll API. +type epollReader struct { + reader io.Reader + file File + cancelSignalReader *os.File + cancelSignalWriter *os.File + epoll int + mu sync.Mutex + canceled bool +} + +// Read reads data from the underlying reader. +func (r *epollReader) Read(p []byte) (int, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + + return r.reader.Read(p) +} + +// Poll waits for data to be available to read with the given timeout. +func (r *epollReader) Poll(timeout time.Duration) (bool, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false, ErrCanceled + } + r.mu.Unlock() + + events := make([]unix.EpollEvent, 1) + + timeoutMs := -1 + if timeout >= 0 { + timeoutMs = int(timeout.Milliseconds()) + } + + for { + n, err := unix.EpollWait(r.epoll, events, timeoutMs) + if errors.Is(err, unix.EINTR) { + continue // try again if the syscall was interrupted + } + + if err != nil { + return false, fmt.Errorf("epoll wait: %w", err) + } + + if n == 0 { + return false, nil // timeout + } + + break + } + + switch events[0].Fd { + case int32(r.file.Fd()): + return true, nil + case int32(r.cancelSignalReader.Fd()): + // remove signal from pipe + var b [1]byte + _, readErr := r.cancelSignalReader.Read(b[:]) + if readErr != nil { + return false, fmt.Errorf("reading cancel signal: %w", readErr) + } + return false, ErrCanceled + } + + return false, fmt.Errorf("unknown error") +} + +// Cancel cancels any ongoing poll or read operations. +func (r *epollReader) Cancel() bool { + r.mu.Lock() + r.canceled = true + r.mu.Unlock() + + // send cancel signal + _, err := r.cancelSignalWriter.Write([]byte{'c'}) + return err == nil +} + +// Close closes the reader and releases any resources. +func (r *epollReader) Close() error { + var errMsgs []error + + // close epoll + err := unix.Close(r.epoll) + if err != nil { + errMsgs = append(errMsgs, fmt.Errorf("closing epoll: %w", err)) + } + + // close pipe + err = r.cancelSignalWriter.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Errorf("closing cancel signal writer: %w", err)) + } + + err = r.cancelSignalReader.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Errorf("closing cancel signal reader: %w", err)) + } + + if len(errMsgs) > 0 { + return errors.Join(errMsgs...) + } + + return nil +} diff --git a/cli/third_party/ultraviolet/poll_select.go b/cli/third_party/ultraviolet/poll_select.go new file mode 100644 index 000000000..ff7756a14 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_select.go @@ -0,0 +1,156 @@ +//go:build solaris || darwin || freebsd || netbsd || openbsd || dragonfly +// +build solaris darwin freebsd netbsd openbsd dragonfly + +package uv + +import ( + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +// newSelectPollReader creates a new SelectReader for the given io.Reader. +func newSelectPollReader(reader io.Reader) (pollReader, error) { + file, ok := reader.(File) + if !ok || file.Fd() >= unix.FD_SETSIZE { + return newFallbackReader(reader) + } + + r := &selectReader{ + reader: reader, + file: file, + } + + var err error + r.cancelSignalReader, r.cancelSignalWriter, err = os.Pipe() + if err != nil { + return nil, err + } + + return r, nil +} + +// selectReader implements pollReader using the POSIX select API. +type selectReader struct { + reader io.Reader + file File + cancelSignalReader *os.File + cancelSignalWriter *os.File + mu sync.Mutex + canceled bool +} + +// Read reads data from the underlying reader. +func (r *selectReader) Read(p []byte) (int, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + + return r.reader.Read(p) +} + +// Poll waits for data to be available to read with the given timeout. +func (r *selectReader) Poll(timeout time.Duration) (bool, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false, ErrCanceled + } + r.mu.Unlock() + + for { + readerFd := int(r.file.Fd()) + abortFd := int(r.cancelSignalReader.Fd()) + + maxFd := readerFd + if abortFd > maxFd { + maxFd = abortFd + } + + // this is a limitation of the select syscall + if maxFd >= unix.FD_SETSIZE { + return false, fmt.Errorf("cannot select on file descriptor %d which is larger than %d", maxFd, unix.FD_SETSIZE) + } + + fdSet := &unix.FdSet{} + fdSet.Set(readerFd) + fdSet.Set(abortFd) + + var tv *unix.Timeval + if timeout >= 0 { + t := unix.NsecToTimeval(timeout.Nanoseconds()) + tv = &t + } + + n, err := unix.Select(maxFd+1, fdSet, nil, nil, tv) + if errors.Is(err, unix.EINTR) { + continue // try again if the syscall was interrupted + } + + if err != nil { + return false, fmt.Errorf("select: %w", err) + } + + if n == 0 { + return false, nil // timeout + } + + if fdSet.IsSet(abortFd) { + // remove signal from pipe + var b [1]byte + _, readErr := r.cancelSignalReader.Read(b[:]) + if readErr != nil { + return false, fmt.Errorf("reading cancel signal: %w", readErr) + } + return false, ErrCanceled + } + + if fdSet.IsSet(readerFd) { + return true, nil + } + + return false, fmt.Errorf("select returned without setting a file descriptor") + } +} + +// Cancel cancels any ongoing poll or read operations. +func (r *selectReader) Cancel() bool { + r.mu.Lock() + r.canceled = true + r.mu.Unlock() + + // send cancel signal + _, err := r.cancelSignalWriter.Write([]byte{'c'}) + return err == nil +} + +// Close closes the reader and releases any resources. +func (r *selectReader) Close() error { + var errMsgs []string + + // close pipe + err := r.cancelSignalWriter.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Sprintf("closing cancel signal writer: %v", err)) + } + + err = r.cancelSignalReader.Close() + if err != nil { + errMsgs = append(errMsgs, fmt.Sprintf("closing cancel signal reader: %v", err)) + } + + if len(errMsgs) > 0 { + return fmt.Errorf("%s", strings.Join(errMsgs, ", ")) + } + + return nil +} diff --git a/cli/third_party/ultraviolet/poll_solaris.go b/cli/third_party/ultraviolet/poll_solaris.go new file mode 100644 index 000000000..7a753da45 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_solaris.go @@ -0,0 +1,12 @@ +//go:build solaris +// +build solaris + +package uv + +import "io" + +// newPollReader creates a new pollReader for the given io.Reader. +// On Solaris, we use the select API. +func newPollReader(reader io.Reader) (pollReader, error) { + return newSelectPollReader(reader) +} diff --git a/cli/third_party/ultraviolet/poll_windows.go b/cli/third_party/ultraviolet/poll_windows.go new file mode 100644 index 000000000..2e1922eb2 --- /dev/null +++ b/cli/third_party/ultraviolet/poll_windows.go @@ -0,0 +1,217 @@ +//go:build windows +// +build windows + +package uv + +import ( + "fmt" + "io" + "os" + "sync" + "time" + + "golang.org/x/sys/windows" +) + +var fileShareValidFlags uint32 = windows.FILE_SHARE_DELETE | windows.FILE_SHARE_WRITE | windows.FILE_SHARE_READ + +// newPollReader creates a new pollReader for the given io.Reader. +func newPollReader(reader io.Reader) (pollReader, error) { + f, ok := reader.(File) + if !ok || f.Fd() != os.Stdin.Fd() { + return newFallbackReader(reader) + } + + // it is necessary to open CONIN$ (NOT windows.STD_INPUT_HANDLE) in + // overlapped mode to be able to use it with WaitForMultipleObjects. + coninPath, err := windows.UTF16PtrFromString("CONIN$") + if err != nil { + return nil, fmt.Errorf("convert CONIN$ to UTF16: %w", err) + } + + conin, err := windows.CreateFile( + coninPath, + windows.GENERIC_READ|windows.GENERIC_WRITE, + fileShareValidFlags, + nil, + windows.OPEN_EXISTING, + windows.FILE_FLAG_OVERLAPPED, + 0) + if err != nil { + return nil, fmt.Errorf("open CONIN$ in overlapping mode: %w", err) + } + + resetConsole, err := preparePollConsole(conin) + if err != nil { + _ = windows.CloseHandle(conin) + return nil, fmt.Errorf("prepare console: %w", err) + } + + // flush input, otherwise it can contain events which trigger + // WaitForMultipleObjects but which ReadFile cannot read, resulting in an + // un-cancelable read + err = windows.FlushConsoleInputBuffer(conin) + if err != nil { + _ = windows.CloseHandle(conin) + return nil, fmt.Errorf("flush console input buffer: %w", err) + } + + cancelEvent, err := windows.CreateEvent(nil, 0, 0, nil) + if err != nil { + _ = windows.CloseHandle(conin) + return nil, fmt.Errorf("create cancel event: %w", err) + } + + return &conReader{ + reader: reader, + conin: conin, + cancelEvent: cancelEvent, + resetConsole: resetConsole, + blockingReadSignal: make(chan struct{}, 1), + }, nil +} + +// conReader implements pollReader using Windows I/O and Console APIs. +type conReader struct { + reader io.Reader + conin windows.Handle + cancelEvent windows.Handle + resetConsole func() error + blockingReadSignal chan struct{} + mu sync.Mutex + canceled bool +} + +// Read reads data from the underlying reader. +func (r *conReader) Read(p []byte) (int, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return 0, ErrCanceled + } + r.mu.Unlock() + + return r.reader.Read(p) +} + +// Poll waits for data to be available to read with the given timeout. +func (r *conReader) Poll(timeout time.Duration) (bool, error) { + r.mu.Lock() + if r.canceled { + r.mu.Unlock() + return false, ErrCanceled + } + r.mu.Unlock() + + timeoutMs := uint32(windows.INFINITE) + if timeout >= 0 { + timeoutMs = uint32(timeout.Milliseconds()) + } + + event, err := windows.WaitForMultipleObjects([]windows.Handle{r.conin, r.cancelEvent}, false, timeoutMs) + switch { + case windows.WAIT_OBJECT_0 <= event && event < windows.WAIT_OBJECT_0+2: + if event == windows.WAIT_OBJECT_0+1 { + return false, ErrCanceled + } + + if event == windows.WAIT_OBJECT_0 { + return true, nil + } + + return false, fmt.Errorf("unexpected wait object is ready: %d", event-windows.WAIT_OBJECT_0) + case windows.WAIT_ABANDONED <= event && event < windows.WAIT_ABANDONED+2: + return false, fmt.Errorf("abandoned") + case event == uint32(windows.WAIT_TIMEOUT): + return false, nil + case event == windows.WAIT_FAILED: + return false, fmt.Errorf("failed") + default: + return false, fmt.Errorf("unexpected error: %w", error(err)) + } +} + +// Cancel cancels any ongoing poll or read operations. +// On Windows Terminal, WaitForMultipleObjects sometimes immediately returns +// without input being available. In this case, graceful cancelation is not +// possible and Cancel() returns false. +func (r *conReader) Cancel() bool { + r.mu.Lock() + r.canceled = true + r.mu.Unlock() + + select { + case r.blockingReadSignal <- struct{}{}: + err := windows.SetEvent(r.cancelEvent) + if err != nil { + return false + } + <-r.blockingReadSignal + case <-time.After(100 * time.Millisecond): + // Read() hangs in a GetOverlappedResult which is likely due to + // WaitForMultipleObjects returning without input being available + // so we cannot cancel this ongoing read. + return false + } + + return true +} + +// Close closes the reader and releases any resources. +func (r *conReader) Close() error { + err := windows.CloseHandle(r.cancelEvent) + if err != nil { + return fmt.Errorf("closing cancel event handle: %w", err) + } + + err = r.resetConsole() + if err != nil { + return err + } + + err = windows.CloseHandle(r.conin) + if err != nil { + return fmt.Errorf("closing CONIN$: %w", err) + } + + return nil +} + +func preparePollConsole(input windows.Handle) (reset func() error, err error) { + var originalMode uint32 + + err = windows.GetConsoleMode(input, &originalMode) + if err != nil { + return nil, fmt.Errorf("get console mode: %w", err) + } + + var newMode uint32 + newMode &^= windows.ENABLE_ECHO_INPUT + newMode &^= windows.ENABLE_LINE_INPUT + newMode &^= windows.ENABLE_MOUSE_INPUT + newMode &^= windows.ENABLE_PROCESSED_INPUT + + newMode |= windows.ENABLE_EXTENDED_FLAGS + newMode |= windows.ENABLE_INSERT_MODE + newMode |= windows.ENABLE_QUICK_EDIT_MODE + newMode |= windows.ENABLE_WINDOW_INPUT // Enable window input events + + // Enabling virtual terminal input is necessary for processing certain + // types of input like X10 mouse events and arrows keys with the current + // bytes-based input reader. + newMode |= windows.ENABLE_VIRTUAL_TERMINAL_INPUT + + err = windows.SetConsoleMode(input, newMode) + if err != nil { + return nil, fmt.Errorf("set console mode: %w", err) + } + + return func() error { + err := windows.SetConsoleMode(input, originalMode) + if err != nil { + return fmt.Errorf("reset console mode: %w", err) + } + + return nil + }, nil +} diff --git a/cli/third_party/ultraviolet/screen/context.go b/cli/third_party/ultraviolet/screen/context.go new file mode 100644 index 000000000..babc41cdd --- /dev/null +++ b/cli/third_party/ultraviolet/screen/context.go @@ -0,0 +1,381 @@ +package screen + +import ( + "fmt" + "image/color" + "strings" + + uv "github.com/charmbracelet/ultraviolet" + "github.com/clipperhouse/uax29/v2/graphemes" +) + +// Context represents a drawing context for rendering operations on a screen. +type Context struct { + scr uv.Screen + + style uv.Style + link uv.Link + pos uv.Position +} + +// NewContext creates a new drawing context for the given screen. +func NewContext(scr uv.Screen) *Context { + c := &Context{scr: scr} + c.Reset() + return c +} + +// Reset resets the context to its default state. +func (c *Context) Reset() { + c.style = uv.Style{} + c.link = uv.Link{} + c.pos = uv.Position{X: 0, Y: 0} +} + +// SetStyle sets the style of the context. +func (c *Context) SetStyle(style uv.Style) { + c.style = style +} + +// WithStyle returns a copy of the context with the given style. +func (c Context) WithStyle(style uv.Style) Context { + c.SetStyle(style) + return c +} + +// SetLink sets the link of the context. +func (c *Context) SetLink(link uv.Link) { + c.link = link +} + +// WithLink returns a copy of the context with the given link. +func (c Context) WithLink(link uv.Link) Context { + c.SetLink(link) + return c +} + +// SetAttrs sets the attributes of the context. +func (c *Context) SetAttrs(attrs uint8) { + c.style.Attrs = attrs +} + +// WithAttrs returns a copy of the context with the given attributes. +func (c Context) WithAttrs(attrs uint8) Context { + c.SetAttrs(attrs) + return c +} + +// SetBackground sets the background color of the context. Use nil to reset to default. +func (c *Context) SetBackground(bg color.Color) { + c.style.Bg = bg +} + +// WithBackground returns a copy of the context with the given background color. +func (c Context) WithBackground(bg color.Color) Context { + c.SetBackground(bg) + return c +} + +// SetForeground sets the foreground color of the context. Use nil to reset to default. +func (c *Context) SetForeground(fg color.Color) { + c.style.Fg = fg +} + +// WithForeground returns a copy of the context with the given foreground color. +func (c Context) WithForeground(fg color.Color) Context { + c.SetForeground(fg) + return c +} + +// SetBold sets whether the text in the context should be bold. +func (c *Context) SetBold(bold bool) { + if bold { + c.style.Attrs |= uv.AttrBold + } else { + c.style.Attrs &^= uv.AttrBold + } +} + +// WithBold returns a copy of the context with the given bold attribute. +func (c Context) WithBold(bold bool) Context { + c.SetBold(bold) + return c +} + +// SetItalic sets whether the text in the context should be italic. +func (c *Context) SetItalic(italic bool) { + if italic { + c.style.Attrs |= uv.AttrItalic + } else { + c.style.Attrs &^= uv.AttrItalic + } +} + +// WithItalic returns a copy of the context with the given italic attribute. +func (c Context) WithItalic(italic bool) Context { + c.SetItalic(italic) + return c +} + +// SetStrikethrough sets whether the text in the context should be strikethrough. +func (c *Context) SetStrikethrough(strikethrough bool) { + if strikethrough { + c.style.Attrs |= uv.AttrStrikethrough + } else { + c.style.Attrs &^= uv.AttrStrikethrough + } +} + +// WithStrikethrough returns a copy of the context with the given strikethrough +// attribute. +func (c Context) WithStrikethrough(strikethrough bool) Context { + c.SetStrikethrough(strikethrough) + return c +} + +// SetFaint sets whether the text in the context should be faint. +func (c *Context) SetFaint(faint bool) { + if faint { + c.style.Attrs |= uv.AttrFaint + } else { + c.style.Attrs &^= uv.AttrFaint + } +} + +// WithFaint returns a copy of the context with the given faint attribute. +func (c Context) WithFaint(faint bool) Context { + c.SetFaint(faint) + return c +} + +// SetBlink sets whether the text in the context should blink. +func (c *Context) SetBlink(blink bool) { + if blink { + c.style.Attrs |= uv.AttrBlink + } else { + c.style.Attrs &^= uv.AttrBlink + } +} + +// WithBlink returns a copy of the context with the given blink attribute. +func (c Context) WithBlink(blink bool) Context { + c.SetBlink(blink) + return c +} + +// SetReverse sets whether the text in the context should be reversed. +func (c *Context) SetReverse(reverse bool) { + if reverse { + c.style.Attrs |= uv.AttrReverse + } else { + c.style.Attrs &^= uv.AttrReverse + } +} + +// WithReverse returns a copy of the context with the given reverse attribute. +func (c Context) WithReverse(reverse bool) Context { + c.SetReverse(reverse) + return c +} + +// SetConceal sets whether the text in the context should be concealed. +func (c *Context) SetConceal(conceal bool) { + if conceal { + c.style.Attrs |= uv.AttrConceal + } else { + c.style.Attrs &^= uv.AttrConceal + } +} + +// WithConceal returns a copy of the context with the given conceal attribute. +func (c Context) WithConceal(conceal bool) Context { + c.SetConceal(conceal) + return c +} + +// SetUnderlineStyle sets the underline style of the context. +func (c *Context) SetUnderlineStyle(u uv.Underline) { + c.style.Underline = u +} + +// WithUnderlineStyle returns a copy of the context with the given underline style. +func (c Context) WithUnderlineStyle(u uv.Underline) Context { + c.SetUnderlineStyle(u) + return c +} + +// SetUnderline sets whether the text in the context should be underlined. +// +// This is a convenience method that sets the underline style to single or +// none. It is equivalent to calling [Context.SetUnderlineStyle] with +// [uv.UnderlineSingle] or [uv.UnderlineNone]. +func (c *Context) SetUnderline(underline bool) { + if underline { + c.SetUnderlineStyle(uv.UnderlineSingle) + } else { + c.SetUnderlineStyle(uv.UnderlineNone) + } +} + +// WithUnderline returns a copy of the context with the given underline +// attribute. +func (c Context) WithUnderline(underline bool) Context { + c.SetUnderline(underline) + return c +} + +// SetUnderlineColor sets the underline color of the context. Use nil to reset to default. +func (c *Context) SetUnderlineColor(color color.Color) { + c.style.UnderlineColor = color +} + +// WithUnderlineColor returns a copy of the context with the given underline color. +func (c Context) WithUnderlineColor(color color.Color) Context { + c.SetUnderlineColor(color) + return c +} + +// SetURL sets the URL link for the context. Use an empty string to reset. +func (c *Context) SetURL(url string, params ...string) { + if url == "" { + c.link = uv.Link{} + return + } + c.link = uv.Link{ + URL: url, + Params: strings.Join(params, ":"), + } +} + +// WithURL returns a copy of the context with the given URL link. +func (c Context) WithURL(url string, params ...string) Context { + c.SetURL(url, params...) + return c +} + +// Position returns the current position of the context. +func (c *Context) Position() (x, y int) { + return c.pos.X, c.pos.Y +} + +// SetPosition moves the current position of the context cursor to the given +// coordinates. +// +// This is an alias for [Context.MoveTo]. +func (c *Context) SetPosition(x, y int) { + c.MoveTo(x, y) +} + +// WithPosition returns a copy of the context with the given position. +func (c Context) WithPosition(x, y int) Context { + c.MoveTo(x, y) + return c +} + +// MoveTo moves the current position of the context cursor to the given +// coordinates. +func (c *Context) MoveTo(x, y int) { + c.pos.X = x + c.pos.Y = y +} + +// Print prints the given string to the screen at the current position, updating +// the position accordingly. +func (c *Context) Print(v ...any) (int, error) { + return fmt.Fprint(c, v...) +} + +// Println prints the given string to the screen at the current position, appending +// a newline, and updating the position accordingly. +func (c *Context) Println(v ...any) (int, error) { + return fmt.Fprintln(c, v...) +} + +// Printf formats according to a format specifier and writes to the screen at the +// current position, updating the position accordingly. +func (c *Context) Printf(format string, a ...any) (int, error) { + return fmt.Fprintf(c, format, a...) +} + +// DrawString draws the given string at the given position with the current +// style and link, cropping the string when it reaches the edge of the screen. +func (c *Context) DrawString(s string, x, y int) { + drawStringAt(c.scr, graphemes.FromString(s), x, y, c.style, c.link, false) +} + +// DrawStringWrapped draws the given string at the given position with the current +// style and link, wrapping the string when it reaches the edge of the screen. +func (c *Context) DrawStringWrapped(s string, x, y int) { + drawStringAt(c.scr, graphemes.FromString(s), x, y, c.style, c.link, true) +} + +// Write implements the [io.Writer] interface for the context, writing the +// given byte slice to the screen at the current position, updating the +// position accordingly. +func (c *Context) Write(p []byte) (n int, err error) { + c.pos.X, c.pos.Y = drawStringAt(c.scr, graphemes.FromBytes(p), c.pos.X, c.pos.Y, c.style, c.link, true) + return len(p), nil +} + +// WriteString implements the [io.StringWriter] interface for the context, +// writing the given string to the screen at the current position, updating the +// position accordingly. +func (c *Context) WriteString(s string) (n int, err error) { + c.pos.X, c.pos.Y = drawStringAt(c.scr, graphemes.FromString(s), c.pos.X, c.pos.Y, c.style, c.link, true) + return len(s), nil +} + +func drawStringAt[T []byte | string](scr uv.Screen, grs *graphemes.Iterator[T], x, y int, style uv.Style, link uv.Link, wrap bool) (int, int) { + bounds := scr.Bounds() + bounds.Max.X -= bounds.Min.X + bounds.Max.Y -= bounds.Min.Y + bounds.Min.X = 0 + bounds.Min.Y = 0 + pos := uv.Pos(x, y) + if !pos.In(bounds) { + return x, y + } + + // The cells share one style and one link record for the whole draw. + stylep, linkp := uv.StyleRef(style), uv.LinkRef(link) + wm := scr.WidthMethod() + for grs.Next() { + gr := string(grs.Value()) + switch gr { + case "\n": + x = bounds.Min.X + y++ + continue + } + + w := wm.StringWidth(gr) + pos := uv.Pos(x, y) + if x+w > bounds.Max.X { + if wrap { + x = bounds.Min.X + y++ + pos = uv.Pos(x, y) + } else { + break + } + } + if !pos.In(bounds) { + break + } + + scr.SetCell(x, y, &uv.Cell{ + Content: gr, + Width: w, + Style: stylep, + Link: linkp, + }) + + x += w + if wrap && x >= bounds.Max.X { + x = bounds.Min.X + y++ + } + } + + return x, y +} diff --git a/cli/third_party/ultraviolet/screen/screen.go b/cli/third_party/ultraviolet/screen/screen.go new file mode 100644 index 000000000..5f3ffdd1c --- /dev/null +++ b/cli/third_party/ultraviolet/screen/screen.go @@ -0,0 +1,117 @@ +// Package screen provides functions and helpers to manipulate a [uv.Screen]. +package screen + +import ( + uv "github.com/charmbracelet/ultraviolet" +) + +// Clear clears the screen with empty cells. This is equivalent to filling the +// screen with empty cells. +// +// If the screen implements a [Clear] method, it will be called instead of +// filling the screen with empty cells. +func Clear(scr uv.Screen) { + if c, ok := scr.(interface { + Clear() + }); ok { + c.Clear() + return + } + Fill(scr, nil) +} + +// ClearArea clears the given area of the screen with empty cells. This is +// equivalent to filling the area with empty cells. +// +// If the screen implements a [ClearArea] method, it will be called instead of +// filling the area with empty cells. +func ClearArea(scr uv.Screen, area uv.Rectangle) { + if c, ok := scr.(interface { + ClearArea(area uv.Rectangle) + }); ok { + c.ClearArea(area) + return + } + FillArea(scr, nil, area) +} + +// Fill fills the screen with the given cell. If the cell is nil, it fills the +// screen with empty cells. +// +// If the screen implements a [Fill] method, it will be called instead of +// filling the screen with empty cells. +func Fill(scr uv.Screen, cell *uv.Cell) { + if f, ok := scr.(interface { + Fill(cell *uv.Cell) + }); ok { + f.Fill(cell) + return + } + FillArea(scr, cell, scr.Bounds()) +} + +// FillArea fills the given area of the screen with the given cell. If the cell +// is nil, it fills the area with empty cells. +// +// If the screen implements a [FillArea] method, it will be called instead of +// filling the area with empty cells. +func FillArea(scr uv.Screen, cell *uv.Cell, area uv.Rectangle) { + if f, ok := scr.(interface { + FillArea(cell *uv.Cell, area uv.Rectangle) + }); ok { + f.FillArea(cell, area) + return + } + cellWidth := 1 + if cell != nil && cell.Width > 1 { + cellWidth = cell.Width + } + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x += cellWidth { + scr.SetCell(x, y, cell) + } + } +} + +// CloneArea clones the given area of the screen and returns a new buffer +// with the same size as the area. The new buffer will contain the same cells +// as the area in the screen. +// Use [uv.Buffer.Draw] to draw the cloned buffer to a screen again. +// +// If the screen implements a [CloneArea] method, it will be called instead of +// cloning the area manually. +func CloneArea(scr uv.Screen, area uv.Rectangle) *uv.Buffer { + if c, ok := scr.(interface { + CloneArea(area uv.Rectangle) *uv.Buffer + }); ok { + return c.CloneArea(area) + } + buf := uv.NewBuffer(area.Dx(), area.Dy()) + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; { + cell := scr.CellAt(x, y) + if cell == nil || cell.IsZero() { + x++ + continue + } + buf.SetCell(x-area.Min.X, y-area.Min.Y, cell) + x += max(cell.Width, 1) + } + } + return buf +} + +// Clone creates a new [uv.Buffer] clone of the given screen. The new buffer will +// have the same size as the screen and will contain the same cells. +// Use [uv.Buffer.Draw] to draw the cloned buffer to a screen again. +// +// If the screen implements a [Clone] method, it will be called instead of +// cloning the entire screen manually. +func Clone(scr uv.Screen) *uv.Buffer { + if c, ok := scr.(interface { + Clone() *uv.Buffer + }); ok { + return c.Clone() + } + return CloneArea(scr, scr.Bounds()) +} diff --git a/cli/third_party/ultraviolet/styled.go b/cli/third_party/ultraviolet/styled.go new file mode 100644 index 000000000..218f172d1 --- /dev/null +++ b/cli/third_party/ultraviolet/styled.go @@ -0,0 +1,498 @@ +package uv + +import ( + "bytes" + "image/color" + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// StyledString is a string that can be decomposed into a series of styled +// lines and cells. It is used to disassemble a rendered string with ANSI +// escape codes into a series of cells that can be used in a [Buffer]. +// A StyledString supports reading [ansi.SGR] and [ansi.Hyperlink] escape +// codes. +type StyledString struct { + // Text is the original string that was used to create the styled string. + Text string + // Wrap determines whether the styled string should wrap to the next line. + Wrap bool + // Tail is the string that will be appended to the end of the line when the + // string is truncated i.e. when [StyledString.Wrap] is false. + Tail string +} + +var _ Drawable = (*StyledString)(nil) + +// NewStyledString creates a new [StyledString] for the given method and styled +// string. The method is used to calculate the width of each line. +func NewStyledString(str string) *StyledString { + ss := new(StyledString) + ss.Text = str + return ss +} + +// String returns the text of the styled string. +// +// It implements the [fmt.Stringer] interface. +func (s *StyledString) String() string { + return s.Text +} + +// Lines returns the styled string decomposed into a slice of [Line]s. +func (s *StyledString) Lines(m ansi.Method) []Line { + return printString(nil, m, 0, 0, Rectangle{}, s.Text, false, "") +} + +// Draw renders the styled string to the given buffer at the +// specified area. +func (s *StyledString) Draw(buf Screen, area Rectangle) { + // Clear the area before drawing. + for y := area.Min.Y; y < area.Max.Y; y++ { + for x := area.Min.X; x < area.Max.X; x++ { + buf.SetCell(x, y, nil) + } + } + str := s.Text + // We need to normalize newlines "\n" to "\r\n" to emulate a raw terminal + // output. + str = strings.ReplaceAll(str, "\r\n", "\n") + printString(buf, buf.WidthMethod(), area.Min.X, area.Min.Y, area, str, !s.Wrap, s.Tail) +} + +// Height returns the number of lines in the styled string. This is the number +// of lines that the styled string will occupy when rendered to the screen. +func (s *StyledString) Height() int { + return strings.Count(s.Text, "\n") + 1 +} + +// UnicodeWidth returns the cells width of the widest line in the styled string +// using the [ansi.GraphemeWidth] method. +func (s *StyledString) UnicodeWidth() int { + w, _ := s.widthHeight(ansi.GraphemeWidth) + return w +} + +// WcWidth returns the cells width of the widest line in the styled string +// using the [ansi.WcWidth] method. +func (s *StyledString) WcWidth() int { + w, _ := s.widthHeight(ansi.WcWidth) + return w +} + +func (s *StyledString) widthHeight(m ansi.Method) (w, h int) { + lines := strings.Split(s.Text, "\n") + h = len(lines) + for _, l := range lines { + w = max(w, m.StringWidth(l)) + } + return +} + +// Bounds returns the minimum area that can contain the whole styled string. +func (s *StyledString) Bounds() Rectangle { + w, h := s.widthHeight(ansi.GraphemeWidth) + return Rect(0, 0, w, h) +} + +// printString draws a string starting at the given position. If s is nil, it +// will build and return a slice of [Line]s instead (unwrapped, ignoring bounds). +// passThrough reports whether a zero-width sequence should be carried in a +// cell's content and replayed to the terminal, rather than dropped. +// +// The string-type sequences carry private data rather than driving the cursor: +// APC for image protocols, DCS for device control, SOS and PM for whatever an +// application agrees with its terminal. One means it to reach the terminal, and +// a cell carrying one still advances by its own width, so the renderer's column +// model still holds. +// +// Everything else is dropped, as it was before: +// +// - A CSI can move the cursor or erase part of the screen, and an ESC Fs +// sequence can reset the terminal outright. Replaying one from inside a +// cell would move the real cursor somewhere the model cannot see, which is +// the drift a cell buffer exists to keep out. +// - An OSC is dropped despite carrying data, because a cell is painted again +// every time it changes and on every full repaint. A window title survives +// that, but a clipboard write (OSC 52) or a notification (OSC 9) is not +// something to fire again on each resize. Hyperlinks, the one OSC a cell +// has a place for, are read into [Link] above. +func passThrough[T []byte | string](seq T) bool { + if !ansi.HasApcPrefix(seq) && !ansi.HasDcsPrefix(seq) && + !ansi.HasSosPrefix(seq) && !ansi.HasPmPrefix(seq) { + return false + } + return terminated(seq) +} + +// terminated reports whether a string-type sequence ended with ST. +// +// The parser hands back whatever it has when the input runs out, so a string +// that stops mid-sequence still arrives here. Carrying an unterminated +// introducer into a cell would be worse than dropping it: the terminal would +// swallow everything painted after that cell, looking for an end that never +// comes. +// +// Only the two-byte ST is accepted. The one-byte C1 form, 0x9c, is also a +// UTF-8 continuation byte, so a sequence that ran out partway through a +// character such as U+071C ("\u071c", encoded dc 9c) ends in a byte +// indistinguishable from a terminator. The parser and the terminal need not +// resolve that ambiguity the same way, and guessing wrong reintroduces exactly +// the swallowing this guards against. +func terminated[T []byte | string](seq T) bool { + n := len(seq) + return n >= 2 && seq[n-1] == '\\' && seq[n-2] == ansi.ESC +} + +// cellAttrs shares the style and link records a parse hands out. A string +// repeats the same few styles across its cells, so a parse allocates one +// record per style rather than per cell, and a string with no escapes +// allocates none at all. +type cellAttrs struct { + styles map[Style]*Style + links map[Link]*Link +} + +// style returns the shared record for style, creating it the first time this +// parse sees it. +func (a *cellAttrs) style(style Style) *Style { + if style.IsZero() { + return nil + } + if a.styles == nil { + a.styles = make(map[Style]*Style) + } + if shared, ok := a.styles[style]; ok { + return shared + } + shared := StyleRef(style) + a.styles[style] = shared + return shared +} + +// link returns the shared record for link, like [cellAttrs.style]. +func (a *cellAttrs) link(link Link) *Link { + if link.IsZero() { + return nil + } + if a.links == nil { + a.links = make(map[Link]*Link) + } + if shared, ok := a.links[link]; ok { + return shared + } + shared := LinkRef(link) + a.links[link] = shared + return shared +} + +func printString[T []byte | string]( + s Screen, + m WidthMethod, + x, y int, + bounds Rectangle, str T, + truncate bool, tail string, +) (lines []Line) { + p := ansi.GetParser() + defer ansi.PutParser(p) + + var tailc Cell + if truncate && len(tail) > 0 { + tailc = *NewCell(m, tail) + } + + // A [WidthMethod] the ansi package doesn't know about falls back to + // wcwidth, so the segmenter below always agrees with the decoder. + decoder, method := ansi.DecodeSequenceWc[T], ansi.WcWidth + if m == ansi.GraphemeWidth { + decoder, method = ansi.DecodeSequence[T], ansi.GraphemeWidth + } + + if s == nil { + lines = []Line{} + } + + var cell Cell + var style Style + var link Link + var attrs cellAttrs + var stylep *Style + var linkp *Link + var state byte + lastX, lastY := -1, -1 // last cell written, for folding in combining marks + var pending []byte // pass-through sequences awaiting a cell to ride on + for len(str) > 0 { + seq, width, n, newState := decoder(str, state, p) + // The decoder's ASCII fast path doesn't check for trailing combining + // sequences, so re-decode as a full cluster when one starts here. + // The str[1] >= 0xc0 check skips the segmenter for plain ASCII. + if n == 1 && seq[0] > 0x1f && seq[0] < 0x7f && len(str) > 1 && str[1] >= 0xc0 { + if cluster, cw := ansi.FirstGraphemeCluster(str, method); len(cluster) > 1 { + seq, width, n = cluster, cw, len(cluster) + } + } + switch { + // Any positive width is a printable grapheme cluster. Wcwidth measures + // a cluster per codepoint, so this is not bounded by how wide a glyph + // can be: a ZWJ emoji sequence such as "👨‍👩‍👧‍👦" is eight columns, + // and capping the width here would fall through to the escape sequence + // branch and drop the cluster from the screen. + case width > 0: + cell.Width = width + cell.Content = string(seq) + // Any pass-through sequences seen since the last cell belong in + // front of this glyph, the order they arrived in. Checked rather + // than joined unconditionally, because there are none at all on the + // overwhelmingly common path and the join is not free. + if len(pending) > 0 { + pending = append(pending, cell.Content...) + cell.Content = string(pending) + pending = pending[:0] + } + cell.Style = stylep + cell.Link = linkp + + if s == nil { + // Building lines: unwrapped, no bounds + if y >= len(lines) { + lines = append(lines, Line{}) + } + lines[y] = append(lines[y], cell) + lastX, lastY = len(lines[y])-1, y + x += width + } else { + // Drawing to screen: handle wrapping, truncation, and bounds + if !truncate && x+cell.Width > bounds.Max.X && y+1 < bounds.Max.Y { + // Wrap the string to the width of the window + x = bounds.Min.X + y++ + } + + pos := Pos(x, y) + if pos.In(bounds) { + if truncate && tailc.Width > 0 && x+cell.Width > bounds.Max.X-tailc.Width { + // Truncate the string and append the tail if any. + cell = tailc + cell.Style = stylep + cell.Link = linkp + s.SetCell(x, y, &cell) + lastX, lastY = x, y + x += tailc.Width + } else { + // Print the cell to the screen + s.SetCell(x, y, &cell) + lastX, lastY = x, y + x += width + } + } + } + + // Reset cell for next iteration + cell = Cell{} + default: + // Valid sequences always have a non-zero Cmd. + // TODO: Handle cursor movement and other sequences + switch { + case ansi.HasCsiPrefix(seq) && p.Command() == 'm': + // SGR - Select Graphic Rendition + ReadStyle(p.Params(), &style) + stylep = attrs.style(style) + case ansi.HasOscPrefix(seq) && p.Command() == 8: + // Hyperlinks + ReadLink(p.Data(), &link) + linkp = attrs.link(link) + case ansi.Equal(seq, T("\n")): + if s == nil { + // When building lines, we need to ensure empty lines are represented. + if y >= len(lines) { + lines = append(lines, Line{}) + } + } + y++ + // Always treat a NL as CR-LF similar to Termios ONLCR. + fallthrough + case ansi.Equal(seq, T("\r")): + if s == nil { + x = 0 + } else { + x = bounds.Min.X + } + case len(seq) > 0 && seq[0] >= 0xc0: + // A zero-width grapheme, i.e. a combining mark the re-decode + // above couldn't fold because an escape sequence sits between + // it and its base, as in "a\x1b[31m\u0301". Every escape + // introducer is a C0 or C1 byte, so a UTF-8 lead byte here is + // always text. The mark belongs to the cell we last wrote; the + // accumulator below would let the next glyph clobber it. + if s == nil { + if lastY >= 0 && lastY < len(lines) && lastX < len(lines[lastY]) { + lines[lastY][lastX].Content += string(seq) + } + } else if lastX >= 0 { + if prev := s.CellAt(lastX, lastY); prev != nil { + folded := *prev + folded.Content += string(seq) + s.SetCell(lastX, lastY, &folded) + } + } + case passThrough(seq): + pending = append(pending, string(seq)...) + } + } + + // Advance the state and data + state = newState + str = str[n:] + + if s != nil && y >= bounds.Max.Y { + // We've reached the bottom of the bounds, stop processing further + // lines. + break + } + } + + // Pass-through sequences left at the end of the string have no glyph to + // ride in front of, so fold them into the last cell written instead. The + // alternative is a width-0 cell one past the content, which lands outside + // the bounds whenever the string filled them. + if len(pending) > 0 { + if s == nil { + if lastY >= 0 && lastY < len(lines) && lastX >= 0 && lastX < len(lines[lastY]) { + lines[lastY][lastX].Content += string(pending) + } + } else if lastX >= 0 { + if prev := s.CellAt(lastX, lastY); prev != nil { + folded := *prev + folded.Content += string(pending) + s.SetCell(lastX, lastY, &folded) + } + } + } + + // Make sure to set the last cell if it's not empty. + if !cell.IsZero() && s != nil { + s.SetCell(x, y, &cell) + } + + return lines +} + +// ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a +// list of parameters into pen. +func ReadStyle(params ansi.Params, pen *Style) { + if len(params) == 0 { + *pen = Style{} + return + } + + for i := 0; i < len(params); i++ { + param, hasMore, _ := params.Param(i, 0) + switch param { + case 0: // Reset + *pen = Style{} + case 1: // Bold + pen.Attrs |= AttrBold + case 2: // Dim/Faint + pen.Attrs |= AttrFaint + case 3: // Italic + pen.Attrs |= AttrItalic + case 4: // Underline + nextParam, _, ok := params.Param(i+1, 0) + if hasMore && ok { // Only accept subparameters i.e. separated by ":" + switch nextParam { + case 0, 1, 2, 3, 4, 5: + i++ + switch nextParam { + case 0: // No Underline + pen.Underline = UnderlineStyleNone + case 1: // Single Underline + pen.Underline = UnderlineStyleSingle + case 2: // Double Underline + pen.Underline = UnderlineStyleDouble + case 3: // Curly Underline + pen.Underline = UnderlineStyleCurly + case 4: // Dotted Underline + pen.Underline = UnderlineStyleDotted + case 5: // Dashed Underline + pen.Underline = UnderlineStyleDashed + } + } + } else { + // Single Underline + pen.Underline = UnderlineStyleSingle + } + case 5: // Slow Blink + pen.Attrs |= AttrBlink + case 6: // Rapid Blink + pen.Attrs |= AttrRapidBlink + case 7: // Reverse + pen.Attrs |= AttrReverse + case 8: // Conceal + pen.Attrs |= AttrConceal + case 9: // Crossed-out/Strikethrough + pen.Attrs |= AttrStrikethrough + case 22: // Normal Intensity (not bold or faint) + pen.Attrs &^= (AttrBold | AttrFaint) + case 23: // Not italic, not Fraktur + pen.Attrs &^= AttrItalic + case 24: // Not underlined + pen.Underline = UnderlineStyleNone + case 25: // Blink off + pen.Attrs &^= (AttrBlink | AttrRapidBlink) + case 27: // Positive (not reverse) + pen.Attrs &^= AttrReverse + case 28: // Reveal + pen.Attrs &^= AttrConceal + case 29: // Not crossed out + pen.Attrs &^= AttrStrikethrough + case 30, 31, 32, 33, 34, 35, 36, 37: // Set foreground + pen.Fg = ansi.Black + ansi.BasicColor(param-30) //nolint:gosec + case 38: // Set foreground 256 or truecolor + var c color.Color + n := ansi.ReadStyleColor(params[i:], &c) + if n > 0 { + pen.Fg = c + i += n - 1 + } + case 39: // Default foreground + pen.Fg = nil + case 40, 41, 42, 43, 44, 45, 46, 47: // Set background + pen.Bg = ansi.Black + ansi.BasicColor(param-40) //nolint:gosec + case 48: // Set background 256 or truecolor + var c color.Color + n := ansi.ReadStyleColor(params[i:], &c) + if n > 0 { + pen.Bg = c + i += n - 1 + } + case 49: // Default Background + pen.Bg = nil + case 58: // Set underline color + var c color.Color + n := ansi.ReadStyleColor(params[i:], &c) + if n > 0 { + pen.UnderlineColor = c + i += n - 1 + } + case 59: // Default underline color + pen.UnderlineColor = nil + case 90, 91, 92, 93, 94, 95, 96, 97: // Set bright foreground + pen.Fg = ansi.BrightBlack + ansi.BasicColor(param-90) //nolint:gosec + case 100, 101, 102, 103, 104, 105, 106, 107: // Set bright background + pen.Bg = ansi.BrightBlack + ansi.BasicColor(param-100) //nolint:gosec + } + } +} + +// ReadLink reads a hyperlink escape sequence from a data buffer into link. +func ReadLink(p []byte, link *Link) { + // OSC 8 sequences have this structure `OSC 8 ; params ; URI ST`. + // Only the first two semicolons are delimiters, semicolons that follow after are part of the URI. + params := bytes.SplitN(p, []byte{';'}, 3) + if len(params) != 3 { + return + } + link.Params = string(params[1]) + link.URL = string(params[2]) +} diff --git a/cli/third_party/ultraviolet/tabstop.go b/cli/third_party/ultraviolet/tabstop.go new file mode 100644 index 000000000..ce13814bc --- /dev/null +++ b/cli/third_party/ultraviolet/tabstop.go @@ -0,0 +1,142 @@ +package uv + +// DefaultTabInterval is the default tab interval. +const DefaultTabInterval = 8 + +// TabStops represents horizontal line tab stops. +type TabStops struct { + stops []int + interval int + width int +} + +// NewTabStops creates a new set of tab stops from a number of columns and an +// interval. +func NewTabStops(width, interval int) *TabStops { + ts := new(TabStops) + ts.interval = interval + ts.width = width + ts.stops = make([]int, (width+(interval-1))/interval) + ts.init(0, width) + return ts +} + +// DefaultTabStops creates a new set of tab stops with the default interval. +func DefaultTabStops(cols int) *TabStops { + return NewTabStops(cols, DefaultTabInterval) +} + +// Resize resizes the tab stops to the given width. +func (ts *TabStops) Resize(width int) { + if width == ts.width { + return + } + + if width < ts.width { + size := (width + (ts.interval - 1)) / ts.interval + ts.stops = ts.stops[:size] + } else { + size := (width - ts.width + (ts.interval - 1)) / ts.interval + ts.stops = append(ts.stops, make([]int, size)...) + } + + ts.init(ts.width, width) + ts.width = width +} + +// Width returns the width of the screen that the tab stops are set for. +func (ts *TabStops) Width() int { + return ts.width +} + +// IsStop returns true if the given column is a tab stop. +func (ts TabStops) IsStop(col int) bool { + mask := ts.mask(col) + i := col >> 3 + if i < 0 || i >= len(ts.stops) { + return false + } + return ts.stops[i]&mask != 0 +} + +// Next returns the next tab stop after the given column. +func (ts TabStops) Next(col int) int { + return ts.Find(col, 1) +} + +// Prev returns the previous tab stop before the given column. +func (ts TabStops) Prev(col int) int { + return ts.Find(col, -1) +} + +// Find returns the prev/next tab stop before/after the given column and delta. +// If delta is positive, it returns the next tab stop after the given column. +// If delta is negative, it returns the previous tab stop before the given column. +// If delta is zero, it returns the given column. +func (ts TabStops) Find(col, delta int) int { + if delta == 0 { + return col + } + + var prev bool + count := delta + if count < 0 { + count = -count + prev = true + } + + for count > 0 { + if !prev { + if col >= ts.width-1 { + return col + } + + col++ + } else { + if col < 1 { + return col + } + + col-- + } + + if ts.IsStop(col) { + count-- + } + } + + return col +} + +// Set adds a tab stop at the given column. +func (ts *TabStops) Set(col int) { + mask := ts.mask(col) + ts.stops[col>>3] |= mask +} + +// Reset removes the tab stop at the given column. +func (ts *TabStops) Reset(col int) { + mask := ts.mask(col) + ts.stops[col>>3] &= ^mask +} + +// Clear removes all tab stops. +func (ts *TabStops) Clear() { + ts.stops = make([]int, len(ts.stops)) +} + +// mask returns the mask for the given column. +func (ts *TabStops) mask(col int) int { + return 1 << (col & (ts.interval - 1)) +} + +// init initializes the tab stops starting from col until width. +func (ts *TabStops) init(col, width int) { + for x := col; x < width; x++ { + if x%ts.interval == 0 { + ts.Set(x) + } else { + ts.Reset(x) + } + } +} diff --git a/cli/third_party/ultraviolet/terminal.go b/cli/third_party/ultraviolet/terminal.go new file mode 100644 index 000000000..9c29686f9 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal.go @@ -0,0 +1,408 @@ +package uv + +import ( + "fmt" + "os" + "os/signal" + "time" + + "github.com/charmbracelet/x/ansi" + "golang.org/x/sync/errgroup" +) + +// DefaultBufferSize is the default size of the input buffer used for reading +// terminal events. +const DefaultBufferSize = 4096 + +// DefaultEventTimeout is the default duration to wait for input events before +// timing out. +const DefaultEventTimeout = 100 * time.Millisecond + +// Options represents options for creating a new [Terminal]. +type Options struct { + // BufferSize is the size of the input buffer used for reading terminal + // events. If zero, [DefaultBufferSize] is used. + BufferSize int + + // EventTimeout is the duration to wait for input events before timing out. + // If zero, a default of 100 milliseconds is used. + EventTimeout time.Duration + + // LegacyKeyEncoding represents any legacy key encoding ambiguities. By + // default, the terminal will use its preferred key encoding settings. + LegacyKeyEncoding LegacyKeyEncoding + + // LookupKeys whether to use a lookup table for common key sequences. If + // true, the terminal will use a lookup table to quickly identify common + // key sequences, reducing the need for more complex decoding logic. This + // can improve performance for common key sequences at the cost of + // increased memory usage. + // + // This is enabled by default. + LookupKeys bool + + // UseTerminfoKeys whether to use terminfo databases key definitions to + // build up the keys lookup table. If true, the terminal will use terminfo + // databases key definitions to build up the keys lookup table, which can + // provide more accurate key mappings for legacy non-xterm like terminals. + // + // This won't take effect if [TerminalOptions.LookupKeys] is false, since + // the lookup table won't be used. + // + // This is disabled by default. + UseTerminfoKeys bool + + // Logger is an optional logger for tracing terminal I/O operations. + // If nil, no logging is performed. + Logger Logger +} + +// DefaultOptions returns the default [Terminal] options. +func DefaultOptions() *Options { + return &Options{ + BufferSize: DefaultBufferSize, + EventTimeout: DefaultEventTimeout, + LookupKeys: true, + } +} + +// Terminal represents an interactive terminal application. +type Terminal struct { + con Console + opts *Options + scr *TerminalScreen + pr pollReader + buf []byte + evc chan Event + errg errgroup.Group + winch chan os.Signal + donec chan struct{} +} + +// DefaultTerminal creates a new [Terminal] instance using the default standard +// console and the given options. Options can be nil to use the default +// options. +// +// This is a convenience function for creating a terminal that uses the +// standard input and output file descriptors. +func DefaultTerminal() *Terminal { + return NewTerminal(nil, nil) +} + +// ControllingTerminal creates a new [Terminal] instance using the controlling +// terminal's input and output file descriptors. +// Options can be nil to use the default options. +// +// This is a convenience function for creating a terminal that uses the +// controlling TTY of the current process. +func ControllingTerminal() (*Terminal, error) { + con, err := ControllingConsole() + if err != nil { + return nil, err + } + return NewTerminal(con, nil), nil +} + +// NewTerminal creates a new [Terminal] instance with the given console and +// options. +// Options can be nil to use the default options. +func NewTerminal(con Console, opts *Options) *Terminal { + t := &Terminal{} + if con == nil { + con = DefaultConsole() + } + if opts == nil { + opts = DefaultOptions() + } + if opts.BufferSize <= 0 { + opts.BufferSize = DefaultBufferSize + } + if opts.EventTimeout <= 0 { + opts.EventTimeout = DefaultEventTimeout + } + t.con = con + t.opts = opts + t.scr = NewTerminalScreen(t.con.Writer(), t.con.Environ()) + t.buf = make([]byte, opts.BufferSize) + // These channels never close during the terminal's lifetime. + t.evc = make(chan Event) + t.winch = make(chan os.Signal, 1) // buffered to avoid missing signals + if opts.Logger != nil { + t.scr.rend.SetLogger(opts.Logger) + } + return t +} + +// GetSize returns the current size of the terminal in characters and pixels. +func (t *Terminal) GetSize() (width, height int, err error) { + w, h, err := t.con.GetSize() + if err != nil { + return 0, 0, fmt.Errorf("getting terminal size: %w", err) + } + return int(w), int(h), nil +} + +// GetWinsize returns the current size of the terminal as a [Winsize] struct. +// This includes both character dimensions (columns and rows) and pixel +// dimensions (xpixel and ypixel). +// +// Note that this only returns the pixel dimensions on Unix-like systems that +// support the TIOCGWINSZ ioctl. On other platforms, the pixel dimensions may +// be zero or not available. +func (t *Terminal) GetWinsize() (*Winsize, error) { + ws, err := t.con.GetWinsize() + if err != nil { + return nil, fmt.Errorf("getting terminal winsize: %w", err) + } + return ws, nil +} + +// Screen returns the terminal's screen. +func (t *Terminal) Screen() *TerminalScreen { + return t.scr +} + +// Events returns the terminal's event channel. +func (t *Terminal) Events() <-chan Event { + return t.evc +} + +// Start starts the terminal application event loop. This is a non-blocking +// call. Use [Terminal.Wait] to wait for the terminal to exit. +func (t *Terminal) Start() error { + _, err := t.con.MakeRaw() + if err != nil { + return fmt.Errorf("failed to set terminal to raw mode: %w", err) + } + + evs := newEventScanner() + evs.lookup = t.opts.LookupKeys + if evs.lookup { + evs.table = buildKeysTable(t.opts.LegacyKeyEncoding, t.con.Getenv("TERM"), t.opts.UseTerminfoKeys) + } + if t.opts.Logger != nil { + evs.setLogger(t.opts.Logger) + } + bufc := make(chan []byte) + t.donec = make(chan struct{}) + t.pr, err = newPollReader(t.con.Reader()) + if err != nil { + return fmt.Errorf("failed to create poll reader: %w", err) + } + + // input loop + // + // The loop holds its own reference to the reader for its lifetime. Stop + // sets t.pr to nil, and a loop that reads the field on every iteration + // can evaluate it after that has happened and dereference nil. Cancel + // and Close on the reader are what stop this loop; nilling the field is + // only bookkeeping for a later Start. + pr := t.pr + t.errg.Go(func() error { + for { + n, err := pr.Read(t.buf) + if err != nil { + return fmt.Errorf("reading terminal input: %w", err) + } + // Hand the event loop its own copy. t.buf is reused by the + // next Read, and the receiver only copies out of the slice + // after the send has completed, so sending t.buf[:n] lets + // one read's bytes be overwritten by the next before they + // have been consumed. + data := make([]byte, n) + copy(data, t.buf[:n]) + select { + case bufc <- data: + case <-t.donec: + return nil + } + } + }) + + // event loop + sendEvents := func(buf []byte, expired bool) int { + n, events := evs.scanEvents(buf, expired) + for _, ev := range events { + t.handleEvent(ev) + t.SendEvent(ev) + } + return n + } + t.errg.Go(func() error { + var buf []byte + timer := time.NewTimer(t.opts.EventTimeout) + timeout := time.Now().Add(t.opts.EventTimeout) + + for { + select { + case <-t.donec: + return nil + case <-timer.C: + expired := len(buf) > 0 && time.Now().After(timeout) + n := sendEvents(buf, expired) + if n > 0 { + buf = buf[min(n, len(buf)):] + } + if len(buf) > 0 { + timer.Reset(t.opts.EventTimeout) + } + case data := <-bufc: + buf = append(buf, data...) + n := sendEvents(buf, false) + timeout = time.Now().Add(t.opts.EventTimeout) + timer.Stop() + if n > 0 { + buf = buf[min(n, len(buf)):] + } + if len(buf) > 0 { + timer.Reset(t.opts.EventTimeout) + } + } + } + }) + + sendWinsize := func() error { + ws, err := t.con.GetWinsize() + if err != nil { + return fmt.Errorf("getting terminal size: %w", err) + } + if ws.Col > 0 && ws.Row > 0 { + t.SendEvent(WindowSizeEvent{ + Width: int(ws.Col), + Height: int(ws.Row), + }) + } + if ws.Xpixel > 0 && ws.Ypixel > 0 { + t.SendEvent(PixelSizeEvent{ + Width: int(ws.Xpixel), + Height: int(ws.Ypixel), + }) + } + return nil + } + + // winch handler + NotifyWinch(t.winch) + t.errg.Go(func() error { + for { + select { + case <-t.donec: + return nil + case <-t.winch: + if err := sendWinsize(); err != nil { + return err + } + } + } + }) + + // init window size + t.errg.Go(func() error { + if err := sendWinsize(); err != nil { + return err + } + return nil + }) + + // Restore any previous screen state. + t.scr.Restore() + // Query whether the terminal supports Unicode core mode (DEC mode 2027) so + // we can negotiate grapheme-cluster width. The response is handled in the + // event loop. + t.scr.requestGraphemeWidth() + if err := t.scr.Flush(); err != nil { + return fmt.Errorf("failed to flush terminal screen: %w", err) + } + + return nil +} + +// handleEvent reacts to internal events before they are forwarded to the +// application. It negotiates Unicode core mode (DEC mode 2027): when the +// terminal reports the mode is in a settable or active state, it enables +// grapheme-cluster width so wide-glyph measurement matches the terminal. The +// event is still forwarded to the application. +// +// The mode is only enabled for settable/active states (mode set, reset but +// settable, or permanently set). It is explicitly not enabled when the mode is +// not recognized or permanently reset, since those terminals cannot honor it. +// Enabling goes through the screen's locked write path so it cannot race with +// the application's Render/Flush. +func (t *Terminal) handleEvent(ev Event) { + if mr, ok := ev.(ModeReportEvent); ok { + if mr.Mode == ansi.ModeUnicodeCore && + (mr.Value.IsSet() || mr.Value == ansi.ModeReset) { + t.scr.enableGraphemeWidth() + } + } +} + +// Wait waits for the terminal event loop to exit and returns any error that +// occurred. +func (t *Terminal) Wait() error { + if err := t.errg.Wait(); err != nil { + return fmt.Errorf("terminal event loop error: %w", err) + } + return nil +} + +// Stop stops the terminal event loop. It is safe to call Stop without a +// prior [Terminal.Start], and safe to call Stop multiple times in a row. +// After Stop returns, [Terminal.Start] may be called again to resume. +func (t *Terminal) Stop() error { + if t.donec != nil { + select { + case <-t.donec: + // Already closed. + default: + close(t.donec) + } + } + if t.winch != nil { + signal.Stop(t.winch) + } + if t.pr != nil { + t.pr.Cancel() + _ = t.pr.Close() + t.pr = nil + } + t.scr.Reset() + if err := t.scr.Flush(); err != nil { + _ = t.con.Restore() + return fmt.Errorf("failed to flush terminal screen: %w", err) + } + if err := t.con.Restore(); err != nil { + return fmt.Errorf("failed to restore terminal state: %w", err) + } + return nil +} + +// SendEvent sends an event to the terminal's event channel. +// +// This can be used to inject custom events into the terminal's event loop, +// such as timer events, signals, or application-specific events. +func (t *Terminal) SendEvent(e Event) { + select { + case t.evc <- e: + case <-t.donec: + } +} + +// Write writes data directly to the terminal's console output. +// +// This is a low-level operation that bypasses the terminal screen buffering +// and writes directly to the console output handler, usually [os.Stdout] or +// the controlling TTY. +func (t *Terminal) Write(p []byte) (n int, err error) { + return t.con.Write(p) +} + +// Read reads data from the terminal's console input. +// +// This is a low-level operation that bypasses the terminal event processing +// and reads directly from the console input handler, usually [os.Stdin] or the +// controlling TTY. Use this method with caution, as it may interfere with the +// terminal's event loop and screen management. +func (t *Terminal) Read(p []byte) (n int, err error) { + return t.con.Read(p) +} diff --git a/cli/third_party/ultraviolet/terminal_bsdly.go b/cli/third_party/ultraviolet/terminal_bsdly.go new file mode 100644 index 000000000..6f64e6566 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_bsdly.go @@ -0,0 +1,10 @@ +//go:build darwin || linux || aix +// +build darwin linux aix + +package uv + +import "golang.org/x/sys/unix" + +func supportsBackspace(lflag uint64) bool { + return lflag&unix.BSDLY == unix.BS0 +} diff --git a/cli/third_party/ultraviolet/terminal_bsdly_other.go b/cli/third_party/ultraviolet/terminal_bsdly_other.go new file mode 100644 index 000000000..24bb50d76 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_bsdly_other.go @@ -0,0 +1,8 @@ +//go:build !darwin && !linux && !aix && !windows +// +build !darwin,!linux,!aix,!windows + +package uv + +func supportsBackspace(uint64) bool { + return false +} diff --git a/cli/third_party/ultraviolet/terminal_other.go b/cli/third_party/ultraviolet/terminal_other.go new file mode 100644 index 000000000..9130fcc4c --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_other.go @@ -0,0 +1,22 @@ +//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !aix && !windows +// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!aix,!windows + +package uv + +import "github.com/charmbracelet/x/term" + +func makeRaw(_, _ term.File) (inTtyState, outTtyState *term.State, err error) { + return nil, nil, ErrPlatformNotSupported +} + +func getSize(_, _ term.File) (w, h int, err error) { + return 0, 0, ErrPlatformNotSupported +} + +func getWinsize(_, _ term.File) (ws Winsize, err error) { + return Winsize{}, ErrPlatformNotSupported +} + +func optimizeMovements(*term.State) (useTabs, useBspace bool) { + return false, false +} diff --git a/cli/third_party/ultraviolet/terminal_reader.go b/cli/third_party/ultraviolet/terminal_reader.go new file mode 100644 index 000000000..5096b434a --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_reader.go @@ -0,0 +1,526 @@ +package uv + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "strconv" + "strings" + "sync" + "time" + "unicode" + "unicode/utf16" + "unicode/utf8" + + "github.com/charmbracelet/x/ansi" + "github.com/muesli/cancelreader" + "github.com/rivo/uniseg" +) + +// ErrReaderNotStarted is returned when the reader has not been started yet. +var ErrReaderNotStarted = fmt.Errorf("reader not started") + +// DefaultEscTimeout is the default timeout at which the [TerminalReader] will +// process ESC sequences. It is set to 50 milliseconds. +const DefaultEscTimeout = 50 * time.Millisecond + +// An OSC 5522 clipboard reply chunk spans several reads, and over a network +// the rest can arrive well after [DefaultEscTimeout]. Flushing it then would +// type its payload into the program, so a buffer that starts one waits this +// long after its last byte, up to maxPendingClipboardOsc bytes. Other +// sequences keep the upstream timeout. +var pendingClipboardOscTimeout = 5 * time.Second + +const maxPendingClipboardOsc = 1 << 20 + +// TerminalReader represents an input event loop that reads input events from +// a reader and parses them into human-readable events. It supports +// reading escape sequences, mouse events, and bracketed paste mode. +type TerminalReader struct { + EventDecoder + + // MouseMode determines whether mouse events are enabled or not. This is a + // platform-specific feature and is only available on Windows. When this is + // true, the reader will be initialized to read mouse events using the + // Windows Console API. + MouseMode *MouseMode + + // EscTimeout is the escape character timeout duration. Most escape + // sequences start with an escape character [ansi.ESC] and are followed by + // one or more characters. If the next character is not received within + // this timeout, the reader will assume that the escape sequence is + // complete and will process the received characters as a complete escape + // sequence. + // + // By default, this is set to [DefaultEscTimeout] (50 milliseconds). + EscTimeout time.Duration + + r io.Reader + table map[string]Key // table is a lookup table for key sequences. + + term string // term is the terminal name $TERM. + + // paste is the bracketed paste mode buffer. + // When nil, bracketed paste mode is disabled. + paste []byte + + lookup bool // lookup indicates whether to use the lookup table for key sequences. + + // vtInput indicates whether we're using Windows Console API VT input mode. + //nolint:unused,nolintlint + vtInput bool + + eventScanner *eventScanner + + // We use these buffers to decode UTF-16 sequences and graphemes from the + // Windows Console API and Win32-Input-Mode events. + utf16Half [2]bool // 0 key up, 1 key down + utf16Buf [2][2]rune // 0 key up, 1 key down + graphemeBuf [2][]rune // 0 key up, 1 key down + //nolint:unused,nolintlint + lastMouseBtns uint32 // the last mouse button state for the previous event + //nolint:unused,nolintlint + lastWinsizeX, lastWinsizeY int16 // the last window size for the previous event to prevent multiple size events from firing + + logger Logger // The logger to use for debugging. +} + +// NewTerminalReader returns a new input event reader. The reader streams input +// events from the terminal and parses escape sequences into human-readable +// events. It supports reading Terminfo databases. +// +// Use [TerminalReader.UseTerminfo] to use Terminfo defined key sequences. +// Use [TerminalReader.Legacy] to control legacy key encoding behavior. +// +// Example: +// +// ```go +// var cr cancelreader.CancelReader +// var evc chan Event +// sc := NewTerminalReader(cr, os.Getenv("TERM")) +// go sc.StreamEvents(ctx, evc) +// ``` +func NewTerminalReader(r io.Reader, termType string) *TerminalReader { + d := &TerminalReader{ + EscTimeout: DefaultEscTimeout, + r: r, + term: termType, + lookup: true, // Use lookup table by default. + } + d.r = r + if d.table == nil { + d.table = buildKeysTable(d.Legacy, d.term, d.UseTerminfo) + } + evs := newEventScanner() + evs.EventDecoder = d.EventDecoder + evs.table = d.table + evs.lookup = d.lookup + evs.setLogger(d.logger) + d.eventScanner = evs + return d +} + +// readBufSize is the size of the read buffer used to read input events at a time. +const readBufSize = 4096 + +// sendBytes reads data from the reader and sends it to the provided channel. +// It stops when an error occurs or when the context is closed. +func (d *TerminalReader) sendBytes(ctx context.Context, readc chan []byte) error { + for { + var readBuf [readBufSize]byte + n, err := d.r.Read(readBuf[:]) + if err != nil { + return err //nolint:wrapcheck + } + + select { + case <-ctx.Done(): + return nil + case readc <- readBuf[:n]: + } + } +} + +// StreamEvents sends events to the provided channel. It stops when the context +// is closed or when an error occurs. +func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) error { + var buf bytes.Buffer + errc := make(chan error, 1) + readc := make(chan []byte) + timeout := time.NewTimer(d.EscTimeout) + ttimeout := time.Now().Add(d.EscTimeout) + var lastRead time.Time + + var wg sync.WaitGroup + wg.Add(1) + + go func() { + defer wg.Done() + if err := d.streamData(ctx, readc); err != nil { + if errors.Is(err, io.EOF) || errors.Is(err, cancelreader.ErrCanceled) { + errc <- nil + return + } + errc <- err + return + } + }() + + for { + select { + case <-ctx.Done(): + d.sendEvents(eventc, buf.Bytes(), true) + wg.Wait() + return nil + case err := <-errc: + d.sendEvents(eventc, buf.Bytes(), true) + wg.Wait() + return err // return the first error encountered + case <-timeout.C: + d.logf("timeout reached") + + // Timeout reached process the buffer including any incomplete sequences. + var n int // n is the number of bytes processed + timedout := time.Now().After(ttimeout) + if timedout && awaitingClipboardReply(buf.Bytes(), lastRead) { + d.logf("waiting for the rest of a clipboard reply") + timeout.Reset(d.EscTimeout) + continue + } + if buf.Len() > 0 && timedout { + d.logf("timeout expired, processing buffer") + n = d.sendEvents(eventc, buf.Bytes(), true) + } + + if n > 0 { + buf.Next(n) + } + + if buf.Len() > 0 { + if !timeout.Stop() { + // drain the channel if it was already running + select { + case <-timeout.C: + default: + } + } + + d.logf("resetting timeout for remaining buffer") + timeout.Reset(d.EscTimeout) + } + + case read := <-readc: + d.logf("input: %q", read) + buf.Write(read) + lastRead = time.Now() + ttimeout = lastRead.Add(d.EscTimeout) + n := d.sendEvents(eventc, buf.Bytes(), false) + if !timeout.Stop() { + // drain the channel if it was already running + select { + case <-timeout.C: + default: + } + } + + if n > 0 { + d.logf("processed %d bytes from buffer", n) + buf.Next(n) + } + + if buf.Len() > 0 { + d.logf("resetting timeout for remaining buffer after parse") + timeout.Reset(d.EscTimeout) + } + } + } +} + +// awaitingClipboardReply reports whether buf starts an OSC 5522 reply whose +// rest may still be on its way. +func awaitingClipboardReply(buf []byte, lastRead time.Time) bool { + return len(buf) <= maxPendingClipboardOsc && time.Since(lastRead) < pendingClipboardOscTimeout && + bytes.HasPrefix(buf, []byte("\x1b]5522;")) +} + +// SetLogger sets the logger to use for debugging. If nil, no logging will be +// performed. +func (d *TerminalReader) SetLogger(logger Logger) { + d.logger = logger +} + +func (d *TerminalReader) sendEvents(eventc chan<- Event, buf []byte, expired bool) int { + n, events := d.eventScanner.scanEvents(buf, expired) + for _, event := range events { + eventc <- event + } + return n +} + +// eventScanner scans the buffer for events and sends them to the event channel. +type eventScanner struct { + EventDecoder + + utf16Half [2]bool // 0 key up, 1 key down + utf16Buf [2][2]rune // 0 key up, 1 key down + graphemeBuf [2][]rune // 0 key up, 1 key down + paste []byte + table map[string]Key + lookup bool + logger Logger +} + +// newEventScanner creates a new event scanner. +func newEventScanner() *eventScanner { + return &eventScanner{} +} + +// setLogger sets the logger to use for debugging. If nil, no logging will be +// performed. +func (d *eventScanner) setLogger(logger Logger) { + d.logger = logger +} + +func (d *eventScanner) logf(format string, v ...interface{}) { + logf(d.logger, format, v...) +} + +func (d *eventScanner) scanEvents(buf []byte, expired bool) (total int, events []Event) { + if len(buf) == 0 { + return 0, nil + } + + var dn int + d.logf("processing buf %d %q", len(buf), buf) + dn, buf = d.deserializeWin32Input(buf) + total += dn + + // Lookup table first + if d.lookup && len(buf) > 2 && buf[0] == ansi.ESC { + if k, ok := d.table[string(buf)]; ok { + return len(buf), []Event{KeyPressEvent(k)} + } + } + + // total is the total number of bytes processed + for len(buf) > 0 { + esc := buf[0] == ansi.ESC + n, event := d.Decode(buf) + + // Handle bracketed-paste + if d.paste != nil { //nolint:nestif + if _, ok := event.(PasteEndEvent); !ok { + switch event := event.(type) { + case KeyPressEvent: + if len(event.Text) > 0 { + d.paste = append(d.paste, event.Text...) + } else { + seq := string(buf[:n]) + isWin32 := strings.HasPrefix(seq, "\x1b[") && strings.HasSuffix(seq, "_") + switch { + case isWin32 && event.Code == KeyEnter && event.Code == event.BaseCode: + // This handles special cases where + // win32-input-mode encodes newlines and other keys + // as keypress events. We need to encode them as + // their respective values. + d.paste = append(d.paste, '\n') + case isWin32 && unicode.IsControl(event.Code) && event.Code == event.BaseCode: + // This handles other cases such as tabs, escapes, etc. + d.paste = append(d.paste, string(event.Code)...) + case !isWin32: + // We ignore all other non-text win32-input-mode events. + if esc && n <= 2 && !expired { + // If the event is an escape sequence and we + // are not expired, we need to wait for more + // input. + return total, events + } + d.paste = append(d.paste, seq...) + } + } + case UnknownEvent: + if !expired { + // If the event is unknown and we are not expired, we + // return need to try to decode the buffer again. + return total, events + } + default: + // Everything else is ignored... + } + buf = buf[n:] + total += n + continue + } + } + + var isUnknown bool + switch event.(type) { + case ignoredEvent: + // ignore this event + event = nil + case UnknownEvent: + isUnknown = true + // Try to look up the event in the table. + if !expired { + return total, events + } + + if k, ok := d.table[string(buf[:n])]; ok { + events = append(events, KeyPressEvent(k)) + return total + n, events + } + + events = append(events, event) + case PasteStartEvent: + d.paste = []byte{} // reset the paste buffer + case PasteEndEvent: + var paste []rune + for len(d.paste) > 0 { + r, w := utf8.DecodeRune(d.paste) + if r != utf8.RuneError { + paste = append(paste, r) + } + d.paste = d.paste[w:] + } + d.paste = nil // reset the paste buffer + events = append(events, PasteEvent{string(paste)}) + } + + if !isUnknown && event != nil { + if esc && n <= 2 && !expired { + // Wait for more input + return total, events + } + + if m, ok := event.(MultiEvent); ok { + // If the event is a MultiEvent, append all events to the queue. + events = append(events, m...) + } else { + // Otherwise, just append the event to the queue. + events = append(events, event) + } + } + + buf = buf[n:] + total += n + } + + return total, events +} + +func (d *eventScanner) encodeGraphemeBufs() []byte { + var b []byte + for kd := range d.graphemeBuf { + if len(d.graphemeBuf[kd]) > 0 { + switch kd { + case 1: + b = append(b, string(d.graphemeBuf[kd])...) + case 0: + // Encode the release grapheme as Kitty Keyboard to get the release event. + grs := uniseg.NewGraphemes(string(d.graphemeBuf[kd])) + for grs.Next() { + var codepoints string + gr := grs.Str() + for i, r := range gr { + if r == 0 { + continue + } + if i > 0 { + codepoints += ":" + } + codepoints += strconv.FormatInt(int64(r), 10) + } + // This is dark :) + // During serializing/deserializing of win32 input events, the + // API will split a grapheme into runes and send them as a + // keydown/keyup sequences. We collect the runes, decoded them + // from UTF-16 just fine. However, [EventDecoder.Decode] will + // always decode graphemes as [KeyPressEvent]s. Thus, to + // workaround that and the existing API, while we are + // intercepting win32 input events, we encode the grapheme + // release events as Kitty Keyboard sequences so that + // [EventDecoder.Decode] can properly decode them as + // [KeyReleaseEvent]s. + seq := fmt.Sprintf("\x1b[%d;1:3;%su", d.graphemeBuf[kd][0], codepoints) + b = append(b, seq...) + } + } + d.graphemeBuf[kd] = d.graphemeBuf[kd][:0] // reset the buffer + } + } + return b +} + +func (d *eventScanner) storeGraphemeRune(kd int, r rune) { + if d.utf16Half[kd] { + // We have a half pair that needs to be decoded. + d.utf16Half[kd] = false + d.utf16Buf[kd][1] = r + r := utf16.DecodeRune(d.utf16Buf[kd][0], d.utf16Buf[kd][1]) + d.graphemeBuf[kd] = append(d.graphemeBuf[kd], r) + } else if utf16.IsSurrogate(r) { + // This is the first half of a UTF-16 surrogate pair. + d.utf16Half[kd] = true + d.utf16Buf[kd][0] = r + } else { + // This should be a single UTF-16 that can be converted + // to UTF-8. + d.graphemeBuf[kd] = append(d.graphemeBuf[kd], r) + } +} + +// deserializeWin32Input deserializes the Win32 input events converting +// KeyEventRecrods to bytes. Before returning the bytes, it will also try to +// decode any UTF-16 pairs that might be present in the input buffer. +func (d *eventScanner) deserializeWin32Input(buf []byte) (int, []byte) { + p := ansi.GetParser() + defer ansi.PutParser(p) + + var processed int + var state byte + des := make([]byte, 0, len(buf)) + + for len(buf) > 0 { + seq, width, n, newState := ansi.DecodeSequence(buf, state, p) + switch width { + case 0: + if p.Command() == '_' { // Win32 Input Mode + vk, _ := p.Param(0, 0) + if vk == 0 { + // This is either a serialized KeyEventRecord or a UTF-16 + // pair. + uc, _ := p.Param(2, 0) + kd, _ := p.Param(3, 0) + kd = clamp(kd, 0, 1) // kd is the key down state (0 or 1) + d.storeGraphemeRune(kd, rune(uc)) + processed += n + break + } + } + fallthrough + default: + des = append(des, d.encodeGraphemeBufs()...) + des = append(des, seq...) + } + + state = newState + buf = buf[n:] + } + + des = append(des, d.encodeGraphemeBufs()...) + + return processed, des +} + +func (d *TerminalReader) logf(format string, v ...interface{}) { + logf(d.logger, format, v...) +} + +func logf(logger Logger, format string, v ...interface{}) { + if logger == nil { + return + } + logger.Printf(format, v...) +} diff --git a/cli/third_party/ultraviolet/terminal_reader_other.go b/cli/third_party/ultraviolet/terminal_reader_other.go new file mode 100644 index 000000000..ca2e9e724 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_reader_other.go @@ -0,0 +1,13 @@ +//go:build !windows +// +build !windows + +package uv + +import ( + "context" +) + +// streamData sends data from the input stream to the event channel. +func (d *TerminalReader) streamData(ctx context.Context, readc chan []byte) error { + return d.sendBytes(ctx, readc) +} diff --git a/cli/third_party/ultraviolet/terminal_reader_windows.go b/cli/third_party/ultraviolet/terminal_reader_windows.go new file mode 100644 index 000000000..7478455a1 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_reader_windows.go @@ -0,0 +1,336 @@ +//go:build windows +// +build windows + +package uv + +import ( + "bytes" + "context" + "fmt" + "strings" + "time" + "unicode/utf16" + + "github.com/charmbracelet/x/ansi" + xwindows "github.com/charmbracelet/x/windows" + "github.com/muesli/cancelreader" + "golang.org/x/sys/windows" +) + +// streamData sends data from the input stream to the event channel. +func (d *TerminalReader) streamData(ctx context.Context, readc chan []byte) error { + cc, ok := d.r.(*conInputReader) + if !ok { + d.logf("streamData: reader is not a conInputReader, falling back to default implementation") + return d.sendBytes(ctx, readc) + } + + // Store the value of VT Input Mode for later use. + d.vtInput = cc.newMode&windows.ENABLE_VIRTUAL_TERMINAL_INPUT != 0 + + var buf bytes.Buffer + var records []xwindows.InputRecord + var err error + for { + for { + records, err = peekNConsoleInputs(cc.conin, readBufSize) + if cc.isCanceled() { + return cancelreader.ErrCanceled + } + if err != nil { + return err + } + if len(records) > 0 { + break + } + + // Sleep for a bit to avoid busy waiting. + time.Sleep(10 * time.Millisecond) + } + + records, err = readNConsoleInputs(cc.conin, uint32(len(records))) //nolint:gosec + if cc.isCanceled() { + return cancelreader.ErrCanceled + } + if err != nil { + return err + } + + // We convert Windows Input Records to VT input sequences for easier + // processing especially when dealing with UTF-16 decoding and + // Win32-Input-Mode processing. + d.serializeWin32InputRecords(records, &buf) + + select { + case <-ctx.Done(): + return nil + case readc <- buf.Bytes(): + } + + buf.Reset() + } +} + +// serializeWin32InputRecords serializes the Win32 input events converting them +// to valid VT input sequences. It will also encode any UTF-16 pairs that might +// be present in the input buffer. The resulting byte slice can be sent to the +// terminal as input. +func (d *TerminalReader) serializeWin32InputRecords(records []xwindows.InputRecord, buf *bytes.Buffer) { + for _, record := range records { + switch record.EventType { + case xwindows.KEY_EVENT: + kevent := record.KeyEvent() + // d.logf("key event: %s", keyEventString(kevent.VirtualKeyCode, kevent.VirtualScanCode, kevent.Char, kevent.KeyDown, kevent.ControlKeyState, kevent.RepeatCount)) + + var kd int + if kevent.KeyDown { + kd = 1 + } + if d.vtInput { //nolint:nestif + // In VT Input Mode, we only capture the Unicode characters + // decoding them along the way. + // This is similar to [TerminalReader.storeGraphemeRune] except + // that we need to write the events directly to the buffer. + if d.utf16Half[kd] { + // We have a half pair that needs to be decoded. + d.utf16Half[kd] = false + d.utf16Buf[kd][1] = kevent.Char + r := utf16.DecodeRune(d.utf16Buf[kd][0], d.utf16Buf[kd][1]) + buf.WriteRune(r) + } else if utf16.IsSurrogate(kevent.Char) { + // This is the first half of a UTF-16 surrogate pair. + d.utf16Half[kd] = true + d.utf16Buf[kd][0] = kevent.Char + } else if kevent.KeyDown { + // Just a regular key press character encoded in VT. + buf.WriteRune(kevent.Char) + } + } else { + // We encode the key to Win32 Input Mode if it is a known key. + if kevent.VirtualKeyCode == 0 { + d.eventScanner.storeGraphemeRune(kd, kevent.Char) + } else { + buf.Write(d.eventScanner.encodeGraphemeBufs()) + fmt.Fprintf(buf, + "\x1b[%d;%d;%d;%d;%d;%d_", + kevent.VirtualKeyCode, + kevent.VirtualScanCode, + kevent.Char, + kd, + kevent.ControlKeyState, + kevent.RepeatCount) + } + } + + case xwindows.MOUSE_EVENT: + if d.MouseMode == nil || *d.MouseMode == 0 { + continue + } + mouseMode := *d.MouseMode + mevent := record.MouseEvent() + + var isRelease bool + var isMotion bool + var button MouseButton + alt := mevent.ControlKeyState&(xwindows.LEFT_ALT_PRESSED|xwindows.RIGHT_ALT_PRESSED) != 0 + ctrl := mevent.ControlKeyState&(xwindows.LEFT_CTRL_PRESSED|xwindows.RIGHT_CTRL_PRESSED) != 0 + shift := mevent.ControlKeyState&xwindows.SHIFT_PRESSED != 0 + wheelDirection := int16(highWord(mevent.ButtonState)) //nolint:gosec + switch mevent.EventFlags { + case 0, xwindows.DOUBLE_CLICK: + button, isRelease = mouseEventButton(d.lastMouseBtns, mevent.ButtonState) + case xwindows.MOUSE_WHEELED: + if wheelDirection > 0 { + button = MouseWheelUp + } else { + button = MouseWheelDown + } + case xwindows.MOUSE_HWHEELED: + if wheelDirection > 0 { + button = MouseWheelRight + } else { + button = MouseWheelLeft + } + case xwindows.MOUSE_MOVED: + button, _ = mouseEventButton(d.lastMouseBtns, mevent.ButtonState) + isMotion = true + } + + // We emulate mouse mode levels on Windows. This is because Windows + // doesn't have a concept of different mouse modes. We use the mouse mode to determine + if button == MouseNone && mouseMode&MouseModeMotion == 0 || + (button != MouseNone && mouseMode&MouseModeDrag == 0) { + continue + } + + // Encode mouse events as SGR mouse sequences that can be read by [EventDecoder]. + buf.WriteString(ansi.MouseSgr( + ansi.EncodeMouseButton(button, isMotion, shift, alt, ctrl), + int(mevent.MousePositon.X), int(mevent.MousePositon.Y), isRelease, + )) + + d.lastMouseBtns = mevent.ButtonState + + case xwindows.WINDOW_BUFFER_SIZE_EVENT: + wevent := record.WindowBufferSizeEvent() + if wevent.Size.X != d.lastWinsizeX || wevent.Size.Y != d.lastWinsizeY { + d.lastWinsizeX, d.lastWinsizeY = wevent.Size.X, wevent.Size.Y + // We encode window resize events as CSI 4 ; height ; width t + // sequence which the [EventDecoder] understands. + buf.WriteString( + ansi.WindowOp( + 8, // Terminal window size in cells + int(wevent.Size.Y), // height + int(wevent.Size.X), // width + ), + ) + } + + case xwindows.FOCUS_EVENT: + fevent := record.FocusEvent() + if fevent.SetFocus { + buf.WriteString(ansi.Focus) + } else { + buf.WriteString(ansi.Blur) + } + + case xwindows.MENU_EVENT: + // ignore + } + } + + // Flush any remaining grapheme buffers. + buf.Write(d.eventScanner.encodeGraphemeBufs()) +} + +func mouseEventButton(p, s uint32) (MouseButton, bool) { + var isRelease bool + button := MouseNone + btn := p ^ s + if btn&s == 0 { + isRelease = true + } + + if btn == 0 { + switch { + case s&xwindows.FROM_LEFT_1ST_BUTTON_PRESSED > 0: + button = MouseLeft + case s&xwindows.FROM_LEFT_2ND_BUTTON_PRESSED > 0: + button = MouseMiddle + case s&xwindows.RIGHTMOST_BUTTON_PRESSED > 0: + button = MouseRight + case s&xwindows.FROM_LEFT_3RD_BUTTON_PRESSED > 0: + button = MouseBackward + case s&xwindows.FROM_LEFT_4TH_BUTTON_PRESSED > 0: + button = MouseForward + } + return button, isRelease + } + + switch btn { + case xwindows.FROM_LEFT_1ST_BUTTON_PRESSED: // left button + button = MouseLeft + case xwindows.RIGHTMOST_BUTTON_PRESSED: // right button + button = MouseRight + case xwindows.FROM_LEFT_2ND_BUTTON_PRESSED: // middle button + button = MouseMiddle + case xwindows.FROM_LEFT_3RD_BUTTON_PRESSED: // unknown (possibly mouse backward) + button = MouseBackward + case xwindows.FROM_LEFT_4TH_BUTTON_PRESSED: // unknown (possibly mouse forward) + button = MouseForward + } + + return button, isRelease +} + +func highWord(data uint32) uint16 { + return uint16((data & 0xFFFF0000) >> 16) //nolint:gosec +} + +func readNConsoleInputs(console windows.Handle, maxEvents uint32) ([]xwindows.InputRecord, error) { + if maxEvents == 0 { + return nil, fmt.Errorf("maxEvents cannot be zero") + } + + records := make([]xwindows.InputRecord, maxEvents) + n, err := readConsoleInput(console, records) + return records[:n], err +} + +func readConsoleInput(console windows.Handle, inputRecords []xwindows.InputRecord) (uint32, error) { + if len(inputRecords) == 0 { + return 0, fmt.Errorf("size of input record buffer cannot be zero") + } + + var read uint32 + + err := xwindows.ReadConsoleInput(console, &inputRecords[0], uint32(len(inputRecords)), &read) //nolint:gosec + + return read, err //nolint:wrapcheck +} + +func peekConsoleInput(console windows.Handle, inputRecords []xwindows.InputRecord) (uint32, error) { + if len(inputRecords) == 0 { + return 0, fmt.Errorf("size of input record buffer cannot be zero") + } + + var read uint32 + + err := xwindows.PeekConsoleInput(console, &inputRecords[0], uint32(len(inputRecords)), &read) //nolint:gosec + + return read, err //nolint:wrapcheck +} + +func peekNConsoleInputs(console windows.Handle, maxEvents uint32) ([]xwindows.InputRecord, error) { + if maxEvents == 0 { + return nil, fmt.Errorf("maxEvents cannot be zero") + } + + records := make([]xwindows.InputRecord, maxEvents) + n, err := peekConsoleInput(console, records) + return records[:n], err +} + +//nolint:unused +func keyEventString(vkc, sc uint16, r rune, keyDown bool, cks uint32, repeatCount uint16) string { + var s strings.Builder + s.WriteString("vkc: ") + fmt.Fprintf(&s, "%d, 0x%02x", vkc, vkc) + s.WriteString(", sc: ") + fmt.Fprintf(&s, "%d, 0x%02x", sc, sc) + s.WriteString(", r: ") + fmt.Fprintf(&s, "%q 0x%x", r, r) + s.WriteString(", down: ") + fmt.Fprintf(&s, "%v", keyDown) + s.WriteString(", cks: [") + if cks&xwindows.LEFT_ALT_PRESSED != 0 { + s.WriteString("left alt, ") + } + if cks&xwindows.RIGHT_ALT_PRESSED != 0 { + s.WriteString("right alt, ") + } + if cks&xwindows.LEFT_CTRL_PRESSED != 0 { + s.WriteString("left ctrl, ") + } + if cks&xwindows.RIGHT_CTRL_PRESSED != 0 { + s.WriteString("right ctrl, ") + } + if cks&xwindows.SHIFT_PRESSED != 0 { + s.WriteString("shift, ") + } + if cks&xwindows.CAPSLOCK_ON != 0 { + s.WriteString("caps lock, ") + } + if cks&xwindows.NUMLOCK_ON != 0 { + s.WriteString("num lock, ") + } + if cks&xwindows.SCROLLLOCK_ON != 0 { + s.WriteString("scroll lock, ") + } + if cks&xwindows.ENHANCED_KEY != 0 { + s.WriteString("enhanced key, ") + } + s.WriteString("], repeat count: ") + fmt.Fprintf(&s, "%d", repeatCount) + return s.String() +} diff --git a/cli/third_party/ultraviolet/terminal_renderer.go b/cli/third_party/ultraviolet/terminal_renderer.go new file mode 100644 index 000000000..25d67d712 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_renderer.go @@ -0,0 +1,1917 @@ +package uv + +import ( + "bytes" + "errors" + "hash/maphash" + "io" + "strings" + "unicode/utf8" + + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/x/ansi" +) + +// ErrInvalidDimensions is returned when the dimensions of a window are invalid +// for the operation. +var ErrInvalidDimensions = errors.New("invalid dimensions") + +// capabilities represents a mask of supported ANSI escape sequences. +type capabilities uint + +const ( + // Vertical Position Absolute [ansi.VPA]. + capVPA capabilities = 1 << iota + // Horizontal Position Absolute [ansi.HPA]. + capHPA + // Cursor Horizontal Absolute [ansi.CHA]. + capCHA + // Cursor Horizontal Tab [ansi.CHT]. + capCHT + // Cursor Backward Tab [ansi.CBT]. + capCBT + // Repeat Previous Character [ansi.REP]. + capREP + // Erase Character [ansi.ECH]. + capECH + // Insert Character [ansi.ICH]. + capICH + // Scroll Down [ansi.SD]. + capSD + // Scroll Up [ansi.SU]. + capSU + // These capabilities depend on the tty termios settings and are not + // enabled by default. + // Tabulation [ansi.HT]. + capHT + // Backspace [ansi.BS]. + capBS + + noCaps capabilities = 0 + allCaps = capVPA | capHPA | capCHA | capCHT | capCBT | capREP | capECH | capICH | capSD | capSU +) + +// Set sets the given capabilities. +func (v *capabilities) Set(c capabilities) { + *v |= c +} + +// Reset resets the given capabilities. +func (v *capabilities) Reset(c capabilities) { + *v &^= c +} + +// Contains returns whether the capabilities contains the given capability. +func (v capabilities) Contains(c capabilities) bool { + return v&c == c +} + +// cursor represents a terminal cursor. +type cursor struct { + Cell + Position +} + +// LineData represents the metadata for a line. +type LineData struct { + // First and last changed cell indices. + FirstCell, LastCell int + // Old index used for scrolling + oldIndex int //nolint:unused +} + +// tFlag is a bitmask of terminal flags. +type tFlag uint + +// Terminal writer flags. +const ( + tRelativeCursor tFlag = 1 << iota + tFullscreen + tMapNewline + tScrollOptim + // tGraphemeWidth indicates the terminal measures cell width using Unicode + // grapheme clustering (DEC mode 2027 / Unicode core). + tGraphemeWidth +) + +// Set sets the given flags. +func (v *tFlag) Set(c tFlag) { + *v |= c +} + +// Reset resets the given flags. +func (v *tFlag) Reset(c tFlag) { + *v &^= c +} + +// Contains returns whether the terminal flags contains the given flags. +func (v tFlag) Contains(c tFlag) bool { + return v&c == c +} + +// TerminalRenderer is a terminal screen render and lazy writer that buffers +// the output until it is flushed. It handles rendering a screen from a +// [Buffer] to the terminal with the minimal necessary escape sequences to +// transition the terminal to the new buffer state. It uses various escape +// sequence optimizations to reduce the number of bytes sent to the terminal. +// It's designed to be lazy and only flush the output when necessary by calling +// the [TerminalRenderer.Flush] method. +// +// The renderer handles the terminal's alternate screen and cursor visibility +// via the [TerminalRenderer.EnterAltScreen], [TerminalRenderer.ExitAltScreen], +// [TerminalRenderer.ShowCursor] and [TerminalRenderer.HideCursor] methods. +// Using these methods will queue the appropriate escape sequences to enter or +// exit the alternate screen and show or hide the cursor respectively to be +// flushed to the terminal. +// +// Use the [io.Writer] and [io.StringWriter] interfaces to queue custom +// commands the renderer. +// +// The renderer is not thread-safe, the caller must protect the renderer when +// using it from multiple goroutines. +type TerminalRenderer struct { + w io.Writer + buf *bytes.Buffer // buffer for writing to the screen + curbuf *RenderBuffer // the current buffer + tabs *TabStops + hasher maphash.Hash + oldhash, newhash []uint64 // the old and new hash values for each line + hashtab []hashmap // the hashmap table + oldnum []int // old indices from previous hash + cur, saved cursor // the current and saved cursors + flags tFlag // terminal writer flags. + method ansi.Method // the width method used to measure cell width + term string // the terminal type + clear bool // whether to force clear the screen + caps capabilities // terminal control sequence capabilities + atPhantom bool // whether the cursor is out of bounds and at a phantom cell + noWrapLine bool // whether autowrap is off for the line currently being repainted + driftRows []bool // rows holding a cell the terminal may measure differently + termW, termH int // the size [TerminalRenderer.Resize] was last told + termResized bool // whether the terminal changed size since the last render + damaged []bool // rows this render disturbed itself, see [TerminalRenderer.damage] + logger Logger // The logger used for debugging. + + // profile is the color profile to use when downsampling colors. This is + // used to determine the appropriate color the terminal can display. + profile colorprofile.Profile +} + +// NewTerminalRenderer returns a new [TerminalRenderer] that uses the given +// writer, terminal type, and initializes the width of the terminal. The +// terminal type is used to determine the capabilities of the terminal and +// should be set to the value of the TERM environment variable. +// +// The renderer will try to detect the color profile from the output and the +// given environment variables. Use [TerminalRenderer.SetColorProfile] method +// to set a specific color profile for downsampling. +// +// See [TerminalRenderer] for more information on how to use the renderer. +func NewTerminalRenderer(w io.Writer, env []string) (s *TerminalRenderer) { + s = new(TerminalRenderer) + s.w = w + s.profile = colorprofile.Detect(w, env) + s.buf = new(bytes.Buffer) + s.term = Environ(env).Getenv("TERM") + s.caps = xtermCaps(s.term) + s.cur = cursor{Cell: EmptyCell, Position: Pos(-1, -1)} // start at -1 to force a move + s.saved = s.cur + s.oldhash, s.newhash = nil, nil + return +} + +// SetLogger sets the logger to use for debugging. If nil, no logging will be +// performed. +func (s *TerminalRenderer) SetLogger(logger Logger) { + s.logger = logger +} + +// SetColorProfile sets the color profile to use for downsampling colors. This +// is used to determine the appropriate color the terminal can display. +func (s *TerminalRenderer) SetColorProfile(profile colorprofile.Profile) { + s.profile = profile +} + +// SetScrollOptim sets whether to use hard scroll optimizations. +func (s *TerminalRenderer) SetScrollOptim(v bool) { + if v { + s.flags.Set(tScrollOptim) + } else { + s.flags.Reset(tScrollOptim) + } +} + +// SetMapNewline sets whether the terminal is currently mapping newlines to +// CRLF or carriage return and line feed. This is used to correctly determine +// how to move the cursor when writing to the screen. +func (s *TerminalRenderer) SetMapNewline(v bool) { + if v { + s.flags.Set(tMapNewline) + } else { + s.flags.Reset(tMapNewline) + } +} + +// SetWidthMethod sets the width method the renderer uses to measure the +// display width of strings. This should match the width method configured on +// the screen so that the renderer doesn't disagree with the cell widths it is +// asked to draw. +func (s *TerminalRenderer) SetWidthMethod(method ansi.Method) { + s.method = method +} + +// SetGraphemeWidth sets whether the terminal measures cell width using Unicode +// grapheme clustering (DEC mode 2027 / Unicode core). When enabled, the +// renderer measures string width using [ansi.GraphemeWidth]; otherwise it +// falls back to [ansi.WcWidth]. +func (s *TerminalRenderer) SetGraphemeWidth(v bool) { + if v { + s.flags.Set(tGraphemeWidth) + s.method = ansi.GraphemeWidth + } else { + s.flags.Reset(tGraphemeWidth) + s.method = ansi.WcWidth + } +} + +// SetBackspace sets whether to use backspace as a movement optimization. +func (s *TerminalRenderer) SetBackspace(v bool) { + if v { + s.caps.Set(capBS) + } else { + s.caps.Reset(capBS) + } +} + +// SetTabStops sets the tab stops for the terminal and enables hard tabs +// movement optimizations. Use -1 to disable hard tabs. This option is ignored +// when the terminal type is "linux" as it does not support hard tabs. +func (s *TerminalRenderer) SetTabStops(width int) { + if width < 0 || strings.HasPrefix(s.term, "linux") { + // Linux terminal does not support hard tabs. + s.caps.Reset(capHT) + } else { + s.caps.Set(capHT) + s.tabs = DefaultTabStops(width) + } +} + +// SetFullscreen sets whether whole screen is being used. This is usually +// paired with the alternate screen mode, and used to control cursor movements +// and optimizations when the terminal is occupying the whole screen. +func (s *TerminalRenderer) SetFullscreen(v bool) { + if v { + s.flags.Set(tFullscreen) + } else { + s.flags.Reset(tFullscreen) + } +} + +// Fullscreen returns whether whole screen is being used. This is usually +// paired with the alternate screen mode, and used to control cursor movements +// and optimizations when the terminal is occupying the whole screen. +func (s *TerminalRenderer) Fullscreen() bool { + return s.flags.Contains(tFullscreen) +} + +// SetRelativeCursor sets whether to use relative cursor movements. +func (s *TerminalRenderer) SetRelativeCursor(v bool) { + if v { + s.flags.Set(tRelativeCursor) + } else { + s.flags.Reset(tRelativeCursor) + } +} + +// SaveCursor saves the current cursor position and styles. This can be used +// when a program enters the alternate screen buffer mode using DECSET 1049 +// [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and +// styles later. +func (s *TerminalRenderer) SaveCursor() { + s.saved = s.cur +} + +// RestoreCursor restores the saved cursor position and styles. This can be +// used when a program exits the alternate screen buffer mode using DECRST 1049 +// [ansi.ModeAltScreenSaveCursor] and wants to restore the cursor position and +// styles saved earlier. +func (s *TerminalRenderer) RestoreCursor() { + s.cur = s.saved +} + +// EnterAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor] +// escape sequence to enter the alternate screen buffer and save cursor mode. +// +// It saves the current cursor properties, enables +// [TerminalRenderer.SetFullscreen] flag, and disables +// [TerminalRenderer.SetRelativeCursor] flag. On the next call to +// [TerminalRenderer.Render], it will move the cursor home and clear the screen +// to prepare for rendering the new buffer. +// +// Note: you might want to reapply the cursor visibility state after calling +// this method, as some terminals reset the cursor visibility when switching to +// the alternate screen. +func (s *TerminalRenderer) EnterAltScreen() { + s.SaveCursor() + s.buf.WriteString(ansi.SetModeAltScreenSaveCursor) + s.SetFullscreen(true) + s.SetRelativeCursor(false) + s.Erase() +} + +// ExitAltScreen is a helper that queues the [ansi.ModeAltScreenSaveCursor] +// escape sequence to exit the alternate screen buffer and restore cursor mode. +// +// It restores the saved cursor properties, disables +// [TerminalRenderer.SetFullscreen] flag, and enables +// [TerminalRenderer.SetRelativeCursor] flag. On the next call to +// [TerminalRenderer.Render], it will move the cursor to the first line and +// clear everything below the cursor to prepare for rendering the new buffer. +// +// Note: you might want to reapply the cursor visibility state after calling +// this method, as some terminals reset the cursor visibility when switching to +// the alternate screen. +func (s *TerminalRenderer) ExitAltScreen() { + s.Erase() + s.SetRelativeCursor(true) + s.SetFullscreen(false) + s.buf.WriteString(ansi.ResetModeAltScreenSaveCursor) + s.RestoreCursor() +} + +// PrependString adds the lines of the given string to the top of the terminal +// screen. The lines prepended are not managed by the renderer and will not be +// cleared or updated by the renderer. +// +// Using this when the terminal is using the alternate screen or when occupying +// the whole screen may not produce any visible effects. This is because +// once the terminal writes the prepended lines, they will get overwritten +// by the next frame. +func (s *TerminalRenderer) PrependString(newbuf *RenderBuffer, str string) { + if len(str) == 0 { + return + } + + // TODO: Use scrolling region if available. + // TODO: Use [Screen.Write] [io.Writer] interface. + + // We need to scroll the screen up by the number of lines in the queue. + // We can't use [ansi.SU] because we want the cursor to move down until + // it reaches the bottom of the screen. + w, h := newbuf.Width(), newbuf.Height() + s.move(newbuf, 0, h-1) + lines := strings.Split(str, "\n") + offset := 0 + for _, line := range lines { + lineWidth := s.method.StringWidth(line) + if w > 0 && lineWidth > w { + offset += (lineWidth / w) + } + if lineWidth == 0 || lineWidth%w != 0 { + offset++ + } + } + + s.buf.WriteString(strings.Repeat("\n", offset)) + s.cur.Y += offset + // XXX: Now go to the top of the screen, insert new lines, and write + // the queued strings. It is important to use [Screen.moveCursor] + // instead of [Screen.move] because we don't want to perform any checks + // on the cursor position. + s.moveCursor(newbuf, 0, 0, false) + s.buf.WriteString(ansi.InsertLine(offset)) + for _, line := range lines { + s.buf.WriteString(line) + s.buf.WriteString("\r\n") + } +} + +// moveCursor moves the cursor to the specified position. +// +// It is safe to call this function with a nil [Buffer], in that case, it won't +// be using any optimizations that depend on the buffer. +func (s *TerminalRenderer) moveCursor(newbuf *RenderBuffer, x, y int, overwrite bool) { + if !s.flags.Contains(tFullscreen) && s.flags.Contains(tRelativeCursor) && + s.cur.X == -1 && s.cur.Y == -1 { + // First cursor movement in inline mode, move the cursor to the first + // column before moving to the target position. + _ = s.buf.WriteByte('\r') + s.cur.X, s.cur.Y = 0, 0 + } + seq := moveCursor(s, newbuf, x, y, overwrite) + _, _ = s.buf.WriteString(seq) + s.cur.X, s.cur.Y = x, y +} + +// move moves the cursor to the specified position in the buffer. +// +// It is safe to call this function with a nil [Buffer], in that case, it won't +// be using any optimizations that depend on the buffer. +func (s *TerminalRenderer) move(newbuf *RenderBuffer, x, y int) { + // XXX: Make sure we use the max height and width of the buffer in case + // we're in the middle of a resize operation. + var width, height int + if s.curbuf != nil { + width, height = s.curbuf.Width(), s.curbuf.Height() + } + if newbuf != nil { + width = max(newbuf.Width(), width) + height = max(newbuf.Height(), height) + } + + if width > 0 && x >= width { + // Handle autowrap + y += (x / width) + x %= width + } + + // XXX: Disable styles if there's any + // Some move operations such as [ansi.LF] can apply styles to the new + // cursor position, thus, we need to reset the styles before moving the + // cursor. + blank := s.clearBlank() + resetPen := y != s.cur.Y && !blank.Equal(&EmptyCell) + if resetPen { + s.updatePen(nil) + } + + // Reset wrap around (phantom cursor) state + if s.atPhantom { + s.cur.X = 0 + _ = s.buf.WriteByte('\r') + s.atPhantom = false // reset phantom cell state + } + + // TODO: Investigate if we need to handle this case and/or if we need the + // following code. + // + // if width > 0 && s.cur.X >= width { + // l := (s.cur.X + 1) / width + // + // s.cur.Y += l + // if height > 0 && s.cur.Y >= height { + // l -= s.cur.Y - height - 1 + // } + // + // if l > 0 { + // s.cur.X = 0 + // s.buf.WriteString("\r" + strings.Repeat("\n", l)) //nolint:errcheck + // } + // } + + if height > 0 { + // Only clamp the remembered cursor row in fullscreen mode, where the + // buffer covers the whole screen. In relative mode the terminal + // screen extends beyond the frame buffer: after a shrink the + // real cursor can legitimately sit below the new frame's last row, + // and clamping the model here would skip the cursor-up move and leave + // the old frame's top lines on screen. + if !s.flags.Contains(tRelativeCursor) && s.cur.Y > height-1 { + s.cur.Y = height - 1 + } + if y > height-1 { + y = height - 1 + } + } + + if x == s.cur.X && y == s.cur.Y { + // We give up later because we need to run checks for the phantom cell + // and others before we can determine if we can give up. + return + } + + // We set the new cursor in tscreen.moveCursor]. + s.moveCursor(newbuf, x, y, true) // Overwrite cells if possible +} + +// cellEqual returns whether the two cells are equal. A nil cell is considered +// a [EmptyCell]. +func cellEqual(a, b *Cell) bool { + if a == b { + return true + } + // TODO: This is needed to handle empty lines correctly when scroll + // optimizations are enabled. Instead, a nil check should be equivalent to + // checking for an [EmptyCell], should it? + // Investigate why when we assign the pointers to &[EmptyCell], this causes + // scroll optimization related artifacts where excess lines are left behind + // in empty lines after scrolling. + if a == nil || b == nil { + return false + } + return a.Equal(b) +} + +// putCell draws a cell at the current cursor position. +// +// The lower right corner is written with autowrap off, since a pending wrap +// there scrolls the screen as soon as anything else prints. A multi-codepoint +// cluster is the exception: with autowrap off the terminal never advances past +// the margin and reads the combining codepoints as belonging to the cell to the +// left, so the cluster keeps autowrap on and the wrap is cancelled after. +func (s *TerminalRenderer) putCell(newbuf *RenderBuffer, cell *Cell) { + width, height := newbuf.Width(), newbuf.Height() + atMargin := s.cur.X == width-1 && !s.noWrapLine + lowerRight := atMargin && s.flags.Contains(tFullscreen) && s.cur.Y == height-1 + + // Only the corner cell can care, so the cluster is measured only there. + if lowerRight && cell != nil && utf8.RuneCountInString(cell.Content) > 1 { + s.putAttrCell(newbuf, cell) + // The cluster kept autowrap on so it landed whole, which leaves the + // cursor pending wrap. On the last row there is no next row to wrap + // onto, so the next print scrolls the screen instead. Cancel it here + // rather than leave the frame ending in a state the model denies. + if s.atPhantom { + _ = s.buf.WriteByte('\r') + s.cur.X = 0 + s.atPhantom = false + } + return + } + + if lowerRight { + s.putCellLR(newbuf, cell) + } else { + s.putAttrCell(newbuf, cell) + } +} + +// wrapCursor wraps the cursor to the next line. +func (s *TerminalRenderer) wrapCursor() { + const autoRightMargin = true + if autoRightMargin { + // Assume we have auto wrap mode enabled. + s.cur.X = 0 + s.cur.Y++ + } else { + s.cur.X-- + } +} + +func (s *TerminalRenderer) putAttrCell(newbuf *RenderBuffer, cell *Cell) { + if cell != nil && cell.Width == 0 { + // XXX: Zero width cells are special and should not be written to the + // screen no matter what other attributes they have. + // Zero width cells are used for wide characters that are split into + // multiple cells. + return + } + + // We're at pending wrap state (phantom cell), incoming cell should + // wrap. + if s.atPhantom { + s.wrapCursor() + s.atPhantom = false + } + + s.updatePen(cell) + cellWidth := 1 + if cell == nil { + _ = s.buf.WriteByte(' ') + } else { + _, _ = s.buf.WriteString(cell.Content) + cellWidth = cell.Width + } + + s.cur.X += cellWidth + if s.cur.X >= newbuf.Width() { + s.atPhantom = true + } +} + +// putCellLR draws a cell at the lower right corner of the screen. +func (s *TerminalRenderer) putCellLR(newbuf *RenderBuffer, cell *Cell) { + // Optimize for the lower right corner cell. + curX := s.cur.X + if !cell.isWidePlaceholder() { + _, _ = s.buf.WriteString(ansi.ResetModeAutoWrap) + s.putAttrCell(newbuf, cell) + // Writing to lower-right corner cell should not wrap. + s.atPhantom = false + s.cur.X = curX + _, _ = s.buf.WriteString(ansi.SetModeAutoWrap) + } +} + +// updatePen updates the cursor pen styles. +func (s *TerminalRenderer) updatePen(cell *Cell) { + if cell == nil { + cell = &EmptyCell + } + + // Downsample pen when we don't have a [colorprofile.TrueColor], + // otherwise, use the original style. + newStyle := ConvertStyle(styleValue(cell.Style), s.profile) + newLink := ConvertLink(linkValue(cell.Link), s.profile) + oldStyle := ConvertStyle(styleValue(s.cur.Style), s.profile) + oldLink := ConvertLink(linkValue(s.cur.Link), s.profile) + + if !newStyle.Equal(&oldStyle) { + seq := newStyle.Diff(&oldStyle) + if newStyle.IsZero() && len(seq) > len(ansi.ResetStyle) { + seq = ansi.ResetStyle + } + _, _ = s.buf.WriteString(seq) + s.cur.Style = cell.Style // Copy the original style + } + if !newLink.Equal(&oldLink) { + _, _ = s.buf.WriteString(ansi.SetHyperlink(newLink.URL, newLink.Params)) + s.cur.Link = cell.Link // Copy the original link + } +} + +// canClearWith checks whether the given cell can be used by clearing commands +// like [ansi.EL] to clear the screen. It tests if a cell is empty i.e. space +// or blank and doesn't include any bad style attributes such as [AttrReverse]. +func canClearWith(c *Cell) bool { + if c == nil { + return true + } + if c.Width != 1 || len(c.Content) != 1 || c.Content != " " { + return false + } + // NOTE: This assumes that the terminal supports bce terminfo capability + // which all xterm-compatible terminals and terminals that use xterm* + // terminal types do. + style := styleValue(c.Style) + return style.Underline == UnderlineNone && + style.Attrs&^(AttrBold|AttrFaint|AttrItalic|AttrBlink|AttrRapidBlink) == 0 && + c.Link.IsZero() +} + +// emitRange emits a range of cells to the buffer. It it equivalent to calling +// tscreen.putCell] for each cell in the range. This is optimized to use +// [ansi.ECH] and [ansi.REP]. +// Returns whether the cursor is at the end of interval or somewhere in the +// middle. +func (s *TerminalRenderer) emitRange(newbuf *RenderBuffer, line Line, n int) (eoi bool) { + hasECH := s.caps.Contains(capECH) + hasREP := s.caps.Contains(capREP) + if hasECH || hasREP { //nolint:nestif + for n > 0 { + var count int + for n > 1 && !cellEqual(line.At(0), line.At(1)) { + s.putCell(newbuf, line.At(0)) + line = line[1:] + n-- + } + + cell0 := line[0] + if n == 1 { + s.putCell(newbuf, &cell0) + return false + } + + count = 2 + for count < n && cellEqual(line.At(count), &cell0) { + count++ + } + + ech := ansi.EraseCharacter(count) + cup := ansi.CursorPosition(s.cur.X+count, s.cur.Y) + rep := ansi.RepeatPreviousCharacter(count) + if hasECH && count > len(ech)+len(cup) && canClearWith(&cell0) { + s.updatePen(&cell0) + _, _ = s.buf.WriteString(ech) + + // If this is the last cell, we don't need to move the cursor. + if count < n { + s.move(newbuf, s.cur.X+count, s.cur.Y) + } else { + return true // cursor in the middle + } + } else if hasREP && count > len(rep) && + (len(cell0.Content) == 1 && cell0.Content[0] >= ansi.US && cell0.Content[0] < ansi.DEL) { + // We only support ASCII characters. Most terminals will handle + // non-ASCII characters correctly, but some might not, ahem xterm. + // + // NOTE: [ansi.REP] only repeats the last rune and won't work + // if the last cell contains multiple runes. + + wrapPossible := s.cur.X+count >= newbuf.Width() + repCount := count + if wrapPossible { + repCount-- + } + + s.updatePen(&cell0) + s.putCell(newbuf, &cell0) + repCount-- // cell0 is a single width cell ASCII character + + _, _ = s.buf.WriteString(ansi.RepeatPreviousCharacter(repCount)) + s.cur.X += repCount + if wrapPossible { + s.putCell(newbuf, &cell0) + } + } else { + for i := 0; i < count; i++ { + s.putCell(newbuf, line.At(i)) + } + } + + line = line[clamp(count, 0, len(line)):] + n -= count + } + + return false + } + + for i := 0; i < n; i++ { + s.putCell(newbuf, line.At(i)) + } + + return false +} + +// putRange puts a range of cells from the old line to the new line. +// Returns whether the cursor is at the end of interval or somewhere in the +// middle. +func (s *TerminalRenderer) putRange(newbuf *RenderBuffer, oldLine, newLine Line, y, start, end int) (eoi bool) { + inline := min(len(ansi.CursorPosition(start+1, y+1)), + min(len(ansi.HorizontalPositionAbsolute(start+1)), + len(ansi.CursorForward(start+1)))) + if (end - start + 1) > inline { //nolint:nestif + var j, same int + for j, same = start, 0; j <= end; j++ { + oldCell, newCell := oldLine.At(j), newLine.At(j) + if same == 0 && oldCell.isWidePlaceholder() && newCell.isWidePlaceholder() { + continue + } + if cellEqual(oldCell, newCell) { + same++ + } else { + if same > end-start { + s.emitRange(newbuf, newLine[start:], j-same-start) + s.move(newbuf, j, y) + start = j + } + same = 0 + } + } + + i := s.emitRange(newbuf, newLine[start:], j-same-start) + + // Always return 1 for the next [tScreen.move] after a + // [tScreen.putRange] if we found identical characters at end of + // interval. + if same == 0 { + return i + } + return true + } + + return s.emitRange(newbuf, newLine[start:], end-start+1) +} + +// clearToEnd clears the screen from the current cursor position to the end of +// line. +func (s *TerminalRenderer) clearToEnd(newbuf *RenderBuffer, blank *Cell, force bool) { + if s.cur.Y >= 0 { + curline := s.curbuf.Line(s.cur.Y) + // We use the newbuf width because the current buffer might be smaller + // than the new buffer during a resize operation and we want to detect + // that. + for j := s.cur.X; j < newbuf.Width(); j++ { + if j >= 0 { + c := curline.At(j) + if !cellEqual(c, blank) { + curline.Set(j, blank) + force = true + } + } + } + } + + if force { + s.updatePen(blank) + count := newbuf.Width() - s.cur.X + if s.el0Cost() <= count { + _, _ = s.buf.WriteString(ansi.EraseLineRight) + } else { + for i := 0; i < count; i++ { + s.putCell(newbuf, blank) + } + } + } +} + +// clearBlank returns a blank cell based on the current cursor background color. +func (s *TerminalRenderer) clearBlank() *Cell { + return &s.cur.Cell +} + +// insertCells inserts the count cells pointed by the given line at the current +// cursor position. +func (s *TerminalRenderer) insertCells(newbuf *RenderBuffer, line Line, count int) { + supportsICH := s.caps.Contains(capICH) + if supportsICH { + // Use [ansi.ICH] as an optimization. + _, _ = s.buf.WriteString(ansi.InsertCharacter(count)) + } else { + // Otherwise, use [ansi.IRM] mode. + _, _ = s.buf.WriteString(ansi.SetModeInsertReplace) + } + + for i := 0; count > 0; i++ { + s.putAttrCell(newbuf, line.At(i)) + count-- + } + + if !supportsICH { + _, _ = s.buf.WriteString(ansi.ResetModeInsertReplace) + } +} + +// el0Cost returns the cost of using [ansi.EL] 0 i.e. [ansi.EraseLineRight]. If +// this terminal supports background color erase, it can be cheaper to use +// [ansi.EL] 0 i.e. [ansi.EraseLineRight] to clear +// trailing spaces. +func (s *TerminalRenderer) el0Cost() int { + if s.caps != noCaps { + return 0 + } + return len(ansi.EraseLineRight) +} + +// lineHasDrift reports whether the line contains a cell that a cell-level +// diff cannot safely reposition across: a wide cell (width > 1), or a cell +// whose width the terminal may measure differently than the model. Wide cells +// occupy several columns, so a diff that lands on a continuation column splits +// the character; and a width disagreement means the model cannot know which +// column each glyph landed on. +func lineHasDrift(m ansi.Method, line Line) bool { + for i := 0; i < len(line); i++ { + c := line.At(i) + if c == nil || c.Width == 0 || len(c.Content) == 0 { + continue + } + if c.Width > 1 { + return true + } + // One printable ASCII byte is one column under every width model, so + // it can never be a cell the models disagree about. Worth saying out + // loud because working the width out means segmenting the content, + // and this runs for every cell of every line the renderer diffs. + if len(c.Content) == 1 && c.Content[0] >= 0x20 && c.Content[0] < 0x7f { + continue + } + if m.StringWidth(c.Content) != ansi.StringWidth(c.Content) { + return true + } + } + return false +} + +// paintLine brings row y of the screen in line with newbuf. A drift-prone row, +// or any row when force is set, is repainted; every other row is diffed. +func (s *TerminalRenderer) paintLine(newbuf *RenderBuffer, y int, force bool) { + drift := lineHasDrift(s.method, s.curbuf.Line(y)) || lineHasDrift(s.method, newbuf.Line(y)) + s.markDrift(y, newbuf.Height(), drift) + switch { + case drift && !s.flags.Contains(tGraphemeWidth): + // Clip a cluster the terminal measures wider than the model instead of + // letting it spill onto the next row, then put the cursor back. + s.noWrapLine = true + _, _ = s.buf.WriteString(ansi.ResetModeAutoWrap) + s.repaintLine(newbuf, y) + s.noWrapLine = false + _, _ = s.buf.WriteString(ansi.SetModeAutoWrap) + s.reanchorWideLine(newbuf) + case drift || force: + s.repaintLine(newbuf, y) + default: + s.transformLine(newbuf, y) + } +} + +// repaintLine erases row y from column 0 and writes newbuf's cells, so the +// result does not depend on what the model believes is on screen. +func (s *TerminalRenderer) repaintLine(newbuf *RenderBuffer, y int) { + oldLine := s.curbuf.Line(y) + newLine := newbuf.Line(y) + + s.move(newbuf, 0, y) + blank := s.clearBlank() + s.updatePen(blank) + _, _ = s.buf.WriteString(ansi.EraseLineRight) + s.cur.X = 0 + + // A cell whose width runs past the right margin cannot be shown, so stop + // there. The buffer can hold one after a resize narrowed the line around + // it, and painting it would put a clipped half-glyph on the screen. + width := newbuf.Width() + clipped := width + for x := 0; x < width; x++ { + if c := newLine.At(x); c != nil && !c.isWidePlaceholder() && x+c.Width > width { + clipped = x + break + } + } + + // Write the content cells. The line was just erased, so trailing blanks + // need no write, and writing them would risk wrapping past the right + // margin if the terminal painted a wide cell wider than the model + // measured. + last := -1 + for x := 0; x < clipped; x++ { + if c := newLine.At(x); c != nil && !c.isWidePlaceholder() && !cellEqual(c, blank) { + last = x + } + } + for x := 0; x <= last; x++ { + s.putCell(newbuf, newLine.At(x)) + } + + // Adopt the new line as the model of what is on screen. The clipped tail + // was never painted, so the model records it as blank: claiming otherwise + // would let a later frame skip the cell, and a resize that widens the line + // would leave the half-glyph on screen forever. + if len(oldLine) == len(newLine) { + copy(oldLine, newLine) + for x := clipped; x < width && x < len(oldLine); x++ { + oldLine[x] = Cell{} + } + } +} + +// markDrift records whether a row holds a cell the terminal may measure +// differently than the model, so a later width change knows which rows to +// repaint. Recorded here rather than rescanned later, because the diff already +// had to work it out. +func (s *TerminalRenderer) markDrift(y, height int, drift bool) { + if y < 0 { + return + } + if n := max(height, y+1); len(s.driftRows) < n { + s.driftRows = append(s.driftRows, make([]bool, n-len(s.driftRows))...) + } + s.driftRows[y] = drift +} + +// transformLine diffs row y against the model and writes only what changed, +// using [ansi.ICH] and [ansi.DCH] to shift cells. It must not see a drift-prone +// row; [TerminalRenderer.paintLine] routes those to a repaint. +func (s *TerminalRenderer) transformLine(newbuf *RenderBuffer, y int) { + var firstCell, oLastCell, nLastCell int // first, old last, new last index + oldLine := s.curbuf.Line(y) + newLine := newbuf.Line(y) + + // Find the first changed cell in the line + blank := newLine.At(0) + + // It might be cheaper to clear leading spaces with [ansi.EL] 1 i.e. + // [ansi.EraseLineLeft]. + if canClearWith(blank) { //nolint:nestif + var oFirstCell, nFirstCell int + for oFirstCell = 0; oFirstCell < s.curbuf.Width(); oFirstCell++ { + if !cellEqual(oldLine.At(oFirstCell), blank) { + break + } + } + for nFirstCell = 0; nFirstCell < newbuf.Width(); nFirstCell++ { + if !cellEqual(newLine.At(nFirstCell), blank) { + break + } + } + + if nFirstCell == oFirstCell { + firstCell = nFirstCell + + // Find the first differing cell + for firstCell < newbuf.Width() && + cellEqual(oldLine.At(firstCell), newLine.At(firstCell)) { + firstCell++ + } + } else if oFirstCell > nFirstCell { + firstCell = nFirstCell + } else if oFirstCell < nFirstCell { + firstCell = oFirstCell + el1Cost := len(ansi.EraseLineLeft) + if el1Cost < nFirstCell-oFirstCell { + if nFirstCell >= newbuf.Width() { + s.move(newbuf, 0, y) + s.updatePen(blank) + _, _ = s.buf.WriteString(ansi.EraseLineRight) + } else { + s.move(newbuf, nFirstCell-1, y) + s.updatePen(blank) + _, _ = s.buf.WriteString(ansi.EraseLineLeft) + } + + for firstCell < nFirstCell { + oldLine.Set(firstCell, blank) + firstCell++ + } + } + } + } else { + // Find the first differing cell + for firstCell < newbuf.Width() && cellEqual(newLine.At(firstCell), oldLine.At(firstCell)) { + firstCell++ + } + } + + // If we didn't find one, we're done + if firstCell >= newbuf.Width() { + return + } + + blank = newLine.At(newbuf.Width() - 1) + if blank != nil && !canClearWith(blank) { + // Find the last differing cell + nLastCell = newbuf.Width() - 1 + for nLastCell > firstCell && cellEqual(newLine.At(nLastCell), oldLine.At(nLastCell)) { + nLastCell-- + } + + if nLastCell >= firstCell { + s.move(newbuf, firstCell, y) + s.putRange(newbuf, oldLine, newLine, y, firstCell, nLastCell) + if firstCell < len(oldLine) && firstCell < len(newLine) { + copy(oldLine[firstCell:], newLine[firstCell:]) + } else { + copy(oldLine, newLine) + } + } + + return + } + + // Find last non-blank cell in the old line. + // We always use the newbuf width to detect new cell changes. + oLastCell = newbuf.Width() - 1 + for oLastCell > firstCell && cellEqual(oldLine.At(oLastCell), blank) { + oLastCell-- + } + + // Find last non-blank cell in the new line. + // We always use the newbuf width to detect new cell changes. + nLastCell = newbuf.Width() - 1 + for nLastCell > firstCell && cellEqual(newLine.At(nLastCell), blank) { + nLastCell-- + } + + if nLastCell == firstCell && s.el0Cost() < oLastCell-nLastCell { //nolint:nestif + s.move(newbuf, firstCell, y) + if !cellEqual(newLine.At(firstCell), blank) { + s.putCell(newbuf, newLine.At(firstCell)) + } + s.clearToEnd(newbuf, blank, false) + } else if nLastCell != oLastCell && + !cellEqual(newLine.At(nLastCell), oldLine.At(oLastCell)) { + s.move(newbuf, firstCell, y) + if oLastCell-nLastCell > s.el0Cost() { + if s.putRange(newbuf, oldLine, newLine, y, firstCell, nLastCell) { + s.move(newbuf, nLastCell+1, y) + } + s.clearToEnd(newbuf, blank, false) + } else { + n := max(nLastCell, oLastCell) + s.putRange(newbuf, oldLine, newLine, y, firstCell, n) + } + } else { + nLastNonBlank := nLastCell + oLastNonBlank := oLastCell + + // Find the last cells that really differ. + // Can be -1 if no cells differ. + for cellEqual(newLine.At(nLastCell), oldLine.At(oLastCell)) { + if !cellEqual(newLine.At(nLastCell-1), oldLine.At(oLastCell-1)) { + break + } + nLastCell-- + oLastCell-- + if nLastCell == -1 || oLastCell == -1 { + break + } + } + + n := min(oLastCell, nLastCell) + if n >= firstCell { + s.move(newbuf, firstCell, y) + s.putRange(newbuf, oldLine, newLine, y, firstCell, n) + } + + if oLastCell < nLastCell { + m := max(nLastNonBlank, oLastNonBlank) + if n != 0 { + for n > 0 { + wide := newLine.At(n + 1) + if !wide.isWidePlaceholder() { + break + } + n-- + oLastCell-- + } + } else if n >= firstCell && newLine.At(n) != nil && newLine.At(n).Width > 1 { + next := newLine.At(n + 1) + for next.isWidePlaceholder() { + n++ + oLastCell++ + next = newLine.At(n + 1) + } + } + + // TODO: This can sometimes send unnecessary cursor movements with + // negative or zero ranges. This could happen on a screen resize + // where oLastCell < nLastCell and oLastCell is -1 or less. + // Investigate and fix. + s.move(newbuf, n+1, y) + ichCost := 3 + nLastCell - oLastCell + if s.caps.Contains(capICH) && (nLastCell < nLastNonBlank || ichCost > (m-n)) { + s.putRange(newbuf, oldLine, newLine, y, n+1, m) + } else { + s.insertCells(newbuf, newLine[n+1:], nLastCell-oLastCell) + } + } else if oLastCell > nLastCell { + s.move(newbuf, n+1, y) + dchCost := 3 + oLastCell - nLastCell + if dchCost > len(ansi.EraseLineRight)+nLastNonBlank-(n+1) { + if s.putRange(newbuf, oldLine, newLine, y, n+1, nLastNonBlank) { + s.move(newbuf, nLastNonBlank+1, y) + } + s.clearToEnd(newbuf, blank, false) + } else { + s.updatePen(blank) + s.deleteCells(oLastCell - nLastCell) + } + } + } + + // Update the old line with the new line + if firstCell < len(oldLine) && firstCell < len(newLine) { + copy(oldLine[firstCell:], newLine[firstCell:]) + } else { + copy(oldLine, newLine) + } +} + +// reanchorWideLine re-anchors the cursor after a line that may have left it +// adrift. This is a best-effort fallback that bounds cursor desync to one line +// on terminals whose width model disagrees with ours. When the terminal +// negotiated Unicode grapheme width (mode 2027) the models agree, so no +// re-anchor is needed. +// +// The row is re-anchored along with the column. A terminal that measures a +// cluster wider than the model does runs past the right margin and wraps, so a +// line the model believes fits can leave the real cursor a row further down. +// Recovering the column alone would then leave every following line painted one +// row off, which is the drift this re-anchor exists to contain. +func (s *TerminalRenderer) reanchorWideLine(newbuf *RenderBuffer) { + // In relative cursor mode there is no absolute row to move to, so the + // column is all that can be recovered. + if s.flags.Contains(tRelativeCursor) { + if s.atPhantom || s.cur.X < 0 || s.cur.X >= newbuf.Width() { + return + } + _, _ = s.buf.WriteString(ansi.CursorHorizontalAbsolute(s.cur.X + 1)) + return + } + + if s.cur.X < 0 || s.cur.Y < 0 { + return + } + + // A pending wrap is as untrustworthy as the column: the terminal may have + // already taken it. An absolute move cancels it and lands on a column the + // model can name, so clamp into the line and record that. + x := min(s.cur.X, newbuf.Width()-1) + _, _ = s.buf.WriteString(ansi.CursorPosition(x+1, s.cur.Y+1)) + s.cur.X = x + s.atPhantom = false +} + +// deleteCells deletes the count cells at the current cursor position and moves +// the rest of the line to the left. This is equivalent to [ansi.DCH]. +func (s *TerminalRenderer) deleteCells(count int) { + // [ansi.DCH] will shift in cells from the right margin so we need to + // ensure that they are the right style. + _, _ = s.buf.WriteString(ansi.DeleteCharacter(count)) +} + +// clearToBottom clears the screen from the current cursor position to the end +// of the screen. +func (s *TerminalRenderer) clearToBottom(blank *Cell) { + row, col := s.cur.Y, s.cur.X + if row < 0 { + row = 0 + } + + s.updatePen(blank) + _, _ = s.buf.WriteString(ansi.EraseScreenBelow) + // Clear the rest of the current line + s.curbuf.ClearArea(Rect(col, row, s.curbuf.Width()-col, 1)) + // Clear everything below the current line + s.curbuf.ClearArea(Rect(0, row+1, s.curbuf.Width(), s.curbuf.Height()-row-1)) +} + +// clearBottom tests if clearing the end of the screen would satisfy part of +// the screen update. Scan backwards through lines in the screen checking if +// each is blank and one or more are changed. +// It returns the top line. +func (s *TerminalRenderer) clearBottom(newbuf *RenderBuffer, total int) (top int) { + if total <= 0 { + return 0 + } + + top = total + last := min(s.curbuf.Width(), newbuf.Width()) + blank := s.clearBlank() + canClearWithBlank := canClearWith(blank) + + if canClearWithBlank { //nolint:nestif + var row int + for row = total - 1; row >= 0; row-- { + oldLine := s.curbuf.Line(row) + newLine := newbuf.Line(row) + + var col int + ok := true + for col = 0; ok && col < last; col++ { + ok = cellEqual(newLine.At(col), blank) + } + if !ok { + break + } + + for col = 0; ok && col < last; col++ { + ok = cellEqual(oldLine.At(col), blank) + } + if !ok { + top = row + } + } + + if top < total { + // top is the first row of the trailing blank region, so the + // erase starts there. Starting a row earlier would wipe a row + // this frame did not touch, and the loop that repaints only + // touched rows would never put it back. + s.move(newbuf, 0, top) + s.clearToBottom(blank) + if s.oldhash != nil && s.newhash != nil && + row < len(s.oldhash) && row < len(s.newhash) { + for row := top; row < newbuf.Height(); row++ { + s.oldhash[row] = s.newhash[row] + } + } + } + } + + return top +} + +// clearScreen clears the screen and put cursor at home. +func (s *TerminalRenderer) clearScreen(blank *Cell) { + s.updatePen(blank) + _, _ = s.buf.WriteString(ansi.CursorHomePosition) + _, _ = s.buf.WriteString(ansi.EraseEntireScreen) + s.cur.X, s.cur.Y = 0, 0 + s.curbuf.Fill(blank) +} + +// clearBelow clears everything below and including the row. +func (s *TerminalRenderer) clearBelow(newbuf *RenderBuffer, blank *Cell, row int) { + s.move(newbuf, 0, row) + s.clearToBottom(blank) +} + +// clearUpdate forces a screen redraw. +func (s *TerminalRenderer) clearUpdate(newbuf *RenderBuffer) { + blank := s.clearBlank() + var nonEmpty int + if s.flags.Contains(tFullscreen) { + // XXX: We're using the maximum height of the two buffers to ensure we + // write newly added lines to the screen in + // [terminalWriter.transformLine]. + nonEmpty = max(s.curbuf.Height(), newbuf.Height()) + s.clearScreen(blank) + } else { + nonEmpty = newbuf.Height() + // FIXME: Investigate the double [ansi.ClearScreenBelow] call. + // Commenting the line below out seems to work but it might cause other + // bugs. + s.clearBelow(newbuf, blank, 0) + } + nonEmpty = s.clearBottom(newbuf, nonEmpty) + for i := 0; i < nonEmpty && i < newbuf.Height(); i++ { + s.paintLine(newbuf, i, false) + } +} + +func (s *TerminalRenderer) logf(format string, args ...any) { + if s.logger == nil { + return + } + s.logger.Printf(format, args...) +} + +// Buffered returns the number of bytes buffered for the next flush. +func (s *TerminalRenderer) Buffered() int { + return s.buf.Len() +} + +// Flush flushes the buffer to the screen. +func (s *TerminalRenderer) Flush() (err error) { + // Write the buffer + if n := s.buf.Len(); n > 0 { + bts := s.buf.Bytes() + if s.logger != nil { + s.logf("output: %q", bts) + } + _, err = s.w.Write(bts) + s.buf.Reset() + } + return +} + +// sizeChange is what a render owes to the screen or the frame having changed +// shape since the last one. +type sizeChange struct { + // frameResized reports that the frame is a different shape than the model, + // so the model has to be resized before anything is diffed against it. + frameResized bool + + // repaintAll requires every row to be painted whatever the model says. + repaintAll bool +} + +// reconcileSize decides what a change of size costs, and is the only place that +// decides it. +// +// A terminal that changed size rewrapped what was on it, and a frame that +// changed shape leaves no row holding its old meaning. Either way the model +// cannot be trusted. What differs is how much of the screen is the renderer's to +// put right: fullscreen owns every cell and clears it, while an inline frame +// shares the screen with whatever came before and so repaints its own rows and +// leaves the rest alone. +func (s *TerminalRenderer) reconcileSize(newbuf *RenderBuffer) sizeChange { + newWidth, newHeight := newbuf.Width(), newbuf.Height() + curWidth, curHeight := s.curbuf.Width(), s.curbuf.Height() + fullscreen := s.flags.Contains(tFullscreen) + + change := sizeChange{ + frameResized: curWidth != newWidth || curHeight != newHeight, + } + + if s.termResized { + if fullscreen { + s.clear = true + } else { + change.repaintAll = true + } + s.termResized = false + } + + if change.frameResized { + // No row keeps its meaning, so the hashes that describe them are worth + // nothing. Inline uses the narrower partial clear in Render instead. + s.oldhash, s.newhash = nil, nil + if fullscreen { + s.clear = true + } + // Nor does the application's touch list, which never saw rows that + // vanished and came back between two frames. + s.damage(0, newHeight) + } + + // The terminal clips a row it measures wider than the model does, and the + // model believes it painted the whole row. Changing the width changes what + // fits, so a row holding a cell the two might measure differently has to be + // painted again. Rows of plain cells are measured the same by everyone, so an + // ASCII screen pays nothing. + if !fullscreen && curWidth != newWidth { + for y, drifts := range s.driftRows { + if drifts { + s.damage(y, 1) + } + } + } + + return change +} + +// damage marks n rows from y as rows this render disturbed on its own: rows it +// scrolled, rows it erased, rows the terminal is about to measure differently +// than the model does. The diff loop paints a damaged row whether or not the +// application drew into it, because the application has no reason to redraw a +// row it did not change and no way to know the renderer moved it. +func (s *TerminalRenderer) damage(y, n int) { + for i := max(y, 0); i < min(y+n, len(s.damaged)); i++ { + s.damaged[i] = true + } +} + +// beginDamage starts a fresh account, sized to the screen this render is about +// to paint. A row outside it cannot be painted, so it cannot be damaged, and +// clamping here is what lets every reader index the record without checking. +// Reset on the way in rather than the way out, so no future exit path has to +// remember to do it. The slice is kept when the size holds, so a steady stream +// of frames allocates nothing. +func (s *TerminalRenderer) beginDamage(height int) { + if len(s.damaged) != height { + s.damaged = make([]bool, height) + return + } + clear(s.damaged) +} + +// Redraw forces a full redraw of the screen. It's equivalent to calling +// [TerminalRenderer.Erase] and [TerminalRenderer.Render]. +func (s *TerminalRenderer) Redraw(newbuf *RenderBuffer) { + s.clear = true + s.Render(newbuf) +} + +// Render renders changes of the screen to the internal buffer. Call +// [terminalWriter.Flush] to flush pending changes to the screen. +func (s *TerminalRenderer) Render(newbuf *RenderBuffer) { + // Do we need to render anything? A latched resize counts: the terminal moved + // content the application cannot know about, so a frame it considers + // unchanged still has to be put back on screen. + touchedLines := newbuf.TouchedLines() + if !s.clear && !s.termResized && touchedLines == 0 { + return + } + + // Every reader below indexes the touch list by screen row, so the list has to + // cover the screen before any of them run. Growing here is what lets them do + // it without a length check each. + newbuf.growTouched() + + if s.curbuf == nil || s.curbuf.Bounds().Empty() { + // Initialize the current buffer + s.curbuf = NewRenderBuffer(newbuf.Width(), newbuf.Height()) + } + + newWidth, newHeight := newbuf.Width(), newbuf.Height() + curHeight := s.curbuf.Height() + + s.beginDamage(newHeight) + + size := s.reconcileSize(newbuf) + + // TODO: Investigate whether this is necessary. Theoretically, terminals + // can add/remove tab stops and we should be able to handle that. We could + // use [ansi.DECTABSR] to read the tab stops, but that's not implemented in + // most terminals :/ + // // Are we using hard tabs? If so, ensure tabs are using the + // // default interval using [ansi.DECST8C]. + // if s.opts.HardTabs && !s.initTabs { + // s.buf.WriteString(ansi.SetTabEvery8Columns) + // s.initTabs = true + // } + + var nonEmpty int + + // An inline frame that gives up rows has to erase what it no longer covers, + // or the tail of the taller frame stays on screen below the shorter one. + // Fullscreen has no such rows: it repaints the whole screen instead. + // + // The erase runs from the new last row to the bottom of the screen, so it + // reaches that residue wherever the terminal moved it. A width change at + // the same time is therefore a reason to erase rather than a reason to skip + // it, since a terminal that rewrapped those rows has spread them further + // than the model can account for. + partialClear := !s.flags.Contains(tFullscreen) && s.cur.X != -1 && s.cur.Y != -1 && + curHeight > 0 && + curHeight > newHeight + + if !s.clear && partialClear { + // From the first row the frame gave up, so the frame's own rows are left + // alone: nothing it still owns needs putting back, and a frame that + // collapsed to nothing starts at its own first row rather than the one + // above, which belongs to whatever shared the screen first. + s.clearBelow(newbuf, nil, newHeight) + } + + // Resize the model before diffing so the loop below walks every row + // of the new screen, including rows added by a grow. + if size.frameResized { + s.curbuf.Resize(newWidth, newHeight) + } + + if s.clear { //nolint:nestif + s.clearUpdate(newbuf) + s.clear = false + } else if touchedLines > 0 || size.repaintAll { + // On Windows, there's a bug with Windows Terminal where [ansi.DECSTBM] + // misbehaves and moves the cursor outside of the scrolling region. For + // now, we disable the optimizations completely on Windows. + // See https://github.com/microsoft/terminal/issues/19016 + if s.flags.Contains(tScrollOptim) && s.flags.Contains(tFullscreen) { + // Optimize scrolling for the alternate screen buffer. + // TODO: Should we optimize for inline mode as well? If so, we need + // to know the actual cursor position to use [ansi.DECSTBM]. + s.scrollOptimize(newbuf) + } + + var changedLines int + var i int + + nonEmpty = newHeight + + nonEmpty = s.clearBottom(newbuf, nonEmpty) + for i = 0; i < nonEmpty; i++ { + // A repaintAll row has to be put back whatever the model says. + if size.repaintAll || s.damaged[i] || (newbuf.Touched[i] != nil && + (newbuf.Touched[i].FirstCell != -1 || newbuf.Touched[i].LastCell != -1)) { + s.paintLine(newbuf, i, size.repaintAll) + changedLines++ + } + } + } + + if !s.flags.Contains(tFullscreen) && size.frameResized { + s.move(newbuf, 0, max(newHeight-1, 0)) + } + + // Sync windows and screen + newbuf.growTouched() + resetTouched(newbuf.Touched) + + s.updatePen(nil) +} + +// Erase marks the screen to be fully erased on the next render. +func (s *TerminalRenderer) Erase() { + s.clear = true +} + +// Resize updates the terminal screen tab stops. This is used to calculate +// terminal tab stops for hard tab optimizations. +// +// Resize also invalidates the cursor model when the renderer can recover +// from it: a terminal may move the cursor on any resize, so the remembered +// position no longer matches reality, and the next move will be absolute. +// +// In relative cursor mode there is no absolute move to fall back on, and +// -1 there means "first move, assume the origin" rather than "unknown", so +// invalidating would assert a position instead of forgetting one. Keep the +// old model in that mode and let the next render diff against it. +// +// A resize also forces the next render to repaint, since the screen moves +// content around to fit and the model cannot see where it went. Whether that +// means the whole screen or only the frame's own rows is decided in +// [TerminalRenderer.Render]. +func (s *TerminalRenderer) Resize(width, height int) { + if s.tabs != nil { + s.tabs.Resize(width) + } + + // Latched against the size last reported, not against the model, because + // Render sees only the size the application draws at: a screen that shrinks + // and grows back between two frames looks unchanged by the time it gets + // there. What the resize costs is decided in Render, which knows the mode. + if width > 0 && height > 0 { + s.termResized = s.termResized || (s.termW > 0 && (width != s.termW || height != s.termH)) + s.termW, s.termH = width, height + } + + if !s.flags.Contains(tRelativeCursor) { + s.cur.X, s.cur.Y = -1, -1 + } +} + +// Position returns the cursor position in the screen buffer after applying any +// pending transformations from the underlying buffer. +func (s *TerminalRenderer) Position() (x, y int) { + return s.cur.X, s.cur.Y +} + +// SetPosition changes the logical cursor position. This can be used when we +// change the cursor position outside of the screen and need to update the +// screen cursor position. +// This changes the cursor position for both normal and alternate screen +// buffers. +func (s *TerminalRenderer) SetPosition(x, y int) { + s.cur.X, s.cur.Y = x, y +} + +// WriteString writes the given string to the underlying buffer. +func (s *TerminalRenderer) WriteString(str string) (int, error) { + return s.buf.WriteString(str) //nolint:wrapcheck +} + +// Write writes the given bytes to the underlying buffer. +func (s *TerminalRenderer) Write(b []byte) (int, error) { + return s.buf.Write(b) //nolint:wrapcheck +} + +// MoveTo calculates and writes the shortest sequence to move the cursor to the +// given position. It uses the current cursor position and the new position to +// calculate the shortest amount of sequences to move the cursor. +func (s *TerminalRenderer) MoveTo(x, y int) { + s.move(nil, x, y) +} + +// notLocal returns whether the coordinates are not considered local movement +// using the defined thresholds. +// This takes the number of columns, and the coordinates of the current and +// target positions. +func notLocal(cols, fx, fy, tx, ty int) bool { + // The typical distance for a [ansi.CUP] sequence. Anything less than this + // is considered local movement. + const longDist = 8 - 1 + return (tx > longDist) && + (tx < cols-1-longDist) && + (abs(ty-fy)+abs(tx-fx) > longDist) +} + +// relativeCursorMove returns the relative cursor movement sequence using one or two +// of the following sequences [ansi.CUU], [ansi.CUD], [ansi.CUF], [ansi.CUB], +// [ansi.VPA], [ansi.HPA]. +// When overwrite is true, this will try to optimize the sequence by using the +// screen cells values to move the cursor instead of using escape sequences. +// +// It is safe to call this function with a nil [Buffer]. In that case, it won't +// use any optimizations that require the new buffer such as overwrite. +func relativeCursorMove(s *TerminalRenderer, newbuf *RenderBuffer, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) string { + var seq strings.Builder + if newbuf == nil { + overwrite = false // We can't overwrite the current buffer. + } + + if ty != fy { //nolint:nestif + var yseq string + if s.caps.Contains(capVPA) && !s.flags.Contains(tRelativeCursor) { + yseq = ansi.VerticalPositionAbsolute(ty + 1) + } + + if ty > fy { + n := ty - fy + if cud := ansi.CursorDown(n); yseq == "" || len(cud) < len(yseq) { + yseq = cud + } + if !s.flags.Contains(tFullscreen) || n < len(yseq) { // n is the cost of using newline characters + yseq = strings.Repeat("\n", n) + if s.flags.Contains(tMapNewline) { + fx = 0 + } + } + } else if ty < fy { + n := fy - ty + if cuu := ansi.CursorUp(n); yseq == "" || len(cuu) < len(yseq) { + yseq = cuu + } + if n == 1 && fy-1 > 0 { + // TODO: Ensure we're not unintentionally scrolling the screen up. + yseq = ansi.ReverseIndex + } + } + + seq.WriteString(yseq) + } + + if tx != fx { //nolint:nestif + var xseq string + if !s.flags.Contains(tRelativeCursor) { + if s.caps.Contains(capHPA) { + xseq = ansi.HorizontalPositionAbsolute(tx + 1) + } else if s.caps.Contains(capCHA) { + xseq = ansi.CursorHorizontalAbsolute(tx + 1) + } + } + + if tx > fx { + n := tx - fx + if useTabs && s.tabs != nil { + var tabs int + var col int + for col = fx; s.tabs.Next(col) <= tx; col = s.tabs.Next(col) { + tabs++ + if col == s.tabs.Next(col) || col >= s.tabs.Width()-1 { + break + } + } + + if tabs > 0 { + cht := ansi.CursorHorizontalForwardTab(tabs) + tab := strings.Repeat("\t", tabs) + if false && s.caps.Contains(capCHT) && len(cht) < len(tab) { + // TODO: The linux console and some terminals such as + // Alacritty don't support [ansi.CHT]. Enable this when + // we have a way to detect this, or after 5 years when + // we're sure everyone has updated their terminals :P + seq.WriteString(cht) + } else { + seq.WriteString(tab) + } + + n = tx - col + fx = col + } + } + + if cuf := ansi.CursorForward(n); xseq == "" || len(cuf) < len(xseq) { + xseq = cuf + } + + // If we have no attribute and style changes, overwrite is cheaper. + var ovw string + if overwrite && ty >= 0 { + for i := 0; i < n; i++ { + cell := newbuf.CellAt(fx+i, ty) + if cell != nil && cell.Width > 0 { + i += cell.Width - 1 + if !cell.Style.Equal(s.cur.Style) || !cell.Link.Equal(s.cur.Link) { + overwrite = false + break + } + } + } + } + + if overwrite && ty >= 0 { + for i := 0; i < n; i++ { + cell := newbuf.CellAt(fx+i, ty) + if cell != nil && cell.Width > 0 { + ovw += cell.String() + i += cell.Width - 1 + } + } + } + + if overwrite && len(ovw) < len(xseq) { + xseq = ovw + } + } else if tx < fx { + n := fx - tx + if useTabs && s.tabs != nil && s.caps.Contains(capCBT) { + // VT100 does not support backward tabs [ansi.CBT]. + + col := fx + + var cbt int // cursor backward tabs count + for s.tabs.Prev(col) >= tx { + col = s.tabs.Prev(col) + cbt++ + if col == s.tabs.Prev(col) || col <= 0 { + break + } + } + + if cbt > 0 { + seq.WriteString(ansi.CursorBackwardTab(cbt)) + n = col - tx + } + } + + if cub := ansi.CursorBackward(n); xseq == "" || len(cub) < len(xseq) { + xseq = cub + } + + if useBackspace && n < len(xseq) { + xseq = strings.Repeat("\b", n) + } + } + + seq.WriteString(xseq) + } + + return seq.String() +} + +// moveCursor moves and returns the cursor movement sequence to move the cursor +// to the specified position. +// When overwrite is true, this will try to optimize the sequence by using the +// screen cells values to move the cursor instead of using escape sequences. +// +// It is safe to call this function with a nil [Buffer]. In that case, it won't +// use any optimizations that require the new buffer such as overwrite. +func moveCursor(s *TerminalRenderer, newbuf *RenderBuffer, x, y int, overwrite bool) (seq string) { + fx, fy := s.cur.X, s.cur.Y + + if !s.flags.Contains(tRelativeCursor) { + width := -1 // Use -1 to indicate that we don't know the width of the screen. + if s.tabs != nil { + width = s.tabs.Width() + } + if newbuf != nil && width == -1 { + // Even though this might not be accurate, we can use the new + // buffer width as a fallback. Technically, if the new buffer + // didn't have the width of the terminal, this would give us a + // wrong result from [notLocal]. + width = newbuf.Width() + } + // Method #0: Use [ansi.CUP] if the distance is long. + seq = ansi.CursorPosition(x+1, y+1) + if fx == -1 || fy == -1 || width == -1 || notLocal(width, fx, fy, x, y) { + return seq + } + } + + // Optimize based on options. + trials := 0 + if s.caps.Contains(capHT) { + trials |= 2 // 0b10 in binary + } + if s.caps.Contains(capBS) { + trials |= 1 // 0b01 in binary + } + + // Try all possible combinations of hard tabs and backspace optimizations. + for i := 0; i <= trials; i++ { + // Skip combinations that are not enabled. + if i & ^trials != 0 { + continue + } + + useHardTabs := i&2 != 0 + useBackspace := i&1 != 0 + + // Method #1: Use local movement sequences. + nseq1 := relativeCursorMove(s, newbuf, fx, fy, x, y, overwrite, useHardTabs, useBackspace) + if (i == 0 && len(seq) == 0) || len(nseq1) < len(seq) { + seq = nseq1 + } + + // Method #2: Use [ansi.CR] and local movement sequences. + nseq2 := relativeCursorMove(s, newbuf, 0, fy, x, y, overwrite, useHardTabs, useBackspace) + nseq2 = "\r" + nseq2 + if len(nseq2) < len(seq) { + seq = nseq2 + } + + if !s.flags.Contains(tRelativeCursor) { + // Method #3: Use [ansi.CursorHomePosition] and local movement sequences. + nseq3 := relativeCursorMove(s, newbuf, 0, 0, x, y, overwrite, useHardTabs, useBackspace) + nseq3 = ansi.CursorHomePosition + nseq3 + if len(nseq3) < len(seq) { + seq = nseq3 + } + } + } + + return seq +} + +// xtermCaps returns whether the terminal is xterm-like. This means that the +// terminal supports ECMA-48 and ANSI X3.64 escape sequences. +// xtermCaps returns a list of control sequence capabilities for the given +// terminal type. This only supports a subset of sequences that can +// be different among terminals. +// NOTE: A hybrid approach would be to support Terminfo databases for a full +// set of capabilities. +func xtermCaps(termtype string) (v capabilities) { + parts := strings.Split(termtype, "-") + if len(parts) == 0 { + return v + } + + switch parts[0] { + case + "contour", + "foot", + "ghostty", + "kitty", + "rio", + "st", + "tmux", + "wezterm": + v = allCaps + case "xterm": + switch { + case len(parts) > 1 && parts[1] == "ghostty": + fallthrough + case len(parts) > 1 && parts[1] == "kitty": + fallthrough + case len(parts) > 1 && parts[1] == "rio": + // These terminals can be defined as xterm- variants for + // compatibility with applications that check for xterm. + v = allCaps + default: + // NOTE: We exclude capHPA from allCaps because terminals like + // Konsole don't support it. Xterm terminfo defines HPA as CHA + // which means we can use CHA instead of HPA. + v = allCaps + v &^= capHPA + v &^= capCHT + v &^= capREP + } + case "alacritty": + v = allCaps + v &^= capCHT // NOTE: alacritty added support for [ansi.CHT] in 2024-12-28 #62d5b13. + case "screen": + // See https://www.gnu.org/software/screen/manual/screen.html#Control-Sequences-1 + v = allCaps + v &^= capREP + case "linux": + // See https://man7.org/linux/man-pages/man4/console_codes.4.html + v = capVPA | capCHA | capHPA | capECH | capICH + } + + return v +} + +// resetTouched marks every line as untouched, reusing the records already there +// rather than allocating a new one per line on every render. +func resetTouched(touched []*LineData) { + for i, ld := range touched { + if ld == nil { + touched[i] = &LineData{FirstCell: -1, LastCell: -1} + continue + } + ld.FirstCell, ld.LastCell = -1, -1 + } +} diff --git a/cli/third_party/ultraviolet/terminal_renderer_hardscroll.go b/cli/third_party/ultraviolet/terminal_renderer_hardscroll.go new file mode 100644 index 000000000..9dc8dbce8 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_renderer_hardscroll.go @@ -0,0 +1,229 @@ +package uv + +import ( + "strings" + + "github.com/charmbracelet/x/ansi" +) + +// scrollOptimize optimizes the screen to transform the old buffer into the new +// buffer. +func (s *TerminalRenderer) scrollOptimize(newbuf *RenderBuffer) { + height := newbuf.Height() + if s.oldnum == nil || len(s.oldnum) < height { + s.oldnum = append(s.oldnum, make([]int, height-len(s.oldnum))...) + } + + // Calculate the indices + s.updateHashmap(newbuf) + if len(s.hashtab) < height { + return + } + + // Pass 1 - from top to bottom scrolling up + for i := 0; i < height; { + for i < height && (s.oldnum[i] == newIndex || s.oldnum[i] <= i) { + i++ + } + if i >= height { + break + } + + shift := s.oldnum[i] - i // shift > 0 + start := i + + i++ + for i < height && s.oldnum[i] != newIndex && s.oldnum[i]-i == shift { + i++ + } + end := i - 1 + shift + + if !s.scrolln(newbuf, shift, start, end, height-1) { + continue + } + } + + // Pass 2 - from bottom to top scrolling down + for i := height - 1; i >= 0; { + for i >= 0 && (s.oldnum[i] == newIndex || s.oldnum[i] >= i) { + i-- + } + if i < 0 { + break + } + + shift := s.oldnum[i] - i // shift < 0 + end := i + + i-- + for i >= 0 && s.oldnum[i] != newIndex && s.oldnum[i]-i == shift { + i-- + } + + start := i + 1 - (-shift) + if !s.scrolln(newbuf, shift, start, end, height-1) { + continue + } + } +} + +// scrolln scrolls the screen up by n lines. +func (s *TerminalRenderer) scrolln(newbuf *RenderBuffer, n, top, bot, maxY int) (v bool) { //nolint:unparam + blank := s.clearBlank() + if n > 0 { //nolint:nestif + // Scroll up (forward) + v = s.scrollUp(newbuf, n, top, bot, 0, maxY, blank) + if !v { + s.buf.WriteString(ansi.SetTopBottomMargins(top+1, bot+1)) + + // XXX: How should we handle this in inline mode when not using alternate screen? + s.cur.X, s.cur.Y = -1, -1 + v = s.scrollUp(newbuf, n, top, bot, top, bot, blank) + s.buf.WriteString(ansi.SetTopBottomMargins(1, maxY+1)) + s.cur.X, s.cur.Y = -1, -1 + } + + if !v { + v = s.scrollIdl(newbuf, n, top, bot-n+1, blank) + } + } else if n < 0 { + // Scroll down (backward) + v = s.scrollDown(newbuf, -n, top, bot, 0, maxY, blank) + if !v { + s.buf.WriteString(ansi.SetTopBottomMargins(top+1, bot+1)) + + // XXX: How should we handle this in inline mode when not using alternate screen? + s.cur.X, s.cur.Y = -1, -1 + v = s.scrollDown(newbuf, -n, top, bot, top, bot, blank) + s.buf.WriteString(ansi.SetTopBottomMargins(1, maxY+1)) + s.cur.X, s.cur.Y = -1, -1 + + if !v { + v = s.scrollIdl(newbuf, -n, bot+n+1, top, blank) + } + } + } + + if !v { + return false + } + + s.scrollBuffer(s.curbuf, n, top, bot, blank) + + // Every row in the range moved, whether or not the application drew into + // it. A row the scroll already put in the right place costs a comparison + // and no output, which is the whole point of scrolling in hardware. + s.damage(top, bot-top+1) + + // shift hash values too, they can be reused + s.scrollOldhash(n, top, bot) + + return true +} + +// scrollBuffer scrolls the buffer by n lines. +func (s *TerminalRenderer) scrollBuffer(b *RenderBuffer, n, top, bot int, blank *Cell) { + if top < 0 || bot < top || bot >= b.Height() { + // Nothing to scroll + return + } + + if n < 0 { + // shift n lines downwards + limit := top - n + for line := bot; line >= limit && line >= 0 && line >= top; line-- { + copy(b.Lines[line], b.Lines[line+n]) + } + for line := top; line < limit && line <= b.Height()-1 && line <= bot; line++ { + b.FillArea(blank, Rect(0, line, b.Width(), 1)) + } + } + + if n > 0 { + // shift n lines upwards + limit := bot - n + for line := top; line <= limit && line <= b.Height()-1 && line <= bot; line++ { + copy(b.Lines[line], b.Lines[line+n]) + } + for line := bot; line > limit && line >= 0 && line >= top; line-- { + b.FillArea(blank, Rect(0, line, b.Width(), 1)) + } + } +} + +// scrollUp scrolls the screen up by n lines. +func (s *TerminalRenderer) scrollUp(newbuf *RenderBuffer, n, top, bot, minY, maxY int, blank *Cell) bool { + if n == 1 && top == minY && bot == maxY { //nolint:nestif + s.move(newbuf, 0, bot) + s.updatePen(blank) + s.buf.WriteByte('\n') + } else if n == 1 && bot == maxY { + s.move(newbuf, 0, top) + s.updatePen(blank) + s.buf.WriteString(ansi.DeleteLine(1)) + } else if top == minY && bot == maxY { + supportsSU := s.caps.Contains(capSU) + s.move(newbuf, 0, bot) + s.updatePen(blank) + if supportsSU { + s.buf.WriteString(ansi.ScrollUp(n)) + } else { + s.buf.WriteString(strings.Repeat("\n", n)) + } + } else if bot == maxY { + s.move(newbuf, 0, top) + s.updatePen(blank) + s.buf.WriteString(ansi.DeleteLine(n)) + } else { + return false + } + return true +} + +// scrollDown scrolls the screen down by n lines. +func (s *TerminalRenderer) scrollDown(newbuf *RenderBuffer, n, top, bot, minY, maxY int, blank *Cell) bool { + if n == 1 && top == minY && bot == maxY { //nolint:nestif + s.move(newbuf, 0, top) + s.updatePen(blank) + s.buf.WriteString(ansi.ReverseIndex) + } else if n == 1 && bot == maxY { + s.move(newbuf, 0, top) + s.updatePen(blank) + s.buf.WriteString(ansi.InsertLine(1)) + } else if top == minY && bot == maxY { + s.move(newbuf, 0, top) + s.updatePen(blank) + if s.caps.Contains(capSD) { + s.buf.WriteString(ansi.ScrollDown(n)) + } else { + s.buf.WriteString(strings.Repeat(ansi.ReverseIndex, n)) + } + } else if bot == maxY { + s.move(newbuf, 0, top) + s.updatePen(blank) + s.buf.WriteString(ansi.InsertLine(n)) + } else { + return false + } + return true +} + +// scrollIdl scrolls the screen n lines by using [ansi.DL] at del and using +// [ansi.IL] at ins. +func (s *TerminalRenderer) scrollIdl(newbuf *RenderBuffer, n, del, ins int, blank *Cell) bool { + if n < 0 { + return false + } + + // Delete lines + s.move(newbuf, 0, del) + s.updatePen(blank) + s.buf.WriteString(ansi.DeleteLine(n)) + + // Insert lines + s.move(newbuf, 0, ins) + s.updatePen(blank) + s.buf.WriteString(ansi.InsertLine(n)) + + return true +} diff --git a/cli/third_party/ultraviolet/terminal_renderer_hashmap.go b/cli/third_party/ultraviolet/terminal_renderer_hashmap.go new file mode 100644 index 000000000..57822b95a --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_renderer_hashmap.go @@ -0,0 +1,298 @@ +package uv + +import "hash/maphash" + +// hash returns the hash value of a [Line]. +func hash(h *maphash.Hash, l Line) uint64 { + h.Reset() + for _, c := range l { + // maphash writes can not fail + _, _ = h.WriteString(c.Content) + } + + return h.Sum64() +} + +// hashmap represents a single [Line] hash. +type hashmap struct { + value uint64 + oldcount, newcount int + oldindex, newindex int +} + +// The value used to indicate lines created by insertions and scrolls. +const newIndex = -1 + +// updateHashmap updates the hashmap with the new hash value. +func (s *TerminalRenderer) updateHashmap(newbuf *RenderBuffer) { + height := newbuf.Height() + + if len(s.oldhash) >= height && len(s.newhash) >= height { + // rehash changed lines + for i := range height { + if newbuf.Touched[i] != nil { + // TODO: Investigate why this is needed. If we remove this + // line, scroll optimization does not work correctly. This + // should happen else where. + s.oldhash[i] = hash(&s.hasher, s.curbuf.Line(i)) + s.newhash[i] = hash(&s.hasher, newbuf.Line(i)) + } + } + } else { + // rehash all + if len(s.oldhash) != height { + s.oldhash = make([]uint64, height) + } + if len(s.newhash) != height { + s.newhash = make([]uint64, height) + } + for i := range height { + s.oldhash[i] = hash(&s.hasher, s.curbuf.Line(i)) + s.newhash[i] = hash(&s.hasher, newbuf.Line(i)) + } + } + + s.hashtab = make([]hashmap, (height+1)*2) + for i := range height { + hashval := s.oldhash[i] + + // Find matching hash or empty slot + var idx int + for idx = 0; idx < len(s.hashtab) && s.hashtab[idx].value != 0; idx++ { + if s.hashtab[idx].value == hashval { + break + } + } + + s.hashtab[idx].value = hashval // in case this is a new hash + s.hashtab[idx].oldcount++ + s.hashtab[idx].oldindex = i + } + for i := range height { + hashval := s.newhash[i] + + // Find matching hash or empty slot + var idx int + for idx = 0; idx < len(s.hashtab) && s.hashtab[idx].value != 0; idx++ { + if s.hashtab[idx].value == hashval { + break + } + } + + s.hashtab[idx].value = hashval // in case this is a new hash + s.hashtab[idx].newcount++ + s.hashtab[idx].newindex = i + s.oldnum[i] = newIndex // init old indices slice + } + + // Mark line pair corresponding to unique hash pairs. + for i := 0; i < len(s.hashtab) && s.hashtab[i].value != 0; i++ { + hsp := &s.hashtab[i] + if hsp.oldcount == 1 && hsp.newcount == 1 && hsp.oldindex != hsp.newindex { + s.oldnum[hsp.newindex] = hsp.oldindex + } + } + + s.growHunks(newbuf) + + // Eliminate bad or impossible shifts. This includes removing those hunks + // which could not grow because of conflicts, as well those which are to be + // moved too far, they are likely to destroy more than carry. + for i := 0; i < height; { + var start, shift, size int + for i < height && s.oldnum[i] == newIndex { + i++ + } + if i >= height { + break + } + start = i + shift = s.oldnum[i] - i + i++ + for i < height && s.oldnum[i] != newIndex && s.oldnum[i]-i == shift { + i++ + } + size = i - start + if size < 3 || size+min(size/8, 2) < abs(shift) { + for start < i { + s.oldnum[start] = newIndex + start++ + } + } + } + + // After clearing invalid hunks, try grow the rest. + s.growHunks(newbuf) +} + +// scrollOldhash scrolls the oldhash slice by 'n' lines between 'top' and 'bot'. +func (s *TerminalRenderer) scrollOldhash(n, top, bot int) { + if len(s.oldhash) == 0 { + return + } + + size := bot - top + 1 - abs(n) + if n > 0 { + // Move existing hashes up + copy(s.oldhash[top:], s.oldhash[top+n:top+n+size]) + // Recalculate hashes for newly shifted-in lines + for i := bot; i > bot-n; i-- { + s.oldhash[i] = hash(&s.hasher, s.curbuf.Line(i)) + } + } else { + // Move existing hashes down + copy(s.oldhash[top-n:], s.oldhash[top:top+size]) + // Recalculate hashes for newly shifted-in lines + for i := top; i < top-n; i++ { + s.oldhash[i] = hash(&s.hasher, s.curbuf.Line(i)) + } + } +} + +func (s *TerminalRenderer) growHunks(newbuf *RenderBuffer) { + var ( + backLimit int // limits for cells to fill + backRefLimit int // limit for references + i int + nextHunk int + ) + + height := newbuf.Height() + for i < height && s.oldnum[i] == newIndex { + i++ + } + for ; i < height; i = nextHunk { + var ( + forwardLimit int + forwardRefLimit int + end int + start = i + shift = s.oldnum[i] - i + ) + + // get forward limit + i = start + 1 + for i < height && + s.oldnum[i] != newIndex && + s.oldnum[i]-i == shift { + i++ + } + + end = i + for i < height && s.oldnum[i] == newIndex { + i++ + } + + nextHunk = i + forwardLimit = i + if i >= height || s.oldnum[i] >= i { + forwardRefLimit = i + } else { + forwardRefLimit = s.oldnum[i] + } + + i = start - 1 + + // grow back + if shift < 0 { + backLimit = backRefLimit + (-shift) + } + for i >= backLimit { + if s.newhash[i] == s.oldhash[i+shift] || + s.costEffective(newbuf, i+shift, i, shift < 0) { + s.oldnum[i] = i + shift + } else { + break + } + i-- + } + + i = end + // grow forward + if shift > 0 { + forwardLimit = forwardRefLimit - shift + } + for i < forwardLimit { + if s.newhash[i] == s.oldhash[i+shift] || + s.costEffective(newbuf, i+shift, i, shift > 0) { + s.oldnum[i] = i + shift + } else { + break + } + i++ + } + + backLimit = i + backRefLimit = backLimit + if shift > 0 { + backRefLimit += shift + } + } +} + +// costEffective returns true if the cost of moving line 'from' to line 'to' seems to be +// cost effective. 'blank' indicates whether the line 'to' would become blank. +func (s *TerminalRenderer) costEffective(newbuf *RenderBuffer, from, to int, blank bool) bool { + if from == to { + return false + } + + newFrom := s.oldnum[from] + if newFrom == newIndex { + newFrom = from + } + + // On the left side of >= is the cost before moving. On the right side -- + // cost after moving. + + // Calculate costs before moving. + var costBeforeMove int + if blank { + // Cost of updating blank line at destination. + costBeforeMove = s.updateCostBlank(newbuf, newbuf.Line(to)) + } else { + // Cost of updating exiting line at destination. + costBeforeMove = s.updateCost(newbuf, s.curbuf.Line(to), newbuf.Line(to)) + } + + // Add cost of updating source line + costBeforeMove += s.updateCost(newbuf, s.curbuf.Line(newFrom), newbuf.Line(from)) + + // Calculate costs after moving. + var costAfterMove int + if newFrom == from { + // Source becomes blank after move + costAfterMove = s.updateCostBlank(newbuf, newbuf.Line(from)) + } else { + // Source gets updated from another line + costAfterMove = s.updateCost(newbuf, s.curbuf.Line(newFrom), newbuf.Line(from)) + } + + // Add cost of moving source line to destination + costAfterMove += s.updateCost(newbuf, s.curbuf.Line(from), newbuf.Line(to)) + + // Return true if moving is cost effective (costs less or equal) + return costBeforeMove >= costAfterMove +} + +func (s *TerminalRenderer) updateCost(_ *RenderBuffer, from, to Line) (cost int) { + var fidx, tidx int + for i := s.curbuf.Width(); i > 0; i, fidx, tidx = i-1, fidx+1, tidx+1 { + if !cellEqual(from.At(fidx), to.At(tidx)) { + cost++ + } + } + return +} + +func (s *TerminalRenderer) updateCostBlank(_ *RenderBuffer, to Line) (cost int) { + // This assumes bce capability. + blank := s.clearBlank() + var tidx int + for i := s.curbuf.Width(); i > 0; i, tidx = i-1, tidx+1 { + if !cellEqual(blank, to.At(tidx)) { + cost++ + } + } + return +} diff --git a/cli/third_party/ultraviolet/terminal_screen.go b/cli/third_party/ultraviolet/terminal_screen.go new file mode 100644 index 000000000..2c9af3b66 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_screen.go @@ -0,0 +1,836 @@ +package uv + +import ( + "bytes" + "image/color" + "io" + "log" + "os" + "strings" + "sync" + + "github.com/charmbracelet/colorprofile" + "github.com/charmbracelet/x/ansi" + "github.com/charmbracelet/x/term" +) + +// TerminalScreen represents a terminal screen, providing methods for managing +// the screen state and rendering content. +type TerminalScreen struct { + win *Window + w io.Writer + buf *bytes.Buffer + rend *TerminalRenderer + rbuf *RenderBuffer + env Environ + profile colorprofile.Profile + + // Terminal state + altScreen bool + keyboardEnhancements *KeyboardEnhancements + bracketedPaste bool + mouseMode MouseMode + mouseEncoding MouseEncoding + cursor *Cursor // initial state is cursor hidden + backgroundColor color.Color + foregroundColor color.Color + progressBar *ProgressBar + windowTitle string + syncUpdates bool // mode 2026 + resetTabs bool // DECST8C - reset terminal tabs on start + + // mu serializes access to the render buffer, output buffer, and + // width-method state so the terminal event loop (which negotiates + // grapheme-cluster width) cannot race with the application's own + // Render/Flush goroutine. + mu sync.Mutex + // widthMethodOverride is set when the application explicitly calls + // [TerminalScreen.SetWidthMethod]. An explicit override suppresses the + // automatic mode-2027 width-method negotiation. + widthMethodOverride bool +} + +var _ Screen = (*TerminalScreen)(nil) + +// NewTerminalScreen creates a new [TerminalScreen] with the given writer and environment. +func NewTerminalScreen(w io.Writer, env Environ) *TerminalScreen { + s := &TerminalScreen{} + s.buf = &bytes.Buffer{} + s.win = NewWindow(0, 0, nil) + s.w = w + s.profile = colorprofile.Detect(w, env) + s.rend = NewTerminalRenderer(s.buf, env) + s.rend.SetFullscreen(false) // by default, we start in inline mode + s.rend.SetRelativeCursor(true) // by default, we start in inline mode + s.rend.SetColorProfile(s.profile) + s.rbuf = NewRenderBuffer(0, 0) + s.env = env + + if debugFile := env.Getenv("UV_DEBUG"); debugFile != "" { + if f, err := os.OpenFile(debugFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644); err == nil { + log.SetOutput(f) + s.rend.SetLogger(log.Default()) + } + } + + // Configure renderer optimizations based on console settings. + f, ok := w.(term.File) + if ok { + state, err := term.GetState(f.Fd()) + if err == nil || isWindows { // Windows supports tabs and backspace by default, so we can ignore errors here. + useTabs, useBspace := optimizeMovements(state) + if useTabs { + s.rend.SetTabStops(0) // the width will be set after calling [TerminalScreen.Resize] + } else { + s.rend.SetTabStops(-1) + } + s.rend.SetBackspace(useBspace) + s.resetTabs = useTabs + } + } + // XXX: Do we still need map nl to crlf handling in the renderer? + s.rend.SetMapNewline(false) + return s +} + +// CellAt returns the cell at the specified x and y coordinates. +func (s *TerminalScreen) CellAt(x, y int) *Cell { + return s.win.CellAt(x, y) +} + +// SetCell sets the cell at the specified x and y coordinates. +func (s *TerminalScreen) SetCell(x, y int, cell *Cell) { + s.win.SetCell(x, y, cell) +} + +// Bounds returns the bounds of the terminal screen as a rectangle. +func (s *TerminalScreen) Bounds() Rectangle { + return s.win.Bounds() +} + +// Width returns the width of the terminal screen. +// +// Note that this is not the actual width of the terminal window, but rather +// the width of the screen we're managing. The actual width of the terminal +// window can be obtained using [Terminal.GetSize] or by reading the "COLUMNS" +// environment variable. +func (s *TerminalScreen) Width() int { + return s.win.Width() +} + +// Height returns the height of the terminal screen. +// +// Note that this is not the actual height of the terminal window, but rather +// the height of the screen we're managing. The actual height of the terminal +// window can be obtained using [Terminal.GetSize] or by reading the "LINES" +// environment variable. +func (s *TerminalScreen) Height() int { + return s.win.Height() +} + +// StringWidth returns the cell width of the given string using the terminal +// screen's width method. This accounts for the configured [WidthMethod] +// (e.g. wcwidth vs grapheme width) so callers don't need to import ansi +// directly. +func (s *TerminalScreen) StringWidth(str string) int { + return s.win.WidthMethod().StringWidth(str) +} + +// WidthMethod returns the width method used by the terminal screen. +func (s *TerminalScreen) WidthMethod() WidthMethod { + return s.win.WidthMethod() +} + +// SetWidthMethod sets the width method for the terminal screen. This is an +// override that propagates to the window/buffer and the renderer so that all +// width measurements use the same method. Calling this marks the width method +// as explicitly overridden, which disables automatic mode-2027 negotiation. +func (s *TerminalScreen) SetWidthMethod(method ansi.Method) { + s.mu.Lock() + defer s.mu.Unlock() + s.widthMethodOverride = true + s.setWidthMethod(method) +} + +// setWidthMethod propagates the width method to the window/buffer and the +// renderer. Callers must hold s.mu. +func (s *TerminalScreen) setWidthMethod(method ansi.Method) { + s.win.SetWidthMethod(method) + s.rend.SetWidthMethod(method) +} + +// requestGraphemeWidth queues a DECRQM request for Unicode core mode (DEC mode +// 2027) so the terminal reports whether it measures cell width using grapheme +// clustering. The response arrives as a [ModeReportEvent]. +func (s *TerminalScreen) requestGraphemeWidth() { + s.mu.Lock() + defer s.mu.Unlock() + s.buf.WriteString(ansi.RequestMode(ansi.ModeUnicodeCore)) +} + +// enableGraphemeWidth enables Unicode core mode (DEC mode 2027) on the terminal +// and switches the screen's width method to [ansi.GraphemeWidth] so wide-glyph +// measurement matches the terminal. The change propagates to the +// window/buffer and renderer. +// +// If the application has explicitly set a width method via +// [TerminalScreen.SetWidthMethod], the explicit choice is preserved and this is +// a no-op. The change is committed to the underlying writer through the +// screen's normal locked write path so it cannot race with Render/Flush. +func (s *TerminalScreen) enableGraphemeWidth() { + s.mu.Lock() + if s.widthMethodOverride { + s.mu.Unlock() + return + } + s.buf.WriteString(ansi.SetMode(ansi.ModeUnicodeCore)) + s.setWidthMethod(ansi.GraphemeWidth) + s.rend.SetGraphemeWidth(true) + s.mu.Unlock() + _ = s.Flush() +} + +// SetColorProfile sets the color profile for the terminal screen. +// This is automatically detected when creating the terminal screen. However, +// you can override it using this method. +func (s *TerminalScreen) SetColorProfile(profile colorprofile.Profile) { + s.profile = profile + s.rend.SetColorProfile(profile) +} + +// Resize resizes the terminal screen to the specified width and height, +// updating the render buffer and renderer accordingly. +func (s *TerminalScreen) Resize(width, height int) { + s.win.Resize(width, height) + s.rbuf.Resize(width, height) + s.rend.Resize(width, height) + s.rend.Erase() +} + +// Display clears the screen and draws the given [Drawable] onto the terminal +// screen and flushes the changes to the underlying writer. +// +// This is a convenience method that combines [TerminalScreen.Render] and +// [TerminalScreen.Flush]. +func (s *TerminalScreen) Display(d Drawable) error { + if d != nil { + s.win.Clear() + d.Draw(s, s.win.Bounds()) + } + s.Render() + return s.Flush() +} + +// Render renders changes that transform the screen from its current state to +// the state represented by the [TerminalScreen]. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) Render() { + s.mu.Lock() + defer s.mu.Unlock() + for y := 0; y < s.win.Height(); y++ { + for x := 0; x < s.win.Width(); { + cell := s.win.CellAt(x, y) + if cell == nil || cell.IsZero() { + x++ + continue + } + s.rbuf.SetCell(x, y, cell) + width := cell.Width + if width <= 0 { + width = 1 + } + x += width + } + } + s.rend.Render(s.rbuf) + _ = s.rend.Flush() +} + +// Flush writes any pending output to the underlying writer. +func (s *TerminalScreen) Flush() error { + s.mu.Lock() + defer s.mu.Unlock() + if s.cursor != nil && !s.cursor.Hidden && s.cursor.X >= 0 && s.cursor.Y >= 0 { + s.rend.MoveTo(s.cursor.X, s.cursor.Y) + } else if !s.altScreen { + // We don't want the cursor to be dangling at the end of the line in + // inline mode because it can cause unwanted line wraps in some + // terminals. So we move it to the beginning of the next line if + // necessary. + // This is only needed when the cursor is hidden because when it's + // visible, we already set its position above. + x, y := s.rend.Position() + if x >= s.win.Width()-1 { + s.rend.MoveTo(0, y) + } + } + + var buf bytes.Buffer + buf.Grow(s.buf.Len()) + + if s.buf.Len() > 0 { + if s.syncUpdates { + buf.Grow(len(ansi.SetModeSynchronizedOutput) + len(ansi.ResetModeSynchronizedOutput)) + + // If synchronized updates are enabled, we need to wrap the output in + // the appropriate control sequences to ensure that the terminal treats + // it as a single atomic update. This is necessary to prevent flickering + // and other visual artifacts that can occur when multiple updates are sent + // separately. + buf.WriteString(ansi.SetModeSynchronizedOutput) + } else if s.cursor != nil && !s.cursor.Hidden { + buf.Grow(len(ansi.HideCursor) + len(ansi.ShowCursor)) + + // If synchronized updates are not enabled, we need to ensure that + // the cursor is hidden before writing any output to prevent + // unwanted cursor visual artifacts. + buf.WriteString(ansi.HideCursor) + } + + buf.Write(s.buf.Bytes()) + + if s.syncUpdates { + buf.WriteString(ansi.ResetModeSynchronizedOutput) + } else if s.cursor != nil && !s.cursor.Hidden { + buf.WriteString(ansi.ShowCursor) + } + } + + _, err := s.w.Write(buf.Bytes()) + if err != nil { + return err + } + s.buf.Reset() + return nil +} + +// EnterAltScreen switches the terminal to the alternate screen buffer, allowing +// applications to use a separate screen for their output without affecting the +// main screen. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) EnterAltScreen() { + var sb strings.Builder + sb.WriteString(ansi.SetModeAltScreenSaveCursor) + if s.cursor == nil || s.cursor.Hidden { + sb.WriteString(ansi.HideCursor) + } else if s.cursor != nil && !s.cursor.Hidden { + sb.WriteString(ansi.ShowCursor) + } + if s.keyboardEnhancements != nil { + EncodeKeyboardEnhancements(&sb, s.keyboardEnhancements) + } + s.buf.WriteString(sb.String()) + + if !s.altScreen { + s.rend.SaveCursor() + s.rend.Erase() + s.rend.SetFullscreen(true) + s.rend.SetRelativeCursor(false) + s.altScreen = true + } +} + +// ExitAltScreen switches the terminal back to the main screen buffer, restoring +// the previous screen state. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) ExitAltScreen() { + var sb strings.Builder + sb.WriteString(ansi.ResetModeAltScreenSaveCursor) + if s.cursor == nil || s.cursor.Hidden { + sb.WriteString(ansi.HideCursor) + } else if s.cursor != nil && !s.cursor.Hidden { + sb.WriteString(ansi.ShowCursor) + } + if s.keyboardEnhancements != nil { + EncodeKeyboardEnhancements(&sb, s.keyboardEnhancements) + } + s.buf.WriteString(sb.String()) + + if s.altScreen { + s.rend.RestoreCursor() + s.rend.Erase() + s.rend.SetFullscreen(false) + s.rend.SetRelativeCursor(true) + s.altScreen = false + } +} + +// AltScreen returns whether the terminal is currently in the alternate screen +// buffer. +func (s *TerminalScreen) AltScreen() bool { + return s.altScreen +} + +// HideCursor hides the terminal cursor. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) HideCursor() { + s.buf.WriteString(ansi.HideCursor) + if s.cursor != nil { + s.cursor.Hidden = true + } +} + +// ShowCursor shows the terminal cursor. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) ShowCursor() { + s.buf.WriteString(ansi.ShowCursor) + if s.cursor != nil { + s.cursor.Hidden = false + } else { + s.cursor = NewCursor(-1, -1) + } +} + +// CursorVisible returns whether the terminal cursor is currently visible. +func (s *TerminalScreen) CursorVisible() bool { + return s.cursor != nil && !s.cursor.Hidden +} + +// SetCursorPosition sets the position of the terminal cursor to the specified +// coordinates. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetCursorPosition(x, y int) { + if s.cursor == nil { + s.cursor = NewCursor(x, y) + s.cursor.Hidden = true + } else { + s.cursor.X = x + s.cursor.Y = y + } +} + +// CursorPosition returns the last set cursor position of the terminal. If the +// cursor position is not set, it returns (-1, -1). +// +// This can be affected by [TerminalScreen.Render] and +// [TerminalScreen.SetCursorPosition] calls. +func (s *TerminalScreen) CursorPosition() (x, y int) { + if s.cursor != nil { + return s.cursor.X, s.cursor.Y + } + return -1, -1 +} + +// SetCursorStyle sets the style of the terminal cursor. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetCursorStyle(shape CursorShape, blink bool) { + EncodeCursorStyle(s.buf, shape, blink) + if s.cursor == nil { + s.cursor = NewCursor(-1, -1) + } + s.cursor.Shape = shape + s.cursor.Blink = blink +} + +// CursorStyle returns the current style of the terminal cursor. +func (s *TerminalScreen) CursorStyle() (shape CursorShape, blink bool) { + if s.cursor != nil { + return s.cursor.Shape, s.cursor.Blink + } + return CursorBlock, true +} + +// SetCursorColor sets the color of the terminal cursor. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetCursorColor(c color.Color) { + EncodeCursorColor(s.buf, c) + if s.cursor == nil { + s.cursor = NewCursor(-1, -1) + } + s.cursor.Color = c +} + +// CursorColor returns the current color of the terminal cursor. +// +// A nil color indicates that the cursor color is the default terminal cursor +// color. +func (s *TerminalScreen) CursorColor() color.Color { + if s.cursor != nil { + return s.cursor.Color + } + return nil +} + +// SetBackgroundColor sets the background color of the terminal. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetBackgroundColor(c color.Color) { + EncodeBackgroundColor(s.buf, c) + s.backgroundColor = c +} + +// BackgroundColor returns the current background color of the terminal. +// +// A nil color indicates that the background color is the default terminal +// background color. +func (s *TerminalScreen) BackgroundColor() color.Color { + return s.backgroundColor +} + +// SetForegroundColor sets the foreground color of the terminal. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetForegroundColor(c color.Color) { + EncodeForegroundColor(s.buf, c) + s.foregroundColor = c +} + +// ForegroundColor returns the current foreground color of the terminal. +// +// A nil color indicates that the foreground color is the default terminal +// foreground color. +func (s *TerminalScreen) ForegroundColor() color.Color { + return s.foregroundColor +} + +// EnableBracketedPaste enables bracketed paste mode, allowing the terminal to +// distinguish between pasted content and user input. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) EnableBracketedPaste() { + s.buf.WriteString(ansi.SetModeBracketedPaste) + s.bracketedPaste = true +} + +// DisableBracketedPaste disables bracketed paste mode. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) DisableBracketedPaste() { + s.buf.WriteString(ansi.ResetModeBracketedPaste) + s.bracketedPaste = false +} + +// BracketedPaste returns whether bracketed paste mode is currently enabled. +func (s *TerminalScreen) BracketedPaste() bool { + return s.bracketedPaste +} + +// SetSynchronizedUpdates sets whether to use synchronized updates (mode 2026), +// which allows applications to batch updates to the terminal screen and flush +// them all at once for improved performance. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetSynchronizedUpdates(enabled bool) { + s.syncUpdates = enabled +} + +// SynchronizedUpdates returns whether synchronized updates (mode 2026) are +// currently enabled. +func (s *TerminalScreen) SynchronizedUpdates() bool { + return s.syncUpdates +} + +// SetMouseMode sets the mouse tracking mode for the terminal, allowing +// applications to receive mouse events. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetMouseMode(mode MouseMode) { + EncodeMouseMode(s.buf, mode) + s.mouseMode = mode +} + +// MouseMode returns the current mouse tracking mode of the terminal. +func (s *TerminalScreen) MouseMode() MouseMode { + return s.mouseMode +} + +// SetMouseEncoding sets the mouse encoding for the terminal. +// The encoding determines how mouse coordinates and buttons are reported. +// This is only meaningful when mouse tracking is enabled via [TerminalScreen.SetMouseMode]. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetMouseEncoding(enc MouseEncoding) { + EncodeMouseEncoding(s.buf, enc) + s.mouseEncoding = enc +} + +// MouseEncoding returns the current mouse encoding of the terminal. +func (s *TerminalScreen) MouseEncoding() MouseEncoding { + return s.mouseEncoding +} + +// SetWindowTitle sets the title of the terminal window. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetWindowTitle(title string) { + EncodeWindowTitle(s.buf, title) + s.windowTitle = title +} + +// WindowTitle returns the current title of the terminal window. +func (s *TerminalScreen) WindowTitle() string { + return s.windowTitle +} + +// SetKeyboardEnhancements sets the keyboard enhancements for the terminal, +// allowing applications to receive enhanced keyboard input. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetKeyboardEnhancements(enh *KeyboardEnhancements) { + EncodeKeyboardEnhancements(s.buf, enh) + s.keyboardEnhancements = enh +} + +// KeyboardEnhancements returns the current keyboard enhancements of the terminal. +// +// A nil value indicates that no keyboard enhancements are currently enabled. +func (s *TerminalScreen) KeyboardEnhancements() *KeyboardEnhancements { + return s.keyboardEnhancements +} + +// SetProgressBar sets the progress bar for the terminal, allowing applications +// to display progress information. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) SetProgressBar(pb *ProgressBar) { + EncodeProgressBar(s.buf, pb) + s.progressBar = pb +} + +// ProgressBar returns the current progress bar of the terminal. +// +// A nil value indicates that no progress bar is currently set. +func (s *TerminalScreen) ProgressBar() *ProgressBar { + return s.progressBar +} + +// Reset resets the terminal screen to its default state, clearing the screen, +// switching back to the main screen buffer if necessary, and resetting all +// terminal settings to their defaults. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) Reset() { + var sb strings.Builder + + hasKeyboardEnhancements := s.keyboardEnhancements != nil + + if s.altScreen { + if hasKeyboardEnhancements { + sb.WriteString(ansi.KittyKeyboard(0, 1)) + } + sb.WriteString(ansi.ResetModeAltScreenSaveCursor) + } + if hasKeyboardEnhancements { + sb.WriteString(ansi.KittyKeyboard(0, 1)) + } + if s.mouseMode != MouseModeNone { + EncodeMouseMode(&sb, MouseModeNone) + } + if s.mouseEncoding != MouseEncodingLegacy { + EncodeMouseEncoding(&sb, MouseEncodingLegacy) + } + + if s.cursor == nil || !s.cursor.Hidden { + sb.WriteString(ansi.ShowCursor) + } + if s.cursor != nil { + if s.cursor.Shape != CursorBlock || !s.cursor.Blink { + sb.WriteString(ansi.SetCursorStyle(0)) + } + if s.cursor.Color != nil { + sb.WriteString(ansi.ResetCursorColor) + } + } + if s.backgroundColor != nil { + sb.WriteString(ansi.ResetBackgroundColor) + } + if s.foregroundColor != nil { + sb.WriteString(ansi.ResetForegroundColor) + } + if s.bracketedPaste { + sb.WriteString(ansi.ResetModeBracketedPaste) + } + if s.windowTitle != "" { + sb.WriteString(ansi.SetWindowTitle("")) + } + if s.progressBar != nil && s.progressBar.State != ProgressBarNone { + sb.WriteString(ansi.ResetProgressBar) + } + + s.buf.WriteString(sb.String()) + + // Go to the bottom of the screen. + // We need to go to the bottom of the screen regardless of whether + // we're in alt screen mode or not to avoid leaving the cursor in the + // middle in terminals that don't support alt screen mode. + // + // This comes after resetting the screen state to ensure that moving the + // cursor is the last thing we do, preventing any unwanted cursor movements + // after resetting the screen. + // + // Note that both [TerminalScreen.rend] writes to [TerminalScreen.buf]. + s.rend.MoveTo(0, s.win.Height()-1) +} + +// Restore restores the terminal screen to its previous state, applying any +// previous settings and state that were reset by the [TerminalScreen.Reset] method. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) Restore() { + var sb strings.Builder + + if s.resetTabs { + sb.WriteString(ansi.SetTabEvery8Columns) + } + if s.altScreen { + sb.WriteString(ansi.SetModeAltScreenSaveCursor) + } + if s.cursor != nil && !s.cursor.Hidden { + sb.WriteString(ansi.ShowCursor) + } else { + // Hide the cursor by default. + sb.WriteString(ansi.HideCursor) + } + if s.keyboardEnhancements != nil { + EncodeKeyboardEnhancements(&sb, s.keyboardEnhancements) + } + if s.mouseMode != MouseModeNone { + EncodeMouseMode(&sb, s.mouseMode) + } + if s.mouseEncoding != MouseEncodingLegacy { + EncodeMouseEncoding(&sb, s.mouseEncoding) + } + if s.cursor != nil { + if s.cursor.Shape != CursorBlock || !s.cursor.Blink { + EncodeCursorStyle(&sb, s.cursor.Shape, s.cursor.Blink) + } + if s.cursor.Color != nil { + EncodeCursorColor(&sb, s.cursor.Color) + } + } + if s.backgroundColor != nil { + EncodeBackgroundColor(&sb, s.backgroundColor) + } + if s.foregroundColor != nil { + EncodeForegroundColor(&sb, s.foregroundColor) + } + if s.bracketedPaste { + sb.WriteString(ansi.SetModeBracketedPaste) + } + if s.windowTitle != "" { + EncodeWindowTitle(&sb, s.windowTitle) + } + if s.progressBar != nil && s.progressBar.State != ProgressBarNone { + EncodeProgressBar(&sb, s.progressBar) + } + + s.buf.WriteString(sb.String()) + + // This needs to be called after restoring the screen state and writing to + // the buffer. + // + // [TerminalScreen.Render] will write to [TerminalScreen.buf], so we need + // to call it after writing the restore commands to the buffer to ensure + // that the restore commands are included in the render output. This + // ensures that the screen is properly restored before rendering any + // changes. + s.Render() + + // Cursor position will be restored by the caller after calling + // [TerminalScreen.Flush]. +} + +// Write writes data to the underlying buffer queuing it for output. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) Write(p []byte) (n int, err error) { + return s.buf.Write(p) +} + +// WriteString writes a string to the underlying buffer queuing it for output. +// +// The changes can be committed to the underlying writer by calling the +// [TerminalScreen.Flush] method. +func (s *TerminalScreen) WriteString(str string) (n int, err error) { + return s.buf.WriteString(str) +} + +// InsertAbove inserts content above the screen pushing the current content +// down. +// +// This is useful for inserting content above the current screen content +// without affecting the current cursor position or screen state. +// +// Note that this won't have any visible effect if the screen is in alt screen +// mode, as the content will be inserted above the alt screen buffer, which is +// not visible. However, if the screen is in inline mode, the content will be +// inserted above and will not be managed by the renderer. +// +// Unlike other methods that modify the screen state, this method writes +// directly to the underlying writer, so there is no need to call +// [TerminalScreen.Flush] after calling this method. +func (s *TerminalScreen) InsertAbove(content string) error { + if len(content) == 0 { + return nil + } + + var sb strings.Builder + w, h := s.win.Width(), s.win.Height() + _, y := s.rend.Position() + + // We need to scroll the screen up by the number of lines in the queue. + sb.WriteByte('\r') + down := h - y - 1 + if down > 0 { + sb.WriteString(ansi.CursorDown(down)) + } + + lines := strings.Split(content, "\n") + offset := len(lines) + for _, line := range lines { + lineWidth := s.win.WidthMethod().StringWidth(line) + if w > 0 && lineWidth > w { + offset += (lineWidth / w) + } + } + + // Scroll the screen up by the offset to make room for the new lines. + sb.WriteString(strings.Repeat("\n", offset)) + + // XXX: Now go to the top of the screen, insert new lines, and write + // the queued strings. It is important to use [Screen.moveCursor] + // instead of [Screen.move] because we don't want to perform any checks + // on the cursor position. + up := offset + h - 1 + sb.WriteString(ansi.CursorUp(up)) + sb.WriteString(ansi.InsertLine(offset)) + for _, line := range lines { + sb.WriteString(line) + sb.WriteString(ansi.EraseLineRight) + sb.WriteString("\r\n") + } + + s.rend.SetPosition(0, 0) + + _, err := io.WriteString(s.w, sb.String()) + return err +} diff --git a/cli/third_party/ultraviolet/terminal_tabdly.go b/cli/third_party/ultraviolet/terminal_tabdly.go new file mode 100644 index 000000000..52c47a225 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_tabdly.go @@ -0,0 +1,10 @@ +//go:build darwin || linux || freebsd || solaris || aix +// +build darwin linux freebsd solaris aix + +package uv + +import "golang.org/x/sys/unix" + +func supportsHardTabs(oflag uint64) bool { + return oflag&unix.TABDLY == unix.TAB0 +} diff --git a/cli/third_party/ultraviolet/terminal_tabdly_other.go b/cli/third_party/ultraviolet/terminal_tabdly_other.go new file mode 100644 index 000000000..30b1914c6 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_tabdly_other.go @@ -0,0 +1,8 @@ +//go:build !darwin && !linux && !freebsd && !solaris && !aix && !windows +// +build !darwin,!linux,!freebsd,!solaris,!aix,!windows + +package uv + +func supportsHardTabs(uint64) bool { + return false +} diff --git a/cli/third_party/ultraviolet/terminal_unix.go b/cli/third_party/ultraviolet/terminal_unix.go new file mode 100644 index 000000000..04ed3e3f6 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_unix.go @@ -0,0 +1,56 @@ +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix +// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix + +package uv + +import ( + "github.com/charmbracelet/x/term" + "github.com/charmbracelet/x/termios" +) + +func makeRaw(inTty, outTty term.File) (inTtyState, outTtyState *term.State, err error) { + if inTty == nil && outTty == nil { + return nil, nil, ErrNotTerminal + } + + // Check if we have a terminal. + for _, f := range []term.File{inTty, outTty} { + if f == nil { + continue + } + inTtyState, err = term.MakeRaw(f.Fd()) + if err == nil { + break + } + } + + if err != nil { + return nil, nil, err //nolint:wrapcheck + } + + return inTtyState, outTtyState, nil +} + +func getWinsize(inTty, outTty term.File) (ws Winsize, err error) { + // Try both inTty and outTty to get the size. + err = ErrNotTerminal + for _, f := range []term.File{inTty, outTty} { + if f == nil { + continue + } + size, err := termios.GetWinsize(int(f.Fd())) + if err == nil { + return Winsize(*size), nil + } + } + return +} + +func getSize(inTty, outTty term.File) (w, h int, err error) { + ws, err := getWinsize(inTty, outTty) + return int(ws.Col), int(ws.Row), err +} + +func optimizeMovements(state *term.State) (useTabs, useBspace bool) { + return supportsHardTabs(uint64(state.Oflag)), supportsBackspace(uint64(state.Lflag)) //nolint:unconvert,nolintlint +} diff --git a/cli/third_party/ultraviolet/terminal_windows.go b/cli/third_party/ultraviolet/terminal_windows.go new file mode 100644 index 000000000..a899ba486 --- /dev/null +++ b/cli/third_party/ultraviolet/terminal_windows.go @@ -0,0 +1,77 @@ +//go:build windows +// +build windows + +package uv + +import ( + "fmt" + + "github.com/charmbracelet/x/term" + "golang.org/x/sys/windows" +) + +func makeRaw(inTty, outTty term.File) (inTtyState, outTtyState *term.State, err error) { + if inTty == nil || outTty == nil || !term.IsTerminal(inTty.Fd()) || !term.IsTerminal(outTty.Fd()) { + return nil, nil, ErrNotTerminal + } + + // Save stdin state and enable VT inpu + // We also need to enable VT input here. + inTtyState, err = term.MakeRaw(inTty.Fd()) + if err != nil { + return nil, nil, fmt.Errorf("error making terminal raw: %w", err) + } + + // Enable VT input + var imode uint32 + if err := windows.GetConsoleMode(windows.Handle(inTty.Fd()), &imode); err != nil { + return nil, nil, fmt.Errorf("error getting console mode: %w", err) + } + + if err := windows.SetConsoleMode(windows.Handle(inTty.Fd()), imode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil { + return nil, nil, fmt.Errorf("error setting console mode: %w", err) + } + + // Save output screen buffer state and enable VT processing. + outTtyState, err = term.GetState(outTty.Fd()) + if err != nil { + return nil, nil, fmt.Errorf("error getting terminal state: %w", err) + } + + var omode uint32 + if err := windows.GetConsoleMode(windows.Handle(outTty.Fd()), &omode); err != nil { + return nil, nil, fmt.Errorf("error getting console mode: %w", err) + } + + if err := windows.SetConsoleMode(windows.Handle(outTty.Fd()), + omode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING| + windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { + return nil, nil, fmt.Errorf("error setting console mode: %w", err) + } + + return inTtyState, outTtyState, nil +} + +func getSize(_, outTty term.File) (w, h int, err error) { + if outTty != nil { + return term.GetSize(outTty.Fd()) //nolint:wrapcheck + } + return 0, 0, ErrNotTerminal +} + +func getWinsize(inTty, outTty term.File) (ws Winsize, err error) { + w, h, err := getSize(inTty, outTty) + return Winsize{Col: uint16(w), Row: uint16(h)}, err +} + +func optimizeMovements(*term.State) (useTabs, useBspace bool) { + return supportsBackspace(0), supportsHardTabs(0) +} + +func supportsBackspace(uint64) bool { + return true +} + +func supportsHardTabs(uint64) bool { + return true +} diff --git a/cli/third_party/ultraviolet/tty.go b/cli/third_party/ultraviolet/tty.go new file mode 100644 index 000000000..7e7bd9945 --- /dev/null +++ b/cli/third_party/ultraviolet/tty.go @@ -0,0 +1,42 @@ +package uv + +import ( + "context" + "os" +) + +// OpenTTY opens the terminal's input and output file descriptors. +// It returns the input and output files, or an error if the terminal is not +// available. +// +// This is useful for applications that need to interact with the terminal +// directly while piping or redirecting input/output. +func OpenTTY() (inTty, outTty *os.File, err error) { + return openTTY() +} + +// Suspend suspends the current process group. +func Suspend() error { + return suspend() +} + +// NotifyWinch sets up a channel to receive window size change signals and any +// other signals needed. This is a drop-in replacement for os/signal.Notify to +// ensure that SIGWINCH is included. +// +// On Windows, this will be a no-op for SIGWINCH, but other signals may still +// be handled. +func NotifyWinch(c chan os.Signal, sigs ...os.Signal) { + notifyWinch(c, sigs...) +} + +// NotifyWinchContext sets up a channel to receive window size change signals +// and any other signals needed, with context cancellation support. This is a +// drop-in replacement for os/signal.NotifyContext to ensure that SIGWINCH is +// included. +// +// On Windows, this will be a no-op for SIGWINCH, but other signals may still +// be handled. +func NotifyWinchContext(ctx context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc) { + return notifyWinchContext(ctx, sigs...) +} diff --git a/cli/third_party/ultraviolet/tty_other.go b/cli/third_party/ultraviolet/tty_other.go new file mode 100644 index 000000000..c4c986ce9 --- /dev/null +++ b/cli/third_party/ultraviolet/tty_other.go @@ -0,0 +1,26 @@ +//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris && !aix && !windows +// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris,!aix,!windows + +package uv + +import ( + "context" + "os" + "os/signal" +) + +func openTTY() (*os.File, *os.File, error) { + return nil, nil, ErrPlatformNotSupported +} + +func suspend() error { + return ErrPlatformNotSupported +} + +func notifyWinch(c chan os.Signal, sigs ...os.Signal) { + signal.Notify(c, sigs...) +} + +func notifyWinchContext(ctx context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc) { + return signal.NotifyContext(ctx, sigs...) +} diff --git a/cli/third_party/ultraviolet/tty_unix.go b/cli/third_party/ultraviolet/tty_unix.go new file mode 100644 index 000000000..328552cb1 --- /dev/null +++ b/cli/third_party/ultraviolet/tty_unix.go @@ -0,0 +1,39 @@ +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || aix +// +build darwin dragonfly freebsd linux netbsd openbsd solaris aix + +package uv + +import ( + "context" + "os" + "os/signal" + "syscall" + + "golang.org/x/sys/unix" +) + +func openTTY() (inTty, outTty *os.File, err error) { + f, err := os.OpenFile("/dev/tty", os.O_RDWR, 0) + if err != nil { + return nil, nil, err //nolint:wrapcheck + } + return f, f, nil +} + +func suspend() (err error) { + // Send SIGTSTP to the entire process group. + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGCONT) + err = syscall.Kill(0, syscall.SIGTSTP) + // blocks until a CONT happens... + <-c + return +} + +func notifyWinch(c chan os.Signal, sigs ...os.Signal) { + signal.Notify(c, append(sigs, unix.SIGWINCH)...) +} + +func notifyWinchContext(ctx context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc) { + return signal.NotifyContext(ctx, append(sigs, unix.SIGWINCH)...) +} diff --git a/cli/third_party/ultraviolet/tty_windows.go b/cli/third_party/ultraviolet/tty_windows.go new file mode 100644 index 000000000..4ad0ecb80 --- /dev/null +++ b/cli/third_party/ultraviolet/tty_windows.go @@ -0,0 +1,39 @@ +//go:build windows +// +build windows + +package uv + +import ( + "context" + "os" + "os/signal" +) + +func openTTY() (inTty, outTty *os.File, err error) { + // On Windows, when the input/output is redirected or piped, we need to + // open the console explicitly. + // See https://learn.microsoft.com/en-us/windows/console/getstdhandle#remarks + inTty, err = os.OpenFile("CONIN$", os.O_RDWR, 0o644) //nolint:gosec + if err != nil { + return nil, nil, err //nolint:wrapcheck + } + outTty, err = os.OpenFile("CONOUT$", os.O_RDWR, 0o644) //nolint:gosec + if err != nil { + return nil, nil, err //nolint:wrapcheck + } + return inTty, outTty, nil +} + +func suspend() (err error) { + // On Windows, suspending the process group is not supported in the same + // way as Unix-like systems. + return nil +} + +func notifyWinch(c chan os.Signal, sigs ...os.Signal) { + signal.Notify(c, sigs...) +} + +func notifyWinchContext(ctx context.Context, sigs ...os.Signal) (context.Context, context.CancelFunc) { + return signal.NotifyContext(ctx, sigs...) +} diff --git a/cli/third_party/ultraviolet/utils.go b/cli/third_party/ultraviolet/utils.go new file mode 100644 index 000000000..6616ebc97 --- /dev/null +++ b/cli/third_party/ultraviolet/utils.go @@ -0,0 +1,15 @@ +package uv + +func abs(x int) int { + if x < 0 { + return -x + } + return x +} + +func clamp(v, low, high int) int { + if high < low { + low, high = high, low + } + return min(high, max(low, v)) +} diff --git a/cli/third_party/ultraviolet/uv.go b/cli/third_party/ultraviolet/uv.go new file mode 100644 index 000000000..4ac3b0057 --- /dev/null +++ b/cli/third_party/ultraviolet/uv.go @@ -0,0 +1,406 @@ +package uv + +import ( + "fmt" + "image/color" + "io" + + "github.com/charmbracelet/x/ansi" + "github.com/lucasb-eyer/go-colorful" +) + +var ( + // ErrNotTerminal is an error that indicates that the file is not a terminal. + ErrNotTerminal = fmt.Errorf("not a terminal") + // ErrPlatformNotSupported is an error that indicates that the platform is not supported. + ErrPlatformNotSupported = fmt.Errorf("platform not supported") +) + +// Drawable represents a drawable component on a [Screen]. +type Drawable interface { + // Draw renders the component on the screen for the given area. + Draw(scr Screen, area Rectangle) +} + +// DrawableFunc is a function that implements the [Drawable] interface. +type DrawableFunc func(scr Screen, rect Rectangle) + +var _ Drawable = DrawableFunc(nil) + +// Draw implements the [Drawable] interface. +func (f DrawableFunc) Draw(scr Screen, rect Rectangle) { + f(scr, rect) +} + +// WidthMethod determines how many columns a grapheme occupies on the screen. +type WidthMethod interface { + StringWidth(s string) int +} + +// Screen represents a screen that can be drawn to. +type Screen interface { + // Bounds returns the bounds of the screen. This is the rectangle that + // includes the start and end points of the screen. + Bounds() Rectangle + + // CellAt returns the cell at the given position. If the position is out of + // bounds, it returns nil. Otherwise, it always returns a cell, even if it + // is empty (i.e., a cell with a space character and a width of 1). + CellAt(x, y int) *Cell + + // SetCell sets the cell at the given position. A nil cell is treated as an + // empty cell with a space character and a width of 1. + SetCell(x, y int, c *Cell) + + // WidthMethod returns the width method used by the screen. + WidthMethod() WidthMethod +} + +// Cursor represents a cursor on the terminal screen. +type Cursor struct { + // Position is a [Position] that determines the cursor's position on the + // screen relative to the top left corner of the frame. + Position + + // Color is a [color.Color] that determines the cursor's color. + Color color.Color + + // Shape is a [CursorShape] that determines the cursor's shape. + Shape CursorShape + + // Blink is a boolean that determines whether the cursor should blink. + Blink bool + + // Hidden is a boolean that determines whether the cursor is hidden. You + // can use this if you want to hide the cursor but still want to change its + // position. + Hidden bool +} + +// NewCursor returns a new cursor with the default settings and the given +// position. +func NewCursor(x, y int) *Cursor { + return &Cursor{ + Position: Position{X: x, Y: y}, + Color: nil, + Shape: CursorBlock, + Blink: true, + } +} + +// ProgressBarState represents the state of the progress bar. +type ProgressBarState int + +// Progress bar states. +const ( + ProgressBarNone ProgressBarState = iota + ProgressBarDefault + ProgressBarError + ProgressBarIndeterminate + ProgressBarWarning +) + +// String return a human-readable value for the given [ProgressBarState]. +func (s ProgressBarState) String() string { + return [...]string{ + "None", + "Default", + "Error", + "Indeterminate", + "Warning", + }[s] +} + +// ProgressBar represents the terminal progress bar. +// +// Support depends on the terminal. +// +// See https://learn.microsoft.com/en-us/windows/terminal/tutorials/progress-bar-sequences +type ProgressBar struct { + // State is the current state of the progress bar. It can be one of + // [ProgressBarNone], [ProgressBarDefault], [ProgressBarError], + // [ProgressBarIndeterminate], and [ProgressBarWarning]. + State ProgressBarState + // Value is the current value of the progress bar. It should be between + // 0 and 100. + Value int +} + +// NewProgressBar returns a new progress bar with the given state and value. +// The value is ignored if the state is [ProgressBarNone] or +// [ProgressBarIndeterminate]. +func NewProgressBar(state ProgressBarState, value int) *ProgressBar { + return &ProgressBar{ + State: state, + Value: min(max(value, 0), 100), + } +} + +// KeyboardEnhancements defines different keyboard enhancement features that +// can be requested from the terminal. +type KeyboardEnhancements struct { + // DisambiguateEscapeCodes requests the terminal to report ambiguous keys + // such as Ctrl+i and Tab, and Ctrl+m and Enter, and others as distinct key + // code sequences. + // If supported, your program will receive distinct [KeyPressEvent]s for + // these keys. + DisambiguateEscapeCodes bool + + // ReportEventTypes requests the terminal to report key repeat and release + // events. + // If supported, your program will receive [KeyReleaseEvent]s and + // [KeyPressEvent] with the [Key.IsRepeat] field set indicating that this + // is a it's part of a key repeat sequence. + ReportEventTypes bool + + // ReportAlternateKeys requests the terminal to report alternate key values + // in addition to the main ones. + // Note that only key events represented as escape codes will affected by + // this enhancement. + ReportAlternateKeys bool + + // ReportAllKeysAsEscapeCodes requests the terminal to report all key + // events, including plain text keys, as escape codes. + // When this is enabled, text won't be sent as plain text but instead as + // escape codes that encode the key value and modifiers. + ReportAllKeysAsEscapeCodes bool + + // ReportAssociatedText requests the terminal to report the text associated + // with key events. + // Note that this is an enhancement to + // [KeyboardEnhancements.ReportAllKeysAsEscapeCodes] and only has an effect + // if that is enabled. + ReportAssociatedText bool +} + +// NewKeyboardEnhancements returns a new [KeyboardEnhancements] with the given +// options as flags. +// +// A zero, or negative, flags value is treated as no enhancements. +// +// See [ansi.KittyKeyboard] for more details on the supported keyboard enhancements. +func NewKeyboardEnhancements(flags int) *KeyboardEnhancements { + if flags <= 0 { + return &KeyboardEnhancements{} + } + + return &KeyboardEnhancements{ + DisambiguateEscapeCodes: flags&ansi.KittyDisambiguateEscapeCodes != 0, + ReportEventTypes: flags&ansi.KittyReportEventTypes != 0, + } +} + +// Flags returns the keyboard enhancements as bits that can be used to set the +// appropriate terminal modes. +func (ke KeyboardEnhancements) Flags() int { + bits := 0 + if ke.DisambiguateEscapeCodes { + bits |= ansi.KittyDisambiguateEscapeCodes + } + if ke.ReportEventTypes { + bits |= ansi.KittyReportEventTypes + } + if ke.ReportAlternateKeys { + bits |= ansi.KittyReportAlternateKeys + } + if ke.ReportAllKeysAsEscapeCodes { + bits |= ansi.KittyReportAllKeysAsEscapeCodes + } + if ke.ReportAssociatedText { + bits |= ansi.KittyReportAssociatedKeys + } + + return bits +} + +// EncodeBackgroundColor encodes the background color to the given writer. Use +// nil to reset the background color to the default. +func EncodeBackgroundColor(w io.Writer, c color.Color) error { + var seq string + if c == nil { + seq = ansi.ResetBackgroundColor + } else if col, ok := colorful.MakeColor(c); ok { + seq = ansi.SetBackgroundColor(col.Hex()) + } else { + return fmt.Errorf("invalid color: %v", c) + } + + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set background color: %w", err) + } + + return nil +} + +// EncodeForegroundColor encodes the foreground color to the given writer. Use +// nil to reset the foreground color to the default. +func EncodeForegroundColor(w io.Writer, c color.Color) error { + var seq string + if c == nil { + seq = ansi.ResetForegroundColor + } else if col, ok := colorful.MakeColor(c); ok { + seq = ansi.SetForegroundColor(col.Hex()) + } else { + return fmt.Errorf("invalid color: %v", c) + } + + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set foreground color: %w", err) + } + + return nil +} + +// EncodeCursorColor encodes the cursor color to the given writer. Use nil to +// reset the cursor color to the default. +func EncodeCursorColor(w io.Writer, c color.Color) error { + var seq string + if c == nil { + seq = ansi.ResetCursorColor + } else if col, ok := colorful.MakeColor(c); ok { + seq = ansi.SetCursorColor(col.Hex()) + } else { + return fmt.Errorf("invalid color: %v", c) + } + + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set cursor color: %w", err) + } + + return nil +} + +// EncodeCursorStyle encodes the cursor style to the given writer. +func EncodeCursorStyle(w io.Writer, shape CursorShape, blink bool) error { + seq := ansi.SetCursorStyle(shape.Encode(blink)) + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set cursor style: %w", err) + } + + return nil +} + +// EncodeBracketedPaste encodes the bracketed paste mode to the given writer. +func EncodeBracketedPaste(w io.Writer, enable bool) error { + var seq string + if enable { + seq = ansi.SetModeBracketedPaste + } else { + seq = ansi.ResetModeBracketedPaste + } + + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set bracketed paste mode: %w", err) + } + + return nil +} + +// EncodeMouseMode encodes the mouse tracking mode to the given writer. +func EncodeMouseMode(w io.Writer, mode MouseMode) error { + var seq string + switch mode { + case MouseModeNone: + seq = ansi.ResetModeMouseX10 + + ansi.ResetModeMouseNormal + + ansi.ResetModeMouseButtonEvent + + ansi.ResetModeMouseAnyEvent + case MouseModePress: + seq = ansi.SetModeMouseX10 + case MouseModeClick: + seq = ansi.SetModeMouseNormal + case MouseModeDrag: + seq = ansi.SetModeMouseButtonEvent + case MouseModeMotion: + seq = ansi.SetModeMouseAnyEvent + } + + _, err := io.WriteString(w, seq) //nolint:errcheck + if err != nil { + return fmt.Errorf("failed to set mouse mode: %w", err) + } + + return nil +} + +// EncodeMouseEncoding encodes the mouse encoding mode to the given writer. +// When enc is [MouseEncodingLegacy], all extended encodings are reset. +func EncodeMouseEncoding(w io.Writer, enc MouseEncoding) error { + var seq string + switch enc { + case MouseEncodingLegacy: + seq = ansi.ResetModeMouseExtSgr + + ansi.ResetModeMouseExtUrxvt + + ansi.ResetModeMouseExtSgrPixel + case MouseEncodingSGR: + seq = ansi.SetModeMouseExtSgr + case MouseEncodingSGRPixel: + seq = ansi.SetModeMouseExtSgrPixel + } + + _, err := io.WriteString(w, seq) //nolint:errcheck + if err != nil { + return fmt.Errorf("failed to set mouse encoding: %w", err) + } + + return nil +} + +// EncodeProgressBar encodes the progress bar to the given writer. +func EncodeProgressBar(w io.Writer, pb *ProgressBar) error { + if pb == nil { + pb = &ProgressBar{State: ProgressBarNone} + } + + var seq string + percent := clamp(pb.Value, 0, 100) + switch pb.State { + case ProgressBarNone: + seq = ansi.ResetProgressBar + case ProgressBarDefault: + seq = ansi.SetProgressBar(percent) + case ProgressBarError: + seq = ansi.SetErrorProgressBar(percent) + case ProgressBarIndeterminate: + seq = ansi.SetIndeterminateProgressBar + case ProgressBarWarning: + seq = ansi.SetWarningProgressBar(percent) + default: + return fmt.Errorf("invalid progress bar state: %d", pb.State) + } + + _, err := io.WriteString(w, seq) + if err != nil { + return fmt.Errorf("failed to set progress bar: %w", err) + } + + return nil +} + +// EncodeKeyboardEnhancements encodes the keyboard enhancements to the given +// writer. +func EncodeKeyboardEnhancements(w io.Writer, ke *KeyboardEnhancements) error { + var flags int + if ke != nil { + flags = ke.Flags() + } + _, err := io.WriteString(w, ansi.KittyKeyboard(flags, 1)) + if err != nil { + return fmt.Errorf("failed to set keyboard enhancements: %w", err) + } + return nil +} + +// EncodeWindowTitle encodes the window title to the given writer. +func EncodeWindowTitle(w io.Writer, title string) error { + _, err := io.WriteString(w, ansi.SetWindowTitle(title)) + if err != nil { + return fmt.Errorf("failed to set window title: %w", err) + } + return nil +} diff --git a/cli/third_party/ultraviolet/winch.go b/cli/third_party/ultraviolet/winch.go new file mode 100644 index 000000000..77533f1cd --- /dev/null +++ b/cli/third_party/ultraviolet/winch.go @@ -0,0 +1,62 @@ +package uv + +import ( + "os" + "sync" + + "github.com/charmbracelet/x/term" +) + +// SizeNotifier represents a notifier that listens for window size +// changes using the SIGWINCH signal and notifies the given channel. +type SizeNotifier struct { + // Channel that receives terminal size change notifications. + C <-chan os.Signal + + f term.File + sig chan os.Signal + m sync.Mutex +} + +// NewSizeNotifier creates a new [SizeNotifier] that listens for window size +// changes on the given TTY file through SIGWINCH signals. +func NewSizeNotifier(f term.File) *SizeNotifier { + if f == nil { + panic("no file set") + } + sig := make(chan os.Signal) + return &SizeNotifier{ + f: f, + sig: sig, + C: sig, + } +} + +// Start starts listening for window size changes and notifies [SizeNotifier.C] +// about any changes. +func (n *SizeNotifier) Start() error { + return n.start() +} + +// Stop stops the notifier and cleans up resources. +func (n *SizeNotifier) Stop() error { + return n.stop() +} + +// GetWindowSize returns the current size of the terminal window. +func (n *SizeNotifier) GetWindowSize() (cells Size, pixels Size, err error) { + return n.getWindowSize() +} + +// GetSize returns the current cell size of the terminal window. +func (n *SizeNotifier) GetSize() (width, height int, err error) { + n.m.Lock() + defer n.m.Unlock() + + width, height, err = term.GetSize(n.f.Fd()) + if err != nil { + return 0, 0, err //nolint:wrapcheck + } + + return width, height, nil +} diff --git a/cli/third_party/ultraviolet/winch_other.go b/cli/third_party/ultraviolet/winch_other.go new file mode 100644 index 000000000..802268780 --- /dev/null +++ b/cli/third_party/ultraviolet/winch_other.go @@ -0,0 +1,17 @@ +//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris +// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris + +package uv + +func (n *SizeNotifier) start() error { + return ErrPlatformNotSupported +} + +func (n *SizeNotifier) stop() error { + return ErrPlatformNotSupported +} + +func (n *SizeNotifier) getWindowSize() (cells Size, pixels Size, err error) { + cells.Width, cells.Height, err = n.GetSize() + return cells, pixels, err +} diff --git a/cli/third_party/ultraviolet/winch_unix.go b/cli/third_party/ultraviolet/winch_unix.go new file mode 100644 index 000000000..efe0ce509 --- /dev/null +++ b/cli/third_party/ultraviolet/winch_unix.go @@ -0,0 +1,50 @@ +//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos +// +build darwin dragonfly freebsd linux netbsd openbsd solaris zos + +package uv + +import ( + "os/signal" + "syscall" + + "github.com/charmbracelet/x/term" + "github.com/charmbracelet/x/termios" +) + +func (n *SizeNotifier) start() error { + n.m.Lock() + defer n.m.Unlock() + if n.f == nil || !term.IsTerminal(n.f.Fd()) { + return ErrNotTerminal + } + + signal.Notify(n.sig, syscall.SIGWINCH) + return nil +} + +func (n *SizeNotifier) stop() error { + n.m.Lock() + signal.Stop(n.sig) + n.m.Unlock() + return nil +} + +func (n *SizeNotifier) getWindowSize() (cells Size, pixels Size, err error) { + n.m.Lock() + defer n.m.Unlock() + + winsize, err := termios.GetWinsize(int(n.f.Fd())) + if err != nil { + return Size{}, Size{}, err //nolint:wrapcheck + } + + cells = Size{ + Width: int(winsize.Col), + Height: int(winsize.Row), + } + pixels = Size{ + Width: int(winsize.Xpixel), + Height: int(winsize.Ypixel), + } + return cells, pixels, nil +} diff --git a/cli/third_party/ultraviolet/window.go b/cli/third_party/ultraviolet/window.go new file mode 100644 index 000000000..e90bef28b --- /dev/null +++ b/cli/third_party/ultraviolet/window.go @@ -0,0 +1,147 @@ +package uv + +import "github.com/charmbracelet/x/ansi" + +// Window represents a rectangular area on the screen. It can be a root window +// with no parent, or a sub-window with a parent window. A window can have its +// own buffer or share the buffer of its parent window (view). +type Window struct { + *Buffer + + method *WidthMethod + parent *Window + bounds Rectangle +} + +var ( + _ Screen = (*Window)(nil) + _ Drawable = (*Window)(nil) +) + +// HasParent returns whether the window has a parent window. This can be used +// to determine if the window is a root window or a sub-window. +func (w *Window) HasParent() bool { + return w.parent != nil +} + +// Parent returns the parent window of the current window. +// If the window does not have a parent, it returns nil. +func (w *Window) Parent() *Window { + return w.parent +} + +// MoveTo moves the window to the specified x and y coordinates. +func (w *Window) MoveTo(x, y int) { + size := w.bounds.Size() + w.bounds.Min.X = x + w.bounds.Min.Y = y + w.bounds.Max.X = x + size.X + w.bounds.Max.Y = y + size.Y +} + +// MoveBy moves the window by the specified delta x and delta y. +func (w *Window) MoveBy(dx, dy int) { + w.bounds.Min.X += dx + w.bounds.Min.Y += dy + w.bounds.Max.X += dx + w.bounds.Max.Y += dy +} + +// Clone creates an exact copy of the window, including its buffer and values. +// The cloned window will have the same parent and method as the original +// window. +func (w *Window) Clone() *Window { + return w.CloneArea(w.Buffer.Bounds()) +} + +// CloneArea creates an exact copy of the window, including its buffer and +// values, but only within the specified area. The cloned window will have the +// same parent and method as the original window, but its bounds will be +// limited to the specified area. +func (w *Window) CloneArea(area Rectangle) *Window { + clone := new(Window) + clone.Buffer = w.Buffer.CloneArea(area) + clone.parent = w.parent + clone.method = w.method + clone.bounds = area + return clone +} + +// Resize resizes the window to the specified width and height. +func (w *Window) Resize(width, height int) { + // Only resize the buffer if this window owns its buffer. + if w.parent == nil || w.Buffer != w.parent.Buffer { + w.Buffer.Resize(width, height) + } + w.bounds.Max.X = w.bounds.Min.X + width + w.bounds.Max.Y = w.bounds.Min.Y + height +} + +// WidthMethod returns the method used to calculate the width of characters in +// the window. +func (w *Window) WidthMethod() WidthMethod { + return *w.method +} + +// Bounds returns the bounds of the window as a rectangle. +func (w *Window) Bounds() Rectangle { + return w.bounds +} + +// NewWindow creates a new window with its own buffer relative to the parent +// window at the specified position and size. +// +// This will panic if width or height is negative. +func (w *Window) NewWindow(x, y, width, height int) *Window { + return newWindow(w, x, y, width, height, w.method, false) +} + +// NewView creates a new view into the parent window at the specified position +// and size. Unlike [Window.NewWindow], this view shares the same buffer as the +// parent window. +func (w *Window) NewView(x, y, width, height int) *Window { + return newWindow(w, x, y, width, height, w.method, true) +} + +// NewWindow creates a new root [Window] with the given size and width method. +// If the method is nil, it defaults to [ansi.WcWidth]. +// +// The [WidthMethod] is used to calculate the width of characters in the +// window, which is important for correctly rendering text, especially when +// dealing with wide characters, combining characters, emojis, and other +// Unicode characters that may have varying widths. +// +// Use [ansi.WcWidth] as the default width method, which is a common +// implementation that handles a wide range of Unicode characters according to +// the Unicode Standard. Use [ansi.GraphemeWidth] if you know that your +// terminal supports grapheme clusters and proper rendering of combining +// characters and emojis, and you want to ensure that the width calculations +// are based on grapheme clusters rather than individual code points. +// +// This will panic if width or height is negative. +func NewWindow(width, height int, method WidthMethod) *Window { + if method == nil { + method = ansi.WcWidth + } + return newWindow(nil, 0, 0, width, height, &method, false) +} + +// SetWidthMethod sets the width method for the window. +func (w *Window) SetWidthMethod(method WidthMethod) { + w.method = &method +} + +// newWindow creates a new [Window] with the specified parent, position, +// method, and size. +func newWindow(parent *Window, x, y, width, height int, method *WidthMethod, view bool) *Window { + w := new(Window) + if view { + w.Buffer = parent.Buffer + } else { + w.Buffer = NewBuffer(width, height) + } + w.parent = parent + w.method = method + w.bounds = Rect(x, y, width, height) + return w +} -- knotmirror 0.0.1