gitstack

grindlemire/go-tui code browser

13.4 KB Go 518 lines 2026-06-03 ยท edfad76 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
//go:build !windows

package tui

import (
	"slices"
	"sync/atomic"
	"testing"
)

// recordingTerminal wraps MockTerminal and records method calls in order.
type recordingTerminal struct {
	*MockTerminal
	calls []string
}

func newRecordingTerminal(width, height int) *recordingTerminal {
	return &recordingTerminal{
		MockTerminal: NewMockTerminal(width, height),
	}
}

func (r *recordingTerminal) DisableMouse() {
	r.calls = append(r.calls, "DisableMouse")
	r.MockTerminal.DisableMouse()
}

func (r *recordingTerminal) ShowCursor() {
	r.calls = append(r.calls, "ShowCursor")
	r.MockTerminal.ShowCursor()
}

func (r *recordingTerminal) HideCursor() {
	r.calls = append(r.calls, "HideCursor")
	r.MockTerminal.HideCursor()
}

func (r *recordingTerminal) ExitAltScreen() {
	r.calls = append(r.calls, "ExitAltScreen")
	r.MockTerminal.ExitAltScreen()
}

func (r *recordingTerminal) EnterAltScreen() {
	r.calls = append(r.calls, "EnterAltScreen")
	r.MockTerminal.EnterAltScreen()
}

func (r *recordingTerminal) ExitRawMode() error {
	r.calls = append(r.calls, "ExitRawMode")
	return r.MockTerminal.ExitRawMode()
}

func (r *recordingTerminal) EnterRawMode() error {
	r.calls = append(r.calls, "EnterRawMode")
	return r.MockTerminal.EnterRawMode()
}

func (r *recordingTerminal) EnableMouse() {
	r.calls = append(r.calls, "EnableMouse")
	r.MockTerminal.EnableMouse()
}

func (r *recordingTerminal) EnableAltScroll() {
	r.calls = append(r.calls, "EnableAltScroll")
	r.MockTerminal.EnableAltScroll()
}

func (r *recordingTerminal) DisableAltScroll() {
	r.calls = append(r.calls, "DisableAltScroll")
	r.MockTerminal.DisableAltScroll()
}

func (r *recordingTerminal) EnableKittyKeyboard() {
	r.calls = append(r.calls, "EnableKittyKeyboard")
	r.MockTerminal.EnableKittyKeyboard()
}

func (r *recordingTerminal) ResetStyle() {
	r.calls = append(r.calls, "ResetStyle")
	r.MockTerminal.ResetStyle()
}

func (r *recordingTerminal) Clear() {
	r.calls = append(r.calls, "Clear")
	r.MockTerminal.Clear()
}

func (r *recordingTerminal) SetCursor(x, y int) {
	r.calls = append(r.calls, "SetCursor")
	r.MockTerminal.SetCursor(x, y)
}

func (r *recordingTerminal) ClearToEnd() {
	r.calls = append(r.calls, "ClearToEnd")
	r.MockTerminal.ClearToEnd()
}

func TestSuspendSequence_FullScreen(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.inAltScreen = true
	term.cursorHidden = true
	term.mouseEnabled = true

	suspendCalled := false
	app := &App{
		terminal:     term,
		mouseEnabled: true,
		onSuspend:    func() { suspendCalled = true },
		stopCh:       make(chan struct{}),
		buffer:       NewBuffer(80, 24),
	}

	// Call the testable part of suspend (without the actual SIGTSTP)
	app.suspendTerminal()

	if !suspendCalled {
		t.Fatal("expected onSuspend to be called")
	}

	// Verify call order
	expected := []string{"DisableMouse", "ShowCursor", "ExitAltScreen", "ExitRawMode"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}
}

func TestSuspendResume_FullScreenNoMouse(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.inAltScreen = true
	term.cursorHidden = true

	app := &App{
		terminal:     term,
		mouseEnabled: false,
		stopCh:       make(chan struct{}),
		buffer:       NewBuffer(80, 24),
	}

	app.suspendTerminal()
	if !containsCall(term.calls, "DisableAltScroll") {
		t.Errorf("suspend did not disable alt-scroll: %v", term.calls)
	}
	if containsCall(term.calls, "DisableMouse") {
		t.Errorf("suspend should not touch mouse when mouse is off: %v", term.calls)
	}

	term.calls = nil
	app.resumeTerminal()
	if !containsCall(term.calls, "EnableAltScroll") {
		t.Errorf("resume did not enable alt-scroll: %v", term.calls)
	}
	if containsCall(term.calls, "EnableMouse") {
		t.Errorf("resume should not enable mouse when mouse is off: %v", term.calls)
	}
}

