gitstack

grindlemire/go-tui code browser

16.2 KB Go 633 lines 2026-06-17 ยท fe77872 raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
package tui

import "strings"

// Buffer is a double-buffered 2D grid of cells.
// Writes go to the back buffer; Flush() computes the diff and swaps buffers.
type Buffer struct {
	front  []Cell // Currently displayed state
	back   []Cell // State being built
	width  int
	height int
}

// CellChange represents a single cell that differs between front and back buffers.
type CellChange struct {
	X, Y int
	Cell Cell
	// EraseToEOL, when true, means "clear from (X, Y) to the end of the row"
	// instead of writing Cell. The diff emits this when a row's trailing cells
	// became empty, so terminals leave them blank (and trim them on copy)
	// rather than recording written spaces.
	EraseToEOL bool
}

// NewBuffer creates a new double-buffered grid of the specified dimensions.
// Both buffers are initialized with spaces and default styling.
func NewBuffer(width, height int) *Buffer {
	if width < 0 {
		width = 0
	}
	if height < 0 {
		height = 0
	}

	size := width * height
	front := make([]Cell, size)
	back := make([]Cell, size)

	// Initialize with spaces (default style is zero value)
	defaultCell := NewCell(' ', NewStyle())
	for i := range front {
		front[i] = defaultCell
		back[i] = defaultCell
	}

	return &Buffer{
		front:  front,
		back:   back,
		width:  width,
		height: height,
	}
}

// Width returns the buffer width in columns.
func (b *Buffer) Width() int {
	return b.width
}

// Height returns the buffer height in rows.
func (b *Buffer) Height() int {
	return b.height
}

// Size returns the buffer dimensions (width, height).
func (b *Buffer) Size() (width, height int) {
	return b.width, b.height
}

// Rect returns the buffer bounds as a Rect starting at (0, 0).
func (b *Buffer) Rect() Rect {
	return NewRect(0, 0, b.width, b.height)
}

// idx converts (x, y) coordinates to a flat index.
// Returns -1 if out of bounds.
func (b *Buffer) idx(x, y int) int {
	if x < 0 || x >= b.width || y < 0 || y >= b.height {
		return -1
	}
	return y*b.width + x
}

// Cell returns the cell at position (x, y) from the back buffer.
// Returns an empty Cell if the position is out of bounds.
func (b *Buffer) Cell(x, y int) Cell {
	idx := b.idx(x, y)
	if idx < 0 {
		return Cell{}
	}
	return b.back[idx]
}

// SetCell sets the cell at position (x, y) in the back buffer.
// Does nothing if the position is out of bounds.
func (b *Buffer) SetCell(x, y int, c Cell) {
	idx := b.idx(x, y)
	if idx < 0 {
		return
	}
	b.back[idx] = c
}

// SetRune sets a rune at position (x, y) with the given style.
// Handles wide characters by setting continuation cells.
// Properly clears overlapped wide characters.
func (b *Buffer) SetRune(x, y int, r rune, style Style) {
	b.setCluster(x, y, string(r), RuneWidth(r), style, "")
}

// setCluster writes a grapheme cluster (text with display width 1 or 2) at
// position (x, y) with the given style and optional hyperlink. It applies the
// same overlap/continuation clearing as a single rune and clones text that is a
// slice of a larger source so the cell owns its bytes.
func (b *Buffer) setCluster(x, y int, text string, width int, style Style, link string) {
	if x < 0 || x >= b.width || y < 0 || y >= b.height {
		return
	}

	currentCell := b.Cell(x, y)

	// If target position is a continuation cell, clear the originating wide char
	if currentCell.IsContinuation() {
		b.clearWideCharAt(x, y)
	}

	// If target position is the START of a wide character, clear its continuation
	if currentCell.Width == 2 && x+1 < b.width {
		b.SetCell(x+1, y, NewCell(' ', NewStyle()))
	}

	// If placing a wide char would overlap an existing wide char at x+1, clear it
	if width == 2 && x+1 < b.width {
		next := b.Cell(x+1, y)
		// If next cell is the start of a wide char (width 2), clear it and its continuation
		if next.Width == 2 {
			b.clearWideCharAt(x+1, y)
		}
		// If next cell is a continuation, clear its originating wide char
		if next.IsContinuation() {
			b.clearWideCharAt(x+1, y)
		}
	}

	// Handle edge case: wide char at last column - can't fit, skip it
	if width == 2 && x+1 >= b.width {
		// Place a space instead since the wide char can't fit
		b.SetCell(x, y, NewCell(' ', style))
		return
	}

	// Set the primary cell (cloning multi-rune text it owns).
	b.SetCell(x, y, newClusterCell(text, uint8(width), style, link))

	// Set continuation cell for wide characters
	if width == 2 {
		b.SetCell(x+1, y, NewCellWithWidth(0, style, 0))
	}
}

