Compare commits
12 commits
main
...
feat/image
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6846e85bc | ||
|
|
f0c1d7df3b | ||
|
|
a101777ad2 | ||
|
|
020ec9b5f8 | ||
|
|
00f3db0962 | ||
|
|
fa2b0f451e | ||
|
|
3d557fb56b | ||
|
|
bb61bd7590 | ||
|
|
ac5b83d3c3 | ||
|
|
0214f4d6be | ||
|
|
6911314131 | ||
|
|
3cf39ac458 |
16 changed files with 1733 additions and 52 deletions
2
.github/workflows/build.yml
vendored
2
.github/workflows/build.yml
vendored
|
|
@ -22,4 +22,4 @@ jobs:
|
|||
ruleguard:
|
||||
uses: charmbracelet/meta/.github/workflows/ruleguard.yml@main
|
||||
with:
|
||||
go-version: 1.26.6
|
||||
go-version: 1.26.7
|
||||
|
|
|
|||
33
README.md
33
README.md
|
|
@ -163,6 +163,33 @@ glow -w 60
|
|||
CLI output can be displayed in your preferred pager with the `-p` flag. This defaults
|
||||
to the ANSI-aware `less -r` if `$PAGER` is not explicitly set.
|
||||
|
||||
### Images
|
||||
|
||||
If your terminal supports the kitty graphics protocol (e.g. kitty, Ghostty,
|
||||
WezTerm) or sixel, images in the document are rendered right in the terminal:
|
||||
|
||||
```bash
|
||||
glow README.md
|
||||
```
|
||||
|
||||
Support is detected automatically, both in the CLI and in the TUI pager, where
|
||||
images scroll with the text. Images can be turned off with the `--images=false`
|
||||
flag, or forced with the `GLOW_IMAGE_PROTOCOL` environment variable (`auto`,
|
||||
`kitty`, `sixel`, or `none`).
|
||||
|
||||
Large images are automatically downscaled to what the terminal can actually
|
||||
display before being transmitted, so even huge photos render quickly. Their
|
||||
size can also be limited with `--image-max-rows` (default 20 terminal rows, 0
|
||||
for no limit), or the `imageMaxRows` config key.
|
||||
|
||||
Images referenced by an `http(s)` URL are not loaded by default: fetching them
|
||||
would reveal your IP address to the image's host, much like a tracking pixel
|
||||
would. Instead, the URL is rendered as a link followed by a note saying the
|
||||
image wasn't loaded. Set `loadRemoteImages: true` in your config (or
|
||||
`GLOW_LOAD_REMOTE_IMAGES=true`) to fetch and render them. In the TUI the
|
||||
document's text appears right away, and a spinner in the status bar spins while
|
||||
the remote images are being fetched.
|
||||
|
||||
### Styles
|
||||
|
||||
You can choose a style with the `-s` flag. When no flag is provided `glow` tries
|
||||
|
|
@ -213,6 +240,12 @@ all: false
|
|||
showLineNumbers: false
|
||||
# preserve newlines in the output
|
||||
preserveNewLines: false
|
||||
# render images when the terminal supports it (kitty or sixel graphics)
|
||||
images: true
|
||||
# maximum number of terminal rows an image may occupy (0 for no limit)
|
||||
imageMaxRows: 20
|
||||
# load images referenced by http(s) URLs, disabled to avoid leaking your IP
|
||||
loadRemoteImages: false
|
||||
```
|
||||
|
||||
## Contributing
|
||||
|
|
|
|||
|
|
@ -23,6 +23,10 @@ pager: false
|
|||
width: 80
|
||||
# show all files, including hidden and ignored.
|
||||
all: false
|
||||
# load images over the network, i.e. from http(s) URLs. Disabled by default,
|
||||
# as fetching them shares your IP address with the image's host. While
|
||||
# disabled, remote images render as their URL with a note.
|
||||
loadRemoteImages: false
|
||||
`
|
||||
|
||||
var configCmd = &cobra.Command{
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
//go:build windows
|
||||
// +build windows
|
||||
|
||||
package main
|
||||
|
|
|
|||
25
glow_test.go
25
glow_test.go
|
|
@ -2,6 +2,9 @@ package main
|
|||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"charm.land/glow/v3/ui"
|
||||
"github.com/caarlos0/env/v11"
|
||||
)
|
||||
|
||||
func TestGlowFlags(t *testing.T) {
|
||||
|
|
@ -39,3 +42,25 @@ func TestGlowFlags(t *testing.T) {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadRemoteImagesEnv checks the environment variable that enables
|
||||
// loading remote images.
|
||||
func TestLoadRemoteImagesEnv(t *testing.T) {
|
||||
t.Setenv("GLOW_LOAD_REMOTE_IMAGES", "false")
|
||||
cfg, err := env.ParseAs[ui.Config]()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.LoadRemoteImages {
|
||||
t.Error("expected remote image loading to be disabled by default")
|
||||
}
|
||||
|
||||
t.Setenv("GLOW_LOAD_REMOTE_IMAGES", "true")
|
||||
cfg, err = env.ParseAs[ui.Config]()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cfg.LoadRemoteImages {
|
||||
t.Error("expected GLOW_LOAD_REMOTE_IMAGES to enable remote image loading")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
18
go.mod
18
go.mod
|
|
@ -1,15 +1,17 @@
|
|||
module charm.land/glow/v3
|
||||
|
||||
go 1.26.6
|
||||
go 1.26.7
|
||||
|
||||
require (
|
||||
charm.land/bubbles/v2 v2.1.1
|
||||
charm.land/bubbletea/v2 v2.0.8
|
||||
charm.land/glamour/v2 v2.0.1
|
||||
charm.land/bubbletea/v2 v2.0.9
|
||||
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec
|
||||
charm.land/lipgloss/v2 v2.0.6
|
||||
github.com/atotto/clipboard v0.1.4
|
||||
github.com/caarlos0/env/v11 v11.3.1
|
||||
github.com/charmbracelet/log v0.4.2
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886
|
||||
github.com/charmbracelet/x/ansi v0.11.8
|
||||
github.com/charmbracelet/x/editor v0.1.0
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/fsnotify/fsnotify v1.9.0
|
||||
|
|
@ -26,7 +28,7 @@ require (
|
|||
github.com/spf13/viper v1.21.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/term v0.43.0
|
||||
golang.org/x/text v0.39.0
|
||||
golang.org/x/text v0.41.0
|
||||
mvdan.cc/sh/v3 v3.13.1
|
||||
)
|
||||
|
||||
|
|
@ -34,10 +36,9 @@ require (
|
|||
github.com/alecthomas/chroma/v2 v2.14.0 // indirect
|
||||
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
|
||||
github.com/aymerick/douceur v0.2.0 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.6 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 // indirect
|
||||
github.com/charmbracelet/ultraviolet v0.0.0-20260811164956-006e29f97886 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.8 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||
github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
|
|
@ -64,12 +65,15 @@ require (
|
|||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
github.com/yuin/goldmark v1.7.17 // indirect
|
||||
github.com/yuin/goldmark v1.8.5 // indirect
|
||||
github.com/yuin/goldmark-emoji v1.0.5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 // indirect
|
||||
golang.org/x/image v0.45.0 // indirect
|
||||
golang.org/x/net v0.55.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
|
||||
|
|
|
|||
24
go.sum
24
go.sum
|
|
@ -1,9 +1,9 @@
|
|||
charm.land/bubbles/v2 v2.1.1 h1:7r55WzBxpo/R3z98hGmY7KKPd3ET6vsf0Fb9sDHOV60=
|
||||
charm.land/bubbles/v2 v2.1.1/go.mod h1:GE6M31gaWZVXzGw73OeuTTgy4lX+OtkH0E5ymnNsHxo=
|
||||
charm.land/bubbletea/v2 v2.0.8 h1:SxTJMhCAI3lbPmy4SgX5LWZ24AdINr4I6UEqzZvYJuY=
|
||||
charm.land/bubbletea/v2 v2.0.8/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss=
|
||||
charm.land/glamour/v2 v2.0.1 h1:xl+r00A4aJWU0z8fgwKd9fQQ4rsphqGUzuEiXZP5n+c=
|
||||
charm.land/glamour/v2 v2.0.1/go.mod h1:jo9z8XqVKPeEFMVdvCRLGk++RyJ3CdUwgNr7EvXLw3k=
|
||||
charm.land/bubbletea/v2 v2.0.9 h1:DpJCMWKgzQK8SJv4zbKKFHAI10ymWy/evClPFk0k0f8=
|
||||
charm.land/bubbletea/v2 v2.0.9/go.mod h1:2SkdgoTXluXJHOUwAoRlRXF/28vklb1rFl6GcgV1/ss=
|
||||
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec h1:fwSkd2b70GxrE+pQr4k4xlcd3GzyPFU4qrAusI82IMA=
|
||||
charm.land/glamour/v2 v2.0.2-0.20260922094102-70fab824e2ec/go.mod h1:s2Vc49ayQNFwtN8L3xVdNh10AdF1PFHMW307oQXpEhI=
|
||||
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||
charm.land/lipgloss/v2 v2.0.6/go.mod h1:ipDDJNSGa1hlwDtSfW1s2/xR8Vdhbut4PXh2zEKZd0Q=
|
||||
github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=
|
||||
|
|
@ -20,6 +20,8 @@ github.com/aymanbagabas/go-udiff v0.4.1 h1:OEIrQ8maEeDBXQDoGCbbTTXYJMYRCRO1fnodZ
|
|||
github.com/aymanbagabas/go-udiff v0.4.1/go.mod h1:0L9PGwj20lrtmEMeyw4WKJ/TMyDtvAoK9bf2u/mNo3w=
|
||||
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
|
||||
github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4=
|
||||
github.com/bits-and-blooms/bitset v1.24.6 h1:qcrftZUVBIwfs+m+nhoCBAPT+ZPZZjti8SbHbDQQkZ4=
|
||||
github.com/bits-and-blooms/bitset v1.24.6/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/caarlos0/env/v11 v11.3.1 h1:cArPWC15hWmEt+gWk7YBi7lEXTXCvpaSdCiZE2X5mCA=
|
||||
github.com/caarlos0/env/v11 v11.3.1/go.mod h1:qupehSf/Y0TUTsxKywqRt/vJjN5nz6vauiYEUUr8P4U=
|
||||
github.com/charmbracelet/colorprofile v0.4.3 h1:QPa1IWkYI+AOB+fE+mg/5/4HRMZcaXex9t5KX76i20Q=
|
||||
|
|
@ -144,6 +146,10 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
|||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE=
|
||||
github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q=
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ=
|
||||
github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
|
|
@ -153,14 +159,16 @@ github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSW
|
|||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.7.1/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=
|
||||
github.com/yuin/goldmark v1.7.17 h1:p36OVWwRb246iHxA/U4p8OPEpOTESm4n+g+8t0EE5uA=
|
||||
github.com/yuin/goldmark v1.7.17/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA=
|
||||
github.com/yuin/goldmark v1.8.5/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/yuin/goldmark-emoji v1.0.5 h1:EMVWyCGPlXJfUXBXpuMu+ii3TIaxbVBnEX9uaDC4cIk=
|
||||
github.com/yuin/goldmark-emoji v1.0.5/go.mod h1:tTkZEbwu5wkPmgTcitqddVxY9osFZiavD+r4AzQrh1U=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8 h1:LoYXNGAShUG3m/ehNk4iFctuhGX/+R1ZpfJ4/ia80JM=
|
||||
golang.org/x/exp v0.0.0-20240604190554-fc45aab8b7f8/go.mod h1:jj3sYF3dwk5D+ghuXyeI3r5MFf+NT2An6/9dOA95KSI=
|
||||
golang.org/x/image v0.45.0 h1:FMb1nTbH5H9vF55SriQHgFw5GnNL9Jg6L25BwXKzhB0=
|
||||
golang.org/x/image v0.45.0/go.mod h1:n62x/7RqlwXDvGsSU4u6IUTUf6KghUZ9Bt7cG/T9Fx4=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
|
|
@ -170,8 +178,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
|||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
|
|
|||
77
main.go
77
main.go
|
|
@ -12,10 +12,12 @@ import (
|
|||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"mvdan.cc/sh/v3/shell"
|
||||
|
||||
"charm.land/glamour/v2"
|
||||
"charm.land/glamour/v2/ansi"
|
||||
"charm.land/glamour/v2/styles"
|
||||
"charm.land/glow/v3/ui"
|
||||
"charm.land/glow/v3/utils"
|
||||
|
|
@ -43,6 +45,14 @@ var (
|
|||
showLineNumbers bool
|
||||
preserveNewLines bool
|
||||
mouse bool
|
||||
images bool
|
||||
imageMaxRows int
|
||||
loadRemoteImages bool
|
||||
|
||||
// imageProtocol is the graphics protocol detected for the terminal. It
|
||||
// is resolved at most once via imageProtocolForCLI.
|
||||
imageProtocol ansi.ImageProtocol
|
||||
detectOnce sync.Once
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "glow [SOURCE|DIR]",
|
||||
|
|
@ -172,6 +182,9 @@ func validateOptions(cmd *cobra.Command) error {
|
|||
showAllFiles = viper.GetBool("all")
|
||||
preserveNewLines = viper.GetBool("preserveNewLines")
|
||||
showLineNumbers = viper.GetBool("showLineNumbers")
|
||||
images = viper.GetBool("images")
|
||||
imageMaxRows = viper.GetInt("imageMaxRows")
|
||||
loadRemoteImages = viper.GetBool("loadRemoteImages")
|
||||
|
||||
if pager && tui {
|
||||
return errors.New("cannot use both pager and tui")
|
||||
|
|
@ -281,21 +294,49 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error {
|
|||
|
||||
// render
|
||||
var baseURL string
|
||||
u, err := url.ParseRequestURI(src.URL)
|
||||
if err == nil {
|
||||
u.Path = filepath.Dir(u.Path)
|
||||
baseURL = u.String() + "/"
|
||||
if isURL(src.URL) {
|
||||
if u, err := url.ParseRequestURI(src.URL); err == nil {
|
||||
u.Path = filepath.Dir(u.Path)
|
||||
baseURL = u.String() + "/"
|
||||
}
|
||||
} else {
|
||||
// Resolve image URLs relative to the document's directory. This
|
||||
// uses a file:// URL so that relative references also resolve on
|
||||
// platforms where absolute paths are no valid URL paths, like
|
||||
// Windows.
|
||||
baseURL = utils.FileBaseURL(src.URL)
|
||||
}
|
||||
|
||||
isCode := !utils.IsMarkdownFile(src.URL)
|
||||
|
||||
// Only the direct output mode can display graphics protocol sequences:
|
||||
// external pagers redraw text themselves and the TUI detects graphics
|
||||
// support on its own.
|
||||
useImages := images && !isCode &&
|
||||
!(pager || cmd.Flags().Changed("pager")) &&
|
||||
!(tui || cmd.Flags().Changed("tui"))
|
||||
|
||||
// initialize glamour
|
||||
r, err := glamour.NewTermRenderer(
|
||||
options := []glamour.TermRendererOption{
|
||||
utils.GlamourStyle(style, isCode),
|
||||
glamour.WithWordWrap(int(width)), //nolint:gosec
|
||||
glamour.WithBaseURL(baseURL),
|
||||
glamour.WithPreservedNewLines(),
|
||||
)
|
||||
}
|
||||
if useImages {
|
||||
if p := imageProtocolForCLI(); p != ansi.ImageProtocolNone {
|
||||
options = append(options,
|
||||
glamour.WithImageProtocol(p),
|
||||
glamour.WithMaxImageSize(0, imageMaxRows),
|
||||
)
|
||||
if loadRemoteImages {
|
||||
options = append(options, glamour.WithRemoteImages())
|
||||
} else {
|
||||
options = append(options, glamour.WithRemoteImageNotLoadedNote(ui.RemoteImageNotLoadedNote))
|
||||
}
|
||||
}
|
||||
}
|
||||
r, err := glamour.NewTermRenderer(options...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("unable to create renderer: %w", err)
|
||||
}
|
||||
|
|
@ -362,6 +403,10 @@ func runTUI(path string, content string) error {
|
|||
cfg.GlamourMaxWidth = width
|
||||
cfg.EnableMouse = mouse
|
||||
cfg.PreserveNewLines = preserveNewLines
|
||||
cfg.Images = viper.GetBool("images")
|
||||
cfg.ImageMaxRows = viper.GetInt("imageMaxRows")
|
||||
// The env var is read by env.ParseAs, the config file by Viper.
|
||||
cfg.LoadRemoteImages = cfg.LoadRemoteImages || viper.GetBool("loadRemoteImages")
|
||||
|
||||
// Run Bubble Tea program
|
||||
if _, err := ui.NewProgram(cfg, content).Run(); err != nil {
|
||||
|
|
@ -371,6 +416,19 @@ func runTUI(path string, content string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// imageProtocolForCLI detects the terminal's graphics protocol at most once
|
||||
// per run, so rendering multiple sources doesn't query the terminal
|
||||
// repeatedly.
|
||||
func imageProtocolForCLI() ansi.ImageProtocol {
|
||||
detectOnce.Do(func() {
|
||||
imageProtocol = utils.DetectImageProtocol()
|
||||
if imageProtocol != ansi.ImageProtocolNone {
|
||||
log.Debug("terminal graphics protocol detected", "protocol", imageProtocol)
|
||||
}
|
||||
})
|
||||
return imageProtocol
|
||||
}
|
||||
|
||||
func main() {
|
||||
closer, err := setupLog()
|
||||
if err != nil {
|
||||
|
|
@ -405,6 +463,8 @@ func init() {
|
|||
rootCmd.Flags().BoolVarP(&showAllFiles, "all", "a", false, "show system files and directories (TUI-mode only)")
|
||||
rootCmd.Flags().BoolVarP(&showLineNumbers, "line-numbers", "l", false, "show line numbers (TUI-mode only)")
|
||||
rootCmd.Flags().BoolVarP(&preserveNewLines, "preserve-new-lines", "n", false, "preserve newlines in the output")
|
||||
rootCmd.Flags().BoolVarP(&images, "images", "", true, "render images when the terminal supports it (kitty or sixel graphics; GLOW_IMAGE_PROTOCOL to override)")
|
||||
rootCmd.Flags().IntVar(&imageMaxRows, "image-max-rows", 20, "maximum number of terminal rows an image may occupy (0 for no limit)")
|
||||
rootCmd.Flags().BoolVarP(&mouse, "mouse", "m", false, "enable mouse wheel (TUI-mode only)")
|
||||
_ = rootCmd.Flags().MarkHidden("mouse")
|
||||
|
||||
|
|
@ -418,10 +478,15 @@ func init() {
|
|||
_ = viper.BindPFlag("preserveNewLines", rootCmd.Flags().Lookup("preserve-new-lines"))
|
||||
_ = viper.BindPFlag("showLineNumbers", rootCmd.Flags().Lookup("line-numbers"))
|
||||
_ = viper.BindPFlag("all", rootCmd.Flags().Lookup("all"))
|
||||
_ = viper.BindPFlag("images", rootCmd.Flags().Lookup("images"))
|
||||
_ = viper.BindPFlag("imageMaxRows", rootCmd.Flags().Lookup("image-max-rows"))
|
||||
|
||||
viper.SetDefault("style", "auto")
|
||||
viper.SetDefault("width", 0)
|
||||
viper.SetDefault("all", true)
|
||||
viper.SetDefault("images", true)
|
||||
viper.SetDefault("imageMaxRows", 20)
|
||||
viper.SetDefault("loadRemoteImages", false)
|
||||
|
||||
rootCmd.AddCommand(configCmd, manCmd)
|
||||
}
|
||||
|
|
|
|||
17
ui/config.go
17
ui/config.go
|
|
@ -11,6 +11,23 @@ type Config struct {
|
|||
EnableMouse bool
|
||||
PreserveNewLines bool
|
||||
|
||||
// Images controls whether to render images in the pager using the
|
||||
// terminal's graphics protocol. ImageProtocol can be one of "auto",
|
||||
// "kitty", or "none" (see utils.ImageProtocol* constants). ImageMaxRows
|
||||
// limits the number of terminal rows an image may occupy; zero means no
|
||||
// limit.
|
||||
Images bool `env:"GLOW_IMAGES" envDefault:"true"`
|
||||
ImageProtocol string `env:"GLOW_IMAGE_PROTOCOL" envDefault:"auto"`
|
||||
ImageMaxRows int `env:"GLOW_IMAGE_MAX_ROWS" envDefault:"20"`
|
||||
|
||||
// LoadRemoteImages controls whether images referenced by http(s) URLs
|
||||
// are fetched and rendered. It is disabled by default: fetching remote
|
||||
// images reveals your IP address to the image's host and uses
|
||||
// bandwidth, much like a tracking pixel would. While disabled, remote
|
||||
// images render as a link followed by a note saying they were not
|
||||
// loaded.
|
||||
LoadRemoteImages bool `env:"GLOW_LOAD_REMOTE_IMAGES" envDefault:"false"`
|
||||
|
||||
// Working directory or file path
|
||||
Path string
|
||||
|
||||
|
|
|
|||
322
ui/pager.go
322
ui/pager.go
|
|
@ -4,12 +4,15 @@ import (
|
|||
"fmt"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"charm.land/bubbles/v2/spinner"
|
||||
"charm.land/bubbles/v2/viewport"
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/glamour/v2"
|
||||
glamansi "charm.land/glamour/v2/ansi"
|
||||
"charm.land/glow/v3/utils"
|
||||
"charm.land/lipgloss/v2"
|
||||
"github.com/atotto/clipboard"
|
||||
|
|
@ -26,11 +29,85 @@ const (
|
|||
lineNumberWidth = 4
|
||||
)
|
||||
|
||||
// RemoteImageNotLoadedNote is appended to the URL of a remote image when
|
||||
// loading remote images is disabled, pointing at the config setting that
|
||||
// loads them.
|
||||
const RemoteImageNotLoadedNote = ` (not loaded. Set "loadRemoteImages: true" in your glow config to load remote images)`
|
||||
|
||||
// remoteImagePattern matches inline markdown images, i.e.
|
||||
// , and HTML ones, i.e. <img src="https://...">, that are
|
||||
// fetched over the network.
|
||||
var remoteImagePattern = regexp.MustCompile(`(?i)!\[[^\]]*\]\(\s*["']?https?://|<img[^>]+src\s*=\s*["']?https?://`)
|
||||
|
||||
var (
|
||||
// referenceImagePattern matches markdown images that point at a link
|
||||
// reference, i.e. ![alt][badge].
|
||||
referenceImagePattern = regexp.MustCompile(`!\[[^\]]*\]\[([^\]]*)\]`)
|
||||
// referenceDefinitionPattern matches the definition of a link
|
||||
// reference, i.e. [badge]: https://example.com/badge.svg.
|
||||
referenceDefinitionPattern = regexp.MustCompile(`(?m)^ {0,3}\[([^\]]+)\]:\s*<?(\S+)`)
|
||||
)
|
||||
|
||||
// hasRemoteImages reports whether the markdown references any image by
|
||||
// http(s) URL, i.e. whether rendering it involves fetching images.
|
||||
func hasRemoteImages(md string) bool {
|
||||
if remoteImagePattern.MatchString(md) {
|
||||
return true
|
||||
}
|
||||
|
||||
// Images can also point at a link reference, e.g. a badge in a README:
|
||||
// ![build][badge] with [badge]: https://example.com/badge.svg. Match the
|
||||
// references that are known to be remote; link labels are
|
||||
// case-insensitive.
|
||||
var remoteReferences map[string]bool
|
||||
for _, m := range referenceDefinitionPattern.FindAllStringSubmatch(md, -1) {
|
||||
if isRemoteURL(m[2]) {
|
||||
if remoteReferences == nil {
|
||||
remoteReferences = make(map[string]bool)
|
||||
}
|
||||
remoteReferences[strings.ToLower(m[1])] = true
|
||||
}
|
||||
}
|
||||
if len(remoteReferences) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, m := range referenceImagePattern.FindAllStringSubmatch(md, -1) {
|
||||
if remoteReferences[strings.ToLower(m[1])] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// isRemoteURL reports whether the given URL is served over http(s).
|
||||
func isRemoteURL(u string) bool {
|
||||
return strings.HasPrefix(u, "http://") || strings.HasPrefix(u, "https://")
|
||||
}
|
||||
|
||||
var pagerHelpHeight int
|
||||
|
||||
type (
|
||||
contentRenderedMsg string
|
||||
reloadMsg struct{}
|
||||
// contentRenderedMsg is sent when the glamour rendering of a document
|
||||
// finishes. graphics holds the graphics protocol sequences that must be
|
||||
// written to the terminal before the content, which references them via
|
||||
// unicode placeholders, is displayed. body is the markdown that was
|
||||
// rendered, and remoteImagesPending reports that it was rendered without
|
||||
// its remote images, which the pager then loads in a second pass.
|
||||
contentRenderedMsg struct {
|
||||
content string
|
||||
graphics []string
|
||||
body string
|
||||
remoteImagesPending bool
|
||||
}
|
||||
// remoteImagesLoadedMsg is sent when the second rendering pass, which
|
||||
// loads the document's remote images, finishes. token identifies the
|
||||
// pass, so a result that was superseded, e.g. by a resize, is ignored.
|
||||
remoteImagesLoadedMsg struct {
|
||||
content string
|
||||
graphics []string
|
||||
token int
|
||||
}
|
||||
reloadMsg struct{}
|
||||
)
|
||||
|
||||
type pagerState int
|
||||
|
|
@ -53,6 +130,20 @@ type pagerModel struct {
|
|||
// it here so we can re-render it on resize.
|
||||
currentDocument markdown
|
||||
|
||||
// pendingContent is content that is waiting on its graphics protocol
|
||||
// sequences to be written to the terminal before it can be displayed.
|
||||
// See the contentRenderedMsg handling in update.
|
||||
pendingContent string
|
||||
|
||||
// remoteImagesLoading reports whether the remote images of the current
|
||||
// document are still being fetched, and remoteSpinner spins while they
|
||||
// are; the text is displayed without them in the meantime.
|
||||
// remoteImagesPass identifies the running fetching pass, so that its
|
||||
// result can be told apart from those of older passes.
|
||||
remoteImagesLoading bool
|
||||
remoteImagesPass int
|
||||
remoteSpinner spinner.Model
|
||||
|
||||
watcher *fsnotify.Watcher
|
||||
}
|
||||
|
||||
|
|
@ -60,10 +151,15 @@ func newPagerModel(common *commonModel) pagerModel {
|
|||
// Init viewport
|
||||
vp := viewport.New()
|
||||
|
||||
sp := spinner.New()
|
||||
sp.Spinner = spinner.Line
|
||||
sp.Style = common.styles.statusBarSpinnerStyle
|
||||
|
||||
m := pagerModel{
|
||||
common: common,
|
||||
state: pagerStateBrowse,
|
||||
viewport: vp,
|
||||
common: common,
|
||||
state: pagerStateBrowse,
|
||||
viewport: vp,
|
||||
remoteSpinner: sp,
|
||||
}
|
||||
m.initWatcher()
|
||||
return m
|
||||
|
|
@ -122,6 +218,7 @@ func (m *pagerModel) unload() {
|
|||
m.statusMessageTimer.Stop()
|
||||
}
|
||||
m.state = pagerStateBrowse
|
||||
m.remoteImagesLoading = false
|
||||
m.viewport.SetContent("")
|
||||
m.viewport.SetYOffset(0)
|
||||
m.unwatchFile()
|
||||
|
|
@ -182,9 +279,70 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) {
|
|||
case contentRenderedMsg:
|
||||
log.Info("content rendered", "state", m.state)
|
||||
|
||||
m.setContent(string(msg))
|
||||
if msg.remoteImagesPending {
|
||||
// The remote images are still being fetched; the content shown
|
||||
// in the meantime is the text without them. Start the second
|
||||
// rendering pass that loads and renders them.
|
||||
m.remoteImagesLoading = true
|
||||
m.remoteImagesPass++
|
||||
cmds = append(cmds, m.remoteSpinner.Tick,
|
||||
loadRemoteImagesCmd(m, msg.body, m.remoteImagesPass))
|
||||
}
|
||||
|
||||
if len(msg.graphics) > 0 {
|
||||
// The content references images via unicode placeholders, so the
|
||||
// graphics sequences must be written to the terminal before it
|
||||
// can be displayed. RawMsg is written out-of-band right before
|
||||
// this model sees it, so stash the content and wait for it.
|
||||
m.pendingContent = msg.content
|
||||
return m, tea.Batch(append(cmds, tea.Raw(strings.Join(msg.graphics, "")))...)
|
||||
}
|
||||
|
||||
m.setContent(msg.content)
|
||||
cmds = append(cmds, m.watchFile)
|
||||
|
||||
// The remote images of the current document have been fetched and
|
||||
// rendered; swap in the content that displays them.
|
||||
case remoteImagesLoadedMsg:
|
||||
if !m.remoteImagesLoading || msg.token != m.remoteImagesPass {
|
||||
// A newer rendering pass took over, or the user left the
|
||||
// document while its images were loading; keep what's on screen.
|
||||
return m, nil
|
||||
}
|
||||
|
||||
m.remoteImagesLoading = false
|
||||
if len(msg.graphics) > 0 {
|
||||
m.pendingContent = msg.content
|
||||
return m, tea.Raw(strings.Join(msg.graphics, ""))
|
||||
}
|
||||
m.setContent(msg.content)
|
||||
|
||||
// A rendering pass failed, e.g. while fetching the document's remote
|
||||
// images. Report it and stop the loading indicator, which would
|
||||
// otherwise stay in the status bar forever.
|
||||
case errMsg:
|
||||
var wasLoading bool
|
||||
wasLoading, m.remoteImagesLoading = m.remoteImagesLoading, false
|
||||
if wasLoading {
|
||||
cmds = append(cmds, m.showStatusMessage(pagerStatusMessage{msg.Error(), true}))
|
||||
}
|
||||
|
||||
// Keep the loading indicator spinning while the remote images load.
|
||||
case spinner.TickMsg:
|
||||
if m.remoteImagesLoading {
|
||||
var cmd tea.Cmd
|
||||
m.remoteSpinner, cmd = m.remoteSpinner.Update(msg)
|
||||
cmds = append(cmds, cmd)
|
||||
}
|
||||
|
||||
// The graphics sequences for the pending content have been written
|
||||
case tea.RawMsg:
|
||||
if m.pendingContent != "" {
|
||||
m.setContent(m.pendingContent)
|
||||
m.pendingContent = ""
|
||||
cmds = append(cmds, m.watchFile)
|
||||
}
|
||||
|
||||
// The file was changed on disk and we're reloading it
|
||||
case reloadMsg:
|
||||
return m, loadLocalMarkdown(&m.currentDocument)
|
||||
|
|
@ -212,7 +370,17 @@ func (m pagerModel) update(msg tea.Msg) (pagerModel, tea.Cmd) {
|
|||
|
||||
func (m pagerModel) View() string {
|
||||
var b strings.Builder
|
||||
fmt.Fprint(&b, m.viewport.View()+"\n")
|
||||
|
||||
// The viewport pads its content to the height it was given, but it draws
|
||||
// nothing at all until it has been sized, i.e. before the first window
|
||||
// size message. The status bar would then end up at the top of the screen,
|
||||
// and the lines it doesn't cover would keep the previous frame on screen.
|
||||
// Fill the gap so the bar always stays at the bottom.
|
||||
content := m.viewport.View()
|
||||
if missing := m.common.height - statusBarHeight - (strings.Count(content, "\n") + 1); m.common.height > 0 && missing > 0 {
|
||||
content += strings.Repeat("\n", missing)
|
||||
}
|
||||
fmt.Fprint(&b, content+"\n")
|
||||
|
||||
// Footer
|
||||
m.statusBarView(&b)
|
||||
|
|
@ -255,22 +423,32 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
|
|||
}
|
||||
|
||||
// Note
|
||||
var note string
|
||||
if showStatusMessage {
|
||||
note = m.statusMessage
|
||||
} else {
|
||||
note = m.currentDocument.Note
|
||||
}
|
||||
note = truncate.StringWithTail(" "+note+" ", uint(max(0, //nolint:gosec
|
||||
noteWidth := max(0,
|
||||
m.common.width-
|
||||
ansi.PrintableRuneWidth(logo)-
|
||||
ansi.PrintableRuneWidth(scrollPercent)-
|
||||
ansi.PrintableRuneWidth(helpNote),
|
||||
)), ellipsis)
|
||||
if showStatusMessage {
|
||||
note = styles.statusBarMessageStyle(note)
|
||||
} else {
|
||||
note = styles.statusBarNoteStyle(note)
|
||||
)
|
||||
// The loading indicator takes the place of the status message, so it's
|
||||
// styled like the file name rather than like a message.
|
||||
showMessage := showStatusMessage && !m.remoteImagesLoading
|
||||
var note string
|
||||
switch {
|
||||
case m.remoteImagesLoading:
|
||||
// The spinner's own styling ends in an ANSI reset which would wipe
|
||||
// the status bar background of everything after it, so the note is
|
||||
// styled in segments around the spinner.
|
||||
spinnerView := m.remoteSpinner.View()
|
||||
textWidth := max(0, noteWidth-ansi.PrintableRuneWidth(spinnerView)-1)
|
||||
note = styles.statusBarNoteStyle(" ") + spinnerView +
|
||||
styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec
|
||||
" Loading remote images... ", uint(textWidth), ellipsis))
|
||||
case showMessage:
|
||||
note = styles.statusBarMessageStyle(truncate.StringWithTail( //nolint:gosec
|
||||
" "+m.statusMessage+" ", uint(noteWidth), ellipsis))
|
||||
default:
|
||||
note = styles.statusBarNoteStyle(truncate.StringWithTail( //nolint:gosec
|
||||
" "+m.currentDocument.Note+" ", uint(noteWidth), ellipsis))
|
||||
}
|
||||
|
||||
// Empty space
|
||||
|
|
@ -282,7 +460,7 @@ func (m pagerModel) statusBarView(b *strings.Builder) {
|
|||
ansi.PrintableRuneWidth(helpNote),
|
||||
)
|
||||
emptySpace := strings.Repeat(" ", padding)
|
||||
if showStatusMessage {
|
||||
if showMessage {
|
||||
emptySpace = styles.statusBarMessageStyle(emptySpace)
|
||||
} else {
|
||||
emptySpace = styles.statusBarNoteStyle(emptySpace)
|
||||
|
|
@ -339,23 +517,73 @@ func (m pagerModel) helpView() (s string) {
|
|||
|
||||
// COMMANDS
|
||||
|
||||
// renderWithGlamour renders the document for the pager. When remote images
|
||||
// are enabled and the document references any, the text is rendered without
|
||||
// them first so it can be displayed right away: fetching them takes a while,
|
||||
// and the document would otherwise stay off the screen until it's done. The
|
||||
// pager then starts a second pass that loads and renders the images, see the
|
||||
// contentRenderedMsg handling in update.
|
||||
func renderWithGlamour(m pagerModel, md string) tea.Cmd {
|
||||
pending := remoteImagesEnabled(m) && hasRemoteImages(md)
|
||||
|
||||
// Images that don't need fetching are loaded in the first pass.
|
||||
return renderContent(m, md, m.common.cfg.LoadRemoteImages && !pending, pending)
|
||||
}
|
||||
|
||||
// renderContent renders a document with glamour and reports the result to
|
||||
// the pager. remote loads images referenced by http(s) URLs; pending marks a
|
||||
// render that leaves the remote images to a follow-up pass.
|
||||
func renderContent(m pagerModel, md string, remote, pending bool) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
s, err := glamourRender(m, md)
|
||||
s, graphics, err := glamourRender(m, md, remote)
|
||||
if err != nil {
|
||||
log.Error("error rendering with Glamour", "error", err)
|
||||
return errMsg{err}
|
||||
}
|
||||
return contentRenderedMsg(s)
|
||||
return contentRenderedMsg{
|
||||
content: s,
|
||||
graphics: graphics,
|
||||
body: md,
|
||||
remoteImagesPending: pending,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remoteImagesEnabled reports whether remote images should be loaded when
|
||||
// rendering the current document.
|
||||
func remoteImagesEnabled(m pagerModel) bool {
|
||||
return m.common.cfg.LoadRemoteImages && glamourImages(m) &&
|
||||
utils.IsMarkdownFile(m.currentDocument.Note)
|
||||
}
|
||||
|
||||
// loadRemoteImagesCmd renders a document a second time, fetching and
|
||||
// rendering its remote images. token identifies the pass, so a result that a
|
||||
// newer pass has superseded can be discarded.
|
||||
func loadRemoteImagesCmd(m pagerModel, md string, token int) tea.Cmd {
|
||||
return func() tea.Msg {
|
||||
s, graphics, err := glamourRender(m, md, true)
|
||||
if err != nil {
|
||||
log.Error("error loading remote images", "error", err)
|
||||
return errMsg{err}
|
||||
}
|
||||
return remoteImagesLoadedMsg{content: s, graphics: graphics, token: token}
|
||||
}
|
||||
}
|
||||
|
||||
// glamourImages reports whether to render images in the pager using the
|
||||
// terminal's graphics protocol.
|
||||
func glamourImages(m pagerModel) bool {
|
||||
return m.common.cfg.GlamourEnabled && m.common.cfg.Images &&
|
||||
m.common.imageProtocol != glamansi.ImageProtocolNone
|
||||
}
|
||||
|
||||
// This is where the magic happens.
|
||||
func glamourRender(m pagerModel, markdown string) (string, error) {
|
||||
func glamourRender(m pagerModel, markdown string, loadRemoteImages bool) (string, []string, error) {
|
||||
images := glamourImages(m)
|
||||
trunc := lipgloss.NewStyle().MaxWidth(m.viewport.Width() - lineNumberWidth).Render
|
||||
|
||||
if !m.common.cfg.GlamourEnabled {
|
||||
return markdown, nil
|
||||
return markdown, nil, nil
|
||||
}
|
||||
|
||||
isCode := !utils.IsMarkdownFile(m.currentDocument.Note)
|
||||
|
|
@ -369,12 +597,48 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
|
|||
glamour.WithWordWrap(width),
|
||||
}
|
||||
|
||||
if images && !isCode {
|
||||
if width == 0 {
|
||||
// Without a wrap width, images would be sized to their
|
||||
// natural dimensions, which can be far larger than the
|
||||
// viewport.
|
||||
width = m.viewport.Width()
|
||||
options[1] = glamour.WithWordWrap(width)
|
||||
}
|
||||
if m.common.cfg.ShowLineNumbers {
|
||||
// Leave room for the line number gutter so the rendered
|
||||
// content, including image placeholder grids, doesn't get
|
||||
// truncated.
|
||||
width = max(0, width-lineNumberWidth)
|
||||
options[1] = glamour.WithWordWrap(width)
|
||||
}
|
||||
options = append(options,
|
||||
glamour.WithImageProtocol(m.common.imageProtocol),
|
||||
glamour.WithMaxImageSize(0, m.common.cfg.ImageMaxRows),
|
||||
)
|
||||
switch {
|
||||
case loadRemoteImages:
|
||||
options = append(options, glamour.WithRemoteImages())
|
||||
case m.common.cfg.LoadRemoteImages:
|
||||
// This is the text-only render that precedes the remote image
|
||||
// loading one, so don't claim the images were not loaded.
|
||||
options = append(options, glamour.WithRemoteImageNotLoadedNote(""))
|
||||
default:
|
||||
options = append(options, glamour.WithRemoteImageNotLoadedNote(RemoteImageNotLoadedNote))
|
||||
}
|
||||
}
|
||||
|
||||
if m.common.cfg.PreserveNewLines {
|
||||
options = append(options, glamour.WithPreservedNewLines())
|
||||
}
|
||||
if m.currentDocument.localPath != "" {
|
||||
// Resolve image URLs relative to the document's directory, the
|
||||
// same way the CLI does.
|
||||
options = append(options, glamour.WithBaseURL(utils.FileBaseURL(m.currentDocument.localPath)))
|
||||
}
|
||||
r, err := glamour.NewTermRenderer(options...)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating glamour renderer: %w", err)
|
||||
return "", nil, fmt.Errorf("error creating glamour renderer: %w", err)
|
||||
}
|
||||
|
||||
if isCode {
|
||||
|
|
@ -383,9 +647,13 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
|
|||
|
||||
out, err := r.Render(markdown)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error rendering markdown: %w", err)
|
||||
return "", nil, fmt.Errorf("error rendering markdown: %w", err)
|
||||
}
|
||||
|
||||
// The graphics commands are out-of-band sequences the caller must write
|
||||
// to the terminal before displaying the rendered content.
|
||||
graphics := r.GraphicsCommands()
|
||||
|
||||
if isCode {
|
||||
out = strings.TrimSpace(out)
|
||||
}
|
||||
|
|
@ -408,7 +676,7 @@ func glamourRender(m pagerModel, markdown string) (string, error) {
|
|||
}
|
||||
}
|
||||
|
||||
return content.String(), nil
|
||||
return content.String(), graphics, nil
|
||||
}
|
||||
|
||||
func (m *pagerModel) initWatcher() {
|
||||
|
|
|
|||
|
|
@ -660,7 +660,7 @@ func (m stashModel) view() string {
|
|||
var s string
|
||||
switch m.viewState {
|
||||
case stashStateShowingError:
|
||||
return errorView(m.common.styles, m.err, false)
|
||||
return fillHeight(errorView(m.common.styles, m.err, false), m.common.height)
|
||||
case stashStateLoadingDocument:
|
||||
s += " " + m.spinner.View() + " Loading document..."
|
||||
case stashStateReady:
|
||||
|
|
@ -733,7 +733,7 @@ func (m stashModel) view() string {
|
|||
help,
|
||||
)
|
||||
}
|
||||
return "\n" + indent(s, stashIndent)
|
||||
return fillHeight("\n"+indent(s, stashIndent), m.common.height)
|
||||
}
|
||||
|
||||
func glowLogoView(styles Styles) string {
|
||||
|
|
|
|||
|
|
@ -42,6 +42,7 @@ type Styles struct {
|
|||
statusBarMessageStyle func(...string) string
|
||||
statusBarMessageScrollPosStyle func(...string) string
|
||||
statusBarMessageHelpStyle func(...string) string
|
||||
statusBarSpinnerStyle lipgloss.Style
|
||||
helpViewStyle func(...string) string
|
||||
lineNumberStyle func(...string) string
|
||||
|
||||
|
|
@ -135,6 +136,10 @@ func newStyles(isDark bool) Styles {
|
|||
Background(green).
|
||||
Render
|
||||
|
||||
s.statusBarSpinnerStyle = lipgloss.NewStyle().
|
||||
Foreground(gray).
|
||||
Background(statusBarBg)
|
||||
|
||||
s.helpViewStyle = lipgloss.NewStyle().
|
||||
Foreground(statusBarNoteFg).
|
||||
Background(s.adaptive("#f2f2f2", "#1B1B1B")).
|
||||
|
|
|
|||
58
ui/ui.go
58
ui/ui.go
|
|
@ -9,8 +9,10 @@ import (
|
|||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/glamour/v2/ansi"
|
||||
"charm.land/glow/v3/utils"
|
||||
"github.com/charmbracelet/log"
|
||||
uv "github.com/charmbracelet/ultraviolet"
|
||||
"github.com/muesli/gitcha"
|
||||
)
|
||||
|
||||
|
|
@ -83,6 +85,12 @@ type commonModel struct {
|
|||
width int
|
||||
height int
|
||||
styles Styles
|
||||
|
||||
// imageProtocol is the graphics protocol resolved for the TUI. It is
|
||||
// ImageProtocolNone until the terminal is known to support displaying
|
||||
// images (see the kitty graphics query in model.Init), at which point
|
||||
// documents are re-rendered with it.
|
||||
imageProtocol ansi.ImageProtocol
|
||||
}
|
||||
|
||||
type model struct {
|
||||
|
|
@ -119,6 +127,14 @@ func newModel(cfg Config, content string) tea.Model {
|
|||
cfg: cfg,
|
||||
styles: newStyles(true),
|
||||
}
|
||||
if cfg.Images {
|
||||
switch cfg.ImageProtocol {
|
||||
case utils.ImageProtocolKitty:
|
||||
common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
|
||||
case utils.ImageProtocolNone:
|
||||
common.imageProtocol = ansi.ImageProtocolNone
|
||||
}
|
||||
}
|
||||
|
||||
m := model{
|
||||
common: &common,
|
||||
|
|
@ -148,10 +164,19 @@ func newModel(cfg Config, content string) tea.Model {
|
|||
} else {
|
||||
cwd, _ := os.Getwd()
|
||||
m.state = stateShowDocument
|
||||
// Keep the raw body around so the pager can re-render the document
|
||||
// on resize or when image support gets enabled mid-session.
|
||||
body := content
|
||||
if body == "" {
|
||||
if b, err := os.ReadFile(path); err == nil {
|
||||
body = string(b)
|
||||
}
|
||||
}
|
||||
m.pager.currentDocument = markdown{
|
||||
localPath: path,
|
||||
Note: stripAbsolutePath(path, cwd),
|
||||
Modtime: info.ModTime(),
|
||||
Body: string(utils.RemoveFrontmatter([]byte(body))),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -161,6 +186,12 @@ func newModel(cfg Config, content string) tea.Model {
|
|||
func (m model) Init() tea.Cmd {
|
||||
cmds := []tea.Cmd{m.stash.spinner.Tick, tea.RequestBackgroundColor}
|
||||
|
||||
// Detect support for the kitty graphics protocol by querying the
|
||||
// terminal. The response arrives as a uv.KittyGraphicsEvent.
|
||||
if m.common.cfg.Images && m.common.cfg.ImageProtocol == utils.ImageProtocolAuto {
|
||||
cmds = append(cmds, tea.Raw(utils.GraphicsQuery()))
|
||||
}
|
||||
|
||||
switch m.state {
|
||||
case stateShowStash:
|
||||
cmds = append(cmds, findLocalFiles(*m.common))
|
||||
|
|
@ -256,6 +287,19 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||
body := string(utils.RemoveFrontmatter([]byte(msg.Body)))
|
||||
cmds = append(cmds, renderWithGlamour(m.pager, body))
|
||||
|
||||
case uv.KittyGraphicsEvent:
|
||||
// The terminal answered our kitty graphics query from Init. Enable
|
||||
// images and re-render the current document, if any, with them.
|
||||
if m.common.cfg.Images && m.common.imageProtocol == ansi.ImageProtocolNone &&
|
||||
utils.KittyGraphicsOK(msg.Options.ID, msg.Payload) {
|
||||
m.common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
|
||||
log.Debug("terminal supports the kitty graphics protocol")
|
||||
if m.state == stateShowDocument {
|
||||
body := string(utils.RemoveFrontmatter([]byte(m.pager.currentDocument.Body)))
|
||||
cmds = append(cmds, renderWithGlamour(m.pager, body))
|
||||
}
|
||||
}
|
||||
|
||||
case contentRenderedMsg:
|
||||
m.state = stateShowDocument
|
||||
|
||||
|
|
@ -306,7 +350,7 @@ func (m model) View() tea.View {
|
|||
var content string
|
||||
switch {
|
||||
case m.fatalErr != nil:
|
||||
content = errorView(m.common.styles, m.fatalErr, true)
|
||||
content = fillHeight(errorView(m.common.styles, m.fatalErr, true), m.common.height)
|
||||
case m.state == stateShowDocument:
|
||||
content = m.pager.View()
|
||||
default:
|
||||
|
|
@ -421,6 +465,18 @@ func stripAbsolutePath(fullPath, cwd string) string {
|
|||
return strings.ReplaceAll(fp, cp+string(os.PathSeparator), "")
|
||||
}
|
||||
|
||||
// fillHeight pads a view with newlines so that it fills the given number of
|
||||
// terminal lines. Views that don't cover the whole terminal leave whatever the
|
||||
// previous frame drew on screen, which is visible as stale lines, e.g. the
|
||||
// status bar of a document stuck at the bottom after going back to the stash.
|
||||
func fillHeight(s string, height int) string {
|
||||
missing := height - (strings.Count(s, "\n") + 1)
|
||||
if height <= 0 || missing <= 0 {
|
||||
return s
|
||||
}
|
||||
return s + strings.Repeat("\n", missing)
|
||||
}
|
||||
|
||||
// Lightweight version of reflow's indent function.
|
||||
func indent(s string, n int) string {
|
||||
if n <= 0 || s == "" {
|
||||
|
|
|
|||
719
ui/ui_test.go
Normal file
719
ui/ui_test.go
Normal file
|
|
@ -0,0 +1,719 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/glamour/v2/ansi"
|
||||
)
|
||||
|
||||
// testPNG returns the bytes of a small PNG image.
|
||||
func testPNG(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
|
||||
img := image.NewRGBA(image.Rect(0, 0, 16, 8))
|
||||
for x := 0; x < 16; x++ {
|
||||
for y := 0; y < 8; y++ {
|
||||
img.Set(x, y, color.RGBA{R: 255, A: 255})
|
||||
}
|
||||
}
|
||||
var pngBuf bytes.Buffer
|
||||
if err := png.Encode(&pngBuf, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pngBuf.Bytes()
|
||||
}
|
||||
|
||||
// writeTestDocument writes a markdown document to a temporary directory and
|
||||
// returns its path.
|
||||
func writeTestDocument(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
|
||||
mdPath := filepath.Join(t.TempDir(), "test.md")
|
||||
if err := os.WriteFile(mdPath, []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return mdPath
|
||||
}
|
||||
|
||||
// writeTestFiles creates a markdown document referencing a PNG image and
|
||||
// returns the markdown file's path.
|
||||
func writeTestFiles(t *testing.T) string {
|
||||
t.Helper()
|
||||
|
||||
if err := os.WriteFile(filepath.Join(t.TempDir(), "test.png"), testPNG(t), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "test.png"), testPNG(t), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mdPath := filepath.Join(dir, "test.md")
|
||||
if err := os.WriteFile(mdPath, []byte("# Hello\n\n\n\nBye!\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return mdPath
|
||||
}
|
||||
|
||||
// TestPagerKittyImages runs the pager on a document with an image and checks
|
||||
// that the image is transmitted out-of-band before the content, which
|
||||
// references it via unicode placeholders, is displayed.
|
||||
func TestPagerKittyImages(t *testing.T) {
|
||||
mdPath := writeTestFiles(t)
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: true,
|
||||
ImageProtocol: "kitty",
|
||||
Path: mdPath,
|
||||
}
|
||||
|
||||
m := newModel(cfg, "")
|
||||
|
||||
var out bytes.Buffer
|
||||
p := tea.NewProgram(m,
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
quit := make(chan struct{})
|
||||
go func() {
|
||||
// Give the program time to render, then shut it down.
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
p.Send(tea.Quit())
|
||||
close(quit)
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-quit
|
||||
|
||||
got := out.String()
|
||||
|
||||
// The image must have been transmitted with a virtual placement.
|
||||
transmit := strings.Index(got, "\x1b_G")
|
||||
if transmit < 0 {
|
||||
t.Fatalf("no kitty graphics commands in output: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "a=p") || !strings.Contains(got, "U=1") {
|
||||
t.Errorf("expected a virtual placement command, got: %q", got)
|
||||
}
|
||||
|
||||
// The content must reference the image via unicode placeholders, which
|
||||
// the terminal replaces with the image as the content scrolls.
|
||||
placeholder := strings.IndexRune(got, 0x10EEEE)
|
||||
if placeholder < 0 {
|
||||
t.Fatalf("no unicode placeholders in output: %q", got)
|
||||
}
|
||||
|
||||
// The transmission must be written to the terminal before the
|
||||
// placeholders are displayed, otherwise the terminal can't resolve them
|
||||
// until the next repaint.
|
||||
if transmit > placeholder {
|
||||
t.Errorf("expected graphics commands (%d) before placeholders (%d)", transmit, placeholder)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPagerNoImages checks that with images disabled the output contains
|
||||
// neither graphics commands nor placeholders.
|
||||
func TestPagerNoImages(t *testing.T) {
|
||||
mdPath := writeTestFiles(t)
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: false,
|
||||
Path: mdPath,
|
||||
}
|
||||
|
||||
m := newModel(cfg, "")
|
||||
|
||||
var out bytes.Buffer
|
||||
p := tea.NewProgram(m,
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
p.Send(tea.Quit())
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := out.String()
|
||||
if strings.Contains(got, "\x1b_G") {
|
||||
t.Errorf("expected no graphics commands, got: %q", got)
|
||||
}
|
||||
if strings.ContainsRune(got, 0x10EEEE) {
|
||||
t.Errorf("expected no placeholders, got: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommonModelImageProtocol checks the initial protocol resolution from
|
||||
// the config.
|
||||
func TestCommonModelImageProtocol(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
protocol string
|
||||
images bool
|
||||
want ansi.ImageProtocol
|
||||
}{
|
||||
{"kitty", true, ansi.ImageProtocolKittyPlaceholders},
|
||||
{"none", true, ansi.ImageProtocolNone},
|
||||
{"auto", true, ansi.ImageProtocolNone},
|
||||
{"kitty", false, ansi.ImageProtocolNone},
|
||||
} {
|
||||
m := newModel(Config{Images: tc.images, ImageProtocol: tc.protocol}, "")
|
||||
if got := m.(model).common.imageProtocol; got != tc.want {
|
||||
t.Errorf("protocol %q, images %v: expected %v, got %v", tc.protocol, tc.images, tc.want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHasRemoteImages checks the detection of images that have to be fetched
|
||||
// over the network.
|
||||
func TestHasRemoteImages(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
markdown string
|
||||
want bool
|
||||
}{
|
||||
{"", true},
|
||||
{"", true},
|
||||
{`<img src="https://example.com/img.png">`, true},
|
||||
{"![build][badge]\n\n[badge]: https://example.com/badge.svg", true},
|
||||
{"![build][BADGE]\n\n[badge]: https://example.com/badge.svg", true},
|
||||
{"![build][badge]\n\n[badge]: badge.svg", false},
|
||||
{"[docs]: https://example.com\n\nsee [docs]", false},
|
||||
{"", false},
|
||||
{"[alt](https://example.com)", false},
|
||||
{`<img src="img.png">`, false},
|
||||
{"no images at all", false},
|
||||
} {
|
||||
if got := hasRemoteImages(tc.markdown); got != tc.want {
|
||||
t.Errorf("%q: expected %v, got %v", tc.markdown, tc.want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPagerRemoteImagesDisabled checks that remote images are not fetched by
|
||||
// default, and that their URL is rendered with a note pointing at the config
|
||||
// setting that loads them.
|
||||
func TestPagerRemoteImagesDisabled(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
t.Error("no remote image may be fetched while remote image loading is disabled")
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
mdPath := writeTestDocument(t, "# Hello\n\n\n")
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: true,
|
||||
ImageProtocol: "kitty",
|
||||
Path: mdPath,
|
||||
}
|
||||
|
||||
m := newModel(cfg, "")
|
||||
|
||||
var out bytes.Buffer
|
||||
p := tea.NewProgram(m,
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
p.Send(tea.Quit())
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := out.String()
|
||||
// The note can wrap or be cut off by the terminal, so check for the
|
||||
// parts of it that always fit.
|
||||
if !strings.Contains(got, "not loaded.") {
|
||||
t.Errorf("expected a note about the image not being loaded, got: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "loadRemoteImage") {
|
||||
t.Errorf("expected a note about the loadRemoteImages setting, got: %q", got)
|
||||
}
|
||||
if strings.Contains(got, "\x1b_G") {
|
||||
t.Errorf("expected no graphics commands, got: %q", got)
|
||||
}
|
||||
if strings.ContainsRune(got, 0x10EEEE) {
|
||||
t.Errorf("expected no placeholders, got: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGlamourRenderRemoteImages checks how remote images are rendered,
|
||||
// depending on the config: with loading disabled they are annotated with a
|
||||
// note, and while they are pending the note is withheld so they aren't
|
||||
// reported as not loaded.
|
||||
func TestGlamourRenderRemoteImages(t *testing.T) {
|
||||
url := "https://example.com/img.png"
|
||||
md := ""
|
||||
|
||||
newPager := func(loadRemoteImages bool) pagerModel {
|
||||
common := &commonModel{
|
||||
cfg: Config{GlamourEnabled: true, Images: true, LoadRemoteImages: loadRemoteImages, GlamourStyle: "dark"},
|
||||
styles: newStyles(true),
|
||||
imageProtocol: ansi.ImageProtocolKitty,
|
||||
}
|
||||
m := newPagerModel(common)
|
||||
// No wrap width, so the rendered note stays on a single line and the
|
||||
// rendering is deterministic.
|
||||
m.setSize(0, 24)
|
||||
m.currentDocument = markdown{Note: "test.md", Body: md}
|
||||
return m
|
||||
}
|
||||
|
||||
// Disabled: the URL is followed by a note pointing at the setting.
|
||||
out, _, err := glamourRender(newPager(false), md, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, RemoteImageNotLoadedNote) {
|
||||
t.Errorf("expected the not-loaded note, got: %q", out)
|
||||
}
|
||||
|
||||
// Enabled: the first pass renders the text without claiming the images
|
||||
// weren't loaded; the second pass loads them.
|
||||
out, _, err = glamourRender(newPager(true), md, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, url) {
|
||||
t.Errorf("expected the image URL to render, got: %q", out)
|
||||
}
|
||||
if strings.Contains(out, "not loaded") {
|
||||
t.Errorf("expected no not-loaded note while the images load, got: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPagerLoadRemoteImages checks that with remote image loading enabled the
|
||||
// document's remote images are fetched and rendered.
|
||||
func TestPagerLoadRemoteImages(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
png := testPNG(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
_, _ = w.Write(png)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
mdPath := writeTestDocument(t, "# Hello\n\n\n\nBye!\n")
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: true,
|
||||
ImageProtocol: "kitty",
|
||||
LoadRemoteImages: true,
|
||||
Path: mdPath,
|
||||
}
|
||||
|
||||
m := newModel(cfg, "")
|
||||
|
||||
var out bytes.Buffer
|
||||
p := tea.NewProgram(m,
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
go func() {
|
||||
// Leave room for the second rendering pass that fetches the image.
|
||||
time.Sleep(time.Second)
|
||||
p.Send(tea.Quit())
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := out.String()
|
||||
if requests.Load() == 0 {
|
||||
t.Error("expected the remote image to be fetched")
|
||||
}
|
||||
// The image may only be transmitted by the second rendering pass, which
|
||||
// fetched it.
|
||||
if !strings.Contains(got, "\x1b_G") {
|
||||
t.Errorf("expected the remote image to be transmitted, got: %q", got)
|
||||
}
|
||||
if !strings.ContainsRune(got, 0x10EEEE) {
|
||||
t.Errorf("expected the image to be displayed via placeholders, got: %q", got)
|
||||
}
|
||||
if strings.Contains(got, "loadRemoteImages") {
|
||||
t.Errorf("expected no not-loaded note, got: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPagerRemoteImagesLoading checks that the pager reports the remote
|
||||
// images as loading, and only displays the results of the current fetching
|
||||
// pass.
|
||||
func TestPagerRemoteImagesLoading(t *testing.T) {
|
||||
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: 24}
|
||||
m := newPagerModel(&common)
|
||||
m.setSize(80, 24)
|
||||
m.currentDocument = markdown{Note: "test.md", Body: ""}
|
||||
|
||||
m, cmd := m.update(contentRenderedMsg{
|
||||
content: "text without images",
|
||||
body: m.currentDocument.Body,
|
||||
remoteImagesPending: true,
|
||||
})
|
||||
if !m.remoteImagesLoading {
|
||||
t.Error("expected the remote images to be reported as loading")
|
||||
}
|
||||
if cmd == nil {
|
||||
t.Error("expected a command that fetches the remote images")
|
||||
}
|
||||
if !strings.Contains(m.View(), "Loading remote images") {
|
||||
t.Errorf("expected a loading indicator, got: %q", m.View())
|
||||
}
|
||||
|
||||
// Results of an older pass, e.g. one superseded by a resize, are stale.
|
||||
m, _ = m.update(remoteImagesLoadedMsg{content: "stale", token: m.remoteImagesPass - 1})
|
||||
if !m.remoteImagesLoading {
|
||||
t.Error("expected the stale result to be ignored")
|
||||
}
|
||||
if got := m.viewport.GetContent(); got != "text without images" {
|
||||
t.Errorf("expected the text to stay on screen, got: %q", got)
|
||||
}
|
||||
|
||||
// The result of the current pass replaces the text-only content.
|
||||
m, _ = m.update(remoteImagesLoadedMsg{content: "text with images", token: m.remoteImagesPass})
|
||||
if m.remoteImagesLoading {
|
||||
t.Error("expected the remote images to be reported as loaded")
|
||||
}
|
||||
if got := m.viewport.GetContent(); got != "text with images" {
|
||||
t.Errorf("expected the rendered images on screen, got: %q", got)
|
||||
}
|
||||
if strings.Contains(m.View(), "Loading remote images") {
|
||||
t.Errorf("expected the loading indicator to be gone, got: %q", m.View())
|
||||
}
|
||||
}
|
||||
|
||||
// TestViewsFillScreen checks that the views shown between documents (loading,
|
||||
// error) and the pager before it has been sized fill the terminal height.
|
||||
// Views that don't cover the whole screen leave whatever the previous frame
|
||||
// drew on it, e.g. a document's status bar stuck at the bottom after going
|
||||
// back to the stash.
|
||||
func TestViewsFillScreen(t *testing.T) {
|
||||
const height = 24
|
||||
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: height}
|
||||
|
||||
check := func(name, view string) {
|
||||
t.Helper()
|
||||
if got := strings.Count(view, "\n") + 1; got != height {
|
||||
t.Errorf("expected the %s view to fill the screen, got %d lines, want %d", name, got, height)
|
||||
}
|
||||
}
|
||||
|
||||
stash := newStashModel(&common)
|
||||
stash.setSize(80, height)
|
||||
stash.loaded = true
|
||||
check("stash", stash.view())
|
||||
|
||||
stash.viewState = stashStateLoadingDocument
|
||||
check("loading", stash.view())
|
||||
|
||||
stash.viewState = stashStateShowingError
|
||||
stash.err = errMsg{err: errors.New("boom")}
|
||||
check("error", stash.view())
|
||||
|
||||
pager := newPagerModel(&common)
|
||||
check("unsized pager", pager.View())
|
||||
pager.setSize(80, height)
|
||||
check("empty pager", pager.View())
|
||||
pager.setContent("hello\nworld")
|
||||
check("pager", pager.View())
|
||||
}
|
||||
|
||||
// TestPagerRemoteImagesLoadError checks that a failed loading pass clears the
|
||||
// loading indicator and reports the error, rather than leaving the indicator
|
||||
// in the status bar forever.
|
||||
func TestPagerRemoteImagesLoadError(t *testing.T) {
|
||||
common := commonModel{cfg: Config{GlamourEnabled: true}, styles: newStyles(true), width: 80, height: 24}
|
||||
m := newPagerModel(&common)
|
||||
m.setSize(80, 24)
|
||||
m.currentDocument = markdown{Note: "test.md", Body: ""}
|
||||
|
||||
m, _ = m.update(contentRenderedMsg{
|
||||
content: "text without images",
|
||||
body: m.currentDocument.Body,
|
||||
remoteImagesPending: true,
|
||||
})
|
||||
if !m.remoteImagesLoading {
|
||||
t.Fatal("expected the remote images to be reported as loading")
|
||||
}
|
||||
|
||||
m, cmd := m.update(errMsg{err: errors.New("boom")})
|
||||
if m.remoteImagesLoading {
|
||||
t.Error("expected the loading indicator to be cleared")
|
||||
}
|
||||
if strings.Contains(m.View(), "Loading remote images") {
|
||||
t.Errorf("expected the loading indicator to be gone, got: %q", m.View())
|
||||
}
|
||||
if !strings.Contains(m.View(), "boom") {
|
||||
t.Errorf("expected the error to be reported, got: %q", m.View())
|
||||
}
|
||||
if cmd == nil {
|
||||
t.Error("expected a status message timeout")
|
||||
}
|
||||
}
|
||||
|
||||
// staticViewModel renders a view that never changes, like the loading
|
||||
// indicator between documents.
|
||||
type staticViewModel struct{}
|
||||
|
||||
func (staticViewModel) Init() tea.Cmd { return nil }
|
||||
func (m staticViewModel) Update(tea.Msg) (tea.Model, tea.Cmd) { return m, nil }
|
||||
func (staticViewModel) View() tea.View {
|
||||
v := tea.NewView("static")
|
||||
v.AltScreen = true
|
||||
return v
|
||||
}
|
||||
|
||||
// syncBuffer is a buffer that can be read while the program writes to it.
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (b *syncBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *syncBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
// TestResizeRedrawsUnchangedView checks that a window resize redraws the
|
||||
// screen even when the view doesn't change, e.g. while a document loads. The
|
||||
// renderer must not skip the screen erase queued by the resize, or the
|
||||
// terminal keeps whatever the previous frame drew, like a document's status
|
||||
// bar left stuck at the bottom (fixed in bubbletea v2.0.9, see
|
||||
// charmbracelet/bubbletea#1755).
|
||||
func TestResizeRedrawsUnchangedView(t *testing.T) {
|
||||
var out syncBuffer
|
||||
p := tea.NewProgram(staticViewModel{},
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
|
||||
// Wait for the initial frame, then resize to the same dimensions so
|
||||
// that only the resize can redraw the screen.
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
before := strings.Count(out.String(), "static")
|
||||
|
||||
p.Send(tea.WindowSizeMsg{Width: 80, Height: 24})
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
|
||||
if after := strings.Count(out.String(), "static"); after <= before {
|
||||
t.Errorf("expected the screen to be redrawn on resize, got no redraw (frames before=%d, after=%d)",
|
||||
before, after)
|
||||
}
|
||||
p.Send(tea.Quit())
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
<-done
|
||||
}
|
||||
|
||||
// testSVG is a small SVG document used in the SVG tests.
|
||||
const testSVG = `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20">
|
||||
<rect width="40" height="20" fill="red"/>
|
||||
<circle cx="20" cy="10" r="8" fill="blue"/>
|
||||
</svg>
|
||||
`
|
||||
|
||||
// TestPagerKittySVGImages runs the pager on a document with an SVG image and
|
||||
// checks that the vector image is rasterized and displayed like other
|
||||
// images.
|
||||
func TestPagerKittySVGImages(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "test.svg"), []byte(testSVG), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mdPath := filepath.Join(dir, "test.md")
|
||||
if err := os.WriteFile(mdPath, []byte("# Hello\n\n\n\nBye!\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: true,
|
||||
ImageProtocol: "kitty",
|
||||
Path: mdPath,
|
||||
}
|
||||
|
||||
m := newModel(cfg, "")
|
||||
|
||||
var out bytes.Buffer
|
||||
p := tea.NewProgram(m,
|
||||
tea.WithOutput(&out),
|
||||
tea.WithInput(strings.NewReader("")),
|
||||
tea.WithWindowSize(80, 24),
|
||||
)
|
||||
|
||||
go func() {
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
p.Send(tea.Quit())
|
||||
}()
|
||||
if _, err := p.Run(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got := out.String()
|
||||
// The SVG must be rasterized and transmitted as a PNG, and displayed via
|
||||
// unicode placeholders.
|
||||
if !strings.Contains(got, "\x1b_G") {
|
||||
t.Errorf("expected the SVG to be transmitted, got: %q", got)
|
||||
}
|
||||
if !strings.ContainsRune(got, 0x10EEEE) {
|
||||
t.Errorf("expected the SVG to be displayed via placeholders, got: %q", got)
|
||||
}
|
||||
// Displayed images don't render their URL next to them.
|
||||
if strings.Contains(got, "test.svg") {
|
||||
t.Errorf("expected the SVG URL not to be rendered next to the image, got: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// kittyPlaceholder is the unicode placeholder cell that anchors an image to
|
||||
// the text grid.
|
||||
const kittyPlaceholder = '\U0010EEEE'
|
||||
|
||||
// escapeSequencePattern matches ANSI SGR, OSC 8 hyperlink, and graphics
|
||||
// protocol sequences.
|
||||
var escapeSequencePattern = regexp.MustCompile(`\x1b\]8;[^\x07\x9c]*(\x07|\x9c)|\x1b\[[0-9;:]*[a-zA-Z]|\x1b_G[^\x1b]*\x1b\\|\x1bP[^\x1b]*\x1b\\`)
|
||||
|
||||
// visibleText returns the text a terminal would display for the given
|
||||
// rendered output, i.e. with all escape sequences removed.
|
||||
func visibleText(s string) string {
|
||||
return escapeSequencePattern.ReplaceAllString(s, "")
|
||||
}
|
||||
|
||||
// testBadgeSVG is a badge in the shape of the ones served by shields.io: a
|
||||
// background split in two, and text drawn in scaled groups.
|
||||
const testBadgeSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="94" height="20">` +
|
||||
`<g><rect width="49" height="20" fill="#555"/>` +
|
||||
`<rect x="49" width="45" height="20" fill="#007ec6"/></g>` +
|
||||
`<g fill="#fff" text-anchor="middle" font-size="110">` +
|
||||
`<g transform="scale(.1)"><text x="255" y="140">release</text></g>` +
|
||||
`<g transform="scale(.1)"><text x="705" y="140">v3.0.0</text></g></g></svg>`
|
||||
|
||||
// testPathBadgeSVG is a badge whose text is drawn as path outlines, and which
|
||||
// uses arcs, like the badges served by godoc.org.
|
||||
const testPathBadgeSVG = `<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20">` +
|
||||
`<path d="M2 0h26v20H2a2 2 0 01-2-2V2a2 2 0 012-2z" fill="#5C5C5C"/>` +
|
||||
`<path d="M87.99 0H28v20h59.99a2 2 0 002-2V2a2 2 0 00-2-2z" fill="#007D9C"/>` +
|
||||
`<path d="M35 14v-3c0-2 2-3 4-3l1 0V14H35z" fill="#FAFAFA"/></svg>`
|
||||
|
||||
// TestPagerKittyBadges runs the pager on a README-style list of badges and
|
||||
// checks that they are rasterized, drawn in the text flow, and rendered next
|
||||
// to each other on one line, the way a browser renders them.
|
||||
func TestPagerKittyBadges(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, content := range map[string]string{
|
||||
"release.svg": testBadgeSVG,
|
||||
"doc.svg": testPathBadgeSVG,
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
mdPath := filepath.Join(dir, "test.md")
|
||||
body := "<p>\n" +
|
||||
" <a href=\"https://example.com\"><img src=\"release.svg\" alt=\"release\"></a>\n" +
|
||||
" <a href=\"https://example.com\"><img src=\"doc.svg\" alt=\"doc\"></a>\n" +
|
||||
"</p>\n"
|
||||
if err := os.WriteFile(mdPath, []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
GlamourEnabled: true,
|
||||
GlamourStyle: "dark",
|
||||
GlamourMaxWidth: 80,
|
||||
Images: true,
|
||||
ImageProtocol: "kitty",
|
||||
}
|
||||
common := commonModel{cfg: cfg, styles: newStyles(true), width: 80, height: 24}
|
||||
common.imageProtocol = ansi.ImageProtocolKittyPlaceholders
|
||||
pager := newPagerModel(&common)
|
||||
pager.setSize(80, 24)
|
||||
pager.currentDocument = markdown{Note: "test.md", localPath: mdPath, Body: body}
|
||||
|
||||
content, graphics, err := glamourRender(pager, body, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The two badges are rasterized and transmitted, and their placeholder
|
||||
// grids are placed on the same line, separated by a space, the way a
|
||||
// browser renders them.
|
||||
if len(graphics) != 4 {
|
||||
t.Errorf("expected transmit and place commands for both badges, got %d", len(graphics))
|
||||
}
|
||||
gridLines := 0
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
if !strings.ContainsRune(line, kittyPlaceholder) {
|
||||
continue
|
||||
}
|
||||
gridLines++
|
||||
|
||||
grid := strings.TrimLeft(visibleText(line), " ")
|
||||
if !strings.HasPrefix(grid, string(kittyPlaceholder)) {
|
||||
t.Errorf("expected the line to start with a badge, got: %q", grid)
|
||||
}
|
||||
if got := strings.Count(grid, string(kittyPlaceholder)); got != 19 {
|
||||
t.Errorf("expected 19 placeholder cells for both badges, got %d", got)
|
||||
}
|
||||
if !strings.Contains(grid, string(kittyPlaceholder)+" ") {
|
||||
t.Errorf("expected a space between the badges, got: %q", grid)
|
||||
}
|
||||
}
|
||||
if gridLines != 1 {
|
||||
t.Fatalf("expected both badges on one line, got %d lines", gridLines)
|
||||
}
|
||||
}
|
||||
261
utils/graphics.go
Normal file
261
utils/graphics.go
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
// Package utils provides utility functions.
|
||||
package utils
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"charm.land/glamour/v2/ansi"
|
||||
xansi "github.com/charmbracelet/x/ansi"
|
||||
"github.com/charmbracelet/x/ansi/kitty"
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// Image protocol names as accepted by the GLOW_IMAGE_PROTOCOL environment
|
||||
// variable.
|
||||
const (
|
||||
ImageProtocolEnv = "GLOW_IMAGE_PROTOCOL"
|
||||
ImageProtocolAuto = "auto"
|
||||
ImageProtocolKitty = "kitty"
|
||||
ImageProtocolSixel = "sixel"
|
||||
ImageProtocolNone = "none"
|
||||
)
|
||||
|
||||
// queryTimeout is how long DetectImageProtocol waits for terminal query
|
||||
// responses before giving up. Terminals respond within a few milliseconds,
|
||||
// so this only matters for terminals that don't respond at all.
|
||||
const queryTimeout = 150 * time.Millisecond
|
||||
|
||||
// kittyQueryID is the image id used for the kitty graphics query. The
|
||||
// terminal echoes it back in its response, and it must not collide with real
|
||||
// image ids. KittyGraphicsOK reports whether a KittyGraphicsEvent is a
|
||||
// successful response to [GraphicsQuery].
|
||||
const kittyQueryID = 31
|
||||
|
||||
// DetectImageProtocol returns the graphics protocol the terminal attached to
|
||||
// os.Stdout and os.Stdin supports.
|
||||
//
|
||||
// The GLOW_IMAGE_PROTOCOL environment variable can be set to "kitty",
|
||||
// "sixel", "auto", or "none" to force a protocol and skip detection. With
|
||||
// "auto" (the default), known terminals are detected via environment
|
||||
// variables, and everything else is detected by querying the terminal: a
|
||||
// kitty graphics query followed by a request for the primary device
|
||||
// attributes, which also reports sixel support. Terminals that answer
|
||||
// neither are assumed to not support graphics.
|
||||
func DetectImageProtocol() ansi.ImageProtocol {
|
||||
switch p := os.Getenv(ImageProtocolEnv); p {
|
||||
case ImageProtocolKitty:
|
||||
return ansi.ImageProtocolKitty
|
||||
case ImageProtocolSixel:
|
||||
return ansi.ImageProtocolSixel
|
||||
case ImageProtocolNone:
|
||||
return ansi.ImageProtocolNone
|
||||
}
|
||||
|
||||
out, in := os.Stdout, os.Stdin
|
||||
if !term.IsTerminal(int(out.Fd())) {
|
||||
// Piping the output elsewhere: don't emit any graphics sequences.
|
||||
return ansi.ImageProtocolNone
|
||||
}
|
||||
|
||||
// Terminals we can identify by environment alone. This keeps them fast,
|
||||
// as they don't need to be queried.
|
||||
if protocol, ok := protocolFromEnvironment(); ok {
|
||||
return protocol
|
||||
}
|
||||
|
||||
if !term.IsTerminal(int(in.Fd())) {
|
||||
// No way to read query responses, e.g. when rendering from stdin.
|
||||
return ansi.ImageProtocolNone
|
||||
}
|
||||
|
||||
resp, err := queryTerminal(out, in, graphicsQuery(), queryTimeout)
|
||||
if err != nil {
|
||||
return ansi.ImageProtocolNone
|
||||
}
|
||||
if hasKitty, hasSixel := parseQueryResponse(resp); hasKitty {
|
||||
return ansi.ImageProtocolKitty
|
||||
} else if hasSixel {
|
||||
return ansi.ImageProtocolSixel
|
||||
}
|
||||
return ansi.ImageProtocolNone
|
||||
}
|
||||
|
||||
// protocolFromEnvironment reports the graphics protocol of terminals that
|
||||
// identify themselves via environment variables, and whether the terminal
|
||||
// is known.
|
||||
func protocolFromEnvironment() (ansi.ImageProtocol, bool) {
|
||||
if os.Getenv("KITTY_WINDOW_ID") != "" {
|
||||
return ansi.ImageProtocolKitty, true
|
||||
}
|
||||
termVar := os.Getenv("TERM")
|
||||
switch {
|
||||
case termVar == "xterm-kitty" || strings.HasPrefix(termVar, "kitty"):
|
||||
return ansi.ImageProtocolKitty, true
|
||||
case strings.Contains(termVar, "ghostty"), os.Getenv("GHOSTTY_RESOURCES_DIR") != "":
|
||||
return ansi.ImageProtocolKitty, true
|
||||
case os.Getenv("TERM_PROGRAM") == "WezTerm":
|
||||
return ansi.ImageProtocolKitty, true
|
||||
case strings.HasPrefix(termVar, "foot"):
|
||||
// foot supports sixel but not the kitty graphics protocol.
|
||||
return ansi.ImageProtocolSixel, true
|
||||
}
|
||||
return ansi.ImageProtocolNone, false
|
||||
}
|
||||
|
||||
// GraphicsQuery returns a kitty graphics query that can be sent to the
|
||||
// terminal to detect support for the kitty graphics protocol. Send it via
|
||||
// tea.Raw and check the response with KittyGraphicsOK. It is the same query
|
||||
// DetectImageProtocol uses.
|
||||
// See https://sw.kovidgoyal.net/kitty/graphics-protocol/#checking-for-support
|
||||
func GraphicsQuery() string {
|
||||
return graphicsQuery()
|
||||
}
|
||||
|
||||
// KittyGraphicsOK reports whether the given kitty graphics event is a
|
||||
// successful response to [GraphicsQuery].
|
||||
func KittyGraphicsOK(optionsID int, payload []byte) bool {
|
||||
return optionsID == kittyQueryID && bytes.HasPrefix(payload, []byte("OK"))
|
||||
}
|
||||
|
||||
// FileBaseURL returns a file:// URL for the directory containing the given
|
||||
// file path, suitable as a glamour base URL, so that relative image
|
||||
// references resolve correctly on all platforms. Relative paths are
|
||||
// resolved against the current working directory.
|
||||
func FileBaseURL(path string) string {
|
||||
dir := filepath.Dir(path)
|
||||
if !isWindowsDrivePath(dir) {
|
||||
if abs, err := filepath.Abs(dir); err == nil {
|
||||
dir = abs
|
||||
}
|
||||
}
|
||||
s := filepath.ToSlash(dir)
|
||||
if !strings.HasPrefix(s, "/") {
|
||||
// A Windows drive letter, e.g. C:/Users/x, needs a leading slash to
|
||||
// form a valid file URL path: /C:/Users/x.
|
||||
s = "/" + s
|
||||
}
|
||||
u := url.URL{Scheme: "file", Path: s}
|
||||
return u.String() + "/"
|
||||
}
|
||||
|
||||
// isWindowsDrivePath reports whether the path starts with a Windows drive
|
||||
// letter, like C:/Users/x. Such paths are absolute on Windows, and treated
|
||||
// as absolute everywhere, so that documents render identically on all
|
||||
// platforms.
|
||||
func isWindowsDrivePath(path string) bool {
|
||||
return len(path) >= 3 && path[1] == ':' && (path[2] == '/' || path[2] == '\\') &&
|
||||
(path[0] >= 'a' && path[0] <= 'z' || path[0] >= 'A' && path[0] <= 'Z')
|
||||
}
|
||||
|
||||
// graphicsQuery returns a kitty graphics query followed by a request for the
|
||||
// primary device attributes. Terminals supporting the kitty graphics
|
||||
// protocol must answer the graphics query immediately, and every terminal
|
||||
// answers the device attributes request, which terminates the wait and
|
||||
// reports sixel support.
|
||||
func graphicsQuery() string {
|
||||
opts := kitty.Options{
|
||||
Action: kitty.Query,
|
||||
ID: kittyQueryID,
|
||||
// One 1x1 RGB pixel, base64 encoded as the payload.
|
||||
ImageWidth: 1,
|
||||
ImageHeight: 1,
|
||||
Transmission: kitty.Direct,
|
||||
Format: kitty.RGB,
|
||||
}
|
||||
return xansi.KittyGraphics([]byte("AAAA"), opts.Options()...) +
|
||||
xansi.RequestPrimaryDeviceAttributes
|
||||
}
|
||||
|
||||
// queryTerminal writes query to out, puts in into raw mode, and reads back
|
||||
// the terminal's response until the primary device attributes response
|
||||
// arrives. It gives up after the given timeout.
|
||||
func queryTerminal(out, in *os.File, query string, timeout time.Duration) (string, error) {
|
||||
fd := int(in.Fd())
|
||||
oldState, err := term.MakeRaw(fd)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer term.Restore(fd, oldState) //nolint:errcheck
|
||||
|
||||
if _, err := out.WriteString(query); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
type result struct {
|
||||
response string
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
|
||||
go func() {
|
||||
var buf bytes.Buffer
|
||||
b := make([]byte, 256)
|
||||
for {
|
||||
n, err := in.Read(b)
|
||||
if n > 0 {
|
||||
buf.Write(b[:n])
|
||||
// The device attributes response terminates the query.
|
||||
if hasDA1Response(buf.Bytes()) {
|
||||
done <- result{response: buf.String()}
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
done <- result{err: err}
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
select {
|
||||
case r := <-done:
|
||||
return r.response, r.err
|
||||
case <-time.After(timeout):
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
// hasDA1Response reports whether data contains a primary device attributes
|
||||
// response, i.e. ESC [ ? ... c.
|
||||
func hasDA1Response(data []byte) bool {
|
||||
for i := 0; i+3 < len(data); i++ {
|
||||
if data[i] == 0x1b && data[i+1] == '[' && data[i+2] == '?' &&
|
||||
bytes.ContainsRune(data[i+3:], 'c') {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseQueryResponse reports whether the terminal's query response indicates
|
||||
// support for the kitty graphics protocol and sixel graphics.
|
||||
func parseQueryResponse(resp string) (hasKitty, hasSixel bool) {
|
||||
// The kitty graphics protocol responds with _Gi=<id>;OK.
|
||||
for _, part := range strings.Split(resp, "\x1b_G") {
|
||||
options, payload, _ := strings.Cut(part, ";")
|
||||
if strings.Contains(options, "i="+strconv.Itoa(kittyQueryID)) &&
|
||||
strings.HasPrefix(payload, "OK") {
|
||||
hasKitty = true
|
||||
}
|
||||
}
|
||||
// DA1 responses are ESC [ ? <attrs> c, where attribute 4 indicates sixel
|
||||
// support.
|
||||
for _, part := range strings.Split(resp, "\x1b[?") {
|
||||
attrs, ok := strings.CutSuffix(part, "c")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for _, attr := range strings.Split(attrs, ";") {
|
||||
if attr == "4" {
|
||||
hasSixel = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return hasKitty, hasSixel
|
||||
}
|
||||
215
utils/graphics_test.go
Normal file
215
utils/graphics_test.go
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
package utils
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"charm.land/glamour/v2/ansi"
|
||||
)
|
||||
|
||||
func TestProtocolFromEnvironment(t *testing.T) {
|
||||
// Clear the variables the detection looks at so tests don't depend on
|
||||
// the environment they run in.
|
||||
clearEnv := func(env map[string]string) {
|
||||
for _, k := range []string{"TERM", "TERM_PROGRAM", "KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR"} {
|
||||
if _, ok := env[k]; !ok {
|
||||
t.Setenv(k, "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
env map[string]string
|
||||
protocol ansi.ImageProtocol
|
||||
known bool
|
||||
}{
|
||||
{
|
||||
name: "kitty via KITTY_WINDOW_ID",
|
||||
env: map[string]string{"KITTY_WINDOW_ID": "1"},
|
||||
protocol: ansi.ImageProtocolKitty,
|
||||
known: true,
|
||||
},
|
||||
{
|
||||
name: "kitty via TERM",
|
||||
env: map[string]string{"TERM": "xterm-kitty"},
|
||||
protocol: ansi.ImageProtocolKitty,
|
||||
known: true,
|
||||
},
|
||||
{
|
||||
name: "ghostty via TERM",
|
||||
env: map[string]string{"TERM": "ghostty"},
|
||||
protocol: ansi.ImageProtocolKitty,
|
||||
known: true,
|
||||
},
|
||||
{
|
||||
name: "wezterm via TERM_PROGRAM",
|
||||
env: map[string]string{"TERM": "xterm-256color", "TERM_PROGRAM": "WezTerm"},
|
||||
protocol: ansi.ImageProtocolKitty,
|
||||
known: true,
|
||||
},
|
||||
{
|
||||
name: "foot",
|
||||
env: map[string]string{"TERM": "foot-extra"},
|
||||
protocol: ansi.ImageProtocolSixel,
|
||||
known: true,
|
||||
},
|
||||
{
|
||||
name: "unknown terminal",
|
||||
env: map[string]string{"TERM": "xterm-256color"},
|
||||
protocol: ansi.ImageProtocolNone,
|
||||
known: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
clearEnv(tc.env)
|
||||
for k, v := range tc.env {
|
||||
t.Setenv(k, v)
|
||||
}
|
||||
protocol, known := protocolFromEnvironment()
|
||||
if protocol != tc.protocol {
|
||||
t.Errorf("expected protocol %v, got %v", tc.protocol, protocol)
|
||||
}
|
||||
if known != tc.known {
|
||||
t.Errorf("expected known %v, got %v", tc.known, known)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseQueryResponse(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
resp string
|
||||
hasKitty bool
|
||||
hasSixel bool
|
||||
}{
|
||||
{
|
||||
name: "kitty",
|
||||
resp: "\x1b_Gi=31;OK\x1b\\\x1b[?62;c",
|
||||
hasKitty: true,
|
||||
},
|
||||
{
|
||||
name: "kitty with other ids",
|
||||
resp: "\x1b_Gi=1;OK\x1b\\\x1b_Gi=31;OK\x1b\\\x1b[?62;c",
|
||||
hasKitty: true,
|
||||
},
|
||||
{
|
||||
name: "sixel only",
|
||||
resp: "\x1b[?62;4;6;9;15;16;17;18;21c",
|
||||
hasSixel: true,
|
||||
},
|
||||
{
|
||||
name: "no graphics support",
|
||||
resp: "\x1b[?1;2c",
|
||||
},
|
||||
{
|
||||
name: "kitty error response",
|
||||
resp: "\x1b_Gi=31;EN\x1b\\\x1b[?62;c",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
hasKitty, hasSixel := parseQueryResponse(tc.resp)
|
||||
if hasKitty != tc.hasKitty {
|
||||
t.Errorf("expected kitty %v, got %v", tc.hasKitty, hasKitty)
|
||||
}
|
||||
if hasSixel != tc.hasSixel {
|
||||
t.Errorf("expected sixel %v, got %v", tc.hasSixel, hasSixel)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasDA1Response(t *testing.T) {
|
||||
if !hasDA1Response([]byte("\x1b[?62;4c")) {
|
||||
t.Error("expected DA1 response to be detected")
|
||||
}
|
||||
if hasDA1Response([]byte("\x1b_Gi=31;OK\x1b\\")) {
|
||||
t.Error("expected no DA1 response to be detected")
|
||||
}
|
||||
if hasDA1Response([]byte("garbage")) {
|
||||
t.Error("expected no DA1 response to be detected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileBaseURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
want string
|
||||
}{
|
||||
// Windows-style absolute paths resolve the same everywhere.
|
||||
{"C:/Users/x/test.md", "file:///C:/Users/x/"},
|
||||
}
|
||||
// Unix-style absolute paths are absolute only on Unix; on Windows they
|
||||
// resolve against the current drive.
|
||||
if runtime.GOOS != "windows" {
|
||||
tests = append(tests, struct {
|
||||
path string
|
||||
want string
|
||||
}{"/tmp/docs/test.md", "file:///tmp/docs/"})
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
if got := FileBaseURL(tc.path); got != tc.want {
|
||||
t.Errorf("FileBaseURL(%q) = %q, want %q", tc.path, got, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
// Relative paths resolve against the working directory. The expected
|
||||
// URL is built from os.Getwd, since the working directory is only
|
||||
// known at runtime, and may differ from the temp dir path on platforms
|
||||
// with symlinked temporary directories, like macOS.
|
||||
dir := t.TempDir()
|
||||
t.Chdir(dir)
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Build the expected URL the same way FileBaseURL does: the path is
|
||||
// slash-separated, and drive-letter paths get a leading slash.
|
||||
want := fileURL(wd) + "/"
|
||||
for _, path := range []string{"", "test.md", "./test.md", "sub/../test.md"} {
|
||||
if got := FileBaseURL(path); got != want {
|
||||
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
want = fileURL(filepath.Join(wd, "img")) + "/"
|
||||
for _, path := range []string{"sub/../img/test.md"} {
|
||||
if got := FileBaseURL(path); got != want {
|
||||
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
want = fileURL(filepath.Join(wd, "..", "img")) + "/"
|
||||
for _, path := range []string{"../img/test.md"} {
|
||||
if got := FileBaseURL(path); got != want {
|
||||
t.Errorf("FileBaseURL(%q) = %q, want %q", path, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphicsQuery(t *testing.T) {
|
||||
q := graphicsQuery()
|
||||
if want := "\x1b_Gf=24,i=31,s=1,v=1,a=q;AAAA\x1b\\"; q != want+"\x1b[c" {
|
||||
t.Errorf("unexpected query %q", q)
|
||||
}
|
||||
}
|
||||
|
||||
// fileURL returns the file URL of a slash-separated path, adding the leading
|
||||
// slash that drive-letter paths need (see FileBaseURL).
|
||||
func fileURL(path string) string {
|
||||
s := filepath.ToSlash(path)
|
||||
if isWindowsDrivePath(s) {
|
||||
s = "/" + s
|
||||
}
|
||||
return (&url.URL{Scheme: "file", Path: s}).String()
|
||||
}
|
||||
Loading…
Reference in a new issue