internal/selection_menu.go

561 lines · 14880 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	"sort"
 13	"strings"
 14	"time"
 15
 16	tea "github.com/charmbracelet/bubbletea"
 17	"github.com/charmbracelet/lipgloss"
 18)
 19
 20// Model represents the application state for the selection prompt
 21type Model struct {
 22	filter         string
 23	filteredKeys   []SelectionOption
 24	allOptions     []SelectionOption
 25	selected       int
 26	terminalWidth  int
 27	terminalHeight int
 28	scrollOffset   int
 29	addNewOption   bool
 30	isHomeMenu     bool // If true, ESC quits; if false, ESC goes back
 31}
 32
 33func isAndroidTerminalMode() bool {
 34	config := GetGlobalConfig()
 35	return config != nil && config.IsAndroid()
 36}
 37
 38var (
 39	// Style definitions
 40	titleStyle = lipgloss.NewStyle().
 41			Foreground(lipgloss.Color("#7CB9E8")). // Light blue
 42			Bold(true)
 43
 44	filterLabelStyle = lipgloss.NewStyle().
 45				Foreground(lipgloss.Color("#FF69B4")). // Hot pink
 46				Bold(true)
 47
 48	filterTextStyle = lipgloss.NewStyle().
 49			Foreground(lipgloss.Color("#98FB98")) // Pale green
 50
 51	selectedItemStyle = lipgloss.NewStyle().
 52				Foreground(lipgloss.Color("#FFFFFF")). // White text
 53				Background(lipgloss.Color("#4A90E2")). // Softer blue background
 54				Bold(true).
 55				Padding(0, 1).
 56				Border(lipgloss.NormalBorder(), false, false, false, true). // Left border only
 57				BorderForeground(lipgloss.Color("#FFFFFF"))                 // White border
 58
 59	regularItemStyle = lipgloss.NewStyle().
 60				Foreground(lipgloss.Color("#E6E6FA")). // Light lavender
 61				Padding(0, 1)
 62
 63	noMatchesStyle = lipgloss.NewStyle().
 64			Foreground(lipgloss.Color("#FF6B6B")). // Coral red
 65			Italic(true)
 66
 67	quitHintStyle = lipgloss.NewStyle().
 68			Foreground(lipgloss.Color("#FFD700")) // Gold
 69)
 70
 71// Init initializes the model
 72func (m Model) Init() tea.Cmd {
 73	return nil
 74}
 75
 76// Update handles user input and updates the model
 77func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 78	// Handle terminal resize messages
 79	if wsm, ok := msg.(tea.WindowSizeMsg); ok {
 80		m.terminalWidth = wsm.Width
 81		m.terminalHeight = wsm.Height
 82	}
 83
 84	updateFilter := false
 85
 86	switch msg := msg.(type) {
 87	case tea.KeyMsg:
 88		switch msg.String() {
 89		case "ctrl+c":
 90			// Return quit selection option directly
 91			return m, tea.Quit
 92		case "esc":
 93			// ESC: quit on home menu, go back on sub-menus
 94			if m.isHomeMenu {
 95				// Quit
 96				m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
 97				m.selected = 0
 98			} else {
 99				// Go back
100				m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
101				m.selected = 0
102			}
103			return m, tea.Quit
104		case "backspace":
105			if len(m.filter) > 0 {
106				m.filter = m.filter[:len(m.filter)-1]
107				updateFilter = true
108			}
109		case "down", "tab", "ctrl+n":
110			// Move the selection cursor down
111			if m.selected < len(m.filteredKeys)-1 {
112				m.selected++
113			}
114
115			// Scroll the view if necessary
116			if m.selected >= m.scrollOffset+m.visibleItemsCount() {
117				m.scrollOffset++
118			}
119		case "up", "shift+tab", "ctrl+p":
120			// Move the selection cursor up
121			if m.selected > 0 {
122				m.selected--
123			}
124
125			// Scroll the view if necessary
126			if m.selected < m.scrollOffset {
127				m.scrollOffset--
128			}
129		case "enter":
130			if m.filteredKeys[m.selected].Key == "add_new" {
131				CurdOut("Adding a new anime...")
132				m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
133				return m, tea.Quit
134			}
135			return m, tea.Quit
136		default:
137			if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
138				m.filter += msg.String()
139				updateFilter = true
140			}
141		}
142	}
143
144	if updateFilter {
145		m.filterOptions()
146		m.selected = 0     // Reset selection to the first item after filtering
147		m.scrollOffset = 0 // Reset scrolling
148	}
149
150	return m, nil
151}
152
153// View renders the UI and only shows as many options as fit in the terminal
154func (m Model) View() string {
155	var b strings.Builder
156	androidMode := isAndroidTerminalMode()
157
158	title := "Search"
159	if androidMode {
160		title = "Search Anime"
161	}
162	b.WriteString(titleStyle.Render(title) + "\n")
163
164	if androidMode {
165		b.WriteString(filterLabelStyle.Render("Query: ") +
166			filterTextStyle.Render(m.filter) + "\n")
167	} else {
168		b.WriteString(filterLabelStyle.Render("Filter: ") +
169			filterTextStyle.Render(m.filter) + "\n")
170	}
171	b.WriteString("\n")
172
173	if len(m.filteredKeys) == 0 {
174		b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
175	} else {
176		visibleItems := m.visibleItemsCount()
177		start := m.scrollOffset
178		end := start + visibleItems
179		if end > len(m.filteredKeys) {
180			end = len(m.filteredKeys)
181		}
182
183		// Render the options within the visible range
184		for i := start; i < end; i++ {
185			label := m.filteredKeys[i].Label
186			if androidMode {
187				label = "  " + label
188			}
189			if i == m.selected {
190				b.WriteString(selectedItemStyle.Render(label) + "\n")
191			} else {
192				b.WriteString(regularItemStyle.Render(label) + "\n")
193			}
194
195			if androidMode {
196				b.WriteString("\n")
197			}
198		}
199	}
200
201	if androidMode {
202		footer := "Enter select  Esc back  Ctrl+C quit  Type to search"
203		if m.isHomeMenu {
204			footer = "Enter select  Esc quit  Ctrl+C quit  Type to search"
205		}
206		b.WriteString("\n" + quitHintStyle.Render(footer))
207	}
208
209	return b.String()
210}
211
212// visibleItemsCount calculates how many options fit in the terminal
213func (m Model) visibleItemsCount() int {
214	// Leave space for the filter and other UI elements
215	if isAndroidTerminalMode() {
216		return max(1, (m.terminalHeight-6)/2)
217	}
218	return max(1, m.terminalHeight-4)
219}
220
221// filterOptions filters and sorts options based on the search term
222func (m *Model) filterOptions() {
223	m.filteredKeys = nil
224	for _, opt := range m.allOptions {
225		if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
226			m.filteredKeys = append(m.filteredKeys, opt)
227		}
228	}
229
230	// Sort the filtered options alphabetically unless this is a menu selection
231	isMenu := false
232	for _, opt := range m.allOptions {
233		if opt.Key == "ALL" || opt.Key == "CURRENT" {
234			isMenu = true
235			break
236		}
237	}
238
239	if !isMenu {
240		sort.Slice(m.filteredKeys, func(i, j int) bool {
241			return m.filteredKeys[i].Label < m.filteredKeys[j].Label
242		})
243	}
244
245	// Add "Add new anime" option if enabled
246	if m.addNewOption {
247		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
248	}
249	// Add Back option before Quit (only for non-home menus)
250	if !m.isHomeMenu {
251		m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
252	}
253	m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
254}
255
256func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
257	go preDownloadImages(options, 14)
258
259	userCurdConfig := GetGlobalConfig()
260	if userCurdConfig.StoragePath == "" {
261		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
262	}
263
264	var rofiInput strings.Builder
265	selectionOptions := make([]SelectionOption, 0, len(options))
266
267	// Prepare options and rofi input
268	for id, opt := range options {
269		cachePath, err := downloadToCache(opt.CoverImage)
270		if err != nil {
271			Log(fmt.Sprintf("Error caching image: %v", err))
272			continue
273		}
274		rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath))
275		selectionOptions = append(selectionOptions, SelectionOption{
276			Label: opt.Title,
277			Key:   id,
278		})
279	}
280
281	if addnewoption {
282		rofiInput.WriteString("Add new anime\n")
283	}
284	// Add Back option before Quit (this is always a sub-menu when using preview)
285	rofiInput.WriteString("Back\n")
286	rofiInput.WriteString("Quit\n")
287
288	// Run rofi
289	configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
290	cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
291	cmd.Stdin = strings.NewReader(rofiInput.String())
292	var stdout, stderr bytes.Buffer
293	cmd.Stdout = &stdout
294	cmd.Stderr = &stderr
295
296	if err := cmd.Run(); err != nil {
297		Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
298		Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
299		// ESC pressed or rofi closed - return back
300		return SelectionOption{Key: "-2", Label: "Back"}, nil
301	}
302
303	selected := strings.TrimSpace(stdout.String())
304
305	// Handle special cases
306	switch selected {
307	case "":
308		// Empty selection - go back
309		return SelectionOption{Key: "-2", Label: "Back"}, nil
310	case "Add new anime":
311		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
312	case "Back":
313		return SelectionOption{Label: "Back", Key: "-2"}, nil
314	case "Quit":
315		return SelectionOption{Label: "Quit", Key: "-1"}, nil
316	}
317
318	// Find matching option
319	for _, opt := range selectionOptions {
320		if opt.Label == selected {
321			return opt, nil
322		}
323	}
324
325	return SelectionOption{}, fmt.Errorf("selection not found in options")
326}
327
328func preDownloadImages(options map[string]RofiSelectPreview, count int) {
329	i := 0
330	for _, option := range options {
331		if i >= count {
332			break
333		}
334		downloadToCache(option.CoverImage)
335		i++
336	}
337}
338
339func downloadToCache(imageURL string) (string, error) {
340	cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
341	if err := os.MkdirAll(cacheDir, 0755); err != nil {
342		return "", fmt.Errorf("failed to create cache directory: %w", err)
343	}
344
345	// Create a hash of the URL to use as filename
346	filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
347	cachePath := filepath.Join(cacheDir, filename)
348
349	// Check if file already exists in cache
350	if _, err := os.Stat(cachePath); err == nil {
351		return cachePath, nil
352	}
353
354	// Download the image
355	resp, err := http.Get(imageURL)
356	if err != nil {
357		return "", err
358	}
359	defer resp.Body.Close()
360
361	file, err := os.Create(cachePath)
362	if err != nil {
363		return "", err
364	}
365	defer file.Close()
366
367	_, err = io.Copy(file, resp.Body)
368	if err != nil {
369		os.Remove(cachePath) // Clean up on error
370		return "", err
371	}
372
373	return cachePath, nil
374}
375
376func showCachedImagePreview(imageURL string) error {
377	cachePath, err := downloadToCache(imageURL)
378	if err != nil {
379		return err
380	}
381
382	// Display the image with ueberzugpp
383	cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
384	err = cmd.Start()
385	if err != nil {
386		return fmt.Errorf("failed to start image preview: %w", err)
387	}
388	time.Sleep(2 * time.Second) // Allow image to load for a moment
389	return nil
390}
391
392func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
393	userCurdConfig := GetGlobalConfig()
394	if userCurdConfig.StoragePath == "" {
395		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
396	}
397
398	// Create ordered list of options
399	var optionsList []string
400	for _, opt := range options {
401		optionsList = append(optionsList, opt.Label)
402	}
403
404	// Add "Back" option before "Quit" (only for non-home menus)
405	if !isHomeMenu {
406		optionsList = append(optionsList, "Back")
407	}
408	// Add "Quit" option at the end
409	optionsList = append(optionsList, "Quit")
410	optionsString := strings.Join(optionsList, "\n")
411
412	// Prepare and run rofi
413	configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi")
414	cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
415	cmd.Stdin = strings.NewReader(optionsString)
416	var stdout, stderr bytes.Buffer
417	cmd.Stdout = &stdout
418	cmd.Stderr = &stderr
419
420	err := cmd.Run()
421	if err != nil {
422		if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
423			// ESC pressed or rofi closed: go back on sub-menus, quit on home menu
424			if isHomeMenu {
425				return SelectionOption{Key: "-1", Label: "Quit"}, nil
426			}
427			return SelectionOption{Key: "-2", Label: "Back"}, nil
428		}
429		return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
430	}
431
432	selected := strings.TrimSpace(stdout.String())
433
434	// Handle special cases
435	switch selected {
436	case "":
437		// Empty selection: go back on sub-menus, quit on home menu
438		if isHomeMenu {
439			return SelectionOption{Key: "-1", Label: "Quit"}, nil
440		}
441		return SelectionOption{Key: "-2", Label: "Back"}, nil
442	case "Back":
443		return SelectionOption{Label: "Back", Key: "-2"}, nil
444	case "Quit":
445		return SelectionOption{Label: "Quit", Key: "-1"}, nil
446	}
447
448	// Find the matching SelectionOption
449	for _, opt := range options {
450		if opt.Label == selected {
451			return opt, nil
452		}
453	}
454
455	return SelectionOption{}, fmt.Errorf("selected option not found in original list")
456}
457
458func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
459	// Detect if this is a home menu by checking for category keys
460	isHomeMenu := false
461	for _, opt := range options {
462		if opt.Key == "ALL" || opt.Key == "CURRENT" {
463			isHomeMenu = true
464			break
465		}
466	}
467
468	if GetGlobalConfig().RofiSelection {
469		return RofiSelect(options, isHomeMenu)
470	}
471
472	model := &Model{
473		allOptions: options,
474		isHomeMenu: isHomeMenu,
475	}
476	model.filterOptions() // Initialize filtered options
477
478	p := tea.NewProgram(model)
479
480	finalModel, err := p.Run()
481	if err != nil {
482		return SelectionOption{}, err
483	}
484
485	// resetting terminal state
486	fmt.Print("\033[?25h") // show cursor
487	fmt.Print("\033[?7h")  // line wrapping
488
489	finalSelectionModel, ok := finalModel.(*Model)
490	if !ok {
491		return SelectionOption{}, fmt.Errorf("unexpected model type")
492	}
493
494	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
495		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
496	}
497	return SelectionOption{}, nil
498}
499
500// DynamicSelect displays a simple selection prompt without extra features
501func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
502	// Detect if this is a home menu by checking for category keys
503	isHomeMenu := false
504	for _, opt := range options {
505		if opt.Key == "ALL" || opt.Key == "CURRENT" {
506			isHomeMenu = true
507			break
508		}
509	}
510
511	if GetGlobalConfig().RofiSelection {
512		return RofiSelect(options, isHomeMenu)
513	}
514
515	// Sort options if this contains menu categories
516	if isHomeMenu {
517		menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
518		optMap := make(map[string]SelectionOption)
519		for _, opt := range options {
520			optMap[opt.Key] = opt
521		}
522
523		sorted := make([]SelectionOption, 0, len(options))
524		for _, key := range menuOrder {
525			if opt, exists := optMap[key]; exists {
526				sorted = append(sorted, opt)
527			}
528		}
529		options = sorted
530	}
531
532	model := &Model{
533		allOptions: options,
534		isHomeMenu: isHomeMenu,
535	}
536	model.filterOptions() // Initialize filtered options
537
538	p := tea.NewProgram(model)
539	finalModel, err := p.Run()
540	if err != nil {
541		return SelectionOption{}, err
542	}
543
544	fmt.Print("\033[?25h") // Show cursor
545	fmt.Print("\033[?7h")  // Enable line wrapping
546
547	finalSelectionModel, ok := finalModel.(*Model)
548	if !ok {
549		return SelectionOption{}, fmt.Errorf("unexpected model type")
550	}
551
552	// Check if the program was quit with Ctrl+C
553	if err != nil {
554		return SelectionOption{Key: "-1", Label: "Quit"}, nil
555	}
556
557	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
558		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
559	}
560	return SelectionOption{}, nil
561}