internal/selection_menu.go

945 lines · 26503 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"crypto/md5"
  6	"fmt"
  7	"io"
  8	"net/http"
  9	"os"
 10	"os/exec"
 11	"path/filepath"
 12	"reflect"
 13	"sort"
 14	"strings"
 15	"time"
 16
 17	tea "github.com/charmbracelet/bubbletea"
 18	"github.com/charmbracelet/lipgloss"
 19)
 20
 21// Model represents the application state for the selection prompt
 22type Model struct {
 23	filter         string
 24	filterActive   bool // when VimKeys is on: true after "/" enters search mode
 25	filteredKeys   []SelectionOption
 26	allOptions     []SelectionOption
 27	selected       int
 28	terminalWidth  int
 29	terminalHeight int
 30	scrollOffset   int
 31	addNewOption   bool
 32	isHomeMenu     bool // If true, ESC quits; if false, ESC goes back
 33	preserveOrder  bool // skip alphabetical sort (action menus with a fixed priority)
 34}
 35
 36type optionsRefreshedMsg struct {
 37	options []SelectionOption
 38}
 39
 40type SelectionRefreshConfig struct {
 41	Updates      <-chan AnimeList
 42	BuildOptions func(AnimeList) []SelectionOption
 43}
 44
 45type PreviewSelectionRefreshConfig struct {
 46	Updates      <-chan AnimeList
 47	BuildOptions func(AnimeList) map[string]RofiSelectPreview
 48}
 49
 50var (
 51	// Style definitions
 52	titleStyle = lipgloss.NewStyle().
 53			Foreground(lipgloss.Color("#7CB9E8")). // Light blue
 54			Bold(true)
 55
 56	filterLabelStyle = lipgloss.NewStyle().
 57				Foreground(lipgloss.Color("#FF69B4")). // Hot pink
 58				Bold(true)
 59
 60	filterTextStyle = lipgloss.NewStyle().
 61			Foreground(lipgloss.Color("#98FB98")) // Pale green
 62
 63	selectedItemStyle = lipgloss.NewStyle().
 64				Foreground(lipgloss.Color("#FFFFFF")). // White text
 65				Background(lipgloss.Color("#4A90E2")). // Softer blue background
 66				Bold(true).
 67				Padding(0, 1).
 68				Border(lipgloss.NormalBorder(), false, false, false, true). // Left border only
 69				BorderForeground(lipgloss.Color("#FFFFFF"))                 // White border
 70
 71	regularItemStyle = lipgloss.NewStyle().
 72				Foreground(lipgloss.Color("#E6E6FA")). // Light lavender
 73				Padding(0, 1)
 74
 75	noMatchesStyle = lipgloss.NewStyle().
 76			Foreground(lipgloss.Color("#FF6B6B")). // Coral red
 77			Italic(true)
 78
 79	quitHintStyle = lipgloss.NewStyle().
 80			Foreground(lipgloss.Color("#FFD700")) // Gold
 81)
 82
 83// Init initializes the model
 84func (m Model) Init() tea.Cmd {
 85	return nil
 86}
 87
 88func (m *Model) moveSelectionDown() {
 89	if m.selected < len(m.filteredKeys)-1 {
 90		m.selected++
 91	}
 92	if m.selected >= m.scrollOffset+m.visibleItemsCount() {
 93		m.scrollOffset++
 94	}
 95}
 96
 97func (m *Model) moveSelectionUp() {
 98	if m.selected > 0 {
 99		m.selected--
100	}
101	if m.selected < m.scrollOffset {
102		m.scrollOffset--
103	}
104}
105
106func (m *Model) confirmSelection() tea.Cmd {
107	if len(m.filteredKeys) == 0 {
108		return nil
109	}
110	if m.filteredKeys[m.selected].Key == "add_new" {
111		CurdOut("Adding a new anime...")
112		m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
113	}
114	return tea.Quit
115}
116
117func (m *Model) exitMenu() tea.Cmd {
118	if m.isHomeMenu {
119		m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
120	} else {
121		m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
122	}
123	m.selected = 0
124	return tea.Quit
125}
126
127// Update handles user input and updates the model
128func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
129	// Handle terminal resize messages
130	if wsm, ok := msg.(tea.WindowSizeMsg); ok {
131		m.terminalWidth = wsm.Width
132		m.terminalHeight = wsm.Height
133	}
134
135	updateFilter := false
136	vimKeys := VimKeysEnabled(nil)
137
138	switch msg := msg.(type) {
139	case optionsRefreshedMsg:
140		m.replaceOptions(msg.options)
141		return m, nil
142	case tea.KeyMsg:
143		key := msg.String()
144
145		switch key {
146		case "ctrl+c":
147			m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
148			m.selected = 0
149			return m, tea.Quit
150		}
151
152		// --- Vim-enabled selection: normal mode vs search mode ---
153		// Normal: hjkl/arrows move. Search (after /): like vim's / — every
154		// printable key including hjkl is part of the query; arrows/tab still move.
155		if vimKeys {
156			if m.filterActive {
157				switch key {
158				case "esc":
159					// Leave search mode but keep the current filter applied.
160					m.filterActive = false
161					return m, nil
162				case "enter":
163					return m, m.confirmSelection()
164				case "backspace":
165					if len(m.filter) > 0 {
166						m.filter = m.filter[:len(m.filter)-1]
167						updateFilter = true
168					}
169				case "down", "tab", "ctrl+n":
170					m.moveSelectionDown()
171				case "up", "shift+tab", "ctrl+p":
172					m.moveSelectionUp()
173				// left/right: optional result navigation without stealing hjkl
174				case "left":
175					m.moveSelectionUp()
176				case "right":
177					m.moveSelectionDown()
178				default:
179					// hjkl and all other printables go into the search query.
180					if len(key) == 1 && key >= " " && key <= "~" {
181						m.filter += key
182						updateFilter = true
183					}
184				}
185				break
186			}
187
188			// Normal mode: motions only; "/" or "?" starts search.
189			switch key {
190			case "/", "?":
191				m.filterActive = true
192				return m, nil
193			case "esc":
194				return m, m.exitMenu()
195			case "enter":
196				return m, m.confirmSelection()
197			case "down", "j", "tab", "ctrl+n", "l", "right":
198				m.moveSelectionDown()
199			case "up", "k", "shift+tab", "ctrl+p", "h", "left":
200				m.moveSelectionUp()
201			case "backspace":
202				// Ignore — filter is only edited in search mode.
203			default:
204				// Do not type into filter in normal mode.
205			}
206			break
207		}
208
209		// --- Legacy behavior: every printable key filters immediately ---
210		switch key {
211		case "esc":
212			return m, m.exitMenu()
213		case "backspace":
214			if len(m.filter) > 0 {
215				m.filter = m.filter[:len(m.filter)-1]
216				updateFilter = true
217			}
218		case "down", "tab", "ctrl+n":
219			m.moveSelectionDown()
220		case "up", "shift+tab", "ctrl+p":
221			m.moveSelectionUp()
222		case "enter":
223			return m, m.confirmSelection()
224		default:
225			if len(key) == 1 && key >= " " && key <= "~" {
226				m.filter += key
227				updateFilter = true
228			}
229		}
230	}
231
232	if updateFilter {
233		m.filterOptions()
234		m.selected = 0     // Reset selection to the first item after filtering
235		m.scrollOffset = 0 // Reset scrolling
236	}
237
238	return m, nil
239}
240
241func (m *Model) replaceOptions(options []SelectionOption) {
242	previousIndex := m.selected
243	previousKey := ""
244	previousLabel := ""
245
246	if m.selected >= 0 && m.selected < len(m.filteredKeys) {
247		previousKey = m.filteredKeys[m.selected].Key
248		previousLabel = m.filteredKeys[m.selected].Label
249	}
250
251	m.allOptions = options
252	m.filterOptions()
253
254	if len(m.filteredKeys) == 0 {
255		m.selected = 0
256		m.scrollOffset = 0
257		return
258	}
259
260	m.selected = findSelectionIndex(m.filteredKeys, previousKey, previousLabel, previousIndex)
261	if m.selected < 0 {
262		m.selected = 0
263	}
264
265	if m.selected < m.scrollOffset {
266		m.scrollOffset = m.selected
267	}
268
269	visibleCount := m.visibleItemsCount()
270	if visibleCount <= 0 {
271		m.scrollOffset = 0
272		return
273	}
274
275	if m.selected >= m.scrollOffset+visibleCount {
276		m.scrollOffset = m.selected - visibleCount + 1
277	}
278	if m.scrollOffset < 0 {
279		m.scrollOffset = 0
280	}
281}
282
283// View renders the UI and only shows as many options as fit in the terminal
284func (m Model) View() string {
285	var b strings.Builder
286
287	// Display the search prompt and filter with colors
288	if VimKeysEnabled(nil) {
289		if m.filterActive {
290			b.WriteString(titleStyle.Render("Search") + " (type query · arrows move · Enter: select · Esc: normal):\n")
291			b.WriteString(filterLabelStyle.Render("/") +
292				filterTextStyle.Render(m.filter+"▌") + "\n\n")
293		} else {
294			b.WriteString(titleStyle.Render("Select") + " (hjkl/arrows · / search · Enter · Esc):\n")
295			if m.filter != "" {
296				b.WriteString(filterLabelStyle.Render("Filter: ") +
297					filterTextStyle.Render(m.filter) + "\n\n")
298			} else {
299				b.WriteString(quitHintStyle.Render("Press / to search") + "\n\n")
300			}
301		}
302	} else {
303		b.WriteString(titleStyle.Render("Search") + " (Press " +
304			quitHintStyle.Render("Ctrl+C") + " to quit):\n")
305		b.WriteString(filterLabelStyle.Render("Filter: ") +
306			filterTextStyle.Render(m.filter) + "\n\n")
307	}
308
309	if len(m.filteredKeys) == 0 {
310		b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
311	} else {
312		visibleItems := m.visibleItemsCount()
313		start := m.scrollOffset
314		end := start + visibleItems
315		if end > len(m.filteredKeys) {
316			end = len(m.filteredKeys)
317		}
318
319		// Render the options within the visible range
320		for i := start; i < end; i++ {
321			if i == m.selected {
322				b.WriteString(selectedItemStyle.Render(m.filteredKeys[i].Label) + "\n")
323			} else {
324				b.WriteString(regularItemStyle.Render(m.filteredKeys[i].Label) + "\n")
325			}
326		}
327	}
328
329	return b.String()
330}
331
332// visibleItemsCount calculates how many options fit in the terminal
333func (m Model) visibleItemsCount() int {
334	// Leave space for the filter and other UI elements
335	count := m.terminalHeight - 4 // Adjust this number based on your terminal layout
336	if count < 1 {
337		return 1
338	}
339	return count
340}
341
342// filterOptions filters and sorts options based on the search term
343func (m *Model) filterOptions() {
344	m.filteredKeys = nil
345	for _, opt := range m.allOptions {
346		if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
347			m.filteredKeys = append(m.filteredKeys, opt)
348		}
349	}
350
351	// Sort alphabetically unless this is a home menu or an ordered action list.
352	isMenu := m.preserveOrder
353	if !isMenu {
354		for _, opt := range m.allOptions {
355			if opt.Key == "ALL" || opt.Key == "CURRENT" {
356				isMenu = true
357				break
358			}
359		}
360	}
361
362	if !isMenu {
363		sort.Slice(m.filteredKeys, func(i, j int) bool {
364			return m.filteredKeys[i].Label < m.filteredKeys[j].Label
365		})
366	}
367
368	// Pin Back / Add new / Quit only when the filter is empty or matches their labels.
369	// Previously Quit/Back were always forced visible, so "/quit" still showed Back first
370	// and Enter could select the wrong row.
371	filterLower := strings.ToLower(strings.TrimSpace(m.filter))
372	pinMatches := func(label string) bool {
373		if filterLower == "" {
374			return true
375		}
376		return strings.Contains(strings.ToLower(label), filterLower)
377	}
378	backMatchesFilter := filterLower != "" && strings.Contains("back", filterLower)
379
380	// If filter targets "back", pin it above Add new anime
381	if !m.isHomeMenu && backMatchesFilter {
382		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
383	}
384
385	// Add new anime when unfiltered or filter matches
386	if m.addNewOption && pinMatches("Add new anime") {
387		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
388	}
389
390	// Back in its default position when unfiltered (or filter matches "back" handled above)
391	if !m.isHomeMenu && !backMatchesFilter && pinMatches("Back") {
392		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
393	}
394
395	// Quit last — only when unfiltered or filter matches "quit"
396	if pinMatches("Quit") {
397		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
398	}
399}
400
401func detectHomeMenu(options []SelectionOption) bool {
402	for _, opt := range options {
403		if opt.Key == "ALL" || opt.Key == "CURRENT" {
404			return true
405		}
406	}
407	return false
408}
409
410// SelectionMeansQuit reports whether the user chose Quit (by key or label).
411func SelectionMeansQuit(opt SelectionOption) bool {
412	if opt.Key == "-1" {
413		return true
414	}
415	label := strings.TrimSpace(opt.Label)
416	return strings.EqualFold(label, "Quit") || strings.EqualFold(label, "quit")
417}
418
419// SelectionMeansBack reports whether the user chose Back / dismiss (by key or label).
420func SelectionMeansBack(opt SelectionOption) bool {
421	if opt.Key == "-2" || strings.EqualFold(opt.Key, "back") {
422		return true
423	}
424	label := strings.ToLower(strings.TrimSpace(opt.Label))
425	return label == "back" || label == "back to menu" || label == "back to list"
426}
427
428// NormalizeSelectionKey forces Quit/Back labels onto the canonical keys used by callers.
429func NormalizeSelectionKey(opt SelectionOption) SelectionOption {
430	if SelectionMeansQuit(opt) {
431		return SelectionOption{Key: "-1", Label: "Quit"}
432	}
433	if SelectionMeansBack(opt) {
434		return SelectionOption{Key: "-2", Label: "Back"}
435	}
436	return opt
437}
438
439func findSelectionIndex(options []SelectionOption, previousKey string, previousLabel string, fallbackIndex int) int {
440	if previousKey != "" {
441		for idx, option := range options {
442			if option.Key == previousKey {
443				return idx
444			}
445		}
446	}
447
448	if previousLabel != "" {
449		for idx, option := range options {
450			if option.Label == previousLabel {
451				return idx
452			}
453		}
454	}
455
456	if fallbackIndex >= 0 && fallbackIndex < len(options) {
457		return fallbackIndex
458	}
459
460	if len(options) == 0 {
461		return -1
462	}
463
464	return min(fallbackIndex, len(options)-1)
465}
466
467func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
468	config := GetGlobalConfig()
469	if config == nil || strings.TrimSpace(config.MenuOrder) == "" {
470		return options
471	}
472
473	menuOrder := strings.Split(config.MenuOrder, ",")
474	optMap := make(map[string]SelectionOption)
475	for _, opt := range options {
476		optMap[opt.Key] = opt
477	}
478
479	sorted := make([]SelectionOption, 0, len(options))
480	for _, key := range menuOrder {
481		if opt, exists := optMap[key]; exists {
482			sorted = append(sorted, opt)
483			delete(optMap, key)
484		}
485	}
486
487	for _, opt := range options {
488		if _, exists := optMap[opt.Key]; exists {
489			sorted = append(sorted, opt)
490			delete(optMap, opt.Key)
491		}
492	}
493
494	return sorted
495}
496
497func previewOptionsToSortedSelection(options map[string]RofiSelectPreview) []SelectionOption {
498	selectionOptions := make([]SelectionOption, 0, len(options))
499	for id, opt := range options {
500		selectionOptions = append(selectionOptions, SelectionOption{
501			Label: opt.Title,
502			Key:   id,
503		})
504	}
505
506	sort.Slice(selectionOptions, func(i, j int) bool {
507		return selectionOptions[i].Label < selectionOptions[j].Label
508	})
509
510	return selectionOptions
511}
512
513func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
514	return DynamicSelectPreviewWithRefresh(options, addnewoption, nil)
515}
516
517func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addnewoption bool, refreshConfig *PreviewSelectionRefreshConfig) (SelectionOption, error) {
518	go preDownloadImages(options, 14)
519
520	// Removed boilerplate check
521
522	currentOptions := options
523
524	for {
525		var rofiInput strings.Builder
526		selectionOptions := previewOptionsToSortedSelection(currentOptions)
527
528		for _, opt := range selectionOptions {
529			cachePath, err := downloadToCache(currentOptions[opt.Key].CoverImage)
530			if err != nil {
531				Log(fmt.Sprintf("Error caching image: %v", err))
532				continue
533			}
534			rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Label, cachePath))
535		}
536
537		if addnewoption {
538
539			rofiInput.WriteString("Add new anime\n")
540		}
541		rofiInput.WriteString("Back\n")
542		rofiInput.WriteString("Quit\n")
543
544		configPath := filepath.Join(GetStoragePath(), "selectanimepreview.rasi")
545		cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
546		cmd.Stdin = strings.NewReader(rofiInput.String())
547		var stdout, stderr bytes.Buffer
548		cmd.Stdout = &stdout
549		cmd.Stderr = &stderr
550
551		if refreshConfig == nil || refreshConfig.Updates == nil {
552			if err := cmd.Run(); err != nil {
553				Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
554				Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
555				return SelectionOption{Key: "-2", Label: "Back"}, nil
556			}
557			return parsePreviewSelection(stdout.String(), selectionOptions)
558		}
559
560		if err := cmd.Start(); err != nil {
561			return SelectionOption{}, fmt.Errorf("failed to run Rofi preview menu: %w", err)
562		}
563
564		waitCh := make(chan error, 1)
565		go func() {
566			waitCh <- cmd.Wait()
567		}()
568
569		restartMenu := false
570
571		for !restartMenu {
572			select {
573			case err := <-waitCh:
574				if err != nil {
575					Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
576					Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
577					return SelectionOption{Key: "-2", Label: "Back"}, nil
578				}
579				return parsePreviewSelection(stdout.String(), selectionOptions)
580			case updatedList, ok := <-refreshConfig.Updates:
581				if !ok {
582					refreshConfig = nil
583					continue
584				}
585
586				updatedOptions := refreshConfig.BuildOptions(updatedList)
587				if reflect.DeepEqual(currentOptions, updatedOptions) {
588					continue
589				}
590
591				currentOptions = updatedOptions
592				restartMenu = true
593
594				if cmd.Process != nil {
595					_ = cmd.Process.Kill()
596				}
597				<-waitCh
598			}
599		}
600	}
601}
602
603func preDownloadImages(options map[string]RofiSelectPreview, count int) {
604	i := 0
605	for _, option := range options {
606		if i >= count {
607			break
608		}
609		downloadToCache(option.CoverImage)
610		i++
611	}
612}
613
614func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOption) (SelectionOption, error) {
615	selected := strings.TrimSpace(rawSelection)
616
617	switch selected {
618	case "":
619		return SelectionOption{Key: "-2", Label: "Back"}, nil
620	case "Add new anime":
621		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
622
623	case "Back":
624		return SelectionOption{Label: "Back", Key: "-2"}, nil
625	case "Quit":
626		return SelectionOption{Label: "Quit", Key: "-1"}, nil
627	}
628
629	for _, opt := range selectionOptions {
630		if opt.Label == selected {
631			return opt, nil
632		}
633	}
634
635	return SelectionOption{}, fmt.Errorf("selection not found in options")
636}
637
638func downloadToCache(imageURL string) (string, error) {
639	if strings.TrimSpace(imageURL) == "" {
640		return "", fmt.Errorf("image URL is empty")
641	}
642
643	cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
644	if err := os.MkdirAll(cacheDir, 0755); err != nil {
645		return "", fmt.Errorf("failed to create cache directory: %w", err)
646	}
647
648	// Create a hash of the URL to use as filename
649	filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
650	cachePath := filepath.Join(cacheDir, filename)
651
652	// Check if file already exists in cache
653	if info, err := os.Stat(cachePath); err == nil {
654		if info.Size() > 0 {
655			return cachePath, nil
656		}
657		_ = os.Remove(cachePath)
658	}
659
660	// Download the image
661	resp, err := sharedHTTPClient.Get(imageURL)
662	if err != nil {
663		return "", err
664	}
665	defer resp.Body.Close()
666	if resp.StatusCode != http.StatusOK {
667		return "", fmt.Errorf("failed to download image: status %d", resp.StatusCode)
668	}
669
670	file, err := os.Create(cachePath)
671	if err != nil {
672		return "", err
673	}
674
675	_, err = io.Copy(file, resp.Body)
676	if err != nil {
677		file.Close()
678		os.Remove(cachePath) // Clean up on error
679		return "", err
680	}
681	if err := file.Close(); err != nil {
682		os.Remove(cachePath)
683		return "", err
684	}
685
686	return cachePath, nil
687}
688
689func showCachedImagePreview(imageURL string) error {
690	cachePath, err := downloadToCache(imageURL)
691	if err != nil {
692		return err
693	}
694
695	// Display the image with ueberzugpp
696	cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
697	err = cmd.Start()
698	if err != nil {
699		return fmt.Errorf("failed to start image preview: %w", err)
700	}
701	time.Sleep(2 * time.Second) // Allow image to load for a moment
702	return nil
703}
704
705func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
706	return RofiSelectWithRefresh(options, isHomeMenu, nil)
707}
708
709// RofiSelectWithMessage shows a Rofi dmenu with an optional -mesg banner (for
710// release notes, error diagnosis, etc.) so callers do not need notify-send spam.
711func RofiSelectWithMessage(options []SelectionOption, isHomeMenu bool, prompt, message string) (SelectionOption, error) {
712	return rofiSelectInternal(options, isHomeMenu, nil, prompt, message)
713}
714
715func RofiSelectWithRefresh(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
716	return rofiSelectInternal(options, isHomeMenu, refreshConfig, "Select", "")
717}
718
719func rofiSelectInternal(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig, prompt, message string) (SelectionOption, error) {
720	currentOptions := options
721	if strings.TrimSpace(prompt) == "" {
722		prompt = "Select"
723	}
724
725	for {
726		optionsString := buildRofiOptionsString(currentOptions, isHomeMenu)
727		configPath := filepath.Join(GetStoragePath(), "selectanime.rasi")
728		// -markup: enable Pango in -mesg (and prompts where supported)
729		args := []string{"-dmenu", "-theme", configPath, "-i", "-markup", "-p", prompt}
730		if msg := strings.TrimSpace(message); msg != "" {
731			args = append(args, "-mesg", msg)
732		}
733		cmd := exec.Command("rofi", args...)
734		cmd.Stdin = strings.NewReader(optionsString)
735		var stdout, stderr bytes.Buffer
736		cmd.Stdout = &stdout
737		cmd.Stderr = &stderr
738
739		if refreshConfig == nil || refreshConfig.Updates == nil {
740			err := cmd.Run()
741			return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
742		}
743
744		if err := cmd.Start(); err != nil {
745			return SelectionOption{}, fmt.Errorf("failed to run Rofi: %w", err)
746		}
747
748		waitCh := make(chan error, 1)
749		go func() {
750			waitCh <- cmd.Wait()
751		}()
752
753		restartMenu := false
754
755		for !restartMenu {
756			select {
757			case err := <-waitCh:
758				if err != nil {
759					Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
760				}
761				return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
762			case updatedList, ok := <-refreshConfig.Updates:
763				if !ok {
764					refreshConfig = nil
765					continue
766				}
767
768				updatedOptions := refreshConfig.BuildOptions(updatedList)
769				if reflect.DeepEqual(currentOptions, updatedOptions) {
770					continue
771				}
772
773				currentOptions = updatedOptions
774				restartMenu = true
775
776				if cmd.Process != nil {
777					_ = cmd.Process.Kill()
778				}
779				<-waitCh
780			}
781		}
782	}
783}
784
785func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
786	return dynamicSelectInternal(options, nil, false)
787}
788
789// DynamicSelect displays a simple selection prompt without extra features
790func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
791	return dynamicSelectInternal(options, nil, false)
792}
793
794// DynamicSelectPreserveOrder is like DynamicSelect but keeps the caller's option order
795// (no alphabetical sort). Use for action menus where the first item is the primary action.
796func DynamicSelectPreserveOrder(options []SelectionOption) (SelectionOption, error) {
797	return dynamicSelectInternal(options, nil, true)
798}
799
800var promptSelect = DynamicSelect
801
802// promptSelectOrdered is used for action menus where option order matters.
803// Tests may replace this the same way as promptSelect.
804var promptSelectOrdered = DynamicSelectPreserveOrder
805
806func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
807	return dynamicSelectInternal(options, refreshConfig, false)
808}
809
810func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRefreshConfig, preserveOrder bool) (SelectionOption, error) {
811	isHomeMenu := detectHomeMenu(options)
812
813	if isHomeMenu {
814		options = sortHomeMenuOptions(options)
815	}
816
817	if config := GetGlobalConfig(); config != nil && config.RofiSelection {
818		return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
819	}
820
821	// Separate out the "add_new" sentinel so it is never sorted alphabetically.
822	// The addNewOption flag causes filterOptions() to append it after the sort.
823	hasAddNew := false
824	cleanOptions := make([]SelectionOption, 0, len(options))
825	for _, opt := range options {
826		if opt.Key == "add_new" {
827			hasAddNew = true
828		} else {
829			cleanOptions = append(cleanOptions, opt)
830		}
831	}
832
833	model := &Model{
834		allOptions:    cleanOptions,
835		isHomeMenu:    isHomeMenu,
836		addNewOption:  hasAddNew,
837		preserveOrder: preserveOrder,
838	}
839	model.filterOptions()
840
841	p := tea.NewProgram(model)
842	stopRefresh := make(chan struct{})
843
844	if refreshConfig != nil && refreshConfig.Updates != nil {
845		go func(lastOptions []SelectionOption) {
846			currentOptions := lastOptions
847			for {
848				select {
849				case <-stopRefresh:
850					return
851				case updatedList, ok := <-refreshConfig.Updates:
852					if !ok {
853						return
854					}
855
856					updatedOptions := refreshConfig.BuildOptions(updatedList)
857					if reflect.DeepEqual(currentOptions, updatedOptions) {
858						continue
859					}
860
861					currentOptions = updatedOptions
862					p.Send(optionsRefreshedMsg{options: updatedOptions})
863				}
864			}
865		}(append([]SelectionOption(nil), options...))
866	}
867
868	finalModel, err := p.Run()
869	close(stopRefresh)
870
871	// Bubbletea may leave the terminal in raw mode; always reset cursor state.
872	fmt.Print("\033[?25h")
873	fmt.Print("\033[?7h")
874	if err != nil {
875		RestoreScreen()
876		return SelectionOption{}, err
877	}
878
879	finalSelectionModel, ok := finalModel.(*Model)
880	if !ok {
881		return SelectionOption{}, fmt.Errorf("unexpected model type")
882	}
883
884	if finalSelectionModel.selected >= 0 && finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
885		return NormalizeSelectionKey(finalSelectionModel.filteredKeys[finalSelectionModel.selected]), nil
886	}
887	// Empty list / out of range — treat as cancel (Back for submenus, Quit on home).
888	if finalSelectionModel.isHomeMenu {
889		return SelectionOption{Key: "-1", Label: "Quit"}, nil
890	}
891	return SelectionOption{Key: "-2", Label: "Back"}, nil
892}
893
894func buildRofiOptionsString(options []SelectionOption, isHomeMenu bool) string {
895	optionsList := make([]string, 0, len(options)+2)
896	for _, opt := range options {
897		optionsList = append(optionsList, opt.Label)
898	}
899
900	if !isHomeMenu {
901		optionsList = append(optionsList, "Back")
902	}
903	optionsList = append(optionsList, "Quit")
904
905	return strings.Join(optionsList, "\n")
906}
907
908func parseRofiSelection(err error, rawSelection string, options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
909	if err != nil {
910		if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
911			if isHomeMenu {
912				return SelectionOption{Key: "-1", Label: "Quit"}, nil
913			}
914			return SelectionOption{Key: "-2", Label: "Back"}, nil
915		}
916		return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
917	}
918
919	selected := strings.TrimSpace(rawSelection)
920	// Strip accidental Pango/markup noise if a theme echoes it.
921	selected = strings.TrimSpace(ansiStrip.ReplaceAllString(selected, ""))
922	switch {
923	case selected == "":
924		if isHomeMenu {
925			return SelectionOption{Key: "-1", Label: "Quit"}, nil
926		}
927		return SelectionOption{Key: "-2", Label: "Back"}, nil
928	case strings.EqualFold(selected, "Back"), strings.EqualFold(selected, "Back to menu"), strings.EqualFold(selected, "Back to list"):
929		return SelectionOption{Label: "Back", Key: "-2"}, nil
930	case strings.EqualFold(selected, "Quit"):
931		return SelectionOption{Label: "Quit", Key: "-1"}, nil
932	}
933
934	for _, opt := range options {
935		if opt.Label == selected || strings.EqualFold(opt.Label, selected) {
936			return NormalizeSelectionKey(opt), nil
937		}
938		// Match when emoji/spacing differs slightly (e.g. double-space after emoji).
939		if strings.EqualFold(strings.Join(strings.Fields(opt.Label), " "), strings.Join(strings.Fields(selected), " ")) {
940			return NormalizeSelectionKey(opt), nil
941		}
942	}
943
944	return SelectionOption{}, fmt.Errorf("selected option not found in original list")
945}