internal/selection_menu.go

459 lines · 12503 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 // Add this field
 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 instead of quitting the program
 91			m.filteredKeys[m.selected] = SelectionOption{"quit", "-1"}
 92			return m, tea.Quit // Properly exit the program
 93		case "backspace":
 94			if len(m.filter) > 0 {
 95				m.filter = m.filter[:len(m.filter)-1]
 96				updateFilter = true
 97			}
 98		case "down":
 99			// Move the selection cursor down
100			if m.selected < len(m.filteredKeys)-1 {
101				m.selected++
102			}
103
104			// Scroll the view if necessary
105			if m.selected >= m.scrollOffset+m.visibleItemsCount() {
106				m.scrollOffset++
107			}
108		case "up":
109			// Move the selection cursor up
110			if m.selected > 0 {
111				m.selected--
112			}
113
114			// Scroll the view if necessary
115			if m.selected < m.scrollOffset {
116				m.scrollOffset--
117			}
118		case "enter":
119			if m.filteredKeys[m.selected].Key == "add_new" {
120				CurdOut("Adding a new anime...")
121				m.filteredKeys[m.selected] = SelectionOption{"add_new", "0"}
122				return m, tea.Quit
123			}
124			return m, tea.Quit
125		default:
126			if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
127				m.filter += msg.String()
128				updateFilter = true
129			}
130		}
131	}
132
133	if updateFilter {
134		m.filterOptions()
135		m.selected = 0     // Reset selection to the first item after filtering
136		m.scrollOffset = 0 // Reset scrolling
137	}
138
139	return m, nil
140}
141
142// View renders the UI and only shows as many options as fit in the terminal
143func (m Model) View() string {
144	var b strings.Builder
145
146	// Display the search prompt and filter with colors
147	b.WriteString(titleStyle.Render("Search") + " (Press " +
148		quitHintStyle.Render("Ctrl+C") + " to quit):\n")
149
150	b.WriteString(filterLabelStyle.Render("Filter: ") +
151		filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing
152
153	if len(m.filteredKeys) == 0 {
154		b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
155	} else {
156		visibleItems := m.visibleItemsCount()
157		start := m.scrollOffset
158		end := start + visibleItems
159		if end > len(m.filteredKeys) {
160			end = len(m.filteredKeys)
161		}
162
163		// Render the options within the visible range
164		for i := start; i < end; i++ {
165			if i == m.selected {
166				b.WriteString(selectedItemStyle.Render(m.filteredKeys[i].Label) + "\n")
167			} else {
168				b.WriteString(regularItemStyle.Render(m.filteredKeys[i].Label) + "\n")
169			}
170		}
171	}
172
173	return b.String()
174}
175
176// visibleItemsCount calculates how many options fit in the terminal
177func (m Model) visibleItemsCount() int {
178	// Leave space for the filter and other UI elements
179	return m.terminalHeight - 4 // Adjust this number based on your terminal layout
180}
181
182// filterOptions filters and sorts options based on the search term
183func (m *Model) filterOptions() {
184	m.filteredKeys = []SelectionOption{}
185
186	for key, value := range m.options {
187		// When the key is " ", compare and display using the value instead
188		if key == " " {
189			if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
190				m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
191			}
192		} else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
193			m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
194		}
195	}
196
197	// Sort the filtered options alphabetically
198	sort.Slice(m.filteredKeys, func(i, j int) bool {
199		return m.filteredKeys[i].Label < m.filteredKeys[j].Label
200	})
201
202	// Add "Add new anime" option if enabled
203	if m.addNewOption {
204		m.filteredKeys = append(m.filteredKeys, SelectionOption{
205			Label: "Add new anime",
206			Key:   "add_new",
207		})
208	}
209
210	m.filteredKeys = append(m.filteredKeys, SelectionOption{
211		Label: "Quit",
212		Key:   "-1",
213	})
214}
215
216func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
217	// Pre-download first 14 images in background
218	go preDownloadImages(options, 14)
219
220	userCurdConfig := GetGlobalConfig()
221	if userCurdConfig.StoragePath == "" {
222		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
223	}
224
225	// Prepare Rofi input with anime titles and their cached image paths
226	var rofiInput strings.Builder
227	for _, option := range options {
228		// Download and get cache path for the image
229		cachePath, err := downloadToCache(option.CoverImage)
230		if err != nil {
231			Log(fmt.Sprintf("Error caching image: %v", err), logFile)
232			continue
233		}
234
235		// Format: "Title\x00icon\x1f/path/to/cached/image\n"
236		// This tells Rofi to use the image as an icon for this entry
237		rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath))
238	}
239
240	// Add "Add new anime" and "Quit" options
241	if addnewoption {
242		rofiInput.WriteString("Add new anime\n")
243	}
244	rofiInput.WriteString("Quit\n")
245
246	// Get the absolute path to the rasi config
247	configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
248
249	// Create the command with explicit arguments
250	args := []string{
251		"-dmenu",
252		"-theme", configPath,
253		"-show-icons",
254		"-p", "Select Anime",
255		"-i",         // Case-insensitive matching
256		"-no-custom", // Disable custom input
257	}
258
259	// Create the command
260	rofiCmd := exec.Command("rofi", args...)
261
262	// Set up pipes for input/output
263	rofiCmd.Stdin = strings.NewReader(rofiInput.String())
264	var stdout, stderr bytes.Buffer
265	rofiCmd.Stdout = &stdout
266	rofiCmd.Stderr = &stderr
267
268	// Run the command
269	err := rofiCmd.Run()
270	if err != nil {
271		// Log both stdout and stderr for debugging
272		Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()), logFile)
273		Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()), logFile)
274		return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
275	}
276
277	selectedTitle := strings.TrimSpace(stdout.String())
278
279	// Handle special cases
280	switch selectedTitle {
281	case "":
282		return SelectionOption{}, fmt.Errorf("no selection made")
283	case "Add new anime":
284		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
285	case "Quit":
286		return SelectionOption{Label: "Quit", Key: "-1"}, nil
287	}
288
289	// Find the selected anime in options
290	for id, option := range options {
291		if option.Title == selectedTitle {
292			return SelectionOption{
293				Label: option.Title,
294				Key:   id,
295			}, nil
296		}
297	}
298
299	return SelectionOption{}, fmt.Errorf("selection not found in options")
300}
301
302func preDownloadImages(options map[string]RofiSelectPreview, count int) {
303	i := 0
304	for _, option := range options {
305		if i >= count {
306			break
307		}
308		downloadToCache(option.CoverImage)
309		i++
310	}
311}
312
313func downloadToCache(imageURL string) (string, error) {
314	cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
315	if err := os.MkdirAll(cacheDir, 0755); err != nil {
316		return "", fmt.Errorf("failed to create cache directory: %w", err)
317	}
318
319	// Create a hash of the URL to use as filename
320	filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
321	cachePath := filepath.Join(cacheDir, filename)
322
323	// Check if file already exists in cache
324	if _, err := os.Stat(cachePath); err == nil {
325		return cachePath, nil
326	}
327
328	// Download the image
329	resp, err := http.Get(imageURL)
330	if err != nil {
331		return "", err
332	}
333	defer resp.Body.Close()
334
335	file, err := os.Create(cachePath)
336	if err != nil {
337		return "", err
338	}
339	defer file.Close()
340
341	_, err = io.Copy(file, resp.Body)
342	if err != nil {
343		os.Remove(cachePath) // Clean up on error
344		return "", err
345	}
346
347	return cachePath, nil
348}
349
350func showCachedImagePreview(imageURL string) error {
351	cachePath, err := downloadToCache(imageURL)
352	if err != nil {
353		return err
354	}
355
356	// Display the image with ueberzugpp
357	cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
358	err = cmd.Start()
359	if err != nil {
360		return fmt.Errorf("failed to start image preview: %w", err)
361	}
362	time.Sleep(2 * time.Second) // Allow image to load for a moment
363	return nil
364}
365
366func RofiSelect(options map[string]string, addanimeopt bool) (SelectionOption, error) {
367	userCurdConfig := GetGlobalConfig()
368	if userCurdConfig.StoragePath == "" {
369		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
370	}
371
372	// Create a slice to store the options in the order we want
373	var optionsList []string
374	for _, value := range options {
375		optionsList = append(optionsList, value)
376	}
377
378	// Sort the options alphabetically
379	sort.Strings(optionsList)
380
381	// Add "Add new anime" and "Quit" options
382	if addanimeopt {
383		optionsList = append(optionsList, "Add new anime", "Quit")
384	} else {
385		optionsList = append(optionsList, "Quit")
386	}
387
388	// Join all options into a single string, separated by newlines
389	optionsString := strings.Join(optionsList, "\n")
390
391	// Prepare the Rofi command
392	cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime")
393
394	// Set up pipes for input and output
395	cmd.Stdin = strings.NewReader(optionsString)
396	var out bytes.Buffer
397	cmd.Stdout = &out
398
399	// Run the command
400	err := cmd.Run()
401	if err != nil {
402		return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
403	}
404
405	// Get the selected option
406	selected := strings.TrimSpace(out.String())
407
408	// Handle special cases
409	switch selected {
410	case "":
411		return SelectionOption{}, fmt.Errorf("no selection made")
412	case "Add new anime":
413		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
414	case "Quit":
415		return SelectionOption{Label: "Quit", Key: "-1"}, nil
416	}
417
418	// Find the key for the selected value
419	for key, value := range options {
420		if value == selected {
421			return SelectionOption{Label: value, Key: key}, nil
422		}
423	}
424
425	// If we get here, the selected option wasn't found in the original map
426	return SelectionOption{}, fmt.Errorf("selected option not found in original list")
427}
428
429// DynamicSelect displays a simple selection prompt without extra features
430func DynamicSelect(options map[string]string, addnewoption bool) (SelectionOption, error) {
431
432	if GetGlobalConfig().RofiSelection {
433		return RofiSelect(options, addnewoption)
434	}
435
436	model := &Model{
437		options:      options,
438		filteredKeys: make([]SelectionOption, 0),
439		addNewOption: addnewoption,
440	}
441
442	model.filterOptions()
443	p := tea.NewProgram(model)
444
445	finalModel, err := p.Run()
446	if err != nil {
447		return SelectionOption{}, err
448	}
449
450	finalSelectionModel, ok := finalModel.(*Model)
451	if !ok {
452		return SelectionOption{}, fmt.Errorf("unexpected model type")
453	}
454
455	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
456		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
457	}
458	return SelectionOption{}, nil
459}