summaryrefslogtreecommitdiff
path: root/internal/tui/pidpicker/model.go
blob: 37af25777f37d17b708c5b1f8125ea82fae55964 (plain)
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
package pidpicker

import (
	"fmt"
	common "ior/internal/tui/common"
	"ior/internal/tui/messages"
	"strings"

	"github.com/charmbracelet/bubbles/key"
	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

const allPIDsLabel = "All PIDs"

// KeyMap defines picker-specific key bindings.
type KeyMap struct {
	Enter   key.Binding
	Esc     key.Binding
	Refresh key.Binding
}

// DefaultKeyMap returns picker defaults.
func DefaultKeyMap() KeyMap {
	return KeyMap{
		Enter:   key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "select")),
		Esc:     key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "back")),
		Refresh: key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "refresh")),
	}
}

func (k KeyMap) PickerShortHelp() []key.Binding {
	return []key.Binding{k.Enter, k.Refresh, k.Esc}
}

var (
	screenStyle    = common.ScreenStyle
	headerStyle    = common.HeaderStyle
	helpBarStyle   = common.HelpBarStyle
	highlightStyle = common.HighlightStyle
	errorStyle     = common.ErrorStyle
)

type processesLoadedMsg struct {
	processes []ProcessInfo
	err       error
}

// Model is the Bubble Tea model for the PID picker screen.
type Model struct {
	input         textinput.Model
	processes     []ProcessInfo
	filtered      []ProcessInfo
	selectedIndex int
	width         int
	height        int
	keys          KeyMap
	lastErr       error
}

// New creates a PID picker model with default shared key bindings.
func New() Model {
	return NewWithKeys(DefaultKeyMap())
}

// NewWithKeys creates a PID picker model with the provided key bindings.
func NewWithKeys(keys KeyMap) Model {
	input := textinput.New()
	input.Prompt = "Filter: "
	input.Placeholder = "pid, comm, or cmdline"
	input.Focus()
	input.CharLimit = 0
	input.Width = 40

	return Model{
		input:    input,
		keys:     keys,
		filtered: []ProcessInfo{},
	}
}

// Init starts the initial process scan.
func (m Model) Init() tea.Cmd {
	return scanProcessesCmd
}

// Update handles key presses and async process-scan responses.
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height
		m.input.Width = clamp(msg.Width-16, 10, 100)
		return m, nil
	case processesLoadedMsg:
		m.processes = msg.processes
		m.lastErr = msg.err
		m.applyFilter()
		return m, nil
	case tea.KeyMsg:
		return m.updateKey(msg)
	}

	var cmd tea.Cmd
	m.input, cmd = m.input.Update(msg)
	m.applyFilter()
	return m, cmd
}

func (m Model) updateKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch {
	case key.Matches(msg, m.keys.Esc):
		return m, tea.Quit
	case msg.Type == tea.KeyCtrlR:
		return m, scanProcessesCmd
	case key.Matches(msg, m.keys.Enter):
		return m, m.emitSelection()
	case msg.Type == tea.KeyUp:
		if m.selectedIndex > 0 {
			m.selectedIndex--
		}
		m.input.Blur()
		return m, nil
	case msg.Type == tea.KeyDown:
		maxIndex := len(m.filtered)
		if m.selectedIndex < maxIndex {
			m.selectedIndex++
		}
		m.input.Blur()
		return m, nil
	}

	if msg.Type == tea.KeyRunes && !m.input.Focused() {
		if key.Matches(msg, m.keys.Refresh) {
			return m, scanProcessesCmd
		}
		m.input.Focus()
	}

	var cmd tea.Cmd
	m.input, cmd = m.input.Update(msg)
	m.applyFilter()
	return m, cmd
}

func (m Model) emitSelection() tea.Cmd {
	if m.selectedIndex <= 0 {
		return func() tea.Msg { return messages.PidSelectedMsg{Pid: 0} }
	}

	idx := m.selectedIndex - 1
	if idx < 0 || idx >= len(m.filtered) {
		return func() tea.Msg { return messages.PidSelectedMsg{Pid: 0} }
	}

	pid := m.filtered[idx].Pid
	return func() tea.Msg { return messages.PidSelectedMsg{Pid: pid} }
}

