internal/selection_menu.go

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