internal/selection_menu.go

981 lines · 27805 bytes

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