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
64 changes: 60 additions & 4 deletions internal/terminalpet/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,40 @@ import (
// list of companions, even when a community pet has the same name.
const builtinSlugPrefix = "zero:"

// Dance and Lunge are extra states that only built-in companions have. They
// play when the companion is clicked.
// Extra states the built-in companions have. Dance and Lunge play when the
// companion is clicked. Thinking and Sleeping are agent states: pets without
// those animations show Running and Idle instead (see Animation.Has), and a
// community pet whose pet.json defines them gets them too.
const (
Dance State = "dance"
Lunge State = "lunge"
Dance State = "dance"
Lunge State = "lunge"
Thinking State = "thinking"
Sleeping State = "sleeping"
)

const (
// TextColumns and TextRows are the terminal cells a built-in companion
// fills when it is drawn as text, for terminals that cannot show images.
TextColumns = 18
TextRows = 8

// textScale draws the 48x40 design at 18x15 pixels. Half-block cells
// stack two pixels each, and one empty pixel row on top leaves room for
// a hop: 18x16 pixels in 18x8 cells.
textScale = 0.375
textHeadroom = 1
)

// TextColors is the colour depth text frames are drawn for.
type TextColors uint8

const (
// TextTrueColor draws with the art's exact 24-bit colours.
TextTrueColor TextColors = iota
// Text256 draws with a fixed 256-colour palette, the nearest colour to
// each art colour by CIEDE2000, which keeps hues a generic conversion
// would lose.
Text256
)

const (
Expand Down Expand Up @@ -114,6 +143,8 @@ var (
Idle: {mood: petart.Idle, start: builtinBlinkSkip, length: 5750 * time.Millisecond, loop: true},
Running: {mood: petart.Working, length: 3100 * time.Millisecond, loop: true},
Waiting: {mood: petart.Waiting, start: builtinBlinkSkip, length: 2900 * time.Millisecond, loop: true},
Thinking: {mood: petart.Thinking, length: 6400 * time.Millisecond, loop: true},
Sleeping: {mood: petart.Sleeping, length: 5200 * time.Millisecond, loop: true},
Review: {mood: petart.Happy, length: 1900 * time.Millisecond},
Failed: {mood: petart.Sad, length: 1800 * time.Millisecond},
Waving: {mood: petart.Hello, length: 2400 * time.Millisecond},
Expand Down Expand Up @@ -197,6 +228,7 @@ type builtinFrame struct {

mu sync.Mutex
pixels *image.NRGBA
text [2][]string
}

// draw paints the frame and keeps nothing. Callers cache what they make from
Expand All @@ -220,6 +252,30 @@ func (f *builtinFrame) rendered() *image.NRGBA {
return f.pixels
}

// textLines draws the frame as terminal text, once per colour depth, and
// keeps it: a frame of text is a few kilobytes, and text frames are redrawn
// on every repaint.
func (f *builtinFrame) textLines(colors TextColors) []string {
slot := 0
if colors == Text256 {
slot = 1
}
f.mu.Lock()
defer f.mu.Unlock()
if f.text[slot] == nil {
frame := petart.RenderWithHeadroom(f.form, f.mood, f.seconds, textScale, textHeadroom)
if f.mirror {
frame.Mirror()
}
if slot == 1 {
f.text[slot] = petart.HalfBlockLines256(frame)
} else {
f.text[slot] = petart.HalfBlockLines(frame)
}
}
return f.text[slot]
}

// drawnFrame returns a picture an encoder can read directly: built-in frames
// are drawn now, and every other frame is returned as it is.
func drawnFrame(frame image.Image) image.Image {
Expand Down
110 changes: 108 additions & 2 deletions internal/terminalpet/builtin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -215,7 +217,7 @@ func TestBuiltinAnimationCoversEveryState(t *testing.T) {
t.Fatal("BuiltinAnimation returned an animation for an unknown form")
}
frameSize := image.Rect(0, 0, 192, 208)
for _, state := range []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge} {
for _, state := range []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge, Thinking, Sleeping} {
frame := animation.Frame(state, 0)
// The frame must match a pet atlas frame, which the layout assumes.
if frame == nil || frame.Bounds() != frameSize {
Expand All @@ -226,7 +228,7 @@ func TestBuiltinAnimationCoversEveryState(t *testing.T) {
}
}
// Loops never settle; one-shot states play for their length and then idle.
for _, state := range []State{Idle, Running, Waiting, MoveLeft, MoveRight} {
for _, state := range []State{Idle, Running, Waiting, MoveLeft, MoveRight, Thinking, Sleeping} {
if got := animation.PrimaryDuration(state); got != 0 {
t.Errorf("%s should loop, PrimaryDuration = %v", state, got)
}
Expand Down Expand Up @@ -318,3 +320,107 @@ func TestBuiltinFramesDrawTheCharacterWithHeadroom(t *testing.T) {
}
}
}

func TestBuiltinTextFramesFitTheTextSlot(t *testing.T) {
sgr := regexp.MustCompile(`\x1b\[[0-9;]*m`)
states := []State{Idle, MoveRight, MoveLeft, Waving, Jumping, Running, Waiting, Review, Failed, Dance, Lunge, Thinking, Sleeping}
for _, form := range petart.Forms() {
animation := BuiltinAnimation(form)
if !animation.HasText() {
t.Fatalf("%s has no text form", form)
}
for _, state := range states {
for _, phase := range []int{0, 3, 17} {
for _, colors := range []TextColors{TextTrueColor, Text256} {
lines, ok := animation.TextFrame(state, phase, colors)
if !ok || len(lines) != TextRows {
t.Fatalf("%s/%s phase %d: %d text lines, ok=%v", form, state, phase, len(lines), ok)
}
drawn := 0
for index, line := range lines {
cells := []rune(sgr.ReplaceAllString(line, ""))
if len(cells) != TextColumns {
t.Fatalf("%s/%s line %d is %d cells wide, want %d", form, state, index, len(cells), TextColumns)
}
for _, cell := range cells {
if cell != ' ' {
drawn++
}
}
}
if drawn < 40 {
t.Errorf("%s/%s phase %d: only %d cells drawn", form, state, phase, drawn)
}
}
}
}
}

// Each colour depth uses its own codes, for the same picture.
truecolor, _ := BuiltinAnimation(petart.Twig).TextFrame(Idle, 0, TextTrueColor)
limited, _ := BuiltinAnimation(petart.Twig).TextFrame(Idle, 0, Text256)
if !strings.Contains(strings.Join(truecolor, ""), ";2;") || strings.Contains(strings.Join(limited, ""), ";2;") ||
!strings.Contains(strings.Join(limited, ""), "38;5;") {
t.Error("text frames do not use the colour codes of their depth")
}
if sgr.ReplaceAllString(strings.Join(truecolor, "\n"), "") != sgr.ReplaceAllString(strings.Join(limited, "\n"), "") {
t.Error("the 256-colour frame draws a different picture")
}

animation := BuiltinAnimation(petart.Twig)
first, _ := animation.TextFrame(Running, 2, TextTrueColor)
again, _ := animation.TextFrame(Running, 2, TextTrueColor)
if &first[0] != &again[0] {
t.Error("a text frame was drawn twice")
}
// The top pixel row is headroom: tall parts such as Robin's feather reach
// it, and a hop rises into it instead of being cut off. A cell whose top
// pixel is drawn is an upper half block, so Merlin standing has none on
// the first line and has some at the top of a hop.
if standing, _ := BuiltinAnimation(petart.Merlin).TextFrame(Idle, 0, TextTrueColor); strings.Contains(sgr.ReplaceAllString(standing[0], ""), "▀") {
t.Errorf("Merlin standing fills the headroom: %q", sgr.ReplaceAllString(standing[0], ""))
}
hopped := false
for phase := 0; phase < 23 && !hopped; phase++ {
frame, _ := BuiltinAnimation(petart.Merlin).TextFrame(Jumping, phase, TextTrueColor)
hopped = strings.Contains(sgr.ReplaceAllString(frame[0], ""), "▀")
}
if !hopped {
t.Error("Merlin never rises into the headroom while celebrating")
}
// Dragging right shows the mirror image of dragging left.
left, _ := animation.TextFrame(MoveLeft, 3, TextTrueColor)
right, _ := animation.TextFrame(MoveRight, 3, TextTrueColor)
if strings.Join(left, "\n") == strings.Join(right, "\n") {
t.Error("MoveRight text is not mirrored")
}
}

func TestPictureAnimationsHaveNoTextOrExtraStates(t *testing.T) {
sheet, err := png.Decode(bytes.NewReader(encodedPNG(t, 24*atlasColumns, 26*9)))
if err != nil {
t.Fatal(err)
}
atlas, err := AtlasAnimation(sheet, 1)
if err != nil {
t.Fatal(err)
}
if atlas.HasText() {
t.Error("an atlas pet reports a text form")
}
if lines, ok := atlas.TextFrame(Idle, 0, TextTrueColor); ok || lines != nil {
t.Errorf("TextFrame for an atlas pet = %v, %v", lines, ok)
}
// Agents fall back to Running and Idle for pets without these states.
if atlas.Has(Thinking) || atlas.Has(Sleeping) || !atlas.Has(Running) || !atlas.Has(Idle) {
t.Errorf("atlas Has: thinking=%v sleeping=%v running=%v idle=%v",
atlas.Has(Thinking), atlas.Has(Sleeping), atlas.Has(Running), atlas.Has(Idle))
}
var none *Animation
if none.Has(Idle) || none.HasText() {
t.Error("a nil animation reports frames")
}
if !BuiltinAnimation(petart.Ember).Has(Thinking) || !BuiltinAnimation(petart.Ember).Has(Sleeping) {
t.Error("built-in companions lack the thinking and sleeping states")
}
}
8 changes: 4 additions & 4 deletions internal/terminalpet/image_renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ func (s ImageSupport) Supported() bool {

func DetectImageSupport(getenv func(string) string) ImageSupport {
if strings.TrimSpace(getenv("TMUX")) != "" || strings.TrimSpace(getenv("TMUX_PANE")) != "" {
return ImageSupport{Reason: "Terminal companions are disabled in tmux because terminal images are not reliably pane-local."}
return ImageSupport{Reason: "tmux does not pass terminal images through reliably."}
}
if strings.TrimSpace(getenv("ZELLIJ")) != "" || strings.TrimSpace(getenv("ZELLIJ_SESSION_NAME")) != "" || strings.TrimSpace(getenv("ZELLIJ_VERSION")) != "" {
return ImageSupport{Reason: "Terminal companions are disabled in Zellij because terminal images are not reliably pane-local."}
return ImageSupport{Reason: "Zellij does not pass terminal images through reliably."}
}
if strings.TrimSpace(getenv("KITTY_WINDOW_ID")) != "" || strings.TrimSpace(getenv("WEZTERM_EXECUTABLE")) != "" || strings.TrimSpace(getenv("WEZTERM_VERSION")) != "" {
return ImageSupport{Protocol: ImageProtocolKitty}
Expand All @@ -53,7 +53,7 @@ func DetectImageSupport(getenv func(string) string) ImageSupport {
if dottedVersionAtLeast(getenv("TERM_PROGRAM_VERSION"), 3, 6, 0) {
return ImageSupport{Protocol: ImageProtocolKittyLocalFile}
}
return ImageSupport{Reason: "Terminal companions require iTerm2 3.6 or newer."}
return ImageSupport{Reason: "Terminal images need iTerm2 3.6 or newer."}
}
if strings.Contains(term, "ghostty") || strings.Contains(program, "ghostty") || strings.TrimSpace(getenv("GHOSTTY_RESOURCES_DIR")) != "" ||
strings.Contains(term, "kitty") || strings.Contains(program, "kitty") || strings.Contains(term, "wezterm") || strings.Contains(program, "wezterm") {
Expand All @@ -62,7 +62,7 @@ func DetectImageSupport(getenv func(string) string) ImageSupport {
if strings.TrimSpace(getenv("WT_SESSION")) != "" || strings.Contains(term, "sixel") || strings.Contains(term, "mlterm") || strings.Contains(term, "foot") {
return ImageSupport{Protocol: ImageProtocolSixel}
}
return ImageSupport{Reason: "Terminal companions need Kitty graphics or Sixel image support."}
return ImageSupport{Reason: "This terminal does not show Kitty or Sixel images."}
}

type ImageDraw struct {
Expand Down
26 changes: 26 additions & 0 deletions internal/terminalpet/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,32 @@ func (a *Animation) Frame(state State, phase int) image.Image {
return frame
}

// Has reports whether the animation has frames of its own for state. Frame
// shows the idle loop for any state the animation lacks.
func (a *Animation) Has(state State) bool {
return a != nil && len(a.frames[state]) > 0
}

// HasText reports whether the animation can be drawn as text, for terminals
// that cannot show images. Only built-in companions can.
func (a *Animation) HasText() bool {
frame, _ := a.frame(Idle, 0)
_, ok := frame.(*builtinFrame)
return ok
}

// TextFrame returns one frame as TextRows lines of styled text, TextColumns
// cells wide, in the given colour depth. The boolean is false for animations
// made from pictures, which have no text form.
func (a *Animation) TextFrame(state State, phase int, colors TextColors) ([]string, bool) {
frame, _ := a.frame(state, phase)
builtin, ok := frame.(*builtinFrame)
if !ok {
return nil, false
}
return builtin.textLines(colors), true
}

func (a *Animation) FrameDelay(state State, phase int) time.Duration {
if a == nil {
return 0
Expand Down
Loading
Loading