func containsCall(haystack []string, needle string) bool {
	return slices.Contains(haystack, needle)
}

func TestSuspendSequence_InlineMode(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.cursorHidden = true

	app := &App{
		terminal:       term,
		inlineHeight:   5,
		inlineStartRow: 19,
		stopCh:         make(chan struct{}),
		buffer:         NewBuffer(80, 5),
	}

	app.suspendTerminal()

	// Inline mode: should clear widget area, NOT call ExitAltScreen
	expected := []string{"ShowCursor", "SetCursor", "ClearToEnd", "ExitRawMode"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}
}

func TestResumeSequence_FullScreen(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	app := &App{
		terminal:     term,
		mouseEnabled: true,
		stopCh:       make(chan struct{}),
		buffer:       NewBuffer(80, 24),
		dirty:        atomic.Bool{},
	}

	resumeCalled := false
	app.onResume = func() { resumeCalled = true }

	app.resumeTerminal()

	if !resumeCalled {
		t.Fatal("expected onResume to be called")
	}

	expected := []string{"EnterRawMode", "EnableKittyKeyboard", "EnterAltScreen", "Clear", "HideCursor", "EnableMouse"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}

	if !app.needsFullRedraw {
		t.Fatal("expected needsFullRedraw to be set")
	}
}

func TestResumeSequence_InlineMode(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	app := &App{
		terminal:       term,
		inlineHeight:   5,
		inlineStartRow: 0, // stale value
		stopCh:         make(chan struct{}),
		buffer:         NewBuffer(80, 5),
		dirty:          atomic.Bool{},
	}

	app.resumeTerminal()

	// Inline mode: should NOT call EnterAltScreen or Clear
	for _, call := range term.calls {
		if call == "EnterAltScreen" || call == "Clear" {
			t.Fatalf("should not call %s in inline mode", call)
		}
	}

	// Should call ResetStyle to invalidate stale style tracking
	hasResetStyle := slices.Contains(term.calls, "ResetStyle")
	if !hasResetStyle {
		t.Fatal("expected ResetStyle to be called in inline mode resume")
	}

	// Should recalculate inlineStartRow from terminal size
	if app.inlineStartRow != 19 { // 24 - 5
		t.Fatalf("expected inlineStartRow=19, got %d", app.inlineStartRow)
	}
}

func TestResumeSequence_CursorVisible(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	app := &App{
		terminal:      term,
		cursorVisible: true,
		stopCh:        make(chan struct{}),
		buffer:        NewBuffer(80, 24),
		dirty:         atomic.Bool{},
	}

	app.resumeTerminal()

	// Should NOT hide cursor when cursorVisible is true
	for _, call := range term.calls {
		if call == "HideCursor" {
			t.Fatal("should not hide cursor when cursorVisible is true")
		}
	}
}

func TestSuspendSequence_MouseDisabled(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.inAltScreen = true

	app := &App{
		terminal:     term,
		mouseEnabled: false,
		stopCh:       make(chan struct{}),
		buffer:       NewBuffer(80, 24),
	}

	app.suspendTerminal()

	// Should NOT call DisableMouse when mouse is not enabled
	for _, call := range term.calls {
		if call == "DisableMouse" {
			t.Fatal("should not call DisableMouse when mouse is not enabled")
		}
	}
}

func TestSuspendResume_HooksNilSafe(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true

	app := &App{
		terminal: term,
		stopCh:   make(chan struct{}),
		buffer:   NewBuffer(80, 24),
		dirty:    atomic.Bool{},
	}

	// Should not panic with nil hooks
	app.suspendTerminal()
	app.resumeTerminal()
}

func TestSuspendSignalRegistration(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	app := &App{
		terminal:       term,
		stopCh:         make(chan struct{}),
		updates:        make(chan Event, 256),
		merged:         make(chan Event, 256),
		watcherQueue:   make(chan func(), 256),
		eventQueueSize: 256,
		buffer:         NewBuffer(80, 24),
	}

	cleanup := app.registerSuspendSignals()
	defer cleanup()

	// Verify cleanup doesn't panic when called multiple times
	cleanup()
}

func TestSuspendSequence_DynamicAltScreen(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.inAltScreen = true
	term.cursorHidden = true

	app := &App{
		terminal:            term,
		inAlternateScreen:   true,
		savedInlineHeight:   5,
		savedInlineStartRow: 19,
		stopCh:              make(chan struct{}),
		buffer:              NewBuffer(80, 24),
	}

	app.suspendTerminal()

	// Should exit alt screen overlay, then clear saved inline widget area
	expected := []string{"ShowCursor", "ExitAltScreen", "SetCursor", "ClearToEnd", "ExitRawMode"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}
}