// SetRuneLink sets a rune like SetRune and, when link is non-empty, attaches it
// as the cell's OSC 8 hyperlink target. Wide-character handling matches SetRune.
func (b *Buffer) SetRuneLink(x, y int, r rune, style Style, link string) {
	b.setCluster(x, y, string(r), RuneWidth(r), style, link)
}

// clearWideCharAt clears a wide character that includes position (x, y).
// If (x, y) is a continuation cell, finds and clears the originating cell.
// If (x, y) is a wide char start, clears it and its continuation.
func (b *Buffer) clearWideCharAt(x, y int) {
	cell := b.Cell(x, y)
	defaultCell := NewCell(' ', NewStyle())

	if cell.IsContinuation() {
		// This is a continuation - the wide char starts at x-1
		if x > 0 {
			b.SetCell(x-1, y, defaultCell)
		}
		b.SetCell(x, y, defaultCell)
	} else if cell.Width == 2 {
		// This is the start of a wide char
		b.SetCell(x, y, defaultCell)
		if x+1 < b.width {
			b.SetCell(x+1, y, defaultCell)
		}
	}
}

// SetString writes a string starting at position (x, y) with the given style.
// Returns the total display width consumed (handles wide characters).
// Stops at buffer edge without wrapping.
func (b *Buffer) SetString(x, y int, s string, style Style) int {
	if y < 0 || y >= b.height {
		return 0
	}

	totalWidth := 0
	curX := x

	for len(s) > 0 {
		cluster, width, size := nextCluster(s)
		if size == 0 {
			break
		}
		s = s[size:]

		if curX >= b.width {
			break
		}
		if curX < 0 {
			// Skip clusters before the visible area
			curX += width
			continue
		}

		// Check if wide cluster fits
		if width == 2 && curX+1 >= b.width {
			// Wide cluster doesn't fit, stop here
			break
		}

		b.setCluster(curX, y, cluster, width, style, "")
		curX += width
		totalWidth += width
	}

	return totalWidth
}

// SetStringClipped writes a string clipped to a rectangle.
// Characters outside clipRect are not rendered.
// Returns the total display width of rendered characters.
func (b *Buffer) SetStringClipped(x, y int, s string, style Style, clipRect Rect) int {
	if y < clipRect.Y || y >= clipRect.Bottom() {
		return 0
	}

	totalWidth := 0
	curX := x

	for len(s) > 0 {
		cluster, width, size := nextCluster(s)
		if size == 0 {
			break
		}
		s = s[size:]

		// Skip if entirely before clip region
		if curX+width <= clipRect.X {
			curX += width
			continue
		}

		// Stop if past clip region
		if curX >= clipRect.Right() {
			break
		}

		// Render if within clip (also check buffer bounds)
		if curX >= clipRect.X && curX < clipRect.Right() {
			// For wide clusters, ensure both cells fit in clip region
			if width == 2 && curX+1 >= clipRect.Right() {
				// Wide cluster doesn't fit, skip it
				curX += width
				continue
			}
			b.setCluster(curX, y, cluster, width, style, "")
			totalWidth += width
		}

		curX += width
	}

	return totalWidth
}

// Fill a rectangle with the given rune and style.
// Handles wide characters appropriately.
func (b *Buffer) Fill(rect Rect, r rune, style Style) {
	// Intersect with buffer bounds
	rect = rect.Intersect(b.Rect())
	if rect.IsEmpty() {
		return
	}

	width := RuneWidth(r)

	for y := rect.Y; y < rect.Bottom(); y++ {
		for x := rect.X; x < rect.Right(); {
			if width == 2 && x+1 >= rect.Right() {
				// Wide char doesn't fit in remaining space, fill with space
				b.SetRune(x, y, ' ', style)
				x++
			} else {
				b.SetRune(x, y, r, style)
				x += width
			}
		}
	}
}

// SetStringGradient writes a string with a gradient applied per grapheme cluster.
// The gradient is applied horizontally along the string; each cluster (CJK, emoji,
// flag, ZWJ family) gets a single color and occupies its full display width.
// Returns the total display width consumed (handles wide characters).
func (b *Buffer) SetStringGradient(x, y int, s string, g Gradient, baseStyle Style) int {
	if y < 0 || y >= b.height || s == "" {
		return 0
	}

	total := clusterCount(s)
	totalWidth := 0
	curX := x
	idx := 0

	for len(s) > 0 {
		cluster, width, size := nextCluster(s)
		if size == 0 {
			break
		}
		s = s[size:]

		if curX >= b.width {
			break
		}
		if curX < 0 {
			// Skip clusters before the visible area.
			curX += width
			idx++
			continue
		}
		// Wide cluster that does not fit at the right edge: stop.
		if width == 2 && curX+1 >= b.width {
			break
		}

		// Gradient position t in [0, 1], one step per cluster.
		t := 0.0
		if total > 1 {
			t = float64(idx) / float64(total-1)
		}
		style := baseStyle
		style.Fg = g.At(t)

		b.setCluster(curX, y, cluster, width, style, "")
		curX += width
		totalWidth += width
		idx++
	}

	return totalWidth
}

