internal/selection_menu.go

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