render.go RawHistoryFolder
1package tui
2
3import (
4 "io"
5 "strings"
6
7 "github.com/mattn/go-runewidth"
8)
9
10// runewidthRune reports the number of cells a rune occupies, pinned
11// here so the renderer does not depend on the editor's helper.
12func runewidthRune(r rune) int { return runewidth.RuneWidth(r) }
13
14// Renderer maintains a previous frame and writes only the lines that
15// changed on each Draw(). Callers pass a full target frame (slice of
16// styled lines, already wrapped to width).
17type Renderer struct {
18 out io.Writer
19 prev []string
20 rows int // terminal rows
21 cols int // terminal cols
22
23 // Cursor position after last draw (for placing input cursor).
24 cursorRow int
25 cursorCol int
26
27 // hideCursor when true prevents ShowCursor from being emitted.
28 hideCursor bool
29
30 // prevHadImage tracks whether the previous frame contained an
31 // inline-image escape so we can force a full clear+repaint whenever
32 // the image set changes. Only matters when inline images are
33 // enabled via ZOT_INLINE_IMAGES; defaults to false.
34 prevHadImage bool
35}
36
37// NewRenderer returns a renderer that writes to out.
38func NewRenderer(out io.Writer) *Renderer {
39 return &Renderer{out: out}
40}
41
42// Resize tells the renderer the current terminal size.
43//
44// On a real size change we also issue a clear-screen so the next Draw
45// starts from a blank slate. Without the clear, characters from the
46// old (wider) layout linger past the new right edge and rows from
47// before the new bottom hang around as garbage.
48func (r *Renderer) Resize(cols, rows int) {
49 if cols != r.cols || rows != r.rows {
50 r.cols = cols
51 r.rows = rows
52 r.prev = nil
53 if r.out != nil {
54 _, _ = io.WriteString(r.out, SeqClearScreen)
55 }
56 }
57}
58
59// Clear forces a full repaint on the next Draw and clears the screen.
60func (r *Renderer) Clear() {
61 r.prev = nil
62 _, _ = io.WriteString(r.out, SeqClearScreen)
63}
64
65// Draw updates the terminal so that the visible frame ends with the
66// given lines (bottom-aligned). cursorRow/cursorCol are offsets within
67// the lines slice indicating where to place the terminal cursor; use
68// -1 to hide it.
69// containsImageEscape reports whether the line carries an inline-image
70// escape we must repaint rather than diff against the previous frame.
71func containsImageEscape(s string) bool {
72 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
73}
74
75// truncateToWidth clips s so its on-screen width doesn't exceed cols
76// cells, preserving ANSI CSI escape sequences (which don't consume
77// cells). Lines carrying an inline-image escape are returned as-is
78// since we can't measure their painted size.
79//
80// Fast path: a byte-length <= cols is a conservative upper bound
81// guaranteeing the cell width is also <= cols, so we skip all the
82// rune-width math. That covers the vast majority of lines in a
83// transcript (narrow terminals wrap early; wide ones leave headroom).
84func truncateToWidth(s string, cols int) string {
85 if cols <= 0 || containsImageEscape(s) {
86 return s
87 }
88 if len(s) <= cols {
89 return s
90 }
91 var out strings.Builder
92 out.Grow(len(s))
93 seen := 0
94 runes := []rune(s)
95 for i := 0; i < len(runes); {
96 r := runes[i]
97 // CSI escape sequence (ESC [ ... final): zero-width.
98 if r == 0x1b && i+1 < len(runes) && runes[i+1] == '[' {
99 out.WriteRune(r)
100 out.WriteRune(runes[i+1])
101 i += 2
102 for i < len(runes) {
103 c := runes[i]
104 out.WriteRune(c)
105 i++
106 if c >= 0x40 && c <= 0x7e {
107 break
108 }
109 }
110 continue
111 }
112 rw := runewidthRune(r)
113 if seen+rw > cols {
114 break
115 }
116 out.WriteRune(r)
117 seen += rw
118 i++
119 }
120 return out.String()
121}
122
123func (r *Renderer) Draw(lines []string, cursorRow, cursorCol int) {
124 if r.cols == 0 || r.rows == 0 {
125 return
126 }
127 // Bottom-align: only the last r.rows lines are visible.
128 visible := lines
129 if len(visible) > r.rows {
130 visible = visible[len(visible)-r.rows:]
131 cursorRow -= len(lines) - len(visible)
132 }
133 // Pad to r.rows with empty lines at the top. Every line is also
134 // hard-truncated to cols so the terminal never soft-wraps our output
135 // (which would push the status bar out of its row).
136 frame := make([]string, r.rows)
137 top := r.rows - len(visible)
138 for i := 0; i < top; i++ {
139 frame[i] = ""
140 }
141 for i, line := range visible {
142 frame[top+i] = truncateToWidth(line, r.cols)
143 }
144
145 var w strings.Builder
146 w.WriteString(SeqSynchronizedOn)
147 w.WriteString(SeqHideCursor)
148
149 // When inline images are in play we always full-repaint (clear
150 // screen first, then rewrite every row). Terminals manage image
151 // pixels in a layer we cannot diff against, so the per-line cache
152 // is unreliable. Inline images are opt-in via ZOT_INLINE_IMAGES;
153 // the common code path below is the fast cached diff.
154 curHasImage := false
155 for _, l := range frame {
156 if containsImageEscape(l) {
157 curHasImage = true
158 break
159 }
160 }
161 forceAll := curHasImage || r.prevHadImage
162 if forceAll {
163 w.WriteString(SeqClearScreen)
164 }
165
166 full := r.prev == nil || len(r.prev) != r.rows
167 for i := 0; i < r.rows; i++ {
168 if full || forceAll || r.prev[i] != frame[i] {
169 w.WriteString(MoveTo(i+1, 1))
170 w.WriteString(SeqClearLine)
171 w.WriteString(frame[i])
172 }
173 }
174
175 if cursorRow >= 0 {
176 absRow := top + cursorRow + 1
177 absCol := cursorCol + 1
178 if absRow >= 1 && absRow <= r.rows {
179 w.WriteString(MoveTo(absRow, absCol))
180 w.WriteString(SeqShowCursor)
181 }
182 }
183 w.WriteString(SeqSynchronizedOff)
184
185 _, _ = io.WriteString(r.out, w.String())
186
187 r.prev = frame
188 r.prevHadImage = curHasImage
189 r.cursorRow = cursorRow
190 r.cursorCol = cursorCol
191}