internal/selection_menu.go

425 lines · 11364 bytes

  1package internal
  2
  3import (
  4	"bytes"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"os"
  9	"os/exec"
 10	"sort"
 11	"strings"
 12	"time"
 13	"github.com/charmbracelet/bubbletea"
 14	"crypto/md5"
 15	"path/filepath"
 16)
 17
 18// SelectionOption holds the label and the internal key
 19type SelectionOption struct {
 20	Label string
 21	Key   string
 22}
 23
 24// Model represents the application state for the selection prompt
 25type Model struct {
 26	options        map[string]string
 27	filter         string
 28	filteredKeys   []SelectionOption
 29	selected       int
 30	terminalWidth  int
 31	terminalHeight int
 32	scrollOffset   int // Track the topmost visible item
 33	addNewOption   bool  // Add this field
 34}
 35
 36// Init initializes the model
 37func (m Model) Init() tea.Cmd {
 38	return nil
 39}
 40
 41// Update handles user input and updates the model
 42func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 43	// Handle terminal resize messages
 44	if wsm, ok := msg.(tea.WindowSizeMsg); ok {
 45		m.terminalWidth = wsm.Width
 46		m.terminalHeight = wsm.Height
 47	}
 48
 49	updateFilter := false
 50
 51	switch msg := msg.(type) {
 52	case tea.KeyMsg:
 53		switch msg.String() {
 54		case "ctrl+c", "q":
 55			// Return quit selection option instead of quitting the program
 56			m.filteredKeys[m.selected] = SelectionOption{"quit", "-1"}
 57			return m, tea.Quit // Properly exit the program
 58		case "backspace":
 59			if len(m.filter) > 0 {
 60				m.filter = m.filter[:len(m.filter)-1]
 61				updateFilter = true
 62			}
 63		case "down":
 64			// Move the selection cursor down
 65			if m.selected < len(m.filteredKeys)-1 {
 66				m.selected++
 67			}
 68
 69			// Scroll the view if necessary
 70			if m.selected >= m.scrollOffset+m.visibleItemsCount() {
 71				m.scrollOffset++
 72			}
 73		case "up":
 74			// Move the selection cursor up
 75			if m.selected > 0 {
 76				m.selected--
 77			}
 78
 79			// Scroll the view if necessary
 80			if m.selected < m.scrollOffset {
 81				m.scrollOffset--
 82			}
 83		case "enter":
 84			if m.filteredKeys[m.selected].Key == "add_new" {
 85				CurdOut("Adding a new anime...")
 86				m.filteredKeys[m.selected] = SelectionOption{"add_new", "0"}
 87				return m, tea.Quit
 88			}
 89			return m, tea.Quit
 90		default:
 91			if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
 92				m.filter += msg.String()
 93				updateFilter = true
 94			}
 95		}
 96	}
 97
 98	if updateFilter {
 99		m.filterOptions()
100		m.selected = 0     // Reset selection to the first item after filtering
101		m.scrollOffset = 0 // Reset scrolling
102	}
103
104	return m, nil
105}
106
107// View renders the UI and only shows as many options as fit in the terminal
108func (m Model) View() string {
109	var b strings.Builder
110
111	// Display the search prompt and filter
112	b.WriteString("Search (Press Ctrl+C to quit):\n")
113	b.WriteString("Filter: " + m.filter + "\n")
114
115	if len(m.filteredKeys) == 0 {
116		b.WriteString("\nNo matches found.\n")
117	} else {
118		visibleItems := m.visibleItemsCount()
119
120		// Determine the slice of items to display based on scroll offset
121		start := m.scrollOffset
122		end := start + visibleItems
123		if end > len(m.filteredKeys) {
124			end = len(m.filteredKeys)
125		}
126
127		// Render the options within the visible range
128		for i := start; i < end; i++ {
129			if i == m.selected {
130				b.WriteString(fmt.Sprintf("▶ %s\n", m.filteredKeys[i].Label)) // Highlight the selected option
131			} else {
132				b.WriteString(fmt.Sprintf("  %s\n", m.filteredKeys[i].Label)) // Regular option
133			}
134		}
135	}
136
137	return b.String()
138}
139
140// visibleItemsCount calculates how many options fit in the terminal
141func (m Model) visibleItemsCount() int {
142	// Leave space for the filter and other UI elements
143	return m.terminalHeight - 4 // Adjust this number based on your terminal layout
144}
145
146// filterOptions filters and sorts options based on the search term
147func (m *Model) filterOptions() {
148	m.filteredKeys = []SelectionOption{}
149
150	for key, value := range m.options {
151		// When the key is " ", compare and display using the value instead
152		if key == " " {
153			if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
154				m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
155			}
156		} else if strings.Contains(strings.ToLower(value), strings.ToLower(m.filter)) {
157			m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: value, Key: key})
158		}
159	}
160
161	// Sort the filtered options alphabetically
162	sort.Slice(m.filteredKeys, func(i, j int) bool {
163		return m.filteredKeys[i].Label < m.filteredKeys[j].Label
164	})
165
166	// Add "Add new anime" option if enabled
167	if m.addNewOption {
168		m.filteredKeys = append(m.filteredKeys, SelectionOption{
169			Label: "Add new anime",
170			Key:   "add_new",
171		})
172	}
173
174	m.filteredKeys = append(m.filteredKeys, SelectionOption{
175		Label: "Quit",
176		Key:   "-1",
177	})
178}
179
180
181func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
182	// Pre-download first 14 images in background
183	go preDownloadImages(options, 14)
184
185	userCurdConfig := GetGlobalConfig()
186	if userCurdConfig.StoragePath == "" {
187		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
188	}
189
190	// Prepare Rofi input with anime titles and their cached image paths
191	var rofiInput strings.Builder
192	for _, option := range options {
193		// Download and get cache path for the image
194		cachePath, err := downloadToCache(option.CoverImage)
195		if err != nil {
196			Log(fmt.Sprintf("Error caching image: %v", err), logFile)
197			continue
198		}
199		
200		// Format: "Title\x00icon\x1f/path/to/cached/image\n"
201		// This tells Rofi to use the image as an icon for this entry
202		rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", option.Title, cachePath))
203	}
204
205	// Add "Add new anime" and "Quit" options
206	if addnewoption {
207		rofiInput.WriteString("Add new anime\n")
208	}
209	rofiInput.WriteString("Quit\n")
210
211	// Get the absolute path to the rasi config
212	configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi")
213	
214	// Create the command with explicit arguments
215	args := []string{
216		"-dmenu",
217		"-theme", configPath,
218		"-show-icons",
219		"-p", "Select Anime",
220		"-i",  // Case-insensitive matching
221		"-no-custom",  // Disable custom input
222	}
223	
224	// Create the command
225	rofiCmd := exec.Command("rofi", args...)
226
227	// Set up pipes for input/output
228	rofiCmd.Stdin = strings.NewReader(rofiInput.String())
229	var stdout, stderr bytes.Buffer
230	rofiCmd.Stdout = &stdout
231	rofiCmd.Stderr = &stderr
232	
233	// Run the command
234	err := rofiCmd.Run()
235	if err != nil {
236		// Log both stdout and stderr for debugging
237		Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()), logFile)
238		Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()), logFile)
239		return SelectionOption{}, fmt.Errorf("failed to execute rofi: %w", err)
240	}
241	
242	selectedTitle := strings.TrimSpace(stdout.String())
243
244	// Handle special cases
245	switch selectedTitle {
246	case "":
247		return SelectionOption{}, fmt.Errorf("no selection made")
248	case "Add new anime":
249		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
250	case "Quit":
251		return SelectionOption{Label: "Quit", Key: "-1"}, nil
252	}
253
254	// Find the selected anime in options
255	for id, option := range options {
256		if option.Title == selectedTitle {
257			return SelectionOption{
258				Label: option.Title,
259				Key:   id,
260			}, nil
261		}
262	}
263
264	return SelectionOption{}, fmt.Errorf("selection not found in options")
265}
266
267func preDownloadImages(options map[string]RofiSelectPreview, count int) {
268	i := 0
269	for _, option := range options {
270		if i >= count {
271			break
272		}
273		downloadToCache(option.CoverImage)
274		i++
275	}
276}
277
278func downloadToCache(imageURL string) (string, error) {
279	cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
280	if err := os.MkdirAll(cacheDir, 0755); err != nil {
281		return "", fmt.Errorf("failed to create cache directory: %w", err)
282	}
283
284	// Create a hash of the URL to use as filename
285	filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
286	cachePath := filepath.Join(cacheDir, filename)
287
288	// Check if file already exists in cache
289	if _, err := os.Stat(cachePath); err == nil {
290		return cachePath, nil
291	}
292
293	// Download the image
294	resp, err := http.Get(imageURL)
295	if err != nil {
296		return "", err
297	}
298	defer resp.Body.Close()
299
300	file, err := os.Create(cachePath)
301	if err != nil {
302		return "", err
303	}
304	defer file.Close()
305
306	_, err = io.Copy(file, resp.Body)
307	if err != nil {
308		os.Remove(cachePath) // Clean up on error
309		return "", err
310	}
311
312	return cachePath, nil
313}
314
315func showCachedImagePreview(imageURL string) error {
316	cachePath, err := downloadToCache(imageURL)
317	if err != nil {
318		return err
319	}
320
321	// Display the image with ueberzugpp
322	cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
323	err = cmd.Start()
324	if err != nil {
325		return fmt.Errorf("failed to start image preview: %w", err)
326	}
327	time.Sleep(2 * time.Second) // Allow image to load for a moment
328	return nil
329}
330
331
332func RofiSelect(options map[string]string, addanimeopt bool) (SelectionOption, error) {
333	userCurdConfig := GetGlobalConfig()
334	if userCurdConfig.StoragePath == "" {
335		userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd")
336	}
337
338	// Create a slice to store the options in the order we want
339	var optionsList []string
340	for _, value := range options {
341		optionsList = append(optionsList, value)
342	}
343	
344	// Sort the options alphabetically
345	sort.Strings(optionsList)
346	
347	// Add "Add new anime" and "Quit" options
348	if addanimeopt {
349		optionsList = append(optionsList, "Add new anime", "Quit")
350	} else {
351		optionsList = append(optionsList, "Quit")
352	}
353	
354	// Join all options into a single string, separated by newlines
355	optionsString := strings.Join(optionsList, "\n")
356	
357	// Prepare the Rofi command
358	cmd := exec.Command("rofi", "-dmenu", "-theme", filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi"), "-i", "-p", "Select an anime")
359	
360	// Set up pipes for input and output
361	cmd.Stdin = strings.NewReader(optionsString)
362	var out bytes.Buffer
363	cmd.Stdout = &out
364	
365	// Run the command
366	err := cmd.Run()
367	if err != nil {
368		return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
369	}
370	
371	// Get the selected option
372	selected := strings.TrimSpace(out.String())
373	
374	// Handle special cases
375	switch selected {
376	case "":
377		return SelectionOption{}, fmt.Errorf("no selection made")
378	case "Add new anime":
379		return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
380	case "Quit":
381		return SelectionOption{Label: "Quit", Key: "-1"}, nil
382	}
383	
384	// Find the key for the selected value
385	for key, value := range options {
386		if value == selected {
387			return SelectionOption{Label: value, Key: key}, nil
388		}
389	}
390	
391	// If we get here, the selected option wasn't found in the original map
392	return SelectionOption{}, fmt.Errorf("selected option not found in original list")
393}
394
395// DynamicSelect displays a simple selection prompt without extra features
396func DynamicSelect(options map[string]string, addnewoption bool) (SelectionOption, error) {
397
398	if GetGlobalConfig().RofiSelection {
399		return RofiSelect(options, addnewoption)
400	}
401
402	model := &Model{
403		options:      options,
404		filteredKeys: make([]SelectionOption, 0),
405		addNewOption: addnewoption,
406	}
407
408	model.filterOptions()
409	p := tea.NewProgram(model)
410
411	finalModel, err := p.Run()
412	if err != nil {
413		return SelectionOption{}, err
414	}
415
416	finalSelectionModel, ok := finalModel.(*Model)
417	if !ok {
418		return SelectionOption{}, fmt.Errorf("unexpected model type")
419	}
420
421	if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
422		return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
423	}
424	return SelectionOption{}, nil
425}