// FillGradient fills a rectangle with a gradient background.
// The gradient direction determines how it's applied:
// - Horizontal: left to right
// - Vertical: top to bottom
// - DiagonalDown: top-left to bottom-right
// - DiagonalUp: bottom-left to top-right
func (b *Buffer) FillGradient(rect Rect, r rune, g Gradient, baseStyle Style) {
	// Intersect with buffer bounds
	rect = rect.Intersect(b.Rect())
	if rect.IsEmpty() {
		return
	}

	width := RuneWidth(r)
	rectWidth := float64(rect.Width)
	rectHeight := float64(rect.Height)

	// Avoid division by zero
	if rectWidth <= 0 {
		rectWidth = 1
	}
	if rectHeight <= 0 {
		rectHeight = 1
	}

	for y := rect.Y; y < rect.Bottom(); y++ {
		for x := rect.X; x < rect.Right(); {
			if width == 2 && x+1 >= rect.Right() {
				// Wide char doesn't fit in remaining space, fill with space
				style := baseStyle
				var t float64
				switch g.Direction {
				case GradientHorizontal:
					t = float64(x-rect.X) / rectWidth
				case GradientVertical:
					t = float64(y-rect.Y) / rectHeight
				case GradientDiagonalDown:
					tx := float64(x-rect.X) / rectWidth
					ty := float64(y-rect.Y) / rectHeight
					t = (tx + ty) / 2
				case GradientDiagonalUp:
					tx := float64(x-rect.X) / rectWidth
					ty := float64(rect.Bottom()-1-y-rect.Y) / rectHeight
					t = (tx + ty) / 2
				default:
					t = float64(x-rect.X) / rectWidth
				}
				style.Bg = g.At(t)
				b.SetRune(x, y, ' ', style)
				x++
			} else {
				// Calculate gradient position based on direction
				var t float64
				switch g.Direction {
				case GradientHorizontal:
					t = float64(x-rect.X) / rectWidth
				case GradientVertical:
					t = float64(y-rect.Y) / rectHeight
				case GradientDiagonalDown:
					tx := float64(x-rect.X) / rectWidth
					ty := float64(y-rect.Y) / rectHeight
					t = (tx + ty) / 2
				case GradientDiagonalUp:
					tx := float64(x-rect.X) / rectWidth
					ty := float64(rect.Bottom()-1-y-rect.Y) / rectHeight
					t = (tx + ty) / 2
				default:
					t = float64(x-rect.X) / rectWidth
				}

				// Get gradient color and apply to style
				gradColor := g.At(t)
				style := baseStyle
				style.Bg = gradColor

				b.SetRune(x, y, r, style)
				x += width
			}
		}
	}
}

// ApplyDim applies the dim attribute to every cell in the back buffer.
// Used by modal backdrop to visually fade background content.
func (b *Buffer) ApplyDim() {
	for i := range b.back {
		b.back[i].Style.Attrs |= AttrDim
	}
}

// FillBlank fills the entire back buffer with default-styled spaces.
// Used by modal backdrop="blank" to hide background content entirely.
func (b *Buffer) FillBlank() {
	defaultCell := NewCell(' ', NewStyle())
	for i := range b.back {
		b.back[i] = defaultCell
	}
}

// Clear clears the entire back buffer to spaces with default style.
func (b *Buffer) Clear() {
	b.ClearRect(b.Rect())
}

// ClearRect clears a rectangular region to spaces with default style.
func (b *Buffer) ClearRect(rect Rect) {
	// Intersect with buffer bounds
	rect = rect.Intersect(b.Rect())
	if rect.IsEmpty() {
		return
	}

	defaultCell := NewCell(' ', NewStyle())

	for y := rect.Y; y < rect.Bottom(); y++ {
		for x := rect.X; x < rect.Right(); x++ {
			// First, handle any wide character cleanup at the edges
			cell := b.Cell(x, y)
			if cell.IsContinuation() && x == rect.X {
				// Clearing starts at a continuation - clear the originating char too
				if x > 0 {
					b.SetCell(x-1, y, defaultCell)
				}
			}
			if cell.Width == 2 && x+1 == rect.Right() {
				// Clearing ends at a wide char - also clear the continuation
				if x+1 < b.width {
					b.SetCell(x+1, y, defaultCell)
				}
			}
			b.SetCell(x, y, defaultCell)
		}
	}
}

