gitstack

grindlemire/go-tui code browser

2.5 KB Go 94 lines 2026-02-14 · 8e3ad6d 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
package tui

// EnterAlternateScreen switches to alternate screen mode for full-screen UI.
// The current scrollback position is preserved and will be restored on exit.
// Use this for overlays like settings panels that should not affect terminal history.
// If already in alternate mode, this is a no-op.
func (a *App) EnterAlternateScreen() error {
	// Guard: already in alternate mode
	if a.inAlternateScreen {
		return nil
	}

	// Save current inline mode state for restoration
	a.savedInlineHeight = a.inlineHeight
	a.savedInlineStartRow = a.inlineStartRow
	a.savedInlineLayout = a.inlineLayout

	// Get terminal dimensions
	width, height := a.terminal.Size()

	// If currently in inline mode, clear the inline region first
	if a.inlineHeight > 0 {
		a.terminal.SetCursor(0, a.inlineStartRow)
		a.terminal.ClearToEnd()
	}

	// Enter alternate screen via terminal
	a.terminal.EnterAltScreen()

	// Update internal state to full-screen mode
	a.inAlternateScreen = true
	a.inlineHeight = 0
	a.inlineStartRow = 0

	// Resize buffer to full terminal size
	a.buffer.Resize(width, height)

	// Mark for full redraw
	if a.root != nil {
		a.root.MarkDirty()
	}
	a.needsFullRedraw = true
	a.MarkDirty()

	return nil
}

// ExitAlternateScreen returns to normal mode, restoring the previous scrollback.
// If not in alternate mode, this is a no-op.
func (a *App) ExitAlternateScreen() error {
	// Guard: not in alternate mode
	if !a.inAlternateScreen {
		return nil
	}

	// Exit alternate screen - this restores the original terminal content
	a.terminal.ExitAltScreen()

	// Restore inline mode state
	a.inlineHeight = a.savedInlineHeight
	a.inlineStartRow = a.savedInlineStartRow
	a.inlineLayout = a.savedInlineLayout
	a.inAlternateScreen = false

	// Get terminal dimensions
	width, height := a.terminal.Size()

	// Reconfigure buffer for restored mode
	if a.inlineHeight > 0 {
		// Inline mode: recalculate start row, resize buffer to inline height
		a.inlineStartRow = height - a.inlineHeight
		a.inlineLayout.clamp(a.inlineStartRow)
		a.buffer.Resize(width, a.inlineHeight)
	} else {
		// Was full-screen normal mode (started with alternate screen)
		// Re-enter alternate screen since that's the normal state for full-screen apps
		a.terminal.EnterAltScreen()
		a.buffer.Resize(width, height)
	}

	// Mark for full redraw
	if a.root != nil {
		a.root.MarkDirty()
	}
	a.needsFullRedraw = true
	a.MarkDirty()

	return nil
}

// IsInAlternateScreen returns true if currently in alternate screen mode.
func (a *App) IsInAlternateScreen() bool {
	return a.inAlternateScreen
}