func TestSuspendSequence_DynamicAltScreenFullScreenUnderlying(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true
	term.inAltScreen = true
	term.cursorHidden = true

	// Dynamic alt screen with full-screen underlying mode (savedInlineHeight == 0)
	app := &App{
		terminal:          term,
		inAlternateScreen: true,
		stopCh:            make(chan struct{}),
		buffer:            NewBuffer(80, 24),
	}

	app.suspendTerminal()

	// Should exit alt screen overlay only (no SetCursor/ClearToEnd)
	expected := []string{"ShowCursor", "ExitAltScreen", "ExitRawMode"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}
}

func TestResumeSequence_DynamicAltScreen(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	app := &App{
		terminal:            term,
		inAlternateScreen:   true,
		savedInlineHeight:   5,
		savedInlineStartRow: 0, // stale value
		stopCh:              make(chan struct{}),
		buffer:              NewBuffer(80, 24),
		dirty:               atomic.Bool{},
	}

	app.resumeTerminal()

	// Should re-enter alt screen overlay, then hide cursor (cursorVisible defaults to false)
	expected := []string{"EnterRawMode", "EnableKittyKeyboard", "EnterAltScreen", "Clear", "HideCursor"}
	if len(term.calls) != len(expected) {
		t.Fatalf("expected %d calls, got %d: %v", len(expected), len(term.calls), term.calls)
	}
	for i, call := range expected {
		if term.calls[i] != call {
			t.Errorf("call[%d] = %q, want %q", i, term.calls[i], call)
		}
	}

	// Should recalculate saved inline start row
	if app.savedInlineStartRow != 19 { // 24 - 5
		t.Fatalf("expected savedInlineStartRow=19, got %d", app.savedInlineStartRow)
	}
}

func TestSelfSuspendedPreventsDoubleResume(t *testing.T) {
	term := newRecordingTerminal(80, 24)

	resumeCount := 0
	app := &App{
		terminal:       term,
		stopCh:         make(chan struct{}),
		updates:        make(chan Event, 256),
		merged:         make(chan Event, 256),
		watcherQueue:   make(chan func(), 256),
		eventQueueSize: 256,
		buffer:         NewBuffer(80, 24),
		dirty:          atomic.Bool{},
		onResume:       func() { resumeCount++ },
	}

	// Simulate self-initiated suspend: flag should prevent SIGCONT handler
	// from enqueuing a duplicate resume.
	app.selfSuspended.Store(true)

	// The SIGCONT handler uses CompareAndSwap(true, false) to atomically
	// check and clear the flag. Verify CAS succeeds when flag is true.
	if !app.selfSuspended.CompareAndSwap(true, false) {
		t.Fatal("expected CAS(true, false) to succeed")
	}

	// After CAS clears the flag, a second CAS should fail (simulates
	// suspend()'s fallback Store(false) being redundant).
	if app.selfSuspended.CompareAndSwap(true, false) {
		t.Fatal("expected CAS(true, false) to fail after flag was cleared")
	}

	// Call resumeTerminal once (as suspend() would)
	app.selfSuspended.Store(true) // reset for the resume simulation
	app.resumeTerminal()
	app.selfSuspended.Store(false)

	if resumeCount != 1 {
		t.Fatalf("expected onResume called once, got %d", resumeCount)
	}
}

func TestKeyCtrlZ_OverrideByStopper(t *testing.T) {
	term := newRecordingTerminal(80, 24)
	term.inRawMode = true

	overrideCalled := false

	// Build a dispatch table with a Stop handler for Ctrl+Z (normalized)
	table := &dispatchTable{
		entries: []dispatchEntry{
			{
				pattern: KeyPattern{Rune: 'z', Mod: ModCtrl},
				handler: func(ke KeyEvent) { overrideCalled = true },
				stop:    true,
			},
		},
	}

	app := &App{
		terminal:      term,
		stopCh:        make(chan struct{}),
		updates:       make(chan Event, 256),
		merged:        make(chan Event, 256),
		watcherQueue:  make(chan func(), 256),
		buffer:        NewBuffer(80, 24),
		focus:         newFocusManager(),
		dispatchTable: table,
		dirty:         atomic.Bool{},
	}

	ke := KeyEvent{Key: KeyRune, Rune: 'z', Mod: ModCtrl, app: app}

	// Dispatch through table - should be consumed by Stop handler
	stopped := app.dispatchTable.dispatch(ke)

	if !stopped {
		t.Fatal("expected dispatch to return stopped=true")
	}
	if !overrideCalled {
		t.Fatal("expected override handler to be called")
	}

	// Verify terminal was NOT touched (suspend should not have fired)
	if len(term.calls) != 0 {
		t.Fatalf("expected no terminal calls, got: %v", term.calls)
	}
}