Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 28 additions & 6 deletions client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,7 @@ func detectTerminalAndCalibrate() {
setDefaultCharSize()
if cfg.Renderer == "auto" {
cfg.Renderer = detectRenderer()
Debug(fmt.Sprintf("Graphics auto-detection selected %s", cfg.Renderer), INFO)
}
if cfg.Renderer == "tcell" {
return
Expand All @@ -867,19 +868,29 @@ func detectRenderer() string {
if err == nil && strings.Contains(response, "i=31;OK") {
return "kitty"
}
if err != nil {
Debug(fmt.Sprintf("Kitty graphics probe failed: %v", err), DEBUG)
} else {
Debug("Kitty graphics probe did not report support", DEBUG)
}
response, err = queryTerminalWithTimeout("\033[c", graphicsProbeTimeoutMs)
if err == nil {
for _, parameter := range strings.Split(strings.TrimSuffix(strings.TrimPrefix(response, "\033[?"), "c"), ";") {
if parameter == "4" {
return "sixel"
}
}
} else {
Debug(fmt.Sprintf("Sixel graphics probe failed: %v", err), DEBUG)
}
return "tcell"
}

func queryTerminalWithTimeout(query string, timeoutMs int) (string, error) {
fd := int(os.Stdin.Fd())
if fd < 0 || fd >= unix.FD_SETSIZE {
return "", fmt.Errorf("terminal descriptor %d is outside select range", fd)
}
old, err := term.MakeRaw(fd)
if err != nil {
return "", err
Expand All @@ -891,25 +902,36 @@ func queryTerminalWithTimeout(query string, timeoutMs int) (string, error) {
deadline := time.Now().Add(time.Duration(timeoutMs) * time.Millisecond)
response := make([]byte, 0, 128)
for time.Now().Before(deadline) {
poll := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
n, err := unix.Poll(poll, max(1, int(time.Until(deadline).Milliseconds())))
remaining := time.Until(deadline)
if remaining <= 0 {
break
}
// The installer reopens stdin through /dev/tty. Darwin's poll returns
// POLLNVAL for that device even though reads work; select supports it.
var readable unix.FdSet
readable.Set(fd)
timeout := unix.NsecToTimeval(remaining.Nanoseconds())
n, err := unix.Select(fd+1, &readable, nil, nil, &timeout)
if err == unix.EINTR {
continue
}
if err != nil {
return "", err
return "", fmt.Errorf("waiting for terminal response: %w", err)
}
if n == 0 {
break
}
if poll[0].Revents&unix.POLLIN == 0 {
return "", fmt.Errorf("terminal closed")
}
buf := make([]byte, 128)
n, err = unix.Read(fd, buf)
if err == unix.EINTR {
continue
}
if err != nil {
return "", err
}
if n == 0 {
return "", io.EOF
}
response = append(response, buf[:n]...)
text := string(response)
if strings.HasSuffix(text, "t") || strings.HasSuffix(text, "c") || strings.HasSuffix(text, "\033\\") {
Expand Down
108 changes: 108 additions & 0 deletions client/terminal_probe_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package main

import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"strings"
"testing"
"time"

"github.com/creack/pty"
"golang.org/x/sys/unix"
)

// A direct PTY slave and an explicitly reopened /dev/tty are different devices
// on macOS. Exercise the installer-style pipe and redirection, not just a PTY.
func TestGraphicsProbePTY(t *testing.T) {
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name, launch, renderer string
delay time.Duration
}{
{"direct-kitty", "direct", "kitty", 500 * time.Millisecond},
{"redirect-kitty", "redirect", "kitty", 0},
{"installer-kitty", "pipe", "kitty", 500 * time.Millisecond},
{"installer-sixel", "pipe", "sixel", 500 * time.Millisecond},
{"installer-no-response", "pipe", "tcell", 0},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, executable, "-test.run=^TestGraphicsProbePTYHelper$")
switch tc.launch {
case "redirect":
cmd = exec.CommandContext(ctx, "bash", "-c", `exec "$TERMIUM_PROBE_EXECUTABLE" -test.run=^TestGraphicsProbePTYHelper$ </dev/tty`)
case "pipe":
cmd = exec.CommandContext(ctx, "bash", "-o", "pipefail", "-c",
`printf '%s\n' 'exec "$TERMIUM_PROBE_EXECUTABLE" -test.run=^TestGraphicsProbePTYHelper$ </dev/tty' | bash`)
}
cmd.Env = append(os.Environ(), "TERMIUM_PROBE_EXECUTABLE="+executable, "TERMIUM_PROBE_EXPECT="+tc.renderer)
terminal, err := pty.StartWithSize(cmd, &pty.Winsize{Rows: 24, Cols: 80})
if err != nil {
t.Fatal(err)
}
defer terminal.Close()
var output bytes.Buffer
drained := make(chan struct{})
go func() {
defer close(drained)
var pending string
buf := make([]byte, 1024)
for {
n, err := terminal.Read(buf)
if n > 0 {
output.Write(buf[:n])
pending += string(buf[:n])
if strings.Contains(pending, "\033_Gi=31,s=1,v=1,a=q,t=d,f=24;AAAA\033\\") {
pending = ""
if tc.renderer == "kitty" {
time.Sleep(tc.delay)
_, _ = io.WriteString(terminal, "\033_Gi=31;OK\033\\")
} else if tc.renderer == "sixel" {
_, _ = io.WriteString(terminal, "\033_Gi=31;ENOTSUP\033\\")
}
}
if strings.Contains(pending, "\033[c") {
pending = ""
if tc.renderer == "sixel" {
time.Sleep(tc.delay)
_, _ = io.WriteString(terminal, "\033[?62;4c")
}
}
}
if err != nil {
return
}
}
}()
err = cmd.Wait()
terminal.Close()
<-drained
t.Logf("PTY output: %q", output.String())
if err != nil {
t.Fatalf("%s: %v", tc.launch, err)
}
})
}
}

func TestGraphicsProbePTYHelper(t *testing.T) {
want := os.Getenv("TERMIUM_PROBE_EXPECT")
if want == "" {
return
}
fds := []unix.PollFd{{Fd: 0, Events: unix.POLLIN}}
n, pollErr := unix.Poll(fds, 0)
fmt.Fprintf(os.Stderr, "initial poll: n=%d revents=%#x err=%v\n", n, fds[0].Revents, pollErr)
got := detectRenderer()
if got != want {
t.Fatalf("renderer=%s, want %s", got, want)
}
}
23 changes: 23 additions & 0 deletions docs/releases/v0.2.4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Termium v0.2.4

Fix graphics detection when the macOS installer automatically launches Termium,
or when launching with input redirected from `/dev/tty`.

The installer reopens terminal input because its script arrives through a pipe.
On macOS, `poll()` reports that reopened device as invalid, causing an immediate
fallback to ASCII graphics. Increasing the timeout in v0.2.3 did not address this
failure. Terminal queries now use `select()`, which supports the device; the
one-second graphics probe deadlines remain.

Debug logs now record graphics probe errors and the automatically selected
renderer. Regression tests exercise direct launch, `/dev/tty` redirection, and
the installer's pipe-and-launch handoff, including delayed responses and ASCII
fallback when no graphics protocol responds.

Close Termium, then update:

```sh
curl -fsSL https://termium.dev/install | bash
```

After quitting, `termium --version` should report `v0.2.4`.
Loading