Ask the terminal before using Kitty graphics; no fontconfig-based sextants on macOS
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019reK4DUGYqDUjniWYJvwUW
This commit is contained in:
@@ -2,6 +2,10 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- **Real images only when the terminal confirms it:** the terminal is asked whether it supports the
|
||||
Kitty graphics protocol before real-image posters are used, so terminals that only look like kitty
|
||||
or Ghostty no longer get graphics commands printed as text. On macOS the sextant blocks are no
|
||||
longer chosen from fontconfig's fonts.
|
||||
- **Ctrl+C quits**; `q` no longer does (also not in the help window, which closes with Esc).
|
||||
- **Series drill-down** shows the series poster and details of the selected season or episode,
|
||||
including the episode's plot.
|
||||
|
||||
@@ -64,8 +64,8 @@ Notes:
|
||||
- Global speed / pause state in the status bar. Pause/resume and delete a SABnzbd job.
|
||||
- **Status bar / help:** the bottom bar lists the keys that work in the current view or panel; the top right shows the connection state of each service; `F9` opens the full key reference.
|
||||
- **Posters:** the detail panes show the poster at the top right; the head (title, facts, path) and the plot are one text that flows along the poster's left side and continues at full width below it (text is wrapped by arr-tui itself, with a narrower width for the first lines); on panes too small for the poster, the text simply uses the full width. Two ways to draw the poster, chosen by `ui.cover_style`:
|
||||
- **Real images** (`kitty`, and `auto` in kitty/Ghostty): the Kitty graphics protocol with Unicode placeholders. The poster (kept up to 640 px tall) is uploaded as PNG (`a=t,f=100,q=2`, 4096-byte base64 chunks) and placed virtually with the cell footprint (`a=p,U=1,c=,r=`) right away. Every footprint (crop and cell size) is its own image id, placed once and never changed: Ghostty kept showing the old, small placement when the size of an existing one was changed, so a new size uploads under a new id and deletes the old one. The poster is shown by writing U+10EEEE placeholder characters whose combining marks give row and column (the 297-entry table from the protocol) and whose foreground color is the image id. Since it is ordinary text, popups, dialogs and view changes cover it correctly and tcell's diffing keeps it in place. The footprint uses the real cell size in pixels (the window's pixel size divided by its cell count, rounded down to whole pixels so padding around the grid does not skew it; all images are deleted whenever the window or cell size changes, block characters stand in while the size keeps changing, and real images are uploaded afresh once it has been stable for 300 ms, because uploading and placing for every intermediate size of a window drag raced with the terminal's own resizing) and a box whose shape is within 3% of the poster's; the remaining sliver is cropped from the poster's edges before upload (one upload per size, the previous one is deleted), because the terminal letterboxes an image that does not fit its box exactly. As a second safeguard the placeholder cells use the panes' background color, so anything the picture does not cover blends in (without it the terminal's own, slightly different, default background showed as grey bars beside the poster). Writes to the terminal go through the screen's tty on the UI goroutine, so they cannot interleave with drawing. Requires 24-bit color; otherwise, and inside tmux/screen, the block fallback is used. Terminals are recognised from `TERM`/`TERM_PROGRAM`/`KITTY_WINDOW_ID`/`GHOSTTY_RESOURCES_DIR`. With `ARR_TUI_DEBUG_GFX=1` the Log (F7) lists every window size, the cell shape, every upload (poster size, crop, cells) and every change of what is drawn (image id, position, cells); with a path (`ARR_TUI_DEBUG_GFX=/tmp/arr-gfx.log`) the same lines also go to that file with millisecond timestamps, so they can be read without leaving the view that shows the problem. The go-termimg library was looked at and not used: its placeholder support is marked experimental, its diacritic table does not match the protocol's, and it writes images straight to the terminal instead of through the screen.
|
||||
- **Block characters** (`quadrant`, `sextant`, and the fallback): every cell shows several pixels in the best two-color split (`quadrant`: 2×2 pixels, glyphs from the Block Elements range every font has; `sextant`: 2×3 pixels, sharper, glyphs from Symbols for Legacy Computing). `auto` picks sextants on kitty, WezTerm, foot and Ghostty, and on other terminals when fontconfig lists a font with the sextant characters (`fc-list :charset=1fb00`, about 20 ms at startup; terminals draw glyphs their font lacks from fallback fonts; skipped over SSH because the installed fonts are the remote machine's), and quadrants otherwise.
|
||||
- **Real images** (`kitty`, and `auto` in kitty/Ghostty): the Kitty graphics protocol with Unicode placeholders. The poster (kept up to 640 px tall) is uploaded as PNG (`a=t,f=100,q=2`, 4096-byte base64 chunks) and placed virtually with the cell footprint (`a=p,U=1,c=,r=`) right away. Every footprint (crop and cell size) is its own image id, placed once and never changed: Ghostty kept showing the old, small placement when the size of an existing one was changed, so a new size uploads under a new id and deletes the old one. The poster is shown by writing U+10EEEE placeholder characters whose combining marks give row and column (the 297-entry table from the protocol) and whose foreground color is the image id. Since it is ordinary text, popups, dialogs and view changes cover it correctly and tcell's diffing keeps it in place. The footprint uses the real cell size in pixels (the window's pixel size divided by its cell count, rounded down to whole pixels so padding around the grid does not skew it; all images are deleted whenever the window or cell size changes, block characters stand in while the size keeps changing, and real images are uploaded afresh once it has been stable for 300 ms, because uploading and placing for every intermediate size of a window drag raced with the terminal's own resizing) and a box whose shape is within 3% of the poster's; the remaining sliver is cropped from the poster's edges before upload (one upload per size, the previous one is deleted), because the terminal letterboxes an image that does not fit its box exactly. As a second safeguard the placeholder cells use the panes' background color, so anything the picture does not cover blends in (without it the terminal's own, slightly different, default background showed as grey bars beside the poster). Writes to the terminal go through the screen's tty on the UI goroutine, so they cannot interleave with drawing. Requires 24-bit color; otherwise, and inside tmux/screen, the block fallback is used. Terminals are recognised from `TERM`/`TERM_PROGRAM`/`KITTY_WINDOW_ID`/`GHOSTTY_RESOURCES_DIR`, and then asked before the screen starts (a Kitty graphics query followed by a device-attributes request, 300 ms timeout): only a terminal that answers the query gets real images, also with `cover_style: kitty`, because a terminal without the protocol prints the commands as text. The Log says which way posters are drawn. With `ARR_TUI_DEBUG_GFX=1` the Log (F7) lists every window size, the cell shape, every upload (poster size, crop, cells) and every change of what is drawn (image id, position, cells); with a path (`ARR_TUI_DEBUG_GFX=/tmp/arr-gfx.log`) the same lines also go to that file with millisecond timestamps, so they can be read without leaving the view that shows the problem. The go-termimg library was looked at and not used: its placeholder support is marked experimental, its diacritic table does not match the protocol's, and it writes images straight to the terminal instead of through the screen.
|
||||
- **Block characters** (`quadrant`, `sextant`, and the fallback): every cell shows several pixels in the best two-color split (`quadrant`: 2×2 pixels, glyphs from the Block Elements range every font has; `sextant`: 2×3 pixels, sharper, glyphs from Symbols for Legacy Computing). `auto` picks sextants on kitty, WezTerm, foot and Ghostty, and on other terminals (not on macOS, whose terminals do not use fontconfig's fonts) when fontconfig lists a font with the sextant characters (`fc-list :charset=1fb00`, about 20 ms at startup; terminals draw glyphs their font lacks from fallback fonts; skipped over SSH because the installed fonts are the remote machine's), and quadrants otherwise.
|
||||
Posters are JPEG, PNG, GIF or WebP (Radarr and Sonarr keep whatever bytes the provider sent under a `.jpg` name, which can be WebP), decoded and downscaled in the process; for any other format the Log says what the data looked like (e.g. AVIF, an HTML error page, or its first bytes). Library items fetch `/MediaCover/<id>/poster-250.jpg` from their Radarr/Sonarr instance with the API key (then the original `poster.jpg`; an instance that answers 200 with an HTML page, i.e. wants a login for `/MediaCover`, is also tried with the key as the `apikey` query parameter; and if the instance has no usable copy, the provider's `remoteUrl`, fetched without credentials); search results fall back to the provider's `remoteUrl` (fetched without credentials). Posters are cached in memory (the terminal's copies are deleted when the cache is dropped and on exit), failed downloads are not retried for two minutes and are written to the Log (F7) with the reason, and the poster shrinks or disappears when the pane is too short. `ui.covers: false` disables it.
|
||||
- **Calendar view (F5):** a two-week window (starting today, moved a week at a time with `[`/`]`, `t` returns to today) with the library's movie releases and airing episodes, grouped by day. Radarr `GET /calendar` supplies the cinema, digital and physical release dates (taken as written: midnight UTC means that calendar day) and Sonarr `GET /calendar?includeSeries=true` the episodes with their air time (shown in local time). Unmonitored items are included with `u`. A movie appears once per release date in the window. Each entry shows type, title, episode or release kind and status (downloaded / missing / upcoming); the detail pane shows poster and plot; `Enter`/`i` starts the release search and `s` an automatic search.
|
||||
- **Download notifications:** a background poller (independent of the visible view) reads SABnzbd's history every 15 s and announces downloads that reach `Completed` or `Failed` as a popup and log entry; the first poll only records the current state. `ui.notify_downloads` (default true) and `ui.bell` (default false, rings the terminal bell) control it. Connection errors are not reported here, the indicators and the log already do that.
|
||||
|
||||
@@ -6,6 +6,7 @@ require (
|
||||
github.com/gdamore/tcell/v2 v2.13.10
|
||||
github.com/rivo/tview v0.42.0
|
||||
golang.org/x/image v0.47.0
|
||||
golang.org/x/term v0.37.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -13,6 +14,5 @@ require (
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/term v0.37.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
)
|
||||
|
||||
@@ -117,6 +117,12 @@ func New(cfg *config.Config) *App {
|
||||
}
|
||||
|
||||
blocks, graphics := resolveCovers(cfg.UI.CoverStyle, os.Getenv)
|
||||
coverNote := "Posters: " + blocks.name + " block characters"
|
||||
if graphics {
|
||||
coverNote = "Posters: real images (the terminal confirmed the Kitty graphics protocol)"
|
||||
} else if cfg.UI.CoverStyle == "kitty" || kittyTerminal(os.Getenv) {
|
||||
coverNote += " (the terminal did not confirm the Kitty graphics protocol)"
|
||||
}
|
||||
a.coverStyle = blocks
|
||||
if graphics {
|
||||
a.gfx = a.newGraphics()
|
||||
@@ -127,6 +133,9 @@ func New(cfg *config.Config) *App {
|
||||
sonarrClient := sonarr.NewClient(cfg.Sonarr.URL, cfg.Sonarr.APIKey)
|
||||
a.radarr, a.sonarr = radarrClient, sonarrClient
|
||||
a.logs = newLogView(a)
|
||||
if a.covers {
|
||||
a.logs.add(levelInfo, coverNote)
|
||||
}
|
||||
sabClient := sabnzbd.NewClient(cfg.SABnzbd.URL, cfg.SABnzbd.APIKey)
|
||||
a.sab = sabClient
|
||||
a.probes = []probe{
|
||||
|
||||
+21
-3
@@ -13,7 +13,9 @@ import (
|
||||
_ "golang.org/x/image/webp"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gdamore/tcell/v2"
|
||||
@@ -147,7 +149,9 @@ func coverStyleFor(setting string, env func(string) string) coverStyle {
|
||||
// font lacks from a fallback font, so sextants work if some installed font
|
||||
// has them. Over SSH the installed fonts are the remote machine's, which
|
||||
// says nothing about the terminal, so keep the safe style there.
|
||||
if env("SSH_CONNECTION") == "" && env("SSH_TTY") == "" && sextantFontAvailable() {
|
||||
// macOS terminals do not draw missing glyphs from fontconfig's fonts, so a
|
||||
// font found there says nothing about them.
|
||||
if runtime.GOOS != "darwin" && env("SSH_CONNECTION") == "" && env("SSH_TTY") == "" && sextantFontAvailable() {
|
||||
return sextantStyle
|
||||
}
|
||||
return quadrantStyle
|
||||
@@ -174,13 +178,27 @@ var sextantFontAvailable = func() bool {
|
||||
func resolveCovers(setting string, env func(string) string) (blocks coverStyle, graphics bool) {
|
||||
switch setting {
|
||||
case "kitty":
|
||||
return coverStyleFor("auto", env), true
|
||||
// Asked for explicitly, but a terminal without the protocol prints the
|
||||
// commands as text, so it is still confirmed.
|
||||
return coverStyleFor("auto", env), kittyGraphicsSupported()
|
||||
case "auto", "":
|
||||
return coverStyleFor("auto", env), kittyTerminal(env)
|
||||
return coverStyleFor("auto", env), kittyTerminal(env) && kittyGraphicsSupported()
|
||||
}
|
||||
return coverStyleFor(setting, env), false
|
||||
}
|
||||
|
||||
var (
|
||||
kittyProbeOnce sync.Once
|
||||
kittyProbeResult bool
|
||||
)
|
||||
|
||||
// kittyGraphicsSupported asks the terminal once (see probeKittyGraphics) and
|
||||
// remembers the answer. It is a variable so tests can replace it.
|
||||
var kittyGraphicsSupported = func() bool {
|
||||
kittyProbeOnce.Do(func() { kittyProbeResult = probeKittyGraphics(300 * time.Millisecond) })
|
||||
return kittyProbeResult
|
||||
}
|
||||
|
||||
// flatPixelError is the squared RGB distance per pixel below which a cell is
|
||||
// drawn flat: smooth areas and noise should not turn into patterns.
|
||||
const flatPixelError = 150
|
||||
|
||||
@@ -165,6 +165,8 @@ func TestPlaceholderCell(t *testing.T) {
|
||||
func TestKittyTerminalDetection(t *testing.T) {
|
||||
defer func(old func() bool) { sextantFontAvailable = old }(sextantFontAvailable)
|
||||
sextantFontAvailable = func() bool { return false } // not what these cases are about
|
||||
defer func(old func() bool) { kittyGraphicsSupported = old }(kittyGraphicsSupported)
|
||||
kittyGraphicsSupported = func() bool { return true } // the terminal confirms
|
||||
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
@@ -368,3 +370,26 @@ func TestGraphicsDebugReportsUploads(t *testing.T) {
|
||||
t.Errorf("debug lines = %q", lines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGraphicsNeedTheTerminalsConfirmation(t *testing.T) {
|
||||
defer func(old func() bool) { kittyGraphicsSupported = old }(kittyGraphicsSupported)
|
||||
env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } }
|
||||
ghostty := env(map[string]string{"TERM": "xterm-ghostty"})
|
||||
|
||||
kittyGraphicsSupported = func() bool { return false } // e.g. a terminal that claims kitty but prints APC as text
|
||||
if _, gfx := resolveCovers("auto", ghostty); gfx {
|
||||
t.Error("auto must not use real images when the terminal does not answer the query")
|
||||
}
|
||||
if _, gfx := resolveCovers("kitty", ghostty); gfx {
|
||||
t.Error("even an explicit kitty setting must not send graphics a terminal does not understand")
|
||||
}
|
||||
|
||||
asked := false
|
||||
kittyGraphicsSupported = func() bool { asked = true; return true }
|
||||
if _, gfx := resolveCovers("auto", env(map[string]string{"TERM": "xterm-256color", "TERM_PROGRAM": "Apple_Terminal"})); gfx || asked {
|
||||
t.Error("a terminal not known for the protocol is not even asked (it might print the query)")
|
||||
}
|
||||
if _, gfx := resolveCovers("auto", ghostty); !gfx || !asked {
|
||||
t.Error("a known terminal that answers gets real images")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
package ui
|
||||
|
||||
import (
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMain keeps the tests from asking the real terminal about graphics
|
||||
// support (the probe writes to and reads from /dev/tty).
|
||||
func TestMain(m *testing.M) {
|
||||
kittyGraphicsSupported = func() bool { return false }
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//go:build !unix
|
||||
|
||||
package ui
|
||||
|
||||
import "time"
|
||||
|
||||
// probeKittyGraphics is not implemented here; the block characters are used.
|
||||
func probeKittyGraphics(time.Duration) bool { return false }
|
||||
@@ -0,0 +1,57 @@
|
||||
//go:build unix
|
||||
|
||||
package ui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
// probeKittyGraphics asks the terminal whether it understands the Kitty
|
||||
// graphics protocol: a tiny query image (which a capable terminal answers with
|
||||
// "OK" and does not show) followed by a Primary Device Attributes request,
|
||||
// which every terminal answers. If the DA answer arrives without a graphics
|
||||
// answer before it, the protocol is not supported. Runs before the screen is
|
||||
// set up, on the controlling terminal.
|
||||
func probeKittyGraphics(timeout time.Duration) bool {
|
||||
tty, err := os.OpenFile("/dev/tty", os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer tty.Close()
|
||||
fd := int(tty.Fd())
|
||||
state, err := term.MakeRaw(fd)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer term.Restore(fd, state)
|
||||
|
||||
const query = "\x1b_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\x1b\\" + "\x1b[c"
|
||||
if _, err := tty.WriteString(query); err != nil {
|
||||
return false
|
||||
}
|
||||
// A terminal that does not know APC sequences may print the query; erase it.
|
||||
defer tty.WriteString("\r\x1b[2K")
|
||||
|
||||
if err := tty.SetReadDeadline(time.Now().Add(timeout)); err != nil {
|
||||
return false
|
||||
}
|
||||
var got []byte
|
||||
buf := make([]byte, 256)
|
||||
for {
|
||||
n, err := tty.Read(buf)
|
||||
got = append(got, buf[:n]...)
|
||||
if bytes.Contains(got, []byte("_Gi=31;OK")) {
|
||||
return true
|
||||
}
|
||||
if da := bytes.Index(got, []byte("\x1b[?")); da >= 0 && bytes.IndexByte(got[da:], 'c') >= 0 {
|
||||
return false // device attributes answered, graphics query not
|
||||
}
|
||||
if err != nil {
|
||||
return false // timeout or error: assume no support
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user