func (m *Model) applyFilter() {
	query := strings.TrimSpace(strings.ToLower(m.input.Value()))
	if query == "" {
		m.filtered = cloneProcesses(m.processes)
		if m.selectedIndex > len(m.filtered) {
			m.selectedIndex = len(m.filtered)
		}
		return
	}

	filtered := make([]ProcessInfo, 0, len(m.processes))
	for _, process := range m.processes {
		if matchesQuery(process, query) {
			filtered = append(filtered, process)
		}
	}

	m.filtered = filtered
	if m.selectedIndex > len(m.filtered) {
		m.selectedIndex = len(m.filtered)
	}
}

func matchesQuery(process ProcessInfo, query string) bool {
	pidStr := fmt.Sprintf("%d", process.Pid)
	if strings.Contains(strings.ToLower(pidStr), query) {
		return true
	}
	if strings.Contains(strings.ToLower(process.Comm), query) {
		return true
	}
	return strings.Contains(strings.ToLower(process.Cmdline), query)
}

func cloneProcesses(in []ProcessInfo) []ProcessInfo {
	if len(in) == 0 {
		return []ProcessInfo{}
	}
	out := make([]ProcessInfo, len(in))
	copy(out, in)
	return out
}

// View renders the PID picker with filter input, list, and help bar.
func (m Model) View() string {
	var b strings.Builder
	b.WriteString(headerStyle.Render("Select PID"))
	b.WriteString("\n")
	b.WriteString(m.input.View())
	b.WriteString("\n\n")

	rows := m.renderRows()
	b.WriteString(rows)

	if m.lastErr != nil {
		b.WriteString("\n")
		b.WriteString(errorStyle.Render("scan error: " + m.lastErr.Error()))
	}

	b.WriteString("\n")
	b.WriteString(helpBarStyle.Render(renderHelp(m.keys.PickerShortHelp())))
	return screenStyle.Render(b.String())
}

func (m Model) renderRows() string {
	lines := make([]string, 0, len(m.filtered)+1)
	lines = append(lines, m.renderRow(0, allPIDsLabel))
	for i, process := range m.filtered {
		label := formatProcess(process)
		lines = append(lines, m.renderRow(i+1, label))
	}

	maxRows := m.visibleRows()
	if maxRows > 0 && len(lines) > maxRows {
		start := m.selectedIndex - (maxRows / 2)
		if start < 0 {
			start = 0
		}
		limit := len(lines) - maxRows
		if start > limit {
			start = limit
		}
		lines = lines[start : start+maxRows]
	}
	return strings.Join(lines, "\n")
}

func (m Model) renderRow(index int, label string) string {
	prefix := "  "
	style := lipgloss.NewStyle()
	if index == m.selectedIndex {
		prefix = "> "
		style = highlightStyle
	}
	return style.Render(prefix + label)
}

func (m Model) visibleRows() int {
	if m.height <= 0 {
		return 0
	}
	const reservedLines = 6
	rows := m.height - reservedLines
	if rows < 1 {
		return 1
	}
	return rows
}

func renderHelp(bindings []key.Binding) string {
	parts := make([]string, 0, len(bindings))
	for _, binding := range bindings {
		help := binding.Help()
		parts = append(parts, fmt.Sprintf("%s %s", help.Key, help.Desc))
	}
	return strings.Join(parts, " • ")
}

func scanProcessesCmd() tea.Msg {
	processes, err := ScanProcesses()
	return processesLoadedMsg{
		processes: processes,
		err:       err,
	}
}

func clamp(v, min, max int) int {
	if v < min {
		return min
	}
	if v > max {
		return max
	}
	return v
}

func formatProcess(process ProcessInfo) string {
	if process.Cmdline == "" {
		return fmt.Sprintf("%d  %s", process.Pid, process.Comm)
	}
	return fmt.Sprintf("%d  %s  %s", process.Pid, process.Comm, process.Cmdline)
}