internal/selection_menu.go

474 lines · 12566 bytes · executable

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