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 // Main-screen flow renderer state. logLines is the full logical
37 // buffer (chat + live bottom band) from the previous DrawLog call.
38 // logViewportTop/logHardwareRow track where that logical buffer sits
39 // in the terminal's visible viewport so we can diff safely, and bail
40 // out to clear+replay when the diff would touch rows that are no
41 // longer addressable.
42 logChat []string
43 logBottom []string
44 logLines []string
45 logViewportTop int
46 logHardwareRow int
47 logInit bool
48}
49
50// NewRenderer returns a renderer that writes to out.
51func NewRenderer(out io.Writer) *Renderer {
52 return &Renderer{out: out}
53}
54
55// Resize tells the renderer the current terminal size.
56//
57// On a real size change we also issue a clear-screen so the next Draw
58// starts from a blank slate. Without the clear, characters from the
59// old (wider) layout linger past the new right edge and rows from
60// before the new bottom hang around as garbage.
61func (r *Renderer) ResetScrollRegion() {
62 if r.out != nil {
63 _, _ = io.WriteString(r.out, SeqResetScrollRegion)
64 }
65}
66
67func (r *Renderer) Resize(cols, rows int) {
68 if cols != r.cols || rows != r.rows {
69 r.cols = cols
70 r.rows = rows
71 r.prev = nil
72 r.logChat = nil
73 r.logBottom = nil
74 r.logLines = nil
75 r.logViewportTop = 0
76 r.logHardwareRow = 0
77 r.logInit = false
78 if r.out != nil {
79 // Clear both screen and scrollback so stale content from
80 // the old width doesn't bleed through. Move to (1,1) so
81 // the next DrawLog/writeFull starts from a clean slate.
82 // Use the no-home variant: the explicit MoveTo below sets
83 // the cursor without triggering VS Code's viewport-snap.
84 _, _ = io.WriteString(r.out, SeqDeleteKittyImages+SeqClearScreenNoHome+SeqClearScrollback+MoveTo(1, 1))
85 }
86 }
87}
88
89// Clear forces a full repaint on the next Draw and clears the screen
90// plus scrollback. In main-screen flow mode this is required whenever
91// already-emitted transcript layout changes (for example ctrl+o
92// expand/collapse), because terminal scrollback cannot be edited
93// reliably once printed.
94func (r *Renderer) Clear() {
95 r.prev = nil
96 r.logChat = nil
97 r.logBottom = nil
98 r.logLines = nil
99 r.logViewportTop = 0
100 r.logHardwareRow = 0
101 r.logInit = false
102 _, _ = io.WriteString(r.out, SeqDeleteKittyImages+SeqClearScreenNoHome+SeqClearScrollback+MoveTo(1, 1))
103}
104
105// Invalidate forces a full repaint on the next Draw without clearing the
106// whole terminal first. Useful when the cached diff is unreliable but a
107// visible full-screen flash would be too distracting.
108func (r *Renderer) Invalidate() {
109 r.prev = nil
110 r.logLines = nil
111}
112
113// Draw updates the terminal so that the visible frame ends with the
114// given lines (bottom-aligned). cursorRow/cursorCol are offsets within
115// the lines slice indicating where to place the terminal cursor; use
116// -1 to hide it.
117// containsImageEscape reports whether the line carries an inline-image
118// escape we must repaint rather than diff against the previous frame.
119func containsImageEscape(s string) bool {
120 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
121}
122
123// truncateToWidth clips s so its on-screen width doesn't exceed cols
124// cells, preserving ANSI CSI escape sequences (which don't consume
125// cells). Lines carrying an inline-image escape are returned as-is
126// since we can't measure their painted size.
127//
128// Fast path: a byte-length <= cols is a conservative upper bound
129// guaranteeing the cell width is also <= cols, so we skip all the
130// rune-width math. That covers the vast majority of lines in a
131// transcript (narrow terminals wrap early; wide ones leave headroom).
132func truncateToWidth(s string, cols int) string {
133 if cols <= 0 || containsImageEscape(s) {
134 return s
135 }
136 if len(s) <= cols {
137 return s
138 }
139 var out strings.Builder
140 out.Grow(len(s))
141 seen := 0
142 runes := []rune(s)
143 for i := 0; i < len(runes); {
144 r := runes[i]
145 // CSI escape sequence (ESC [ ... final): zero-width.
146 if r == 0x1b && i+1 < len(runes) && runes[i+1] == '[' {
147 out.WriteRune(r)
148 out.WriteRune(runes[i+1])
149 i += 2
150 for i < len(runes) {
151 c := runes[i]
152 out.WriteRune(c)
153 i++
154 if c >= 0x40 && c <= 0x7e {
155 break
156 }
157 }
158 continue
159 }
160 rw := runewidthRune(r)
161 if seen+rw > cols {
162 // Flush any trailing ANSI escapes (resets, erase-to-EOL)
163 // so background colors and cleanup sequences survive.
164 for i < len(runes) {
165 if runes[i] == 0x1b && i+1 < len(runes) && runes[i+1] == '[' {
166 out.WriteRune(runes[i])
167 out.WriteRune(runes[i+1])
168 i += 2
169 for i < len(runes) {
170 c := runes[i]
171 out.WriteRune(c)
172 i++
173 if c >= 0x40 && c <= 0x7e {
174 break
175 }
176 }
177 } else {
178 break
179 }
180 }
181 break
182 }
183 out.WriteRune(r)
184 seen += rw
185 i++
186 }
187 return out.String()
188}
189
190func (r *Renderer) Draw(lines []string, cursorRow, cursorCol int) {
191 if r.cols == 0 || r.rows == 0 {
192 return
193 }
194 // Bottom-align: only the last r.rows lines are visible.
195 visible := lines
196 if len(visible) > r.rows {
197 visible = visible[len(visible)-r.rows:]
198 cursorRow -= len(lines) - len(visible)
199 }
200 // Pad to r.rows with empty lines at the top. Every line is also
201 // hard-truncated to cols so the terminal never soft-wraps our output
202 // (which would push the status bar out of its row).
203 frame := make([]string, r.rows)
204 top := r.rows - len(visible)
205 for i := 0; i < top; i++ {
206 frame[i] = ""
207 }
208 for i, line := range visible {
209 frame[top+i] = truncateToWidth(line, r.cols)
210 }
211
212 var w strings.Builder
213 w.WriteString(SeqSynchronizedOn)
214 w.WriteString(SeqHideCursor)
215
216 // When inline images are in play we always full-repaint (clear
217 // screen first, then rewrite every row). Terminals manage image
218 // pixels in a layer we cannot diff against, so the per-line cache
219 // is unreliable. Inline images are opt-in via ZOT_INLINE_IMAGES;
220 // the common code path below is the fast cached diff.
221 curHasImage := false
222 curHasKittyImage := false
223 for _, l := range frame {
224 if containsImageEscape(l) {
225 curHasImage = true
226 if strings.Contains(l, "\x1b_G") {
227 curHasKittyImage = true
228 }
229 }
230 }
231 forceAll := curHasImage || r.prevHadImage
232 if forceAll {
233 w.WriteString(SeqClearScreen)
234 if curHasKittyImage {
235 // Delete previously placed kitty images once per frame,
236 // before rewriting all rows. Doing this inside each image
237 // escape makes only the last image in the frame survive.
238 w.WriteString("\x1b_Ga=d\x1b\\")
239 }
240 }
241
242 // Detect selection highlights: if the current OR previous frame
243 // has selection-background rows, force full repaint. VS Code's
244 // terminal doesn't reliably clear background colors on row
245 // overwrites, leaving ghost highlights behind.
246 hasSelection := false
247 for _, l := range frame {
248 if strings.Contains(l, "\x1b[48;5;") {
249 hasSelection = true
250 break
251 }
252 }
253 if !hasSelection && r.prev != nil {
254 for _, l := range r.prev {
255 if strings.Contains(l, "\x1b[48;5;") {
256 hasSelection = true
257 break
258 }
259 }
260 }
261
262 full := r.prev == nil || len(r.prev) != r.rows
263 for i := 0; i < r.rows; i++ {
264 if full || forceAll || hasSelection || r.prev[i] != frame[i] {
265 w.WriteString(MoveTo(i+1, 1))
266 w.WriteString("\x1b[0m") // reset all attributes first
267 w.WriteString(SeqClearLine)
268 w.WriteString(frame[i])
269 }
270 }
271
272 if cursorRow >= 0 {
273 absRow := top + cursorRow + 1
274 absCol := cursorCol + 1
275 if absRow >= 1 && absRow <= r.rows {
276 w.WriteString(MoveTo(absRow, absCol))
277 w.WriteString(SeqShowCursor)
278 }
279 }
280 w.WriteString(SeqSynchronizedOff)
281
282 _, _ = io.WriteString(r.out, w.String())
283
284 r.prev = frame
285 r.prevHadImage = curHasImage
286 r.cursorRow = cursorRow
287 r.cursorCol = cursorCol
288}
289
290// DrawLog renders zot in the terminal's main screen as normal terminal
291// flow rather than a fixed full-screen frame. Chat lines are emitted once
292// into the host terminal scrollback; the current bottom block (dialogs,
293// slash popup, status, editor) is erased and redrawn in place at the end.
294//
295// cursorBottomRow/cursorCol are offsets into bottom, not the full frame.
296func (r *Renderer) DrawLog(chat, bottom []string, cursorBottomRow, cursorCol int) {
297 if r.cols == 0 || r.rows == 0 {
298 return
299 }
300 if len(bottom) == 0 {
301 bottom = []string{""}
302 }
303 chatFrame := make([]string, len(chat))
304 for i, line := range chat {
305 chatFrame[i] = truncateToWidth(line, r.cols)
306 }
307 bottomFrame := make([]string, len(bottom))
308 for i, line := range bottom {
309 bottomFrame[i] = truncateToWidth(line, r.cols)
310 }
311
312 // Always reserve one real row below the editor/status band. This is
313 // renderer-owned (not a best-effort trailing blank in the caller's
314 // bottom block), so the logical-buffer diff keeps it visible and cursor
315 // placement remains relative to the editor itself.
316 const bottomMarginRows = 1
317 lines := make([]string, 0, len(chatFrame)+len(bottomFrame)+bottomMarginRows)
318 lines = append(lines, chatFrame...)
319 lines = append(lines, bottomFrame...)
320 for range bottomMarginRows {
321 lines = append(lines, "")
322 }
323 if len(lines) == 0 {
324 lines = []string{""}
325 }
326
327 cursorTargetRow := -1
328 if cursorBottomRow >= 0 && cursorBottomRow < len(bottomFrame) {
329 cursorTargetRow = len(chatFrame) + cursorBottomRow
330 }
331
332 var w strings.Builder
333 w.WriteString(SeqSynchronizedOn)
334 w.WriteString(SeqHideCursor)
335
336 writeFull := func(clear bool) {
337 if clear {
338 w.WriteString(SeqDeleteKittyImages)
339 w.WriteString(SeqClearScreenNoHome)
340 w.WriteString(SeqClearScrollback)
341 w.WriteString(MoveTo(1, 1))
342 }
343 for idx, line := range lines {
344 if idx > 0 {
345 w.WriteString("\r\n")
346 }
347 w.WriteString("\x1b[0m")
348 w.WriteString(SeqClearLine)
349 w.WriteString(line)
350 }
351 r.logHardwareRow = len(lines) - 1
352 r.logViewportTop = len(lines) - r.rows
353 if r.logViewportTop < 0 {
354 r.logViewportTop = 0
355 }
356 }
357
358 moveToLogicalRow := func(targetRow int) {
359 if targetRow < 0 {
360 targetRow = 0
361 }
362 if targetRow >= len(lines) {
363 targetRow = len(lines) - 1
364 }
365 viewportBottom := r.logViewportTop + r.rows - 1
366 if targetRow > viewportBottom {
367 currentScreenRow := r.logHardwareRow - r.logViewportTop
368 if currentScreenRow < 0 {
369 currentScreenRow = 0
370 }
371 if currentScreenRow >= r.rows {
372 currentScreenRow = r.rows - 1
373 }
374 moveToBottom := r.rows - 1 - currentScreenRow
375 if moveToBottom > 0 {
376 w.WriteString("\x1b[" + itoa(moveToBottom) + "B")
377 }
378 scroll := targetRow - viewportBottom
379 for s := 0; s < scroll; s++ {
380 w.WriteString("\r\n")
381 }
382 r.logViewportTop += scroll
383 r.logHardwareRow = targetRow
384 return
385 }
386 currentScreenRow := r.logHardwareRow - r.logViewportTop
387 targetScreenRow := targetRow - r.logViewportTop
388 lineDiff := targetScreenRow - currentScreenRow
389 if lineDiff > 0 {
390 w.WriteString("\x1b[" + itoa(lineDiff) + "B")
391 } else if lineDiff < 0 {
392 w.WriteString("\x1b[" + itoa(-lineDiff) + "A")
393 }
394 r.logHardwareRow = targetRow
395 }
396
397 positionCursor := func() {
398 if cursorTargetRow < 0 || cursorTargetRow >= len(lines) {
399 return
400 }
401 moveToLogicalRow(cursorTargetRow)
402 w.WriteString("\r")
403 if cursorCol > 0 {
404 w.WriteString("\x1b[" + itoa(cursorCol) + "C")
405 }
406 w.WriteString(SeqShowCursor)
407 }
408
409 // Selection-highlight workaround removed: it could mis-invalidate
410 // user-bubble padding rows whose colored bg made botHasHL trip,
411 // causing the next diff pass to leave those rows visually thinned
412 // because the cached entry was the \x00 sentinel rather than the
413 // real previous bg-colored row.
414
415 full := !r.logInit || len(r.logLines) == 0
416 if full {
417 writeFull(true)
418 r.logInit = true
419 } else {
420 firstChanged := -1
421 lastChanged := -1
422 maxLines := len(lines)
423 if len(r.logLines) > maxLines {
424 maxLines = len(r.logLines)
425 }
426 for idx := 0; idx < maxLines; idx++ {
427 oldLine := ""
428 if idx < len(r.logLines) {
429 oldLine = r.logLines[idx]
430 }
431 newLine := ""
432 if idx < len(lines) {
433 newLine = lines[idx]
434 }
435 if oldLine != newLine {
436 if firstChanged == -1 {
437 firstChanged = idx
438 }
439 lastChanged = idx
440 }
441 }
442 // Buffer grew but the appended rows were empty (or otherwise
443 // equal to the implicit "" past the old end). The diff above
444 // won't flag those rows, yet the renderer still needs to
445 // advance its hardware cursor / viewport tracking past them so
446 // the next render starts from the correct position. Treat the
447 // extension as changed.
448 if len(lines) > len(r.logLines) {
449 if firstChanged == -1 {
450 firstChanged = len(r.logLines)
451 }
452 if lastChanged < len(lines)-1 {
453 lastChanged = len(lines) - 1
454 }
455 }
456
457 if firstChanged == -1 {
458 // No content changes; the final cursor positioning below may still
459 // move the hardware cursor if the editor cursor changed.
460 } else if firstChanged < r.logViewportTop {
461 // Changes above the visible viewport cannot be patched safely.
462 writeFull(true)
463 } else {
464 prevViewportTop := r.logViewportTop
465 viewportTop := prevViewportTop
466 hardwareRow := r.logHardwareRow
467 prevViewportBottom := prevViewportTop + r.rows - 1
468 appendStart := len(lines) > len(r.logLines) && firstChanged == len(r.logLines) && firstChanged > 0
469 moveTarget := firstChanged
470 if appendStart {
471 moveTarget = firstChanged - 1
472 }
473
474 if moveTarget > prevViewportBottom {
475 currentScreenRow := hardwareRow - prevViewportTop
476 if currentScreenRow < 0 {
477 currentScreenRow = 0
478 }
479 if currentScreenRow >= r.rows {
480 currentScreenRow = r.rows - 1
481 }
482 moveToBottom := r.rows - 1 - currentScreenRow
483 if moveToBottom > 0 {
484 w.WriteString("\x1b[" + itoa(moveToBottom) + "B")
485 }
486 scroll := moveTarget - prevViewportBottom
487 for s := 0; s < scroll; s++ {
488 w.WriteString("\r\n")
489 }
490 prevViewportTop += scroll
491 viewportTop += scroll
492 hardwareRow = moveTarget
493 }
494
495 currentScreenRow := hardwareRow - prevViewportTop
496 targetScreenRow := moveTarget - viewportTop
497 lineDiff := targetScreenRow - currentScreenRow
498 if lineDiff > 0 {
499 w.WriteString("\x1b[" + itoa(lineDiff) + "B")
500 } else if lineDiff < 0 {
501 w.WriteString("\x1b[" + itoa(-lineDiff) + "A")
502 }
503 if appendStart {
504 w.WriteString("\r\n")
505 } else {
506 w.WriteString("\r")
507 }
508
509 renderEnd := lastChanged
510 if renderEnd >= len(lines) {
511 renderEnd = len(lines) - 1
512 }
513 for idx := firstChanged; idx <= renderEnd; idx++ {
514 if idx > firstChanged {
515 w.WriteString("\r\n")
516 }
517 w.WriteString("\x1b[0m")
518 w.WriteString(SeqClearLine)
519 w.WriteString(lines[idx])
520 }
521 finalRow := renderEnd
522 if len(r.logLines) > len(lines) {
523 extra := len(r.logLines) - len(lines)
524 if extra > r.rows {
525 writeFull(true)
526 } else {
527 for e := 0; e < extra; e++ {
528 w.WriteString("\x1b[1B")
529 w.WriteString("\r")
530 w.WriteString("\x1b[0m")
531 w.WriteString(SeqClearLine)
532 finalRow++
533 }
534 if extra > 0 {
535 w.WriteString("\x1b[" + itoa(extra) + "A")
536 finalRow -= extra
537 }
538 }
539 }
540 r.logHardwareRow = finalRow
541 r.logViewportTop = viewportTop
542 if minTop := r.logHardwareRow - r.rows + 1; minTop > r.logViewportTop {
543 r.logViewportTop = minTop
544 }
545 if r.logViewportTop < 0 {
546 r.logViewportTop = 0
547 }
548 }
549 }
550
551 positionCursor()
552 w.WriteString(SeqSynchronizedOff)
553 _, _ = io.WriteString(r.out, w.String())
554
555 r.logChat = append(r.logChat[:0], chatFrame...)
556 r.logBottom = append(r.logBottom[:0], bottomFrame...)
557 r.logLines = append(r.logLines[:0], lines...)
558 r.cursorRow = cursorBottomRow
559 r.cursorCol = cursorCol
560}
561
562func writeBlock(w *strings.Builder, lines []string) {
563 for i, line := range lines {
564 w.WriteString("\x1b[0m")
565 w.WriteString(SeqClearLine)
566 w.WriteString(line)
567 if i < len(lines)-1 {
568 w.WriteString("\r\n")
569 }
570 }
571}
572
573func tailTruncated(lines []string, maxRows, cols int) []string {
574 if maxRows <= 0 {
575 return nil
576 }
577 if len(lines) > maxRows {
578 lines = lines[len(lines)-maxRows:]
579 }
580 out := make([]string, len(lines))
581 for i, line := range lines {
582 out[i] = truncateToWidth(line, cols)
583 }
584 return out
585}