From 8e1e222e491b39305707611e212a6e22d40f00b5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:24:24 +0000 Subject: [PATCH] build(deps): bump charm.land/lipgloss/v2 from 2.0.5 to 2.1.1 in /src Bumps charm.land/lipgloss/v2 from 2.0.5 to 2.1.1. --- updated-dependencies: - dependency-name: charm.land/lipgloss/v2 dependency-version: 2.1.1 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- src/go.mod | 6 +- src/go.sum | 27 +- src/vendor/charm.land/lipgloss/v2/borders.go | 6 +- src/vendor/charm.land/lipgloss/v2/canvas.go | 5 +- src/vendor/charm.land/lipgloss/v2/color.go | 13 +- src/vendor/charm.land/lipgloss/v2/get.go | 2 +- src/vendor/charm.land/lipgloss/v2/set.go | 12 +- src/vendor/charm.land/lipgloss/v2/style.go | 54 +- src/vendor/charm.land/lipgloss/v2/unset.go | 4 +- src/vendor/charm.land/lipgloss/v2/wrap.go | 47 +- .../charmbracelet/ultraviolet/.golangci.yml | 40 +- .../charmbracelet/ultraviolet/README.md | 173 ++- .../charmbracelet/ultraviolet/TUTORIAL.md | 256 ++-- .../charmbracelet/ultraviolet/buffer.go | 362 +++-- .../charmbracelet/ultraviolet/cell.go | 6 + .../charmbracelet/ultraviolet/console.go | 219 +++ .../charmbracelet/ultraviolet/console_unix.go | 13 + .../ultraviolet/console_windows.go | 13 + .../charmbracelet/ultraviolet/decoder.go | 5 +- .../charmbracelet/ultraviolet/doc.go | 45 +- .../charmbracelet/ultraviolet/event.go | 8 +- .../charmbracelet/ultraviolet/layout.go | 137 -- .../charmbracelet/ultraviolet/mouse.go | 70 +- .../charmbracelet/ultraviolet/poll.go | 38 + .../charmbracelet/ultraviolet/poll_bsd.go | 165 +++ .../charmbracelet/ultraviolet/poll_default.go | 12 + .../ultraviolet/poll_fallback.go | 158 +++ .../charmbracelet/ultraviolet/poll_linux.go | 175 +++ .../charmbracelet/ultraviolet/poll_select.go | 156 +++ .../charmbracelet/ultraviolet/poll_solaris.go | 12 + .../charmbracelet/ultraviolet/poll_windows.go | 217 +++ .../charmbracelet/ultraviolet/styled.go | 150 ++- .../charmbracelet/ultraviolet/terminal.go | 1200 +++++------------ .../ultraviolet/terminal_other.go | 17 +- .../ultraviolet/terminal_reader.go | 75 +- .../ultraviolet/terminal_reader_windows.go | 16 +- .../ultraviolet/terminal_renderer.go | 302 +++-- .../terminal_renderer_hardscroll.go | 14 +- .../ultraviolet/terminal_renderer_hashmap.go | 14 +- .../ultraviolet/terminal_screen.go | 837 ++++++++++++ .../ultraviolet/terminal_unix.go | 59 +- .../ultraviolet/terminal_windows.go | 50 +- .../charmbracelet/ultraviolet/tty.go | 26 +- .../charmbracelet/ultraviolet/tty_other.go | 14 +- .../charmbracelet/ultraviolet/tty_unix.go | 11 + .../charmbracelet/ultraviolet/tty_windows.go | 14 +- .../charmbracelet/ultraviolet/uv.go | 297 +++- .../charmbracelet/ultraviolet/window.go | 147 ++ .../github.com/charmbracelet/x/ansi/color.go | 2 +- .../charmbracelet/x/ansi/kitty/options.go | 21 +- .../charmbracelet/x/ansi/kitty/writer.go | 7 +- .../github.com/charmbracelet/x/ansi/mouse.go | 2 +- .../x/ansi/parser/transition_table.go | 4 +- .../charmbracelet/x/ansi/parser_decode.go | 10 +- .../charmbracelet/x/ansi/wcwidth.go | 100 ++ .../github.com/charmbracelet/x/ansi/width.go | 12 + .../github.com/gdamore/tcell/v3/screen.go | 26 +- .../github.com/gdamore/tcell/v3/tscreen.go | 15 +- src/vendor/modules.txt | 10 +- 59 files changed, 4186 insertions(+), 1722 deletions(-) create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/console.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/console_unix.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/console_windows.go delete mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/layout.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_bsd.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_default.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_fallback.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_linux.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_select.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_solaris.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/poll_windows.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/terminal_screen.go create mode 100644 src/vendor/github.com/charmbracelet/ultraviolet/window.go create mode 100644 src/vendor/github.com/charmbracelet/x/ansi/wcwidth.go diff --git a/src/go.mod b/src/go.mod index 3858fae5..fba67848 100644 --- a/src/go.mod +++ b/src/go.mod @@ -3,7 +3,7 @@ module notmutt go 1.26.6 require ( - charm.land/lipgloss/v2 v2.0.5 + charm.land/lipgloss/v2 v2.1.1 github.com/BurntSushi/toml v1.6.0 github.com/andybalholm/cascadia v1.3.4 github.com/emersion/go-message v0.18.2 @@ -35,8 +35,8 @@ require ( git.sr.ht/~jackmordaunt/go-toast v1.1.2 // indirect github.com/alecthomas/chroma/v2 v2.21.1 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect - github.com/charmbracelet/ultraviolet v0.0.0-20251205161215-1948445e3318 // indirect - github.com/charmbracelet/x/ansi v0.11.7 // indirect + github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect + github.com/charmbracelet/x/ansi v0.11.8 // indirect github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect diff --git a/src/go.sum b/src/go.sum index 7385465f..18feff7b 100644 --- a/src/go.sum +++ b/src/go.sum @@ -1,21 +1,25 @@ -charm.land/lipgloss/v2 v2.0.5 h1:kbNxgeeUOYv5J0YdpxFjfvf3dFvqH8Aci4zB6xqFtrY= -charm.land/lipgloss/v2 v2.0.5/go.mod h1:9oqhxt4yxIMe6q5A4kHr44DremZk7J9UNh74GlWa5nc= +charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc= +charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc= git.sr.ht/~jackmordaunt/go-toast v1.1.2 h1:/yrfI55LRt1M7H1vkaw+NaH1+L1CDxrqDltwm5euVuE= git.sr.ht/~jackmordaunt/go-toast v1.1.2/go.mod h1:jA4OqHKTQ4AFBdwrSnwnskUIIS3HYzlJSgdzCKqfavo= github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= +github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= +github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.2.0/go.mod h1:vf4zrexSH54oEjJ7EdB65tGNHmH3pGZmVkgTP5RHvAs= github.com/alecthomas/chroma/v2 v2.21.1 h1:FaSDrp6N+3pphkNKU6HPCiYLgm8dbe5UXIXcoBhZSWA= github.com/alecthomas/chroma/v2 v2.21.1/go.mod h1:NqVhfBR0lte5Ouh3DcthuUCTUpDC9cxBOfyMbMQPs3o= github.com/alecthomas/repr v0.0.0-20220113201626-b1b626ac65ae/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= +github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs= +github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= 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/ultraviolet v0.0.0-20251205161215-1948445e3318 h1:OqDqxQZliC7C8adA7KjelW3OjtAxREfeHkNcd66wpeI= -github.com/charmbracelet/ultraviolet v0.0.0-20251205161215-1948445e3318/go.mod h1:Y6kE2GzHfkyQQVCSL9r2hwokSrIlHGzZG+71+wDYSZI= -github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI= -github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 h1:rdnVWKgJpTVXKuKuJyxDJ+NFJdUaUqGvyGy61OcvlbA= +github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886/go.mod h1:nAw0d9PhFp1qdzi2xhQU5YOu5sVpDIHWlaW2Uz/bCro= +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= @@ -31,18 +35,12 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.4.0/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= -github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ= github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= github.com/emersion/go-message v0.18.2 h1:rl55SQdjd9oJcIoQNhubD2Acs1E6IzlZISRTK7x/Lpg= github.com/emersion/go-message v0.18.2/go.mod h1:XpJyL70LwRvq2a8rVbHXikPgKj8+aI0kGdHlg16ibYA= github.com/esiqveland/notify v0.13.3 h1:QCMw6o1n+6rl+oLUfg8P1IIDSFsDEb2WlXvVvIJbI/o= github.com/esiqveland/notify v0.13.3/go.mod h1:hesw/IRYTO0x99u1JPweAl4+5mwXJibQVUcP0Iu5ORE= -github.com/fishman/go.notmuch v0.40.4 h1:vR5hSOKsvw7+UxksxMb7BEZNcUtuHu46WePZet3/cR8= -github.com/fishman/go.notmuch v0.40.4/go.mod h1:AKg575C53q19SkRGHdc/zKhimx3i0UX7q7XnFLtlAvI= -github.com/fishman/go.notmuch v0.40.5 h1:CqQjoMoirJlvo1asHeGL34mMB3zM1up7GQvb63ulAfo= -github.com/fishman/go.notmuch v0.40.5/go.mod h1:AKg575C53q19SkRGHdc/zKhimx3i0UX7q7XnFLtlAvI= github.com/fishman/go.notmuch v0.40.6 h1:rSjT5M8udYtTccjZf2pNtnUoWj7kqJaRMhfSEKPfcv0= github.com/fishman/go.notmuch v0.40.6/go.mod h1:AKg575C53q19SkRGHdc/zKhimx3i0UX7q7XnFLtlAvI= github.com/fishman/zaman v0.1.2 h1:WjeSaOO6BJzvy2RA9Rj1tO6V0eSB13cWg5ojDCanqzc= @@ -51,8 +49,6 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= -github.com/gdamore/tcell/v3 v3.4.2 h1:gGW+6z2Bz5Wl2mNwFlm9+eRmg2JQrWcKjSkL1LRfpNU= -github.com/gdamore/tcell/v3 v3.4.2/go.mod h1:Oe5U3S3jm3NzypswDNUhe+LUnF5CoFq2b4sepD++QHo= github.com/gdamore/tcell/v3 v3.5.0 h1:SCp9czLv2K2aPORgD6+4fjV0xNAzKIkiezCkp6bHLe4= github.com/gdamore/tcell/v3 v3.5.0/go.mod h1:Oe5U3S3jm3NzypswDNUhe+LUnF5CoFq2b4sepD++QHo= github.com/gen2brain/beeep v0.11.2 h1:+KfiKQBbQCuhfJFPANZuJ+oxsSKAYNe88hIpJuyKWDA= @@ -67,6 +63,8 @@ github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbc github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= +github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/jackmordaunt/icns/v3 v3.0.1 h1:xxot6aNuGrU+lNgxz5I5H0qSeCjNKp8uTXB1j8D4S3o= github.com/jackmordaunt/icns/v3 v3.0.1/go.mod h1:5sHL59nqTd2ynTnowxB/MDQFhKNqkK8X687uKNygaSQ= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -128,7 +126,6 @@ github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE= github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= github.com/yuin/goldmark-highlighting/v2 v2.0.0-20220924101305-151362477c87 h1:Py16JEzkSdKAtEFJjiaYLYBOWGXc1r/xHj/Q/5lA37k= github.com/yuin/goldmark-highlighting/v2 v2.0.0-20220924101305-151362477c87/go.mod h1:ovIvrum6DQJA4QsJSovrkC4saKHQVs7TvcaeO8AIl5I= -github.com/yuin/goldmark-highlighting/v2 v2.0.0-20230729083705-37449abec8cc/go.mod h1:ovIvrum6DQJA4QsJSovrkC4saKHQVs7TvcaeO8AIl5I= github.com/yuin/gopher-lua v1.1.2 h1:yF/FjE3hD65tBbt0VXLE13HWS9h34fdzJmrWRXwobGA= github.com/yuin/gopher-lua v1.1.2/go.mod h1:7aRmXIWl37SqRf0koeyylBEzJ+aPt8A+mmkQ4f1ntR8= go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0= diff --git a/src/vendor/charm.land/lipgloss/v2/borders.go b/src/vendor/charm.land/lipgloss/v2/borders.go index 7f12360f..f56c14b0 100644 --- a/src/vendor/charm.land/lipgloss/v2/borders.go +++ b/src/vendor/charm.land/lipgloss/v2/borders.go @@ -512,7 +512,11 @@ func renderHorizontalEdge(left, middle, right string, width int) string { for i := 0; i < width-leftWidth-rightWidth; { r := runes[j] out.WriteRune(r) - i += ansi.StringWidth(string(r)) + runeWidth := ansi.StringWidth(string(r)) + if runeWidth < 1 { + runeWidth = 1 + } + i += runeWidth j++ if j >= len(runes) { j = 0 diff --git a/src/vendor/charm.land/lipgloss/v2/canvas.go b/src/vendor/charm.land/lipgloss/v2/canvas.go index 396defb8..e6cc3b45 100644 --- a/src/vendor/charm.land/lipgloss/v2/canvas.go +++ b/src/vendor/charm.land/lipgloss/v2/canvas.go @@ -82,7 +82,8 @@ func (c *Canvas) Draw(scr uv.Screen, area uv.Rectangle) { c.scr.Draw(scr, area) } -// Render renders the canvas into a styled string. +// Render renders the canvas into a styled string. Any trailing spaces are +// trimmed. func (c *Canvas) Render() string { - return c.scr.Render() + return uv.TrimSpace(c.scr.Render()) } diff --git a/src/vendor/charm.land/lipgloss/v2/color.go b/src/vendor/charm.land/lipgloss/v2/color.go index 7443dc10..0990945a 100644 --- a/src/vendor/charm.land/lipgloss/v2/color.go +++ b/src/vendor/charm.land/lipgloss/v2/color.go @@ -144,12 +144,7 @@ type RGBColor struct { // RGBA returns the RGBA value of this color. This satisfies the Go Color // interface. func (c RGBColor) RGBA() (r, g, b, a uint32) { - const shift = 8 - r |= uint32(c.R) << shift - g |= uint32(c.G) << shift - b |= uint32(c.B) << shift - a = 0xFFFF - return + return color.RGBA{R: c.R, G: c.G, B: c.B, A: 255}.RGBA() } // ANSIColor is a color specified by an ANSI256 color value. @@ -211,8 +206,8 @@ func LightDark(isDark bool) LightDarkFunc { } } -// isDarkColor returns whether the given color is dark (based on the luminance -// portion of the color as interpreted as HSL). +// isDarkColor returns whether the given color is dark, based on its CIELAB +// lightness. // // Example usage: // @@ -228,7 +223,7 @@ func isDarkColor(c color.Color) bool { return true } - _, _, l := col.Hsl() + l, _, _ := col.Lab() return l < 0.5 //nolint:mnd } diff --git a/src/vendor/charm.land/lipgloss/v2/get.go b/src/vendor/charm.land/lipgloss/v2/get.go index d1fe1d66..febff843 100644 --- a/src/vendor/charm.land/lipgloss/v2/get.go +++ b/src/vendor/charm.land/lipgloss/v2/get.go @@ -505,7 +505,7 @@ func (s Style) getAsBool(k propKey, defaultVal bool) bool { if !s.isSet(k) { return defaultVal } - return s.attrs&int(k) != 0 + return s.attrs&int64(k) != 0 } func (s Style) getAsColors(k propKey) (colors []color.Color) { diff --git a/src/vendor/charm.land/lipgloss/v2/set.go b/src/vendor/charm.land/lipgloss/v2/set.go index f10b4538..f1600989 100644 --- a/src/vendor/charm.land/lipgloss/v2/set.go +++ b/src/vendor/charm.land/lipgloss/v2/set.go @@ -89,16 +89,16 @@ func (s *Style) set(key propKey, value any) { default: if v, ok := value.(bool); ok { //nolint:nestif if v { - s.attrs |= int(key) + s.attrs |= int64(key) } else { - s.attrs &^= int(key) + s.attrs &^= int64(key) } - } else if attrs, ok := value.(int); ok { + } else if attrs, ok := value.(int64); ok { // bool attrs - if attrs&int(key) != 0 { - s.attrs |= int(key) + if attrs&int64(key) != 0 { + s.attrs |= int64(key) } else { - s.attrs &^= int(key) + s.attrs &^= int64(key) } } } diff --git a/src/vendor/charm.land/lipgloss/v2/style.go b/src/vendor/charm.land/lipgloss/v2/style.go index 3cd65952..3fda722e 100644 --- a/src/vendor/charm.land/lipgloss/v2/style.go +++ b/src/vendor/charm.land/lipgloss/v2/style.go @@ -147,7 +147,7 @@ type Style struct { link, linkParams string // we store bool props values here - attrs int + attrs int64 // props that have values fgColor color.Color @@ -399,9 +399,11 @@ func (s Style) Render(strs ...string) string { // carriage returns can cause strange behaviour when rendering. str = strings.ReplaceAll(str, "\r\n", "\n") - // Strip newlines in single line mode + // Strip newlines in single line mode. Replace with a space so that + // words on separate lines stay separated when collapsed onto one + // line (e.g. "hello\nworld" -> "hello world", not "helloworld"). if inline { - str = strings.ReplaceAll(str, "\n", "") + str = strings.ReplaceAll(str, "\n", " ") } // Include borders in block size. @@ -426,13 +428,28 @@ func (s Style) Render(strs ...string) string { b.WriteRune('\n') } if useSpaceStyler { - // Look for spaces and apply a different styler - for _, r := range line { - if unicode.IsSpace(r) { - b.WriteString(teSpace.Styled(string(r))) - continue + // Look for spaces and apply a different styler, while passing + // through any ANSI escape sequences already present in the line + // so they are not mangled (e.g. when rendering an + // already-styled string). + // See https://github.com/charmbracelet/lipgloss/issues/233. + var state byte + for len(line) > 0 { + seq, width, n, newState := ansi.DecodeSequence(line, state, nil) + if n == 0 { + break } - b.WriteString(te.Styled(string(r))) + switch { + case width == 0: + // Control or escape sequence: emit verbatim, unstyled. + b.WriteString(seq) + case isSpaceSequence(seq): + b.WriteString(teSpace.Styled(seq)) + default: + b.WriteString(te.Styled(seq)) + } + line = line[n:] + state = newState } } else { b.WriteString(te.Styled(line)) @@ -525,6 +542,17 @@ func (s Style) Render(strs ...string) string { return str } +// isSpaceSequence reports whether the given grapheme consists solely of +// whitespace runes. +func isSpaceSequence(s string) bool { + for _, r := range s { + if !unicode.IsSpace(r) { + return false + } + } + return s != "" +} + func (s Style) maybeConvertTabs(str string) string { tw := tabWidthDefault if s.isSet(tabWidthKey) { @@ -568,11 +596,15 @@ func (s Style) applyMargins(str string, inline bool) string { _, width := getLines(str) spaces := strings.Repeat(" ", width) + // Style each margin line on its own so the reset lands before the + // newline, not at the start of the next line (see #115). if topMargin > 0 { - str = style.Styled(strings.Repeat(spaces+"\n", topMargin)) + str + line := style.Styled(spaces) + str = strings.Repeat(line+"\n", topMargin) + str } if bottomMargin > 0 { - str += style.Styled(strings.Repeat("\n"+spaces, bottomMargin)) + line := style.Styled(spaces) + str += strings.Repeat("\n"+line, bottomMargin) } } diff --git a/src/vendor/charm.land/lipgloss/v2/unset.go b/src/vendor/charm.land/lipgloss/v2/unset.go index b81ee882..99295e85 100644 --- a/src/vendor/charm.land/lipgloss/v2/unset.go +++ b/src/vendor/charm.land/lipgloss/v2/unset.go @@ -19,7 +19,9 @@ func (s Style) UnsetItalic() Style { // UnsetUnderline removes the underline style rule, if set. func (s Style) UnsetUnderline() Style { - return s.Underline(false) + s.unset(underlineKey) + s.ul = UnderlineNone + return s } // UnsetStrikethrough removes the strikethrough style rule, if set. diff --git a/src/vendor/charm.land/lipgloss/v2/wrap.go b/src/vendor/charm.land/lipgloss/v2/wrap.go index ccffe89b..3243820a 100644 --- a/src/vendor/charm.land/lipgloss/v2/wrap.go +++ b/src/vendor/charm.land/lipgloss/v2/wrap.go @@ -12,9 +12,12 @@ import ( func Wrap(s string, width int, breakpoints string) string { var buf bytes.Buffer s = ansi.Wrap(s, width, breakpoints) + // The writer only inserts resets around newlines, so the output is + // the same length as the input plus a little. Size it once. + buf.Grow(len(s) + len(s)/8) w := NewWrapWriter(&buf) - defer w.Close() //nolint:errcheck _, _ = io.WriteString(w, s) + _ = w.Close() return buf.String() } @@ -69,27 +72,39 @@ func (w *WrapWriter) Write(p []byte) (int, error) { // nested writer chains; treat it as a no-op rather than panicking. return len(p), nil } + // Bytes are forwarded in runs rather than one at a time: only a + // newline needs anything written around it, so everything between + // newlines is a single downstream Write instead of one per byte. + start := 0 for i := range p { b := p[i] w.p.Advance(b) - if b == '\n' { - if !w.style.IsZero() { - _, _ = w.w.Write([]byte(ansi.ResetStyle)) - } - if !w.link.IsZero() { - _, _ = w.w.Write([]byte(ansi.ResetHyperlink())) - } + if b != '\n' { + continue } - _, _ = w.w.Write([]byte{b}) - if b == '\n' { - if !w.link.IsZero() { - _, _ = w.w.Write([]byte(ansi.SetHyperlink(w.link.URL, w.link.Params))) - } - if !w.style.IsZero() { - _, _ = w.w.Write([]byte(w.style.String())) - } + if i > start { + _, _ = w.w.Write(p[start:i]) } + if !w.style.IsZero() { + _, _ = w.w.Write([]byte(ansi.ResetStyle)) + } + if !w.link.IsZero() { + _, _ = w.w.Write([]byte(ansi.ResetHyperlink())) + } + + _, _ = w.w.Write(p[i : i+1]) + start = i + 1 + + if !w.link.IsZero() { + _, _ = w.w.Write([]byte(ansi.SetHyperlink(w.link.URL, w.link.Params))) + } + if !w.style.IsZero() { + _, _ = w.w.Write([]byte(w.style.String())) + } + } + if start < len(p) { + _, _ = w.w.Write(p[start:]) } return len(p), nil diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/.golangci.yml b/src/vendor/github.com/charmbracelet/ultraviolet/.golangci.yml index 929cb0ac..64474889 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/.golangci.yml +++ b/src/vendor/github.com/charmbracelet/ultraviolet/.golangci.yml @@ -1,38 +1,42 @@ version: "2" -run: - tests: false linters: enable: - bodyclose - - exhaustive - - goconst - - godot - - gomoddirectives + # - exhaustive + # - goconst + # - godot + # - godox + # - gomoddirectives - goprintffuncname - - gosec + # - gosec - misspell - - nakedret - - nestif - - nilerr + # - nakedret + # - nestif + # - nilerr - noctx - nolintlint - - prealloc - - revive + # - prealloc + # - revive - rowserrcheck - sqlclosecheck + - staticcheck - tparallel - - unconvert - - unparam + # - unconvert + # - unparam - whitespace - - wrapcheck + # - wrapcheck + disable: + - errcheck + - ineffassign + - unused exclusions: + generated: lax + presets: + - common-false-positives rules: - text: '(slog|log)\.\w+' linters: - noctx - generated: lax - presets: - - common-false-positives issues: max-issues-per-linter: 0 max-same-issues: 0 diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/README.md b/src/vendor/github.com/charmbracelet/ultraviolet/README.md index eb83cc5e..b28ccdd6 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/README.md +++ b/src/vendor/github.com/charmbracelet/ultraviolet/README.md @@ -7,108 +7,141 @@ Build Status

-Ultraviolet is a set of primitives for manipulating terminal emulators, with a focus on terminal user interfaces (TUIs). It provides a set of tools and abstractions for interaction that can handle user input and display dynamic, cell-based content. It’s the product of many years of research, development, collaboration and ingenuity. +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 is not a framework by design, however it can be used standalone to create powerful terminal applications. It’s in use in production and powers critical portions of [Bubble Tea v2][bbt] and [Lip Gloss v2][lg], and was instrumental in the development of [Crush][crush]. +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. -[crush]: https://github.com/charmbracelet/crush [bbt]: https://github.com/charmbracelet/bubbletea [lg]: https://github.com/charmbracelet/lipgloss -> [!CAUTION] -> This project currently exists to serve internal use cases. API stability is a goal, but expect no stability guarantees as of now. +## Install -## Features +```bash +go get github.com/charmbracelet/ultraviolet@latest +``` + +## Quick Start + +```go +package main + +import ( + "log" -Ultraviolet is built with several core features in mind to make terminal -application development easy and performant: + uv "github.com/charmbracelet/ultraviolet" + "github.com/charmbracelet/ultraviolet/screen" +) -### 👺 The Cursed Renderer +func main() { + t := uv.DefaultTerminal() + scr := t.Screen() -The cell-based rendering model—called _The Cursed Render_—was inspired by the infamous -[ncurses](https://invisible-island.net/ncurses/) library, which has been an -essential part of terminal applications for decades. Ultraviolet takes this -concept and modernizes it for the Go programming language, providing a more -ergonomic and efficient way to work with terminal cells without the need for -archaic technologies like `terminfo` or `termcap` databases. + scr.EnterAltScreen() -Unlike ncurses, it supports both full-window and inline use-cases as we see inline TUIs as important in maintaining user context and flow. + if err := t.Start(); err != nil { + log.Fatalf("failed to start terminal: %v", err) + } + defer t.Stop() -### 🏎️ High Speeds and Low Bandwidth + ctx := screen.NewContext(scr) + text := "Hello, World!" + textWidth := scr.StringWidth(text) -The built-in terminal renderer efficiently handles content updates by utilizing -a powerful cell-based diffing algorithm that minimizes the amount of data -written to the terminal using various ANSI escape sequences to accomplish this. -This allows applications to update only the parts of the terminal that have -changed, significantly improving performance and responsiveness. + 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() + } -In practical terms, Ultraviolet optimizes for fast redraws that use minimal data transfer. This is very important locally and critically important over the network (for example, via SSH). + 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 + } + } + } +} +``` -### 💬 Universal Input +## Architecture -Input handling in terminals can be complex, especially when dealing with -multiple input sources, different platforms, and ancient terminal baggage. -Ultraviolet simplifies this by providing a unified interface for handling user -input, allowing developers to focus on building their applications without -getting bogged down in the intricacies of terminal input handling. +Ultraviolet is organized as a set of layered primitives: -### 🎮 Cross-Platform Compatibility +- **Terminal** — manages the application lifecycle: raw mode, input event loop, + start/stop. Create one with `DefaultTerminal()` or `NewTerminal(console, opts)`. -Ultraviolet is designed to work seamlessly across different platforms and -terminal emulators. It abstracts away the differences in terminal capabilities -and provides a consistent API for developers to work with, ensuring that -applications built with Ultraviolet will run smoothly on various systems. +- **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()`. -On Windows, it uses the [Windows Console API](https://learn.microsoft.com/en-us/windows/console/console-functions) to -provide a consistent experience, while on Unix-like systems, it relies on the -standard Termios API along with ANSI escape sequences to manipulate the -terminal. +- **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. -In short: Ultraviolet provides first-class support for both Unix and Windows-based systems. +- **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`. -### 🧩 Extensible Architecture +- **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 -Ultraviolet is built with extensibility in mind, providing a solid API that can -be embedded into other applications or used as a foundation for building custom -terminal user interfaces. It allows developers to create their own components, -styles, and behaviors, making it a versatile tool for building terminal -applications. +- **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. -## FAQ +- **Universal input** — unified keyboard and mouse event handling across + platforms. Supports legacy encodings, Kitty keyboard protocol, SGR mouse, + and Windows Console input. -### 🐈 What about other Charm libraries? +- **Inline and fullscreen** — works in both alternate screen (fullscreen) and + inline mode. Inline TUIs preserve terminal context and scrollback. -Ultraviolet is not a replacement for existing libraries like [Bubble Tea](https://github.com/charmbracelet/bubbletea) or [Lip -Gloss](https://github.com/charmbracelet/lipgloss). Instead, it serves as a -foundation for the latest versions of both of these libraries and others like them, providing the -underlying primitives and abstractions needed to build terminal user interfaces -applications and frameworks. +- **Cross-platform** — first-class support for Unix (termios + ANSI) and + Windows (Console API). Consistent behavior across terminal emulators. -### 🛁 How is it different from Bubble Tea? +- **Suspend/resume** — `Stop()` and `Start()` can be called repeatedly for + suspend/resume cycles, shelling out to editors, or process suspension + via `uv.Suspend()`. -Ultraviolet is a lower-level library that focuses on the core primitives of -terminal manipulation, rendering, and input handling. It provides the building -blocks for creating terminal applications, while Bubble Tea is a higher-level -framework that builds on top of Ultraviolet to provide a more structured and -opinionated way to build terminal user interfaces. +## Examples -### 💋 Is it a replacement for Lip Gloss? +See the [`examples/`](./examples/) directory for core examples and +[`examples/advanced/`](./examples/advanced/) for more complex demos. -Simply put, no. Ultraviolet is not a replacement for Lip Gloss. Instead, it -provides the underlying rendering capabilities that Lip Gloss can use to create -styled terminal content. Lip Gloss is a higher-level library that builds on top -of Ultraviolet by utilizing the cell-based rendering model to provide a -simplified and ergonomic way to create styled terminal content and composition -of terminal user interfaces. +## Tutorial -## ✏️ Tutorial +See [TUTORIAL.md](./TUTORIAL.md) for a step-by-step guide to building your +first Ultraviolet application. -You can find a simple tutorial on how to create a UV application that displays -"Hello, World!" on the screen in the [TUTORIAL.md](./TUTORIAL.md) file. +> [!NOTE] +> Ultraviolet is in active development. The API may change. -## Whatcha think? +## Feedback -We’d love to hear your thoughts on this project. Feel free to drop us a note! +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) diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/TUTORIAL.md b/src/vendor/github.com/charmbracelet/ultraviolet/TUTORIAL.md index 65561721..d456d5a4 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/TUTORIAL.md +++ b/src/vendor/github.com/charmbracelet/ultraviolet/TUTORIAL.md @@ -1,199 +1,167 @@ -# Hello World! +# Tutorial: Hello World -This is a simple tutorial on how to create a UV application that displays -"Hello, World!" on the screen. UV is a terminal UI toolkit that allows you to -create terminal applications with ease. It provides a simple API to handle -screen management, input handling, and rendering content. +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. -## Tutorial +## Creating a Terminal -What does UV consist of? A UV application consists of a screen that displays -content, has some sort of input sources that can be used to interact with the -screen, and is meant to display content or programs on the screen. - -First, we need to create a screen that will display our program. UV comes with -a `Terminal` screen that is used to display content on a terminal. +A `Terminal` manages the console, input event loop, and screen state. ```go -t := uv.NewTerminal(os.Stdin, os.Stdout, os.Environ()) -// Or simply use... -// t := uv.DefaultTerminal() +t := uv.DefaultTerminal() ``` -A terminal screen has a few properties that are unique to it. For example, a -terminal screen can go into raw mode, which is important to disable echoing of -input characters, and to disable signal handling so that we can receive things -like ctrl+c without the terminal interfering with our program. +You can also create a terminal with a custom console and options: -Another important property of a terminal screen is the alternate screen buffer. -This property puts the terminal screen into a special mode that allows us to -display content without interfering with the normal screen buffer. +```go +con := uv.NewConsole(os.Stdin, os.Stdout, os.Environ()) +t := uv.NewTerminal(con, &uv.Options{ + Logger: myLogger, // optional, for debugging I/O +}) +``` -In this tutorial, we will use the alternate screen buffer to display our -program so that we don't affect the normal screen buffer. +## Getting the Screen -```go -// Set the terminal to raw mode. -if err := t.MakeRaw(); err != nil { - log.Fatal(err) -} +The terminal's screen is where you draw content, manage the alternate screen +buffer, and set cells. -// Enter the alternate screen buffer. This will -// only take affect once we flush or display -// our program on the terminal screen. -t.EnterAltScreen() +```go +scr := t.Screen() +``` -// My program -// ... +## Alternate Screen -// Make sure we leave the alternate screen buffer when we -// are done with our program. This will be called automatically -// when we use [t.Shutdown(ctx)] later. -t.LeaveAltScreen() +The alternate screen buffer lets your application display content without +affecting the user's scrollback. Most fullscreen TUIs use it. -// Make sure we restore the terminal to its original state -// before we exit. We don't care about errors here, but you -// can handle them if you want. This will be called automatically -// when we use [t.Shutdown(ctx)] later. -_ = t.Restore() //nolint:errcheck +```go +scr.EnterAltScreen() ``` -Now that we have our screen set to raw mode and in the alternate screen buffer, -we can create our program that will be displayed on the screen. A program is an -abstraction layer that handles different screen types and implementations. It -only cares about displaying content on the screen. +## Starting the Terminal -We need to start our program before we can display anything on the screen. This -will ensure that the program and screen are initialized and ready to display -content. Internally, this will also call `t.Start()` to start the terminal -screen. +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 program: %v", err) + log.Fatalf("failed to start terminal: %v", err) } +defer t.Stop() ``` -Let's display a simple frame with some text in it. A frame is a container that -holds the buffer we're displaying. The final cursor position we want our cursor -to be at, and the viewport area we are working with to display our content. +`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!" { - // We iterate over the string to display each character - // in a separate cell. Ideally, we want each cell - // to have exactly one grapheme. In this case, since - // we're using a simple ASCII string, we know that - // each character is a single grapheme with a width of 1. - var c uv.Cell - c.Content = string(r) - c.Width = 1 - t.SetCell(i, 0, &c) + scr.SetCell(i, 0, &uv.Cell{Content: string(r), Width: 1}) } -// Now we simply render the changes and flush them -// to the terminal screen. -_ = p.Display() ``` -Different screen models have different ways to receive input. Some models have -a remote control, while others have a touch screen. A terminal can receive -input from various peripherals usually through control codes and escape -sequences. Our terminal has a `t.Events(ctx)` method that returns a channel -which will receive events from different terminal input sources. +Or use the `screen` helper package for convenience: ```go -// We want to be able to stop the terminal input loop -// whenever we call cancel(). -ctx, cancel := context.WithCancel(context.Background()) -defer cancel() - -for ev := range t.Events(ctx) { - switch ev := ev.(type) { - case uv.WindowSizeEvent: - // Our terminal screen is resizable. This is important - // as we want to inform our terminal screen with the - // size we'd like to display our program in. - // When we're using the full terminal window size, - // we can assume that the terminal screen will - // also have the same size as our program. - // However, with inline programs, usually we want - // the height to be the height of our program. - // So if our inline program takes 10 lines, we - // want to resize the terminal screen to 10 lines - // high. - width, height := ev.Width, ev.Height - if !altscreen { - height = 10 - } - t.Resize(width, height) - case uv.KeyPressEvent: - if ev.MatchStrings("q", "ctrl+c") { - // This will stop the input loop and cancel the context. - cancel() - } - } +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) } ``` -Now that we've handled displaying our program and receiving input from the -terminal, we need to handle the program's lifecycle. We need to make sure that -we restore the terminal to its original state when we exit the program. A -terminal program can be stopped gracefully using the `t.Shutdown(ctx)` method. +## Handling Events + +The terminal provides a channel of input events. Range over it to process +keyboard, mouse, and resize events: ```go -// We need to make sure we stop the program gracefully -// after we exit the input loop. -if err := t.Shutdown(ctx); err != nil { - log.Fatal(err) +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 + } + } } ``` -Finally, let's put everything together and create a simple program that displays -a frame with "Hello, World!" in it. The program will exit when we press -ctrl+c or q. +`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.NewTerminal(os.Stdin, os.Stdout, os.Environ()) + t := uv.DefaultTerminal() + scr := t.Screen() - if err := t.MakeRaw(); err != nil { - log.Fatalf("failed to make terminal raw: %v", err) - } + scr.EnterAltScreen() if err := t.Start(); err != nil { - log.Fatalf("failed to start program: %v", err) + 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() } - t.EnterAltScreen() - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - for ev := range t.Events(ctx) { + for ev := range t.Events() { switch ev := ev.(type) { case uv.WindowSizeEvent: - width, height := ev.Width, ev.Height - t.Erase() - t.Resize(width, height) + scr.Resize(ev.Width, ev.Height) + display() case uv.KeyPressEvent: - if ev.MatchStrings("q", "ctrl+c") { - cancel() + if ev.MatchString("q", "ctrl+c") { + return } } - - for i, r := range "Hello, World!" { - var c uv.Cell - c.Content = string(r) - c.Width = 1 - t.SetCell(i, 0, &c) - } - if err := t.Display(); err != nil { - log.Fatal(err) - } - } - - if err := t.Shutdown(ctx); err != nil { - log.Fatal(err) } } ``` diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/buffer.go b/src/vendor/github.com/charmbracelet/ultraviolet/buffer.go index 30c770c7..5a83fc37 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/buffer.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/buffer.go @@ -39,9 +39,6 @@ func NewLine(width int) Line { // Set sets the cell at the given x position. func (l Line) Set(x int, c *Cell) { - // maxCellWidth is the maximum width a terminal cell is expected to have. - const maxCellWidth = 5 - lineWidth := len(l) if x < 0 || x >= lineWidth { return @@ -60,10 +57,10 @@ func (l Line) Set(x int, c *Cell) { } } else if pw == 0 { // Writing to wide cell placeholders - for j := 1; j < maxCellWidth && x-j >= 0; j++ { + 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 := 0; k < ww; k++ { + for k := range ww { l[x-j+k] = *wide l[x-j+k].Empty() } @@ -92,8 +89,7 @@ func (l Line) Set(x int, c *Cell) { } if cw > 1 { - // Mark wide cells with an zero cells. - // We set the wide cell down below + // Mark wide cells with zero-width placeholder cells. for j := 1; j < cw && x+j < lineWidth; j++ { l[x+j] = Cell{} } @@ -116,15 +112,13 @@ func (l Line) String() string { var buf strings.Builder var pending bytes.Buffer for _, c := range l { - if cellEqual(&c, nil) { - pending.WriteByte(' ') + if c.IsZero() { continue } - - if c.IsZero() { + if c.Equal(&EmptyCell) { + pending.WriteByte(' ') continue } - if pending.Len() > 0 { buf.WriteString(pending.String()) pending.Reset() @@ -149,7 +143,10 @@ func renderLine(buf io.StringWriter, l Line) { var pending bytes.Buffer for _, c := range l { - if cellEqual(&c, nil) { + if c.IsZero() { + continue + } + if c.Equal(&EmptyCell) { if !pen.IsZero() { _, _ = buf.WriteString(ansi.ResetStyle) pen = Style{} @@ -190,6 +187,9 @@ func renderLine(buf io.StringWriter, l Line) { _, _ = buf.WriteString(c.String()) } + if pending.Len() > 0 { + _, _ = buf.WriteString(pending.String()) + } if link.URL != "" { _, _ = buf.WriteString(ansi.ResetHyperlink()) } @@ -198,15 +198,56 @@ func renderLine(buf io.StringWriter, l Line) { } } +// 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 - // Touched represents the lines that have been modified or touched. It is - // used to track which lines need to be redrawn. - Touched []*LineData } +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 { @@ -218,34 +259,19 @@ func NewBuffer(width int, height int) *Buffer { b.Lines[i][j] = EmptyCell } } - b.Touched = make([]*LineData, height) b.Resize(width, height) return b } // String returns the string representation of the buffer. func (b *Buffer) String() string { - var buf strings.Builder - for i, l := range b.Lines { - buf.WriteString(l.String()) - if i < len(b.Lines)-1 { - _ = buf.WriteByte('\n') - } - } - return buf.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 { - var buf strings.Builder - for i, l := range b.Lines { - renderLine(&buf, l) - if i < len(b.Lines)-1 { - _ = buf.WriteByte('\n') - } - } - return buf.String() + return Lines(b.Lines).Render() } // Line returns a pointer to the line at the given y position. @@ -272,41 +298,9 @@ func (b *Buffer) SetCell(x, y int, c *Cell) { return } - if !cellEqual(b.CellAt(x, y), c) { - width := 1 - if c != nil && c.Width > 0 { - width = c.Width - } - b.TouchLine(x, y, width) - } b.Lines[y].Set(x, c) } -// Touch marks the cell at the given x, y position as touched. -func (b *Buffer) Touch(x, y int) { - b.TouchLine(x, y, 0) -} - -// TouchLine marks a line n times starting at the given x position as touched. -func (b *Buffer) TouchLine(x, y, n int) { - if y < 0 || y >= len(b.Lines) { - return - } - - if y >= len(b.Touched) { - b.Touched = append(b.Touched, make([]*LineData, y-len(b.Touched)+1)...) - } - - 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 -} - // Height implements Screen. func (b *Buffer) Height() int { return len(b.Lines) @@ -317,16 +311,12 @@ func (b *Buffer) Width() int { if len(b.Lines) == 0 { return 0 } - w := len(b.Lines[0]) - for _, l := range b.Lines { - if len(l) > w { - w = len(l) - } - } - return w + 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()) } @@ -386,7 +376,12 @@ func (b *Buffer) FillArea(c *Cell, area Rectangle) { // Clear clears the buffer with space cells and rectangle. func (b *Buffer) Clear() { - b.ClearArea(b.Bounds()) + 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 @@ -404,12 +399,14 @@ func (b *Buffer) CloneArea(area Rectangle) *Buffer { } 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; x++ { + 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 @@ -429,7 +426,7 @@ func (b *Buffer) Draw(scr Screen, area Rectangle) { // Ensure the area is within the bounds of the screen. bounds := scr.Bounds() - if !area.In(bounds) { + if !area.Overlaps(bounds) { return } @@ -441,7 +438,11 @@ func (b *Buffer) Draw(scr Screen, area Rectangle) { continue } scr.SetCell(x, y, c) - x += c.Width + width := c.Width + if width <= 0 { + width = 1 + } + x += width } } } @@ -476,8 +477,6 @@ func (b *Buffer) InsertLineArea(y, n int, c *Cell, area Rectangle) { // We don't need to clone c here because we're just moving lines down. b.Lines[i][x] = b.Lines[i-n][x] } - 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) } // Clear the newly inserted lines within bounds @@ -510,8 +509,6 @@ func (b *Buffer) DeleteLineArea(y, n int, c *Cell, area Rectangle) { // We don't need to clone c here because we're just moving cells up. b.Lines[dst][x] = b.Lines[src][x] } - b.TouchLine(area.Min.X, dst, area.Max.X-area.Min.X) - b.TouchLine(area.Min.X, src, area.Max.X-area.Min.X) } // Fill the bottom n lines with blank cells @@ -557,8 +554,6 @@ func (b *Buffer) InsertCellArea(x, y, n int, c *Cell, area Rectangle) { // right. b.Lines[y][i] = b.Lines[y][i-n] } - // Touch the lines that were moved - b.TouchLine(x, y, n) // Clear the newly inserted cells within rectangle bounds for i := x; i < x+n && i < area.Max.X; i++ { @@ -597,8 +592,6 @@ func (b *Buffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle) { b.SetCell(i, y, b.CellAt(i+n, y)) } } - // Touch the line that was modified - b.TouchLine(x, y, n) // Fill the vacated positions with the given cell for i := area.Max.X - n; i < area.Max.X; i++ { @@ -608,17 +601,20 @@ func (b *Buffer) DeleteCellArea(x, y, n int, c *Cell, area Rectangle) { // ScreenBuffer is a buffer that can be used as a [Screen]. type ScreenBuffer struct { - *Buffer + *RenderBuffer Method ansi.Method } -var _ Screen = ScreenBuffer{} +var ( + _ Screen = ScreenBuffer{} + _ Drawable = ScreenBuffer{} +) // NewScreenBuffer creates a new ScreenBuffer with the given width and height. func NewScreenBuffer(width, height int) ScreenBuffer { return ScreenBuffer{ - Buffer: NewBuffer(width, height), - Method: ansi.WcWidth, + RenderBuffer: NewRenderBuffer(width, height), + Method: ansi.WcWidth, } } @@ -646,3 +642,193 @@ func TrimSpace(s string) string { } 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 []*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 + } + + if y >= len(b.Touched) { + b.Touched = append(b.Touched, make([]*LineData, y-len(b.Touched)+1)...) + } + + // Re-check bounds: a concurrent resize may have cleared Touched + if y >= len(b.Touched) { + return + } + + 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 { + if b.Touched == nil { + return 0 + } + 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) +} + +// 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) + } +} diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/cell.go b/src/vendor/github.com/charmbracelet/ultraviolet/cell.go index ea89b553..a5d9e823 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/cell.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/cell.go @@ -65,6 +65,12 @@ func (c *Cell) IsZero() bool { return *c == Cell{} } +// 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) diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/console.go b/src/vendor/github.com/charmbracelet/ultraviolet/console.go new file mode 100644 index 00000000..7ef37fd6 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/console_unix.go b/src/vendor/github.com/charmbracelet/ultraviolet/console_unix.go new file mode 100644 index 00000000..5460efff --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/console_windows.go b/src/vendor/github.com/charmbracelet/ultraviolet/console_windows.go new file mode 100644 index 00000000..0836f1c3 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/decoder.go b/src/vendor/github.com/charmbracelet/ultraviolet/decoder.go index 6d4ffc67..a891dc27 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/decoder.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/decoder.go @@ -642,7 +642,7 @@ func (p *EventDecoder) parseCsi(b []byte) (int, Event) { if !hOk || !wOk { break } - return i, WindowPixelSizeEvent{Width: width, Height: height} + return i, PixelSizeEvent{Width: width, Height: height} } case 6: // Report Terminal character cell size. if paramsLen == 3 { @@ -673,7 +673,7 @@ func (p *EventDecoder) parseCsi(b []byte) (int, Event) { } return i, MultiEvent{ WindowSizeEvent{Width: cellWidth, Height: cellHeight}, - WindowPixelSizeEvent{Width: pixelWidth, Height: pixelHeight}, + PixelSizeEvent{Width: pixelWidth, Height: pixelHeight}, } } } @@ -1530,7 +1530,6 @@ func parseKittyKeyboard(params ansi.Params) (Event Event) { func parseKittyKeyboardExt(params ansi.Params, k KeyPressEvent) Event { // Handle Kitty keyboard protocol if len(params) > 2 && // We have at least 3 parameters - params[0].Param(1) == 1 && // The first parameter is 1 (defaults to 1) 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: diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/doc.go b/src/vendor/github.com/charmbracelet/ultraviolet/doc.go index af352053..27b8a25c 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/doc.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/doc.go @@ -1,3 +1,46 @@ -// Package uv (Ultraviolet) is a library for creating terminal-based user +// 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/src/vendor/github.com/charmbracelet/ultraviolet/event.go b/src/vendor/github.com/charmbracelet/ultraviolet/event.go index d3492c5e..2d0d8cf2 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/event.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/event.go @@ -94,7 +94,7 @@ type MultiEvent []Event func (e MultiEvent) String() string { var sb strings.Builder for _, ev := range e { - sb.WriteString(fmt.Sprintf("%v\n", ev)) + fmt.Fprintf(&sb, "%v\n", ev) } return sb.String() } @@ -121,11 +121,11 @@ func (s WindowSizeEvent) Bounds() Rectangle { return Size(s).Bounds() } -// WindowPixelSizeEvent represents the window size in pixels. -type WindowPixelSizeEvent Size +// PixelSizeEvent represents the window size in pixels. +type PixelSizeEvent Size // Bounds returns the bounds corresponding to the size. -func (s WindowPixelSizeEvent) Bounds() Rectangle { +func (s PixelSizeEvent) Bounds() Rectangle { return Size(s).Bounds() } diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/layout.go b/src/vendor/github.com/charmbracelet/ultraviolet/layout.go deleted file mode 100644 index a246e06c..00000000 --- a/src/vendor/github.com/charmbracelet/ultraviolet/layout.go +++ /dev/null @@ -1,137 +0,0 @@ -package uv - -import "image" - -// Constraint represents a size constraint for layout purposes. -type Constraint interface { - // Apply applies the constraint to the given size and returns the - // constrained size. - Apply(size int) int -} - -// Percent is a constraint that represents a percentage of the available size. -type Percent int - -// Apply applies the percentage constraint to the given size. -func (p Percent) Apply(size int) int { - if p < 0 { - return 0 - } - if p > 100 { - return size - } - return size * int(p) / 100 -} - -// Ratio is a constraint that represents a ratio of the available size. It is a -// syntactic sugar for [Percent]. -func Ratio(numerator, denominator int) Percent { - if denominator == 0 { - return 0 - } - return Percent(numerator * 100 / denominator) -} - -// Fixed is a constraint that represents a fixed size. -type Fixed int - -// Apply applies the fixed size constraint to the given size. -func (f Fixed) Apply(size int) int { - if f < 0 { - return 0 - } - if int(f) > size { - return size - } - return int(f) -} - -// SplitVertical splits the area vertically into two parts based on the given -// [Constraint]. -// -// It returns the top and bottom rectangles. -func SplitVertical(area Rectangle, constraint Constraint) (top Rectangle, bottom Rectangle) { - height := min(constraint.Apply(area.Dy()), area.Dy()) - top = Rectangle{Min: area.Min, Max: Position{X: area.Max.X, Y: area.Min.Y + height}} - bottom = Rectangle{Min: Position{X: area.Min.X, Y: area.Min.Y + height}, Max: area.Max} - return -} - -// SplitHorizontal splits the area horizontally into two parts based on the -// given [Constraint]. -// -// It returns the left and right rectangles. -func SplitHorizontal(area Rectangle, constraint Constraint) (left Rectangle, right Rectangle) { - width := min(constraint.Apply(area.Dx()), area.Dx()) - left = Rectangle{Min: area.Min, Max: Position{X: area.Min.X + width, Y: area.Max.Y}} - right = Rectangle{Min: Position{X: area.Min.X + width, Y: area.Min.Y}, Max: area.Max} - return -} - -// CenterRect returns a new [Rectangle] centered within the given area with the -// specified width and height. -func CenterRect(area Rectangle, width, height int) Rectangle { - centerX := area.Min.X + area.Dx()/2 - centerY := area.Min.Y + area.Dy()/2 - minX := centerX - width/2 - minY := centerY - height/2 - maxX := minX + width - maxY := minY + height - return image.Rect(minX, minY, maxX, maxY) -} - -// TopLeftRect returns a new [Rectangle] positioned at the top-left corner of the -// given area with the specified width and height. -func TopLeftRect(area Rectangle, width, height int) Rectangle { - return image.Rect(area.Min.X, area.Min.Y, area.Min.X+width, area.Min.Y+height).Intersect(area) -} - -// TopCenterRect returns a new [Rectangle] positioned at the top-center of the -// given area with the specified width and height. -func TopCenterRect(area Rectangle, width, height int) Rectangle { - centerX := area.Min.X + area.Dx()/2 - minX := centerX - width/2 - return image.Rect(minX, area.Min.Y, minX+width, area.Min.Y+height).Intersect(area) -} - -// TopRightRect returns a new [Rectangle] positioned at the top-right corner of -// the given area with the specified width and height. -func TopRightRect(area Rectangle, width, height int) Rectangle { - return image.Rect(area.Max.X-width, area.Min.Y, area.Max.X, area.Min.Y+height).Intersect(area) -} - -// RightCenterRect returns a new [Rectangle] positioned at the right-center of -// the given area with the specified width and height. -func RightCenterRect(area Rectangle, width, height int) Rectangle { - centerY := area.Min.Y + area.Dy()/2 - minY := centerY - height/2 - return image.Rect(area.Max.X-width, minY, area.Max.X, minY+height).Intersect(area) -} - -// LeftCenterRect returns a new [Rectangle] positioned at the left-center of the -// given area with the specified width and height. -func LeftCenterRect(area Rectangle, width, height int) Rectangle { - centerY := area.Min.Y + area.Dy()/2 - minY := centerY - height/2 - return image.Rect(area.Min.X, minY, area.Min.X+width, minY+height).Intersect(area) -} - -// BottomLeftRect returns a new [Rectangle] positioned at the bottom-left corner -// of the given area with the specified width and height. -func BottomLeftRect(area Rectangle, width, height int) Rectangle { - return image.Rect(area.Min.X, area.Max.Y-height, area.Min.X+width, area.Max.Y).Intersect(area) -} - -// BottomCenterRect returns a new [Rectangle] positioned at the bottom-center of -// the given area with the specified width and height. -func BottomCenterRect(area Rectangle, width, height int) Rectangle { - centerX := area.Min.X + area.Dx()/2 - minX := centerX - width/2 - return image.Rect(minX, area.Max.Y-height, minX+width, area.Max.Y).Intersect(area) -} - -// BottomRightRect returns a new [Rectangle] positioned at the bottom-right -// corner of the given area with the specified width and height. -func BottomRightRect(area Rectangle, width, height int) Rectangle { - return image.Rect(area.Max.X-width, area.Max.Y-height, area.Max.X, area.Max.Y).Intersect(area) -} diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/mouse.go b/src/vendor/github.com/charmbracelet/ultraviolet/mouse.go index e86d94b8..a74cdf99 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/mouse.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/mouse.go @@ -4,16 +4,37 @@ import ( "github.com/charmbracelet/x/ansi" ) -// MouseMode represents the mouse mode for the terminal. It is used to enable -// or disable mouse support on the terminal. -type MouseMode byte +// MouseMode represents the mouse tracking mode for the terminal. +type MouseMode uint8 -// Mouse modes. +// 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 ( - MouseModeNone MouseMode = iota - MouseModeClick - MouseModeDrag - MouseModeMotion + 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. @@ -55,7 +76,8 @@ const ( // messages. // // The X and Y coordinates are zero-based, with (0,0) being the upper left -// corner of the terminal. +// 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) { @@ -96,3 +118,33 @@ func (m Mouse) String() (s string) { 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/src/vendor/github.com/charmbracelet/ultraviolet/poll.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll.go new file mode 100644 index 00000000..209211f5 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_bsd.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_bsd.go new file mode 100644 index 00000000..94744875 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_default.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_default.go new file mode 100644 index 00000000..464c70fb --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_fallback.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_fallback.go new file mode 100644 index 00000000..187a1ed8 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_linux.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_linux.go new file mode 100644 index 00000000..bbe2c9fa --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_select.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_select.go new file mode 100644 index 00000000..ff7756a1 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_solaris.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_solaris.go new file mode 100644 index 00000000..7a753da4 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/poll_windows.go b/src/vendor/github.com/charmbracelet/ultraviolet/poll_windows.go new file mode 100644 index 00000000..2e1922eb --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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/src/vendor/github.com/charmbracelet/ultraviolet/styled.go b/src/vendor/github.com/charmbracelet/ultraviolet/styled.go index 5118bd66..83b09621 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/styled.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/styled.go @@ -4,7 +4,6 @@ import ( "bytes" "image/color" "strings" - "sync" "github.com/charmbracelet/x/ansi" ) @@ -41,6 +40,11 @@ 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) { @@ -92,74 +96,97 @@ func (s *StyledString) Bounds() Rectangle { return Rect(0, 0, w, h) } -var parserPool = &sync.Pool{ - New: func() any { - return ansi.NewParser() - }, -} - -// printString draws a string starting at the given position. +// 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). func printString[T []byte | string]( s Screen, m WidthMethod, x, y int, bounds Rectangle, str T, truncate bool, tail string, -) { - // We don't need to use a large buffer parser here. [ansi.GetParser] - // returns a 4MB parsers which are too large for our use case. We use our - // own pool of parsers that are smaller and more efficient for our use - // case. - p := parserPool.Get().(*ansi.Parser) - defer parserPool.Put(p) +) (lines []Line) { + p := ansi.GetParser() + defer ansi.PutParser(p) var tailc Cell if truncate && len(tail) > 0 { tailc = *NewCell(m, tail) } - decoder := ansi.DecodeSequenceWc[T] + // 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 = ansi.DecodeSequence[T] + decoder, method = ansi.DecodeSequence[T], ansi.GraphemeWidth + } + + if s == nil { + lines = []Line{} } var cell Cell var style Style var link Link var state byte + lastX, lastY := -1, -1 // last cell written, for folding in combining marks for len(str) > 0 { seq, width, n, newState := decoder(str, state, p) - switch width { - case 1, 2, 3, 4: // wide cells can go up to 4 cells wide + // 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) + cell.Style = style + cell.Link = link - 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++ - } + 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 = style - cell.Link = link - s.SetCell(x, y, &cell) - x += tailc.Width - } else { - // Print the cell to the screen - cell.Style = style - cell.Link = link - s.SetCell(x, y, &cell) - x += width + 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 = style + cell.Link = link + 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 + } } } - // String is too long for the line, truncate it. - // Make sure we reset the cell for the next iteration. + // Reset cell for next iteration cell = Cell{} default: // Valid sequences always have a non-zero Cmd. @@ -172,11 +199,39 @@ func printString[T []byte | string]( // Hyperlinks ReadLink(p.Data(), &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")): - x = bounds.Min.X + 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) + } + } default: cell.Content += string(seq) } @@ -185,13 +240,20 @@ func printString[T []byte | string]( // Advance the state and data state = newState str = str[n:] + + if y >= bounds.Max.Y { + // We've reached the bottom of the bounds, stop processing further + // lines. + break + } } // Make sure to set the last cell if it's not empty. - if !cell.IsZero() { + if !cell.IsZero() && s != nil { s.SetCell(x, y, &cell) - cell = Cell{} } + + return lines } // ReadStyle reads a Select Graphic Rendition (SGR) escape sequences from a diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal.go index ba67edbc..a9fb4538 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal.go @@ -1,968 +1,394 @@ package uv import ( - "context" "fmt" - "image/color" - "io" - "log" "os" - "strings" - "sync" - "sync/atomic" + "os/signal" "time" - "github.com/charmbracelet/colorprofile" "github.com/charmbracelet/x/ansi" - "github.com/charmbracelet/x/term" - "github.com/muesli/cancelreader" "golang.org/x/sync/errgroup" ) -var ( - // ErrNotTerminal is returned when one of the I/O streams is not a terminal. - ErrNotTerminal = fmt.Errorf("not a terminal") - - // ErrPlatformNotSupported is returned when the platform is not supported. - ErrPlatformNotSupported = fmt.Errorf("platform not supported") - - // ErrRunning is returned when the terminal is already running. - ErrRunning = fmt.Errorf("terminal is running") - - // ErrNotRunning is returned when the terminal is not running. - ErrNotRunning = fmt.Errorf("terminal not running") -) - -// Terminal represents a terminal screen that can be manipulated and drawn to. -// It handles reading events from the terminal using [TerminalReader]. +// 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 { - // Terminal I/O streams and state. - in io.Reader - out io.Writer - inTty term.File - inTtyState *term.State - outTty term.File - outTtyState *term.State - running atomic.Bool // Indicates if the terminal is running - - // Terminal type, screen and buffer. - termtype string // The $TERM type. - environ Environ // The environment variables. - buf *Buffer // Reference to the last buffer used. - scr *TerminalRenderer // The actual screen to be drawn to. - size Size // The last known full size of the terminal. - pixSize Size // The last known pixel size of the terminal. - method ansi.Method // The width method used by the terminal. - profile colorprofile.Profile - useTabs bool // Whether to use hard tabs or not. - useBspace bool // Whether to use backspace or not. - - // Terminal input stream. - cr cancelreader.CancelReader - rd *TerminalReader - winchn *SizeNotifier // The window size notifier for the terminal. - evs chan Event // receiving event channel. - evch chan Event // event loop channel - evctx context.Context // context for the event channel. - evcancel context.CancelFunc // The cancel function for the event channel. - evloop chan struct{} // Channel to signal the event loop has exited. - once sync.Once - errg *errgroup.Group - m sync.RWMutex // Mutex to protect the terminal state. - - // Renderer state. - state state - lastState *state - prepend []string - - logger Logger // The debug logger for I/O. -} - -type state struct { - altscreen bool - curHidden bool - cur Position -} - -// DefaultTerminal returns a new default terminal instance that uses -// [os.Stdin], [os.Stdout], and [os.Environ]. -func DefaultTerminal() *Terminal { - return NewTerminal(os.Stdin, os.Stdout, os.Environ()) -} - -// NewTerminal creates a new [Terminal] instance with the given I/O streams and -// environment variables. -func NewTerminal(in io.Reader, out io.Writer, env []string) *Terminal { - t := new(Terminal) - t.in = in - t.out = out - if f, ok := in.(term.File); ok { - t.inTty = f - } - if f, ok := out.(term.File); ok { - t.outTty = f - } - t.environ = env - t.termtype = t.environ.Getenv("TERM") - t.scr = NewTerminalRenderer(t.out, t.environ) - t.buf = NewBuffer(0, 0) - t.method = ansi.WcWidth // Default width method. - t.SetColorProfile(colorprofile.Detect(out, env)) - t.evs = make(chan Event) - t.evch = make(chan Event) - t.once = sync.Once{} - - // Create a new context to manage input events. - t.evctx, t.evcancel = context.WithCancel(context.Background()) - t.errg, t.evctx = errgroup.WithContext(t.evctx) - - // Window size changes only for non-Windows platforms. - if !isWindows { - // Create default input receivers. - winchTty := t.inTty - if winchTty == nil { - winchTty = t.outTty - } - t.winchn = NewSizeNotifier(winchTty) - } - - // Handle debugging I/O. - debug, ok := os.LookupEnv("UV_DEBUG") - if ok && len(debug) > 0 { - f, err := os.OpenFile(debug, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o600) - if err != nil { - panic("failed to open debug file: " + err.Error()) - } - - logger := log.New(f, "uv: ", log.LstdFlags|log.Lshortfile) - t.SetLogger(logger) - } - return t -} - -// SetLogger sets the debug logger for the terminal. This is used to log debug -// information about the terminal I/O. By default, it is set to a no-op logger. -func (t *Terminal) SetLogger(logger Logger) { - t.logger = logger -} - -// ColorProfile returns the currently used color profile for the terminal. -func (t *Terminal) ColorProfile() colorprofile.Profile { - return t.profile -} - -// SetColorProfile sets a custom color profile for the terminal. This is useful -// for forcing a specific color output. By default, the terminal will use the -// system's color profile inferred by the environment variables. -func (t *Terminal) SetColorProfile(p colorprofile.Profile) { - t.profile = p -} - -// ColorModel returns the color model of the terminal screen. -func (t *Terminal) ColorModel() color.Model { - return t.ColorProfile() -} - -// SetWidthMethod sets the width method used by the terminal. This is typically -// used to determine how the terminal calculates the width of a single -// grapheme. -// The default method is [ansi.WcWidth]. -func (t *Terminal) SetWidthMethod(method ansi.Method) { - t.method = method -} - -// WidthMethod returns the width method used by the terminal. This is typically -// used to determine how the terminal calculates the width of a single -// grapheme. -func (t *Terminal) WidthMethod() WidthMethod { - return t.method -} - -var _ color.Model = (*Terminal)(nil) - -// Convert converts the given color to the terminal's color profile. This -// implements the [color.Model] interface, allowing you to convert any color to -// the terminal's preferred color model. -func (t *Terminal) Convert(c color.Color) color.Color { - return t.profile.Convert(c) -} - -// GetSize returns the size of the terminal screen. It errors if the size -// cannot be determined. -func (t *Terminal) GetSize() (width, height int, err error) { - w, h, err := t.getSize() - if err != nil { - return 0, 0, fmt.Errorf("error getting terminal size: %w", err) - } - // Cache the last known size. - t.m.Lock() - t.size.Width = w - t.size.Height = h - t.m.Unlock() - return w, h, nil -} - -// Size returns the last known size of the terminal screen. This is updated -// whenever a window size change event is received. If you need to get the -// current size of the terminal, use [Terminal.GetSize]. -func (t *Terminal) Size() Size { - t.m.RLock() - defer t.m.RUnlock() - return t.size -} - -// Bounds returns the bounds of the terminal screen buffer. This is the -// rectangle that contains start and end points of the screen buffer. -// This is different from [Terminal.GetSize] which queries the size of the -// terminal window. The screen buffer can occupy a portion or all of the -// terminal window. Use [Terminal.Resize] to change the size of the screen -// buffer. -func (t *Terminal) Bounds() Rectangle { - return Rect(0, 0, t.buf.Width(), t.buf.Height()) -} - -// SetCell sets the cell at the given x, y position in the terminal buffer. -func (t *Terminal) SetCell(x int, y int, c *Cell) { - t.buf.SetCell(x, y, c) -} - -// CellAt returns the cell at the given x, y position in the terminal buffer. -func (t *Terminal) CellAt(x int, y int) *Cell { - return t.buf.CellAt(x, y) -} - -var _ Screen = (*Terminal)(nil) - -// Clear fills the terminal screen with empty cells, and clears the -// terminal screen. -// -// This is different from [Terminal.Erase], which only fills the screen -// buffer with empty cells without erasing the terminal screen first. -func (t *Terminal) Clear() { - t.buf.Clear() -} - -// ClearArea fills the given area of the terminal screen with empty cells. -func (t *Terminal) ClearArea(area Rectangle) { - t.buf.ClearArea(area) -} - -// Fill fills the terminal screen with the given cell. If the cell is nil, it -// fills the screen with empty cells. -func (t *Terminal) Fill(c *Cell) { - t.buf.Fill(c) -} - -// FillArea fills the given area of the terminal screen with the given cell. -// If the cell is nil, it fills the area with empty cells. -func (t *Terminal) FillArea(c *Cell, area Rectangle) { - t.buf.FillArea(c, area) -} - -// Clone returns a copy of the terminal screen buffer. This is useful for -// creating a snapshot of the current terminal state without modifying the -// original buffer. -func (t *Terminal) Clone() *Buffer { - return t.buf.Clone() -} - -// CloneArea clones the given area of the terminal 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 terminal screen. -func (t *Terminal) CloneArea(area Rectangle) *Buffer { - return t.buf.CloneArea(area) -} - -// Position returns the last known position of the cursor in the terminal. -func (t *Terminal) Position() (int, int) { - return t.scr.Position() -} - -// SetPosition sets the position of the cursor in the terminal. This is -// typically used when the cursor was moved manually outside of the [Terminal] -// context. -func (t *Terminal) SetPosition(x, y int) { - t.scr.SetPosition(x, y) -} - -// MoveTo moves the cursor to the given x, y position in the terminal. This -// won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) MoveTo(x, y int) { - t.state.cur = Pos(x, y) -} - -func (t *Terminal) configureRenderer() { - t.scr.SetColorProfile(t.profile) - if t.useTabs { - t.m.RLock() - t.scr.SetTabStops(t.size.Width) - t.m.RUnlock() - } - t.scr.SetBackspace(t.useBspace) - t.scr.SetLogger(t.logger) -} - -// Erase fills the screen buffer with empty cells, and wipe the terminal -// screen. This is different from [Terminal.Clear], which only fills the -// terminal with empty cells. + 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 won't take any effect until the next [Terminal.Display]. -func (t *Terminal) Erase() { - t.buf.Touched = nil - t.scr.Erase() - t.Clear() +// 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) } -// Draw draws the given drawable component to the terminal screen buffer. It -// automatically resizes the screen buffer to match the size of the drawable -// component. +// 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 won't take any effect until the next [Terminal.Display]. -func (t *Terminal) Draw(d Drawable) { - frameArea := t.size.Bounds() - if d == nil { - // If the component is nil, we should clear the screen buffer. - frameArea.Max.Y = 0 - } - - // We need to resizes the screen based on the frame height and - // terminal width. This is because the frame height can change based on - // the content of the frame. For example, if the frame contains a list - // of items, the height of the frame will be the number of items in the - // list. This is different from the alt screen buffer, which has a - // fixed height and width. - frameHeight := frameArea.Dy() - switch layer := d.(type) { - case *StyledString: - frameHeight = layer.Height() - case interface{ Height() int }: - frameHeight = layer.Height() - case interface{ Bounds() Rectangle }: - frameHeight = layer.Bounds().Dy() - } - - if frameHeight != frameArea.Dy() { - frameArea.Max.Y = frameHeight - } - - // Resize the screen buffer to match the frame area. This is necessary - // to ensure that the screen buffer is the same size as the frame area - // and to avoid rendering issues when the frame area is smaller than - // the screen buffer. - t.buf.Resize(frameArea.Dx(), frameArea.Dy()) - - // Clear our screen buffer before copying the new frame into it to ensure - // we erase any old content. - t.buf.Clear() - if d != nil { - d.Draw(t, t.buf.Bounds()) - } - - // If the frame height is greater than the screen height, we drop the - // lines from the top of the buffer. - if frameHeight := frameArea.Dy(); frameHeight > t.size.Height { - t.buf.Lines = t.buf.Lines[frameHeight-t.size.Height:] +// 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 } -// Display computes the necessary changes to the terminal screen and renders -// the current buffer to the terminal screen. -// -// Typically, you would call this after modifying the terminal buffer using -// [Terminal.SetCell] or [Terminal.PrependString]. -func (t *Terminal) Display() error { - state := t.state // Capture the current state. - - // alternate screen buffer. - altscreenChanged := t.lastState == nil || t.lastState.altscreen != state.altscreen - if altscreenChanged { - setAltScreen(t, state.altscreen) +// 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() } - - // cursor visibility. - cursorVisChanged := t.lastState == nil || t.lastState.curHidden != state.curHidden - if cursorVisChanged || altscreenChanged { - if state.curHidden { - _, _ = t.scr.WriteString(ansi.ResetModeTextCursorEnable) - } else { - _, _ = t.scr.WriteString(ansi.SetModeTextCursorEnable) - } + if opts == nil { + opts = DefaultOptions() } - - // render the buffer. - t.scr.Render(t.buf) - - // add any prepended strings. - if len(t.prepend) > 0 { - for _, line := range t.prepend { - prependLine(t, line) - } - t.prepend = t.prepend[:0] - } - - if state.cur != Pos(-1, -1) { - // MoveTo must come after [TerminalRenderer.Render] because the cursor - // position might get updated during rendering. - t.scr.MoveTo(state.cur.X, state.cur.Y) + if opts.BufferSize <= 0 { + opts.BufferSize = DefaultBufferSize } - - if err := t.Flush(); err != nil { - return fmt.Errorf("error flushing terminal: %w", err) + if opts.EventTimeout <= 0 { + opts.EventTimeout = DefaultEventTimeout } - - t.lastState = &state // Save the last state. - - return nil -} - -// Flush flushes any pending renders to the terminal screen. This is typically -// used to flush the underlying screen buffer to the terminal. -// -// Use [Terminal.Buffered] to check how many bytes pending to be flushed. -func (t *Terminal) Flush() error { - if err := t.scr.Flush(); err != nil { - return fmt.Errorf("error flushing terminal: %w", err) + 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 nil + return t } -func prependLine(t *Terminal, line string) { - strLines := strings.Split(line, "\n") - for i, line := range strLines { - // If the line is wider than the screen, truncate it. - strLines[i] = ansi.Truncate(line, t.size.Width, "") +// 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) } - t.scr.PrependString(t.buf, strings.Join(strLines, "\n")) -} - -// Buffered returns the number of bytes buffered for the flush operation. -func (t *Terminal) Buffered() int { - return t.scr.Buffered() -} - -// Touched returns the number of touched lines in the terminal buffer. -func (t *Terminal) Touched() int { - return t.scr.Touched(t.buf) + return int(w), int(h), nil } -// EnterAltScreen enters the alternate screen buffer. This is typically used -// for applications that want to take over the entire terminal screen. -// -// Note that this won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) EnterAltScreen() { - t.state.altscreen = true -} - -// ExitAltScreen exits the alternate screen buffer and returns to the normal -// screen buffer. -// -// The [Terminal] manages the alternate screen buffer for you based on the -// [Viewport] used during [Terminal.Display]. This means that you don't need to -// call this unless you know what you're doing. +// 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 won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) ExitAltScreen() { - t.state.altscreen = false -} - -// ShowCursor shows the terminal cursor. -// -// The [Terminal] manages the visibility of the cursor for you based on the -// [Viewport] used during [Terminal.Display]. This means that you don't need to -// call this unless you know what you're doing. -// -// Note that this won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) ShowCursor() { - t.state.curHidden = false -} - -// HideCursor hides the terminal cursor. -// -// The [Terminal] manages the visibility of the cursor for you based on the -// [Viewport] used during [Terminal.Display]. This means that you don't need to -// call this unless you know what you're doing. -// -// Note that this won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) HideCursor() { - t.state.curHidden = true -} - -// Resize resizes the terminal screen buffer to the given width and height. -// This won't affect [Terminal.Size] or the terminal size, but it will resize -// the screen buffer used by the terminal. -func (t *Terminal) Resize(width, height int) error { - // We need to reset the touched lines buffer to match the new height. - t.buf.Touched = nil - t.buf.Resize(width, height) - if t.scr != nil { - t.scr.Resize(width, height) - } - return nil -} - -// Start prepares the terminal for use. It starts the input reader and -// initializes the terminal state. This should be called before using the -// terminal. -func (t *Terminal) Start() error { - if t.running.Load() { - return ErrRunning - } - - if t.inTty == nil && t.outTty == nil { - return ErrNotTerminal - } - - // Create a new terminal renderer. - t.scr = NewTerminalRenderer(t.out, t.environ) - - // First run, add some default states. - if t.lastState == nil { - t.EnterAltScreen() - t.HideCursor() - t.state.cur = Pos(-1, -1) - } - - // Store the initial terminal size. - w, h, err := t.GetSize() +// 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 fmt.Errorf("error getting initial terminal size: %w", err) - } - - t.size = Size{Width: w, Height: h} - - if t.buf.Width() == 0 && t.buf.Height() == 0 { - // If the buffer is not initialized, set it to the terminal size. - t.buf.Resize(t.size.Width, t.size.Height) - t.scr.Erase() - } - - t.scr.Resize(t.buf.Width(), t.buf.Height()) - - if err := t.initialize(); err != nil { - _ = t.restore() - return err - } - - // We need to call [Terminal.optimizeMovements] before creating the screen - // to populate [Terminal.useBspace] and [Terminal.useTabs]. - t.optimizeMovements() - t.configureRenderer() - - t.running.Store(true) - - return t.initializeState() -} - -// Pause pauses the terminal input reader. This is typically used to pause the -// terminal input reader when the terminal is not in use, such as when -// switching to another application. -func (t *Terminal) Pause() error { - if !t.running.Load() { - return ErrNotRunning - } - - t.running.Store(false) - - if err := t.restore(); err != nil { - return fmt.Errorf("error restoring terminal: %w", err) + return nil, fmt.Errorf("getting terminal winsize: %w", err) } - return nil -} - -// Resume resumes the terminal input reader. This is typically used to resume -// the terminal input reader when the terminal is in use again, such as when -// switching back to the terminal application. -func (t *Terminal) Resume() error { - if t.running.Load() { - return ErrRunning - } - - t.running.Store(true) - - if err := t.initialize(); err != nil { - return fmt.Errorf("error entering raw mode: %w", err) - } - - return t.initializeState() -} - -// Stop stops the terminal and restores the terminal to its original state. -// This is typically used to stop the terminal gracefully. -func (t *Terminal) Stop() error { - return t.stop() -} - -// Teardown is similar to [Terminal.Stop], but it also closes the input reader -// and the event channel as well as any other resources used by the terminal. -// This is typically used to completely shutdown the application. -func (t *Terminal) Teardown() error { - if err := t.stop(); err != nil { - return fmt.Errorf("error stopping terminal: %w", err) - } - _ = t.cr.Close() - t.evcancel() - return nil -} - -// Wait waits for the terminal to shutdown and all pending events to be -// processed. This is typically used to wait for the terminal to shutdown -// gracefully. -func (t *Terminal) Wait() error { - if err := t.errg.Wait(); err != nil { - return fmt.Errorf("error waiting for terminal: %w", err) - } - return nil + return ws, nil } -// Shutdown gracefully tears down the terminal, restoring its original state -// and stopping the event channel. It waits for any pending events to be -// processed or the context to be done before closing the event channel. -func (t *Terminal) Shutdown(ctx context.Context) error { - if err := t.Teardown(); err != nil { - return err - } - errc := make(chan error, 1) - go func() { - errc <- t.Wait() - }() - select { - case <-ctx.Done(): - return ctx.Err() //nolint:wrapcheck - case err := <-errc: - return err - } +// Screen returns the terminal's screen. +func (t *Terminal) Screen() *TerminalScreen { + return t.scr } -// Events returns the event channel used by the terminal to send input events. -// Use [Terminal.SendEvent] to send events to the terminal event loop. +// Events returns the terminal's event channel. func (t *Terminal) Events() <-chan Event { - return t.evs + return t.evc } -// SendEvent sends the given event to the terminal event loop. This is -// typically used to send custom events to the terminal, such as -// application-specific events. -func (t *Terminal) SendEvent(ev Event) { - select { - case <-t.evctx.Done(): - case t.evch <- ev: - } -} - -// PrependString adds the given string to the top of the terminal screen. The -// string is split into lines and each line is added as a new line at the top -// of the screen. The added lines are not managed by the terminal and will not -// be cleared or updated by the [Terminal]. -// -// This will truncate each line to the terminal width, so if the string is -// longer than the terminal width, it will be truncated to fit. -// -// 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. -// -// Note that this won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) PrependString(str string) { - t.prepend = append(t.prepend, str) -} - -// PrependLines adds lines of cells to the top of the terminal screen. The -// added line is unmanaged and will not be cleared or updated by the -// [Terminal]. -// -// This will truncate each line to the terminal width, so if the string is -// longer than the terminal width, it will be truncated to fit. -// -// 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. -// -// Note that this won't take any effect until the next [Terminal.Display] call. -func (t *Terminal) PrependLines(lines ...Line) { - for _, l := range lines { - t.prepend = append(t.prepend, l.Render()) - } -} - -// Write writes the given bytes to the underlying terminal renderer. -// This is typically used to write arbitrary data to the terminal, usually -// escape sequences or control characters. -// -// This can affect the renderer state and the terminal screen, so it should be -// used with caution. -// -// Note that this won't take any effect until the next [Terminal.Display] or -// [Terminal.Flush] call. -func (t *Terminal) Write(p []byte) (n int, err error) { - return t.scr.Write(p) -} - -// WriteString writes the given string to the underlying terminal renderer. -// This is typically used to write arbitrary data to the terminal, usually -// escape sequences or control characters. -// -// This can affect the renderer state and the terminal screen, so it should be -// used with caution. -// -// Note that this won't take any effect until the next [Terminal.Display] or -// [Terminal.Flush] call. -func (t *Terminal) WriteString(s string) (n int, err error) { - return t.scr.WriteString(s) -} - -func (t *Terminal) stop() error { - if !t.running.Load() { - return ErrNotRunning - } - - if err := t.restore(); err != nil { - return fmt.Errorf("error restoring terminal: %w", err) - } - - t.running.Store(false) - return nil -} - -func setAltScreen(t *Terminal, enable bool) { - if enable { - t.scr.EnterAltScreen() - } else { - t.scr.ExitAltScreen() - } -} - -func (t *Terminal) initializeState() error { - if t.lastState == nil { - setAltScreen(t, true) - return nil - } - - setAltScreen(t, t.lastState.altscreen) - - if t.lastState.curHidden { - _, _ = t.scr.WriteString(ansi.ResetModeTextCursorEnable) - } else { - _, _ = t.scr.WriteString(ansi.SetModeTextCursorEnable) - } - if t.lastState.cur != Pos(-1, -1) { - t.MoveTo(t.lastState.cur.X, t.lastState.cur.Y) - } - - return t.scr.Flush() -} - -func (t *Terminal) initialize() error { - // Initialize the terminal IO streams. - if err := t.makeRaw(); err != nil { - return fmt.Errorf("error entering raw mode: %w", err) - } - - // Initialize input. - cr, err := NewCancelReader(t.in) +// 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("error creating cancel reader: %w", err) + return fmt.Errorf("failed to set terminal to raw mode: %w", err) } - t.cr = cr - t.rd = NewTerminalReader(t.cr, t.termtype) - t.rd.SetLogger(t.logger) - t.evloop = make(chan struct{}) - - // Send the initial window size to the event channel. - t.errg.Go(t.initialResizeEvent) - - // Start the window size notifier if it is available. - if t.winchn != nil { - if err := t.winchn.Start(); err != nil { - return fmt.Errorf("error starting window size notifier: %w", err) - } - // Start SIGWINCH listener if available. - t.errg.Go(t.resizeLoop) + evs := newEventScanner() + evs.lookup = t.opts.LookupKeys + if evs.lookup { + evs.table = buildKeysTable(t.opts.LegacyKeyEncoding, t.con.Getenv("TERM"), t.opts.UseTerminfoKeys) } - - // Input and event loops - t.errg.Go(t.inputLoop) - t.errg.Go(t.eventLoop) - - return nil -} - -func (t *Terminal) initialResizeEvent() error { - var cells, pixels Size - var err error - if t.winchn == nil { - cells.Width, cells.Height, err = t.GetSize() - } else { - cells, pixels, err = t.winchn.GetWindowSize() + 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 err - } - - events := []Event{ - WindowSizeEvent(cells), - } - if pixels.Width > 0 && pixels.Height > 0 { - events = append(events, WindowPixelSizeEvent(pixels)) - } - for _, e := range events { - select { - case <-t.evctx.Done(): - return nil - case t.evch <- e: - } + return fmt.Errorf("failed to create poll reader: %w", err) } - return nil -} -func (t *Terminal) resizeLoop() error { - if t.winchn == nil { - return nil - } - for { - select { - case <-t.evctx.Done(): - return nil - case <-t.winchn.C: - cells, pixels, err := t.winchn.GetWindowSize() + // input loop + t.errg.Go(func() error { + for { + n, err := t.pr.Read(t.buf) if err != nil { - return err + return fmt.Errorf("reading terminal input: %w", err) } + select { + case bufc <- t.buf[:n]: + 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) - t.m.RLock() - size, pixSize := t.size, t.pixSize - t.m.RUnlock() - - if cells != size { - select { - case <-t.evctx.Done(): - return nil - case t.evch <- WindowSizeEvent(cells): + 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 pixels != pixSize && pixels.Width > 0 && pixels.Height > 0 { - select { - case <-t.evctx.Done(): - return nil - case t.evch <- WindowPixelSizeEvent(pixels): + 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) } } - - t.m.Lock() - t.size = cells - if pixels.Width > 0 && pixels.Height > 0 { - t.pixSize = pixels - } - t.m.Unlock() } - } -} - -func (t *Terminal) inputLoop() error { - defer close(t.evloop) + }) - if err := t.rd.StreamEvents(t.evctx, t.evch); err != nil { - return err + 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 } - return nil -} -func (t *Terminal) eventLoop() error { - for { - select { - case <-t.evctx.Done(): - return nil - case ev, ok := <-t.evch: - if !ok { - return nil - } - switch ev := ev.(type) { - case WindowSizeEvent: - t.m.Lock() - t.size = Size(ev) - t.m.Unlock() - case WindowPixelSizeEvent: - t.m.Lock() - t.pixSize = Size(ev) - t.m.Unlock() - } + // winch handler + NotifyWinch(t.winch) + t.errg.Go(func() error { + for { select { - case <-t.evctx.Done(): + case <-t.donec: return nil - case t.evs <- ev: + case <-t.winch: + if err := sendWinsize(); err != nil { + return err + } } } - } -} + }) -// restoreTTY restores the terminal TTY to its original state. -func (t *Terminal) restoreTTY() error { - if t.inTtyState != nil { - if err := term.Restore(t.inTty.Fd(), t.inTtyState); err != nil { - return fmt.Errorf("error restoring input terminal state: %w", err) + // init window size + t.errg.Go(func() error { + if err := sendWinsize(); err != nil { + return err } - t.inTtyState = nil - } - if t.outTtyState != nil { - if err := term.Restore(t.outTty.Fd(), t.outTtyState); err != nil { - return fmt.Errorf("error restoring output terminal state: %w", err) - } - t.outTtyState = nil + 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) } - if t.winchn != nil { - if err := t.winchn.Stop(); err != nil { - return fmt.Errorf("error stopping window size notifier: %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 } -// restoreState restores the terminal state, including modes, colors, and -// cursor position. If flush is false, it won't commit the changes to the -// terminal immediately. -func (t *Terminal) restoreState() error { - if t.cr != nil { - t.cr.Cancel() +// 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.evloop: - case <-time.After(500 * time.Millisecond): - // Timeout waiting for the event loop to exit. + case <-t.donec: + // Already closed. + default: + close(t.donec) } } - if ls := t.lastState; ls != nil { - if ls.altscreen { - setAltScreen(t, false) - } else { - // Go to the bottom of the screen. - t.scr.MoveTo(0, t.buf.Height()-1) - _, _ = t.WriteString("\r" + ansi.EraseScreenBelow) - } - if ls.curHidden { - _, _ = t.scr.WriteString(ansi.SetModeTextCursorEnable) - } + 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 { - return fmt.Errorf("error flushing terminal: %w", err) + _ = 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) } - - // Reset cursor position for next start. - t.scr.SetPosition(-1, -1) - return nil } -// restore is a helper function that restores the terminal TTY and state. It also moves the cursor -// to the bottom of the screen to avoid overwriting any terminal content. -func (t *Terminal) restore() error { - if err := t.restoreState(); err != nil { - return err - } - if err := t.restoreTTY(); err != nil { - return err +// 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: } - return nil +} + +// 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/src/vendor/github.com/charmbracelet/ultraviolet/terminal_other.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_other.go index ccd11569..9130fcc4 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_other.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_other.go @@ -3,15 +3,20 @@ package uv -func (*Terminal) makeRaw() error { - return ErrPlatformNotSupported +import "github.com/charmbracelet/x/term" + +func makeRaw(_, _ term.File) (inTtyState, outTtyState *term.State, err error) { + return nil, nil, ErrPlatformNotSupported } -func (*Terminal) getSize() (int, int, error) { +func getSize(_, _ term.File) (w, h int, err error) { return 0, 0, ErrPlatformNotSupported } -func (t *Terminal) optimizeMovements() {} +func getWinsize(_, _ term.File) (ws Winsize, err error) { + return Winsize{}, ErrPlatformNotSupported +} -func (*Terminal) enableWindowsMouse() error { return ErrPlatformNotSupported } -func (*Terminal) disableWindowsMouse() error { return ErrPlatformNotSupported } +func optimizeMovements(*term.State) (useTabs, useBspace bool) { + return false, false +} diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader.go index 4cb1b34e..b3b79cd0 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader.go @@ -8,6 +8,7 @@ import ( "io" "strconv" "strings" + "sync" "time" "unicode" "unicode/utf16" @@ -62,6 +63,8 @@ type TerminalReader struct { //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 @@ -101,6 +104,12 @@ func NewTerminalReader(r io.Reader, termType string) *TerminalReader { 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 } @@ -134,7 +143,11 @@ func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) timeout := time.NewTimer(d.EscTimeout) ttimeout := time.Now().Add(d.EscTimeout) + 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 @@ -148,10 +161,12 @@ func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) for { select { case <-ctx.Done(): - d.sendEvents(buf.Bytes(), true, eventc) + d.sendEvents(eventc, buf.Bytes(), true) + wg.Wait() return nil case err := <-errc: - d.sendEvents(buf.Bytes(), true, eventc) + d.sendEvents(eventc, buf.Bytes(), true) + wg.Wait() return err // return the first error encountered case <-timeout.C: d.logf("timeout reached") @@ -161,7 +176,7 @@ func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) timedout := time.Now().After(ttimeout) if buf.Len() > 0 && timedout { d.logf("timeout expired, processing buffer") - n = d.sendEvents(buf.Bytes(), true, eventc) + n = d.sendEvents(eventc, buf.Bytes(), true) } if n > 0 { @@ -185,7 +200,7 @@ func (d *TerminalReader) StreamEvents(ctx context.Context, eventc chan<- Event) d.logf("input: %q", read) buf.Write(read) ttimeout = time.Now().Add(d.EscTimeout) - n := d.sendEvents(buf.Bytes(), false, eventc) + n := d.sendEvents(eventc, buf.Bytes(), false) if !timeout.Stop() { // drain the channel if it was already running select { @@ -213,15 +228,43 @@ func (d *TerminalReader) SetLogger(logger Logger) { d.logger = logger } -func (d *TerminalReader) sendEvents(buf []byte, expired bool, eventc chan<- Event) int { - n, events := d.scanEvents(buf, expired) +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 } -func (d *TerminalReader) scanEvents(buf []byte, expired bool) (total int, events []Event) { +// 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 } @@ -344,7 +387,7 @@ func (d *TerminalReader) scanEvents(buf []byte, expired bool) (total int, events return total, events } -func (d *TerminalReader) encodeGraphemeBufs() []byte { +func (d *eventScanner) encodeGraphemeBufs() []byte { var b []byte for kd := range d.graphemeBuf { if len(d.graphemeBuf[kd]) > 0 { @@ -387,7 +430,7 @@ func (d *TerminalReader) encodeGraphemeBufs() []byte { return b } -func (d *TerminalReader) storeGraphemeRune(kd int, r rune) { +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 @@ -408,9 +451,9 @@ func (d *TerminalReader) storeGraphemeRune(kd int, r rune) { // 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 *TerminalReader) deserializeWin32Input(buf []byte) (int, []byte) { - p := parserPool.Get().(*ansi.Parser) - defer parserPool.Put(p) +func (d *eventScanner) deserializeWin32Input(buf []byte) (int, []byte) { + p := ansi.GetParser() + defer ansi.PutParser(p) var processed int var state byte @@ -449,8 +492,12 @@ func (d *TerminalReader) deserializeWin32Input(buf []byte) (int, []byte) { } func (d *TerminalReader) logf(format string, v ...interface{}) { - if d.logger == nil { + logf(d.logger, format, v...) +} + +func logf(logger Logger, format string, v ...interface{}) { + if logger == nil { return } - d.logger.Printf(format, v...) + logger.Printf(format, v...) } diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader_windows.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader_windows.go index deacc8b9..8a526b95 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader_windows.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_reader_windows.go @@ -108,9 +108,9 @@ func (d *TerminalReader) serializeWin32InputRecords(records []xwindows.InputReco } else { // We encode the key to Win32 Input Mode if it is a known key. if kevent.VirtualKeyCode == 0 { - d.storeGraphemeRune(kd, kevent.Char) + d.eventScanner.storeGraphemeRune(kd, kevent.Char) } else { - buf.Write(d.encodeGraphemeBufs()) + buf.Write(d.eventScanner.encodeGraphemeBufs()) fmt.Fprintf(buf, "\x1b[%d;%d;%d;%d;%d;%d_", kevent.VirtualKeyCode, @@ -200,7 +200,7 @@ func (d *TerminalReader) serializeWin32InputRecords(records []xwindows.InputReco } // Flush any remaining grapheme buffers. - buf.Write(d.encodeGraphemeBufs()) + buf.Write(d.eventScanner.encodeGraphemeBufs()) } func mouseEventButton(p, s uint32) (MouseButton, bool) { @@ -295,13 +295,13 @@ func peekNConsoleInputs(console windows.Handle, maxEvents uint32) ([]xwindows.In func keyEventString(vkc, sc uint16, r rune, keyDown bool, cks uint32, repeatCount uint16) string { var s strings.Builder s.WriteString("vkc: ") - s.WriteString(fmt.Sprintf("%d, 0x%02x", vkc, vkc)) + fmt.Fprintf(&s, "%d, 0x%02x", vkc, vkc) s.WriteString(", sc: ") - s.WriteString(fmt.Sprintf("%d, 0x%02x", sc, sc)) + fmt.Fprintf(&s, "%d, 0x%02x", sc, sc) s.WriteString(", r: ") - s.WriteString(fmt.Sprintf("%q 0x%x", r, r)) + fmt.Fprintf(&s, "%q 0x%x", r, r) s.WriteString(", down: ") - s.WriteString(fmt.Sprintf("%v", keyDown)) + fmt.Fprintf(&s, "%v", keyDown) s.WriteString(", cks: [") if cks&xwindows.LEFT_ALT_PRESSED != 0 { s.WriteString("left alt, ") @@ -331,6 +331,6 @@ func keyEventString(vkc, sc uint16, r rune, keyDown bool, cks uint32, repeatCoun s.WriteString("enhanced key, ") } s.WriteString("], repeat count: ") - s.WriteString(fmt.Sprintf("%d", repeatCount)) + fmt.Fprintf(&s, "%d", repeatCount) return s.String() } diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer.go index 6c0ef22c..41ba8eb6 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer.go @@ -87,6 +87,10 @@ 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. @@ -127,7 +131,7 @@ func (v tFlag) Contains(c tFlag) bool { type TerminalRenderer struct { w io.Writer buf *bytes.Buffer // buffer for writing to the screen - curbuf *Buffer // the current buffer + curbuf *RenderBuffer // the current buffer tabs *TabStops hasher maphash.Hash oldhash, newhash []uint64 // the old and new hash values for each line @@ -135,11 +139,12 @@ type TerminalRenderer struct { 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 - scrollHeight int // keeps track of how many lines we've scrolled down (inline mode) 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 + lineHadWide bool // whether the line currently being transformed contained a wide cell logger Logger // The logger used for debugging. // profile is the color profile to use when downsampling colors. This is @@ -166,7 +171,6 @@ func NewTerminalRenderer(w io.Writer, env []string) (s *TerminalRenderer) { 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.scrollHeight = 0 s.oldhash, s.newhash = nil, nil return } @@ -183,6 +187,15 @@ 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. @@ -194,6 +207,28 @@ func (s *TerminalRenderer) SetMapNewline(v bool) { } } +// 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 { @@ -307,7 +342,7 @@ func (s *TerminalRenderer) ExitAltScreen() { // 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 *Buffer, str string) { +func (s *TerminalRenderer) PrependString(newbuf *RenderBuffer, str string) { if len(str) == 0 { return } @@ -323,7 +358,7 @@ func (s *TerminalRenderer) PrependString(newbuf *Buffer, str string) { lines := strings.Split(str, "\n") offset := 0 for _, line := range lines { - lineWidth := ansi.StringWidth(line) + lineWidth := s.method.StringWidth(line) if w > 0 && lineWidth > w { offset += (lineWidth / w) } @@ -350,7 +385,7 @@ func (s *TerminalRenderer) PrependString(newbuf *Buffer, str string) { // // 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 *Buffer, x, y int, overwrite bool) { +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 @@ -358,9 +393,7 @@ func (s *TerminalRenderer) moveCursor(newbuf *Buffer, x, y int, overwrite bool) _ = s.buf.WriteByte('\r') s.cur.X, s.cur.Y = 0, 0 } - seq, scrollHeight := moveCursor(s, newbuf, x, y, overwrite) - // If we scrolled the screen, we need to update the scroll height. - s.scrollHeight = max(s.scrollHeight, scrollHeight) + seq := moveCursor(s, newbuf, x, y, overwrite) _, _ = s.buf.WriteString(seq) s.cur.X, s.cur.Y = x, y } @@ -369,7 +402,7 @@ func (s *TerminalRenderer) moveCursor(newbuf *Buffer, x, y int, overwrite bool) // // 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 *Buffer, x, y int) { +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 @@ -446,17 +479,20 @@ func cellEqual(a, b *Cell) bool { if a == b { return true } - if a == nil { - a = &EmptyCell - } - if b == nil { - b = &EmptyCell + // 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. -func (s *TerminalRenderer) putCell(newbuf *Buffer, cell *Cell) { +func (s *TerminalRenderer) putCell(newbuf *RenderBuffer, cell *Cell) { width, height := newbuf.Width(), newbuf.Height() if s.flags.Contains(tFullscreen) && s.cur.X == width-1 && s.cur.Y == height-1 { s.putCellLR(newbuf, cell) @@ -477,8 +513,8 @@ func (s *TerminalRenderer) wrapCursor() { } } -func (s *TerminalRenderer) putAttrCell(newbuf *Buffer, cell *Cell) { - if cell != nil && cell.IsZero() { +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 @@ -506,13 +542,17 @@ func (s *TerminalRenderer) putAttrCell(newbuf *Buffer, cell *Cell) { if s.cur.X >= newbuf.Width() { s.atPhantom = true } + + if cellWidth > 1 { + s.lineHadWide = true + } } // putCellLR draws a cell at the lower right corner of the screen. -func (s *TerminalRenderer) putCellLR(newbuf *Buffer, cell *Cell) { +func (s *TerminalRenderer) putCellLR(newbuf *RenderBuffer, cell *Cell) { // Optimize for the lower right corner cell. curX := s.cur.X - if cell == nil || !cell.IsZero() { + if !cell.isWidePlaceholder() { _, _ = s.buf.WriteString(ansi.ResetModeAutoWrap) s.putAttrCell(newbuf, cell) // Writing to lower-right corner cell should not wrap. @@ -579,7 +619,7 @@ func canClearWith(c *Cell) bool { // [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 *Buffer, line Line, n int) (eoi bool) { +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 @@ -661,7 +701,7 @@ func (s *TerminalRenderer) emitRange(newbuf *Buffer, line Line, n int) (eoi bool // 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 *Buffer, oldLine, newLine Line, y, start, end int) (eoi bool) { +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)))) @@ -669,7 +709,7 @@ func (s *TerminalRenderer) putRange(newbuf *Buffer, oldLine, newLine Line, y, st var j, same int for j, same = start, 0; j <= end; j++ { oldCell, newCell := oldLine.At(j), newLine.At(j) - if same == 0 && oldCell != nil && oldCell.IsZero() { + if same == 0 && oldCell.isWidePlaceholder() && newCell.isWidePlaceholder() { continue } if cellEqual(oldCell, newCell) { @@ -700,7 +740,7 @@ func (s *TerminalRenderer) putRange(newbuf *Buffer, oldLine, newLine Line, y, st // clearToEnd clears the screen from the current cursor position to the end of // line. -func (s *TerminalRenderer) clearToEnd(newbuf *Buffer, blank *Cell, force bool) { +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 @@ -737,7 +777,7 @@ func (s *TerminalRenderer) clearBlank() *Cell { // insertCells inserts the count cells pointed by the given line at the current // cursor position. -func (s *TerminalRenderer) insertCells(newbuf *Buffer, line Line, count int) { +func (s *TerminalRenderer) insertCells(newbuf *RenderBuffer, line Line, count int) { supportsICH := s.caps.Contains(capICH) if supportsICH { // Use [ansi.ICH] as an optimization. @@ -768,14 +808,91 @@ func (s *TerminalRenderer) el0Cost() int { 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 || m.StringWidth(c.Content) != ansi.StringWidth(c.Content) { + return true + } + } + return false +} + +// repaintLine repaints a line from scratch. Unlike +// [TerminalRenderer.transformLine] it does not diff against the previous +// frame: it erases the whole line from column 0 with [ansi.EraseLineRight] +// and then writes the new frame's cells. Erasing from column 0 removes the +// entire line including any wide cells the terminal painted at a different +// width than the model measured, whose real extent the model cannot know. +// The repaint then starts from a known-empty line and an absolute cursor +// position, so the result does not depend on where the previous frame left +// the cursor. +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 + + // 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 < newbuf.Width(); 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. + if len(oldLine) == len(newLine) { + copy(oldLine, newLine) + } +} + // transformLine transforms the given line in the current window to the // corresponding line in the new window. It uses [ansi.ICH] and [ansi.DCH] to // insert or delete characters. -func (s *TerminalRenderer) transformLine(newbuf *Buffer, y int) { +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) + s.lineHadWide = false + defer s.reanchorWideLine(newbuf) + + // If either frame's line holds a cell that a cell-level diff cannot + // safely reposition across, repaint the whole line instead. A wide cell + // (width > 1) occupies several columns, so a diff that lands on a + // continuation column splits the character, and per DEC semantics (also + // implemented by ghostty and x/vt) an erase that splits a multi-cell + // character erases the whole character, including a head cell that + // belongs to the new frame. A cell whose width the terminal measures + // differently than the model (an emoji cluster, a keycap) leaves the + // real cursor at a column the model cannot predict, so a later erase in + // the same transform fires at the wrong column. Repainting depends only + // on an absolute cursor position and a known-empty line. + if lineHasDrift(s.method, oldLine) || lineHasDrift(s.method, newLine) { + s.repaintLine(newbuf, y) + return + } + // Find the first changed cell in the line blank := newLine.At(0) @@ -917,7 +1034,7 @@ func (s *TerminalRenderer) transformLine(newbuf *Buffer, y int) { if n != 0 { for n > 0 { wide := newLine.At(n + 1) - if wide == nil || !wide.IsZero() { + if !wide.isWidePlaceholder() { break } n-- @@ -925,18 +1042,18 @@ func (s *TerminalRenderer) transformLine(newbuf *Buffer, y int) { } } else if n >= firstCell && newLine.At(n) != nil && newLine.At(n).Width > 1 { next := newLine.At(n + 1) - for next != nil && next.IsZero() { + for next.isWidePlaceholder() { n++ oLastCell++ + next = newLine.At(n + 1) } } - if oLastCell >= 0 && nLastCell >= 0 { - // Only move the cursor when we actually have changes to make. - // This prevents unnecessary cursor movements when we're adding - // new columns with blank cells. - s.move(newbuf, n+1, y) - } + // 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) @@ -966,6 +1083,22 @@ func (s *TerminalRenderer) transformLine(newbuf *Buffer, y int) { } } +// reanchorWideLine re-anchors the cursor with a single absolute horizontal +// move after a line that contained a wide cell. 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. +func (s *TerminalRenderer) reanchorWideLine(newbuf *RenderBuffer) { + if !s.lineHadWide || s.flags.Contains(tGraphemeWidth) { + return + } + s.lineHadWide = false + if s.atPhantom || s.cur.X < 0 || s.cur.X >= newbuf.Width() { + return + } + _, _ = s.buf.WriteString(ansi.CursorHorizontalAbsolute(s.cur.X + 1)) +} + // 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) { @@ -994,7 +1127,7 @@ func (s *TerminalRenderer) clearToBottom(blank *Cell) { // 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 *Buffer, total int) (top int) { +func (s *TerminalRenderer) clearBottom(newbuf *RenderBuffer, total int) (top int) { if total <= 0 { return 0 } @@ -1052,13 +1185,13 @@ func (s *TerminalRenderer) clearScreen(blank *Cell) { } // clearBelow clears everything below and including the row. -func (s *TerminalRenderer) clearBelow(newbuf *Buffer, blank *Cell, row int) { +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 *Buffer) { +func (s *TerminalRenderer) clearUpdate(newbuf *RenderBuffer) { blank := s.clearBlank() var nonEmpty int if s.flags.Contains(tFullscreen) { @@ -1106,38 +1239,25 @@ func (s *TerminalRenderer) Flush() (err error) { return } -// Touched returns the number of lines that have been touched or changed. -func (s *TerminalRenderer) Touched(buf *Buffer) (n int) { - if buf.Touched == nil { - return buf.Height() - } - for _, ch := range buf.Touched { - if ch != nil { - n++ - } - } - return -} - // Redraw forces a full redraw of the screen. It's equivalent to calling // [TerminalRenderer.Erase] and [TerminalRenderer.Render]. -func (s *TerminalRenderer) Redraw(newbuf *Buffer) { +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 *Buffer) { +func (s *TerminalRenderer) Render(newbuf *RenderBuffer) { // Do we need to render anything? - touchedLines := s.Touched(newbuf) + touchedLines := newbuf.TouchedLines() if !s.clear && touchedLines == 0 { return } if s.curbuf == nil || s.curbuf.Bounds().Empty() { // Initialize the current buffer - s.curbuf = NewBuffer(newbuf.Width(), newbuf.Height()) + s.curbuf = NewRenderBuffer(newbuf.Width(), newbuf.Height()) } newWidth, newHeight := newbuf.Width(), newbuf.Height() @@ -1145,6 +1265,14 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { if curWidth != newWidth || curHeight != newHeight { s.oldhash, s.newhash = nil, nil + // A shrink makes the terminal reflow in emulator-defined ways the + // incremental model cannot predict; force a full repaint. Only in + // fullscreen, where the renderer owns every cell it is about to + // clear. Inline mode shares the screen with whatever came before, + // so it uses the narrower partial clear below instead. + if s.flags.Contains(tFullscreen) && (newWidth < curWidth || newHeight < curHeight) { + s.clear = true + } } // TODO: Investigate whether this is necessary. Theoretically, terminals @@ -1173,6 +1301,12 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { s.clearBelow(newbuf, nil, newHeight-1) } + // Resize the model before diffing so the loop below walks every row + // of the new screen, including rows added by a grow. + if curWidth != newWidth || curHeight != newHeight { + s.curbuf.Resize(newWidth, newHeight) + } + if s.clear { //nolint:nestif s.clearUpdate(newbuf) s.clear = false @@ -1181,7 +1315,7 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { // 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(tFullscreen) && !isWindows { + 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]. @@ -1191,14 +1325,10 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { var changedLines int var i int - if s.flags.Contains(tFullscreen) { - nonEmpty = min(curHeight, newHeight) - } else { - nonEmpty = newHeight - } + nonEmpty = newHeight nonEmpty = s.clearBottom(newbuf, nonEmpty) - for i = 0; i < nonEmpty && i < newHeight; i++ { + for i = 0; i < nonEmpty; i++ { if newbuf.Touched == nil || i >= len(newbuf.Touched) || (newbuf.Touched[i] != nil && (newbuf.Touched[i].FirstCell != -1 || newbuf.Touched[i].LastCell != -1)) { s.transformLine(newbuf, i) @@ -1219,7 +1349,7 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { } } - if !s.flags.Contains(tFullscreen) && s.scrollHeight < newHeight-1 { + if !s.flags.Contains(tFullscreen) && (curWidth != newWidth || curHeight != newHeight) { s.move(newbuf, 0, newHeight-1) } @@ -1236,15 +1366,6 @@ func (s *TerminalRenderer) Render(newbuf *Buffer) { } } - if curWidth != newWidth || curHeight != newHeight { - // Resize the old buffer to match the new buffer. - s.curbuf.Resize(newWidth, newHeight) - // Sync new lines to old lines - for i := curHeight - 1; i < newHeight; i++ { - copy(s.curbuf.Line(i), newbuf.Line(i)) - } - } - s.updatePen(nil) // nil indicates a blank cell with no styles } @@ -1255,11 +1376,22 @@ func (s *TerminalRenderer) Erase() { // 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. func (s *TerminalRenderer) Resize(width, _ int) { if s.tabs != nil { s.tabs.Resize(width) } - s.scrollHeight = 0 + 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 @@ -1315,9 +1447,8 @@ func notLocal(cols, fx, fy, tx, ty int) bool { // // 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 *Buffer, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) (string, int) { +func relativeCursorMove(s *TerminalRenderer, newbuf *RenderBuffer, fx, fy, tx, ty int, overwrite, useTabs, useBackspace bool) string { var seq strings.Builder - var scrollHeight int if newbuf == nil { overwrite = false // We can't overwrite the current buffer. } @@ -1333,10 +1464,8 @@ func relativeCursorMove(s *TerminalRenderer, newbuf *Buffer, fx, fy, tx, ty int, if cud := ansi.CursorDown(n); yseq == "" || len(cud) < len(yseq) { yseq = cud } - shouldScroll := !s.flags.Contains(tFullscreen) && ty > s.scrollHeight - if shouldScroll || n < len(yseq) { // n is the cost of using newline characters + if !s.flags.Contains(tFullscreen) || n < len(yseq) { // n is the cost of using newline characters yseq = strings.Repeat("\n", n) - scrollHeight = ty if s.flags.Contains(tMapNewline) { fx = 0 } @@ -1420,8 +1549,6 @@ func relativeCursorMove(s *TerminalRenderer, newbuf *Buffer, fx, fy, tx, ty int, if cell != nil && cell.Width > 0 { ovw += cell.String() i += cell.Width - 1 - } else { - ovw += " " } } } @@ -1463,7 +1590,7 @@ func relativeCursorMove(s *TerminalRenderer, newbuf *Buffer, fx, fy, tx, ty int, seq.WriteString(xseq) } - return seq.String(), scrollHeight + return seq.String() } // moveCursor moves and returns the cursor movement sequence to move the cursor @@ -1473,7 +1600,7 @@ func relativeCursorMove(s *TerminalRenderer, newbuf *Buffer, fx, fy, tx, ty int, // // 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 *Buffer, x, y int, overwrite bool) (seq string, scrollHeight int) { +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) { @@ -1491,7 +1618,7 @@ func moveCursor(s *TerminalRenderer, newbuf *Buffer, x, y int, overwrite bool) ( // 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, 0 + return seq } } @@ -1515,32 +1642,29 @@ func moveCursor(s *TerminalRenderer, newbuf *Buffer, x, y int, overwrite bool) ( useBackspace := i&1 != 0 // Method #1: Use local movement sequences. - nseq1, nscrollHeight1 := relativeCursorMove(s, newbuf, fx, fy, x, y, overwrite, useHardTabs, useBackspace) + nseq1 := relativeCursorMove(s, newbuf, fx, fy, x, y, overwrite, useHardTabs, useBackspace) if (i == 0 && len(seq) == 0) || len(nseq1) < len(seq) { seq = nseq1 - scrollHeight = max(scrollHeight, nscrollHeight1) } // Method #2: Use [ansi.CR] and local movement sequences. - nseq2, nscrollHeight2 := relativeCursorMove(s, newbuf, 0, fy, x, y, overwrite, useHardTabs, useBackspace) + nseq2 := relativeCursorMove(s, newbuf, 0, fy, x, y, overwrite, useHardTabs, useBackspace) nseq2 = "\r" + nseq2 if len(nseq2) < len(seq) { seq = nseq2 - scrollHeight = max(scrollHeight, nscrollHeight2) } if !s.flags.Contains(tRelativeCursor) { // Method #3: Use [ansi.CursorHomePosition] and local movement sequences. - nseq3, nscrollHeight3 := relativeCursorMove(s, newbuf, 0, 0, x, y, overwrite, useHardTabs, useBackspace) + nseq3 := relativeCursorMove(s, newbuf, 0, 0, x, y, overwrite, useHardTabs, useBackspace) nseq3 = ansi.CursorHomePosition + nseq3 if len(nseq3) < len(seq) { seq = nseq3 - scrollHeight = max(scrollHeight, nscrollHeight3) } } } - return seq, scrollHeight + return seq } // xtermCaps returns whether the terminal is xterm-like. This means that the diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hardscroll.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hardscroll.go index 58dd4ad7..3b7eb00e 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hardscroll.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hardscroll.go @@ -8,7 +8,7 @@ import ( // scrollOptimize optimizes the screen to transform the old buffer into the new // buffer. -func (s *TerminalRenderer) scrollOptimize(newbuf *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))...) @@ -68,7 +68,7 @@ func (s *TerminalRenderer) scrollOptimize(newbuf *Buffer) { } // scrolln scrolls the screen up by n lines. -func (s *TerminalRenderer) scrolln(newbuf *Buffer, n, top, bot, maxY int) (v bool) { //nolint:unparam +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) @@ -117,7 +117,7 @@ func (s *TerminalRenderer) scrolln(newbuf *Buffer, n, top, bot, maxY int) (v boo } // scrollBuffer scrolls the buffer by n lines. -func (s *TerminalRenderer) scrollBuffer(b *Buffer, n, top, bot int, blank *Cell) { +func (s *TerminalRenderer) scrollBuffer(b *RenderBuffer, n, top, bot int, blank *Cell) { if top < 0 || bot < top || bot >= b.Height() { // Nothing to scroll return @@ -149,7 +149,7 @@ func (s *TerminalRenderer) scrollBuffer(b *Buffer, n, top, bot int, blank *Cell) } // touchLine marks the line as touched. -func (s *TerminalRenderer) touchLine(newbuf *Buffer, y, n int, changed bool) { +func (s *TerminalRenderer) touchLine(newbuf *RenderBuffer, y, n int, changed bool) { height := newbuf.Height() if n < 0 || y < 0 || y >= height || newbuf.Touched == nil || len(newbuf.Touched) < height { return // Nothing to touch @@ -166,7 +166,7 @@ func (s *TerminalRenderer) touchLine(newbuf *Buffer, y, n int, changed bool) { } // scrollUp scrolls the screen up by n lines. -func (s *TerminalRenderer) scrollUp(newbuf *Buffer, n, top, bot, minY, maxY int, blank *Cell) bool { +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) @@ -195,7 +195,7 @@ func (s *TerminalRenderer) scrollUp(newbuf *Buffer, n, top, bot, minY, maxY int, } // scrollDown scrolls the screen down by n lines. -func (s *TerminalRenderer) scrollDown(newbuf *Buffer, n, top, bot, minY, maxY int, blank *Cell) bool { +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) @@ -224,7 +224,7 @@ func (s *TerminalRenderer) scrollDown(newbuf *Buffer, n, top, bot, minY, maxY in // scrollIdl scrolls the screen n lines by using [ansi.DL] at del and using // [ansi.IL] at ins. -func (s *TerminalRenderer) scrollIdl(newbuf *Buffer, n, del, ins int, blank *Cell) bool { +func (s *TerminalRenderer) scrollIdl(newbuf *RenderBuffer, n, del, ins int, blank *Cell) bool { if n < 0 { return false } diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hashmap.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hashmap.go index 15984eeb..ad776ff8 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hashmap.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_renderer_hashmap.go @@ -24,7 +24,7 @@ type hashmap struct { const newIndex = -1 // updateHashmap updates the hashmap with the new hash value. -func (s *TerminalRenderer) updateHashmap(newbuf *Buffer) { +func (s *TerminalRenderer) updateHashmap(newbuf *RenderBuffer) { height := newbuf.Height() if len(s.oldhash) >= height && len(s.newhash) >= height { @@ -149,7 +149,7 @@ func (s *TerminalRenderer) scrollOldhash(n, top, bot int) { } } -func (s *TerminalRenderer) growHunks(newbuf *Buffer) { +func (s *TerminalRenderer) growHunks(newbuf *RenderBuffer) { var ( backLimit int // limits for cells to fill backRefLimit int // limit for references @@ -232,7 +232,7 @@ func (s *TerminalRenderer) growHunks(newbuf *Buffer) { // 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 *Buffer, from, to int, blank bool) bool { +func (s *TerminalRenderer) costEffective(newbuf *RenderBuffer, from, to int, blank bool) bool { if from == to { return false } @@ -275,9 +275,9 @@ func (s *TerminalRenderer) costEffective(newbuf *Buffer, from, to int, blank boo return costBeforeMove >= costAfterMove } -func (s *TerminalRenderer) updateCost(newbuf *Buffer, from, to Line) (cost int) { +func (s *TerminalRenderer) updateCost(_ *RenderBuffer, from, to Line) (cost int) { var fidx, tidx int - for i := newbuf.Width() - 1; i > 0; i, fidx, tidx = i-1, fidx+1, tidx+1 { + 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++ } @@ -285,11 +285,11 @@ func (s *TerminalRenderer) updateCost(newbuf *Buffer, from, to Line) (cost int) return } -func (s *TerminalRenderer) updateCostBlank(newbuf *Buffer, to Line) (cost int) { +func (s *TerminalRenderer) updateCostBlank(_ *RenderBuffer, to Line) (cost int) { // This assumes bce capability. blank := s.clearBlank() var tidx int - for i := newbuf.Width() - 1; i > 0; i, tidx = i-1, tidx+1 { + for i := s.curbuf.Width(); i > 0; i, tidx = i-1, tidx+1 { if !cellEqual(blank, to.At(tidx)) { cost++ } diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_screen.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_screen.go new file mode 100644 index 00000000..4078ce3e --- /dev/null +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_screen.go @@ -0,0 +1,837 @@ +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() + s.rbuf.Touched = nil +} + +// 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/src/vendor/github.com/charmbracelet/ultraviolet/terminal_unix.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_unix.go index eea42beb..04ed3e3f 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_unix.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_unix.go @@ -5,73 +5,52 @@ package uv import ( "github.com/charmbracelet/x/term" + "github.com/charmbracelet/x/termios" ) -func (t *Terminal) makeRaw() error { - var err error - - if t.inTty == nil && t.outTty == nil { - return ErrNotTerminal +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{t.inTty, t.outTty} { + for _, f := range []term.File{inTty, outTty} { if f == nil { continue } - t.inTtyState, err = term.MakeRaw(f.Fd()) + inTtyState, err = term.MakeRaw(f.Fd()) if err == nil { break } } if err != nil { - return err //nolint:wrapcheck + return nil, nil, err //nolint:wrapcheck } - return nil + return inTtyState, outTtyState, nil } -func (t *Terminal) getSize() (w, h int, err error) { +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{t.inTty, t.outTty} { + for _, f := range []term.File{inTty, outTty} { if f == nil { continue } - w, h, err = term.GetSize(f.Fd()) + size, err := termios.GetWinsize(int(f.Fd())) if err == nil { - return w, h, nil + return Winsize(*size), nil } } return } -func (t *Terminal) optimizeMovements() { - // Try both inTty and outTty to get the size. - var state *term.State - var err error - for _, s := range []*term.State{t.inTtyState, t.outTtyState} { - if s == nil { - continue - } - state = s - break - } - if state == nil { - for _, f := range []term.File{t.inTty, t.outTty} { - if f == nil { - continue - } - state, err = term.GetState(f.Fd()) - if err == nil { - break - } - } - } - if state == nil { - return - } - t.useTabs = supportsHardTabs(uint64(state.Oflag)) //nolint:unconvert,nolintlint - t.useBspace = supportsBackspace(uint64(state.Lflag)) //nolint:unconvert,nolintlint +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/src/vendor/github.com/charmbracelet/ultraviolet/terminal_windows.go b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_windows.go index 31a7eeda..a899ba48 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/terminal_windows.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/terminal_windows.go @@ -10,58 +10,62 @@ import ( "golang.org/x/sys/windows" ) -func (t *Terminal) makeRaw() (err error) { - if t.inTty == nil || t.outTty == nil || !term.IsTerminal(t.inTty.Fd()) || !term.IsTerminal(t.outTty.Fd()) { - return ErrNotTerminal +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 input. + // Save stdin state and enable VT inpu // We also need to enable VT input here. - t.inTtyState, err = term.MakeRaw(t.inTty.Fd()) + inTtyState, err = term.MakeRaw(inTty.Fd()) if err != nil { - return fmt.Errorf("error making terminal raw: %w", err) + return nil, nil, fmt.Errorf("error making terminal raw: %w", err) } // Enable VT input var imode uint32 - if err := windows.GetConsoleMode(windows.Handle(t.inTty.Fd()), &imode); err != nil { - return fmt.Errorf("error getting console mode: %w", err) + 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(t.inTty.Fd()), imode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil { - return fmt.Errorf("error setting 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. - t.outTtyState, err = term.GetState(t.outTty.Fd()) + outTtyState, err = term.GetState(outTty.Fd()) if err != nil { - return fmt.Errorf("error getting terminal state: %w", err) + return nil, nil, fmt.Errorf("error getting terminal state: %w", err) } var omode uint32 - if err := windows.GetConsoleMode(windows.Handle(t.outTty.Fd()), &omode); err != nil { - return fmt.Errorf("error getting console mode: %w", err) + 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(t.outTty.Fd()), + if err := windows.SetConsoleMode(windows.Handle(outTty.Fd()), omode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING| windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil { - return fmt.Errorf("error setting console mode: %w", err) + return nil, nil, fmt.Errorf("error setting console mode: %w", err) } - return //nolint:nakedret + return inTtyState, outTtyState, nil } -func (t *Terminal) getSize() (w, h int, err error) { - if t.outTty != nil { - return term.GetSize(t.outTty.Fd()) //nolint:wrapcheck +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 (t *Terminal) optimizeMovements() { - t.useBspace = supportsBackspace(0) - t.useTabs = supportsHardTabs(0) +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 { diff --git a/src/vendor/github.com/charmbracelet/ultraviolet/tty.go b/src/vendor/github.com/charmbracelet/ultraviolet/tty.go index 1f1496e6..7e7bd994 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/tty.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/tty.go @@ -1,6 +1,9 @@ package uv -import "os" +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 @@ -16,3 +19,24 @@ func OpenTTY() (inTty, outTty *os.File, err error) { 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/src/vendor/github.com/charmbracelet/ultraviolet/tty_other.go b/src/vendor/github.com/charmbracelet/ultraviolet/tty_other.go index 5ca07954..c4c986ce 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/tty_other.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/tty_other.go @@ -3,7 +3,11 @@ package uv -import "os" +import ( + "context" + "os" + "os/signal" +) func openTTY() (*os.File, *os.File, error) { return nil, nil, ErrPlatformNotSupported @@ -12,3 +16,11 @@ func openTTY() (*os.File, *os.File, error) { 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/src/vendor/github.com/charmbracelet/ultraviolet/tty_unix.go b/src/vendor/github.com/charmbracelet/ultraviolet/tty_unix.go index 2b272d17..328552cb 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/tty_unix.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/tty_unix.go @@ -4,9 +4,12 @@ package uv import ( + "context" "os" "os/signal" "syscall" + + "golang.org/x/sys/unix" ) func openTTY() (inTty, outTty *os.File, err error) { @@ -26,3 +29,11 @@ func suspend() (err error) { <-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/src/vendor/github.com/charmbracelet/ultraviolet/tty_windows.go b/src/vendor/github.com/charmbracelet/ultraviolet/tty_windows.go index 32fecd3e..4ad0ecb8 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/tty_windows.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/tty_windows.go @@ -3,7 +3,11 @@ package uv -import "os" +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 @@ -25,3 +29,11 @@ func suspend() (err error) { // 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/src/vendor/github.com/charmbracelet/ultraviolet/uv.go b/src/vendor/github.com/charmbracelet/ultraviolet/uv.go index a7c2890e..dac088a9 100644 --- a/src/vendor/github.com/charmbracelet/ultraviolet/uv.go +++ b/src/vendor/github.com/charmbracelet/ultraviolet/uv.go @@ -1,11 +1,20 @@ package uv import ( + "fmt" "image/color" - "runtime" + "io" + + "github.com/charmbracelet/x/ansi" + "github.com/lucasb-eyer/go-colorful" ) -var isWindows = runtime.GOOS == "windows" +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 { @@ -13,6 +22,16 @@ type Drawable interface { 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 @@ -51,6 +70,11 @@ type Cursor struct { // 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 @@ -111,3 +135,272 @@ func NewProgressBar(state ProgressBarState, value int) *ProgressBar { 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/src/vendor/github.com/charmbracelet/ultraviolet/window.go b/src/vendor/github.com/charmbracelet/ultraviolet/window.go new file mode 100644 index 00000000..e90bef28 --- /dev/null +++ b/src/vendor/github.com/charmbracelet/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 +} diff --git a/src/vendor/github.com/charmbracelet/x/ansi/color.go b/src/vendor/github.com/charmbracelet/x/ansi/color.go index 09feb975..eacca595 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/color.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/color.go @@ -236,7 +236,7 @@ func Convert256(c color.Color) IndexedColor { if colorDist <= grayDist { return IndexedColor(16 + ci) //nolint:gosec } - return IndexedColor(232 + greyIdx) //nolint:gosec + return IndexedColor(232 + greyIdx) // // Is grey or 6x6x6 color closest? // d := distSq(cr, cg, cb, int(r), int(g), int(b)) diff --git a/src/vendor/github.com/charmbracelet/x/ansi/kitty/options.go b/src/vendor/github.com/charmbracelet/x/ansi/kitty/options.go index 1ddfcdbb..bf3f8f06 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/kitty/options.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/kitty/options.go @@ -12,6 +12,8 @@ var ( _ encoding.TextUnmarshaler = &Options{} ) +// Stringish is a type constraint for types that are either a string or a +// byte slice. type Stringish interface{ string | []byte } // Options represents a Kitty Graphics Protocol options. @@ -23,10 +25,16 @@ type Options struct { // [Animate], [Compose]. Action byte - // Quite mode (q=0) is the quiet mode. Can be either zero, one, or two + // Quite is the kitty graphics quiet mode. + // + // Deprecated: misspelled field, use [Options.Quiet] instead. Any non-zero + // Quite overrides Quiet. + Quite byte + + // Quiet mode (q=0) is the quiet mode. Can be either zero, one, or two // where zero is the default, 1 suppresses OK responses, and 2 suppresses // both OK and error responses. - Quite byte + Quiet byte // Transmission options. @@ -173,8 +181,13 @@ func (o *Options) Options() (opts []string) { opts = append(opts, fmt.Sprintf("f=%d", o.Format)) } + quiet := o.Quiet if o.Quite > 0 { - opts = append(opts, fmt.Sprintf("q=%d", o.Quite)) + // handle deprecated Quite field. + quiet = o.Quite + } + if quiet > 0 { + opts = append(opts, fmt.Sprintf("q=%d", quiet)) } if o.ID > 0 { @@ -324,7 +337,7 @@ func (o *Options) UnmarshalText(text []byte) error { case "i": o.ID = v case "q": - o.Quite = byte(v) + o.Quiet = byte(v) //nolint:gosec case "p": o.PlacementID = v case "I": diff --git a/src/vendor/github.com/charmbracelet/x/ansi/kitty/writer.go b/src/vendor/github.com/charmbracelet/x/ansi/kitty/writer.go index 90f822d1..6093b95b 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/kitty/writer.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/kitty/writer.go @@ -167,8 +167,13 @@ func buildChunkOptions(o *Options, isFirstChunk, isLastChunk bool) []string { opts = o.Options() } else { // These options are allowed in subsequent chunks + quiet := o.Quiet if o.Quite > 0 { - opts = append(opts, fmt.Sprintf("q=%d", o.Quite)) + // handle deprecated Quite field. + quiet = o.Quite + } + if quiet > 0 { + opts = append(opts, fmt.Sprintf("q=%d", quiet)) } if o.Action == Frame { opts = append(opts, "a=f") diff --git a/src/vendor/github.com/charmbracelet/x/ansi/mouse.go b/src/vendor/github.com/charmbracelet/x/ansi/mouse.go index 94b8b485..bac4620f 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/mouse.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/mouse.go @@ -148,7 +148,7 @@ const x10Offset = 32 // // See: https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking func MouseX10(b byte, x, y int) string { - return "\x1b[M" + string(b+x10Offset) + string(byte(x)+x10Offset+1) + string(byte(y)+x10Offset+1) + return "\x1b[M" + string(b+x10Offset) + string(byte(x)+x10Offset+1) + string(byte(y)+x10Offset+1) //nolint:gosec } // MouseSgr returns an escape sequence representing a mouse event in SGR mode. diff --git a/src/vendor/github.com/charmbracelet/x/ansi/parser/transition_table.go b/src/vendor/github.com/charmbracelet/x/ansi/parser/transition_table.go index ef46b7b6..14daaf51 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/parser/transition_table.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/parser/transition_table.go @@ -52,7 +52,7 @@ func (t TransitionTable) AddMany(codes []byte, state State, action Action, next // AddRange adds a range of transitions. func (t TransitionTable) AddRange(start, end byte, state State, action Action, next State) { for i := int(start); i <= int(end); i++ { - t.AddOne(byte(i), state, action, next) + t.AddOne(byte(i), state, action, next) //nolint:gosec } } @@ -67,7 +67,7 @@ func (t TransitionTable) Transition(state State, code byte) (State, Action) { func r(start, end byte) []byte { var a []byte for i := int(start); i <= int(end); i++ { - a = append(a, byte(i)) + a = append(a, byte(i)) //nolint:gosec } return a } diff --git a/src/vendor/github.com/charmbracelet/x/ansi/parser_decode.go b/src/vendor/github.com/charmbracelet/x/ansi/parser_decode.go index 24a8f8c5..486135b7 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/parser_decode.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/parser_decode.go @@ -437,13 +437,13 @@ func FirstGraphemeCluster[T string | []byte](b T, m Method) (T, int) { case string: cluster := graphemes.FromString(b).First() if m == WcWidth { - return T(cluster), wcOptions.StringWidth(cluster) + return T(cluster), wcClusterWidth(cluster) } return T(cluster), dwOptions.String(cluster) case []byte: cluster := graphemes.FromBytes(b).First() if m == WcWidth { - return T(cluster), wcOptions.StringWidth(string(cluster)) + return T(cluster), wcClusterWidth(cluster) } return T(cluster), dwOptions.Bytes(cluster) } @@ -460,7 +460,7 @@ type Cmd int // range of 0x3C-0x3F. // Zero is returned if the sequence does not have a prefix. func (c Cmd) Prefix() byte { - return byte(parser.Prefix(int(c))) + return byte(parser.Prefix(int(c))) //nolint:gosec } // Intermediate returns the unpacked intermediate byte of the CSI sequence. @@ -469,12 +469,12 @@ func (c Cmd) Prefix() byte { // ',', '-', '.', '/'. // Zero is returned if the sequence does not have an intermediate byte. func (c Cmd) Intermediate() byte { - return byte(parser.Intermediate(int(c))) + return byte(parser.Intermediate(int(c))) //nolint:gosec } // Final returns the unpacked command byte of the CSI sequence. func (c Cmd) Final() byte { - return byte(parser.Command(int(c))) + return byte(parser.Command(int(c))) //nolint:gosec } // Command packs a command with the given prefix, intermediate, and final. A diff --git a/src/vendor/github.com/charmbracelet/x/ansi/wcwidth.go b/src/vendor/github.com/charmbracelet/x/ansi/wcwidth.go new file mode 100644 index 00000000..642a4f6f --- /dev/null +++ b/src/vendor/github.com/charmbracelet/x/ansi/wcwidth.go @@ -0,0 +1,100 @@ +package ansi + +import ( + "slices" + "unicode" + "unicode/utf8" +) + +// zeroWidthTables are the categories whose runes don't advance the cursor: +// nonspacing and enclosing marks, and format characters such as ZWJ and the +// variation selectors. +var zeroWidthTables = []*unicode.RangeTable{unicode.Mn, unicode.Me, unicode.Cf} + +// zeroWidthBMP is a bitset of the [zeroWidthTables] runes in the basic +// multilingual plane. Measuring runs a lookup per rune, and a bit test is a +// good deal cheaper than searching three range tables. Runes above the BMP are +// rare enough in terminal output to leave on the slow path. +var zeroWidthBMP [0x10000 / 64]uint64 + +// zeroWidthHigh holds the [zeroWidthTables] runes above the BMP, expanded and +// sorted so a lookup is one binary search. +var zeroWidthHigh []rune + +func init() { + for _, t := range zeroWidthTables { + for _, r := range t.R16 { + for c := rune(r.Lo); c <= rune(r.Hi); c += rune(r.Stride) { + zeroWidthBMP[c>>6] |= 1 << (c & 63) + } + } + for _, r := range t.R32 { + // R32 range bounds are always valid runes. + for c := rune(r.Lo); c <= rune(r.Hi); c += rune(r.Stride) { //nolint:gosec + zeroWidthHigh = append(zeroWidthHigh, c) + } + } + } + slices.Sort(zeroWidthHigh) +} + +// isZeroWidthHigh reports whether a rune above the BMP is zero width. +func isZeroWidthHigh(r rune) bool { + _, ok := slices.BinarySearch(zeroWidthHigh, r) + return ok +} + +// wcRuneWidth returns the number of columns a single rune advances the cursor, +// i.e. wcwidth(3). +// +// Nonspacing and enclosing marks, along with format characters such as ZWJ and +// the variation selectors, never advance the cursor. [runewidth] reports some +// of them, most notably the Indic combining marks, as single width, so they're +// classified here instead. +func wcRuneWidth(r rune) int { + switch { + case r < 0x20, r >= 0x7f && r < 0xa0: + // C0 and C1 controls, and DEL, don't print. + return 0 + case r < 0x7f: + // Printable ASCII. Everything above it can be East Asian Ambiguous, + // so it has to go through runewidth. + return 1 + case r < 0x10000: + if zeroWidthBMP[r>>6]&(1<<(r&63)) != 0 { + return 0 + } + case isZeroWidthHigh(r): + return 0 + } + return wcOptions.RuneWidth(r) +} + +// wcClusterWidth returns the number of columns a grapheme cluster occupies +// under [WcWidth], which is the sum of the widths of its codepoints. +// +// Terminals that don't implement Unicode core mode (DEC mode 2027) advance the +// cursor once per codepoint and know nothing about cluster boundaries. So a +// cluster can be wider than the glyph it draws: Unicode 15.1 merged Indic +// conjuncts into single clusters, and a terminal still puts "स्ते" in two +// columns, one per consonant. ZWJ emoji sequences behave the same way, with +// "👨‍👩‍👧‍👦" taking the eight columns of the four emoji it's built from. +// +// Measuring the cluster as a unit is [GraphemeWidth]'s job. +func wcClusterWidth[T string | []byte](cluster T) int { + var width int + switch c := any(cluster).(type) { + case string: + for _, r := range c { + width += wcRuneWidth(r) + } + case []byte: + // Ranging over string(c) would copy the slice, so decode in place. + for len(c) > 0 { + r, size := utf8.DecodeRune(c) + width += wcRuneWidth(r) + c = c[size:] + } + } + return width +} diff --git a/src/vendor/github.com/charmbracelet/x/ansi/width.go b/src/vendor/github.com/charmbracelet/x/ansi/width.go index a4735b8a..30c7caa0 100644 --- a/src/vendor/github.com/charmbracelet/x/ansi/width.go +++ b/src/vendor/github.com/charmbracelet/x/ansi/width.go @@ -2,6 +2,7 @@ package ansi import ( "bytes" + "unicode/utf8" "github.com/charmbracelet/x/ansi/parser" ) @@ -88,6 +89,17 @@ func stringWidth(m Method, s string) int { for i := 0; i < len(s); i++ { state, action := parser.Table.Transition(pstate, s[i]) if action == parser.PrintAction || state == parser.Utf8State { + if m == WcWidth { + // Wcwidth sums codepoints, so where the cluster boundaries + // fall makes no difference to the total. Skipping the + // segmentation is a good deal cheaper. + r, size := utf8.DecodeRuneInString(s[i:]) + width += wcRuneWidth(r) + i += size - 1 + pstate = parser.GroundState + continue + } + cluster, w := FirstGraphemeCluster(s[i:], m) width += w diff --git a/src/vendor/github.com/gdamore/tcell/v3/screen.go b/src/vendor/github.com/gdamore/tcell/v3/screen.go index 7413e2db..1274fd93 100644 --- a/src/vendor/github.com/gdamore/tcell/v3/screen.go +++ b/src/vendor/github.com/gdamore/tcell/v3/screen.go @@ -20,18 +20,6 @@ import ( "github.com/gdamore/tcell/v3/color" ) -// Capabilities is a bitfield of terminal capabilities reported during Init. -type Capabilities uint - -const ( - // CapabilityClipboard: OSC 52 support. Many terminals support the - // clipboard without reporting it, so a false bit is not conclusive. - CapabilityClipboard Capabilities = 1 << iota - - // CapabilitySixel: sixel graphics support (DA1, param 4). - CapabilitySixel -) - // Screen represents the physical (or emulated) screen. // This can be a terminal window or a physical console. Platforms implement // this differently. @@ -259,15 +247,10 @@ type Screen interface { // prevent this for security reasons. GetClipboard() - // Capabilities returns the capabilities reported during Init. - // Negotiation completes before Init returns, so this is a - // synchronous query, not an event: an event would only delay an - // already-known answer until the event queue is drained, and the - // app needs it before rendering its first frame. - Capabilities() Capabilities - - // HasClipboard reports OSC 52 clipboard support; equivalent to - // Capabilities()&CapabilityClipboard != 0. + // HasClipboard is true if the screen claims to support the clipboard. + // Note that GetClipboard may still not work, but SetClipboard should be functional. + // Note that many terminals that support the clipboard don't actually report that they + // do, so a false indication is not necessarily conclusive. HasClipboard() bool // ShowNotification is used to show a desktop notification, when the terminal @@ -381,7 +364,6 @@ type screenImpl interface { Tty() (Tty, bool) SetClipboard([]byte) GetClipboard() - Capabilities() Capabilities HasClipboard() bool ShowNotification(string, string) KeyboardProtocol() KeyProtocol diff --git a/src/vendor/github.com/gdamore/tcell/v3/tscreen.go b/src/vendor/github.com/gdamore/tcell/v3/tscreen.go index 7ed31ef9..940207fe 100644 --- a/src/vendor/github.com/gdamore/tcell/v3/tscreen.go +++ b/src/vendor/github.com/gdamore/tcell/v3/tscreen.go @@ -241,7 +241,7 @@ type tScreen struct { truecolor bool noColor bool legacy bool - caps Capabilities // capabilities reported via DA1 + hasClipboard bool // true if OSC 52 reported via DA1 finiOnce sync.Once initFiniLock sync.Mutex enterUrl string @@ -509,12 +509,7 @@ func (t *tScreen) processInitQ() { if ev.Clipboard && t.setClipboard == "" { t.setClipboard = setClipboard } - if ev.Clipboard { - t.caps |= CapabilityClipboard - } - if ev.Sixel { - t.caps |= CapabilitySixel - } + t.hasClipboard = ev.Clipboard t.initted = true return case *eventTermName: @@ -1818,12 +1813,8 @@ func (t *tScreen) GetClipboard() { t.Unlock() } -func (t *tScreen) Capabilities() Capabilities { - return t.caps -} - func (t *tScreen) HasClipboard() bool { - return t.caps&CapabilityClipboard != 0 + return t.hasClipboard } func (t *tScreen) ShowNotification(title string, body string) { diff --git a/src/vendor/modules.txt b/src/vendor/modules.txt index 0fed4630..35ef892a 100644 --- a/src/vendor/modules.txt +++ b/src/vendor/modules.txt @@ -1,5 +1,5 @@ -# charm.land/lipgloss/v2 v2.0.5 -## explicit; go 1.25.0 +# charm.land/lipgloss/v2 v2.1.1 +## explicit; go 1.26.0 charm.land/lipgloss/v2 # git.sr.ht/~jackmordaunt/go-toast v1.1.2 ## explicit; go 1.20 @@ -24,10 +24,10 @@ github.com/andybalholm/cascadia # github.com/charmbracelet/colorprofile v0.4.3 ## explicit; go 1.25.0 github.com/charmbracelet/colorprofile -# github.com/charmbracelet/ultraviolet v0.0.0-20251205161215-1948445e3318 -## explicit; go 1.24.2 +# github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 +## explicit; go 1.25.0 github.com/charmbracelet/ultraviolet -# github.com/charmbracelet/x/ansi v0.11.7 +# github.com/charmbracelet/x/ansi v0.11.8 ## explicit; go 1.24.2 github.com/charmbracelet/x/ansi github.com/charmbracelet/x/ansi/kitty