// Diff returns all cells that changed between front and back buffers.
// Cells are returned in row-major order (top-to-bottom, left-to-right)
// which optimizes terminal output by minimizing cursor moves.
func (b *Buffer) Diff() []CellChange {
	changes := make([]CellChange, 0, b.width) // Pre-allocate one row
	for y := 0; y < b.height; y++ {
		// Rightmost non-empty cell in the new (back) row. Everything past it is
		// empty, so a trailing clear can replace per-cell space writes there.
		lastContent := -1
		for x := b.width - 1; x >= 0; x-- {
			c := b.back[y*b.width+x]
			if !c.IsEmpty() && !c.IsContinuation() {
				lastContent = x
				// A wide character also occupies the next column via its
				// continuation cell. Keep that column inside the content region
				// so the trailing erase can never clip the glyph's second half.
				if c.Width == 2 && x+1 < b.width {
					lastContent = x + 1
				}
				break
			}
		}

		// Emit changed cells up to and including the last content cell.
		for x := 0; x <= lastContent; x++ {
			idx := y*b.width + x
			if !b.back[idx].Equal(b.front[idx]) {
				changes = append(changes, CellChange{X: x, Y: y, Cell: b.back[idx]})
			}
		}

		// The trailing region (lastContent+1 .. width-1) is all empty in the new
		// frame. If any of it changed (the row used to have content there), clear
		// it with one erase-to-end-of-line instead of writing spaces.
		tailStart := lastContent + 1
		tailChanged := false
		for x := tailStart; x < b.width; x++ {
			idx := y*b.width + x
			if !b.back[idx].Equal(b.front[idx]) {
				tailChanged = true
				break
			}
		}
		if tailChanged {
			changes = append(changes, CellChange{X: tailStart, Y: y, EraseToEOL: true})
		}
	}
	return changes
}

// Swap copies the back buffer to the front buffer.
// Call this after flushing changes to the terminal.
func (b *Buffer) Swap() {
	copy(b.front, b.back)
}

// String renders the back buffer to a string for debugging.
// Each row is separated by a newline. Continuation cells (from wide characters) are skipped.
func (b *Buffer) String() string {
	var sb strings.Builder
	for y := 0; y < b.height; y++ {
		for x := 0; x < b.width; x++ {
			cell := b.back[y*b.width+x]
			if cell.IsContinuation() {
				continue // Skip continuation cells
			}
			if cell.Text == "" {
				sb.WriteRune(' ')
			} else {
				sb.WriteString(cell.Text)
			}
		}
		if y < b.height-1 {
			sb.WriteRune('\n')
		}
	}
	return sb.String()
}

// StringTrimmed returns the back buffer content with trailing spaces removed from each line.
func (b *Buffer) StringTrimmed() string {
	var sb strings.Builder
	for y := 0; y < b.height; y++ {
		var line strings.Builder
		for x := 0; x < b.width; x++ {
			cell := b.back[y*b.width+x]
			if cell.IsContinuation() {
				continue
			}
			if cell.Text == "" {
				line.WriteRune(' ')
			} else {
				line.WriteString(cell.Text)
			}
		}
		sb.WriteString(strings.TrimRight(line.String(), " "))
		if y < b.height-1 {
			sb.WriteRune('\n')
		}
	}
	return sb.String()
}

// Resize changes the buffer dimensions, preserving content where possible.
// Content in the overlapping region is preserved; new areas are cleared.
func (b *Buffer) Resize(width, height int) {
	if width < 0 {
		width = 0
	}
	if height < 0 {
		height = 0
	}

	if width == b.width && height == b.height {
		return
	}

	newSize := width * height
	newFront := make([]Cell, newSize)
	newBack := make([]Cell, newSize)

	// Initialize with spaces
	defaultCell := NewCell(' ', NewStyle())
	for i := range newFront {
		newFront[i] = defaultCell
		newBack[i] = defaultCell
	}

	// Copy overlapping content
	copyWidth := min(width, b.width)
	copyHeight := min(height, b.height)

	for y := range copyHeight {
		for x := range copyWidth {
			oldIdx := y*b.width + x
			newIdx := y*width + x
			newFront[newIdx] = b.front[oldIdx]
			newBack[newIdx] = b.back[oldIdx]
		}
	}

	b.front = newFront
	b.back = newBack
	b.width = width
	b.height = height
}