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