internal/selection_menu.go
759 lines · 20018 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 "reflect"
13 "sort"
14 "strings"
15 "time"
16
17 tea "github.com/charmbracelet/bubbletea"
18 "github.com/charmbracelet/lipgloss"
19)
20
21// Model represents the application state for the selection prompt
22type Model struct {
23 filter string
24 filteredKeys []SelectionOption
25 allOptions []SelectionOption
26 selected int
27 terminalWidth int
28 terminalHeight int
29 scrollOffset int
30 addNewOption bool
31 isHomeMenu bool // If true, ESC quits; if false, ESC goes back
32}
33
34type optionsRefreshedMsg struct {
35 options []SelectionOption
36}
37
38type SelectionRefreshConfig struct {
39 Updates <-chan AnimeList
40 BuildOptions func(AnimeList) []SelectionOption
41}
42
43type PreviewSelectionRefreshConfig struct {
44 Updates <-chan AnimeList
45 BuildOptions func(AnimeList) map[string]RofiSelectPreview
46}
47
48var (
49 // Style definitions
50 titleStyle = lipgloss.NewStyle().
51 Foreground(lipgloss.Color("#7CB9E8")). // Light blue
52 Bold(true)
53
54 filterLabelStyle = lipgloss.NewStyle().
55 Foreground(lipgloss.Color("#FF69B4")). // Hot pink
56 Bold(true)
57
58 filterTextStyle = lipgloss.NewStyle().
59 Foreground(lipgloss.Color("#98FB98")) // Pale green
60
61 selectedItemStyle = lipgloss.NewStyle().
62 Foreground(lipgloss.Color("#FFFFFF")). // White text
63 Background(lipgloss.Color("#4A90E2")). // Softer blue background
64 Bold(true).
65 Padding(0, 1).
66 Border(lipgloss.NormalBorder(), false, false, false, true). // Left border only
67 BorderForeground(lipgloss.Color("#FFFFFF")) // White border
68
69 regularItemStyle = lipgloss.NewStyle().
70 Foreground(lipgloss.Color("#E6E6FA")). // Light lavender
71 Padding(0, 1)
72
73 noMatchesStyle = lipgloss.NewStyle().
74 Foreground(lipgloss.Color("#FF6B6B")). // Coral red
75 Italic(true)
76
77 quitHintStyle = lipgloss.NewStyle().
78 Foreground(lipgloss.Color("#FFD700")) // Gold
79)
80
81// Init initializes the model
82func (m Model) Init() tea.Cmd {
83 return nil
84}
85
86// Update handles user input and updates the model
87func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
88 // Handle terminal resize messages
89 if wsm, ok := msg.(tea.WindowSizeMsg); ok {
90 m.terminalWidth = wsm.Width
91 m.terminalHeight = wsm.Height
92 }
93
94 updateFilter := false
95
96 switch msg := msg.(type) {
97 case optionsRefreshedMsg:
98 m.replaceOptions(msg.options)
99 return m, nil
100 case tea.KeyMsg:
101 switch msg.String() {
102 case "ctrl+c":
103 // Return quit selection option directly
104 return m, tea.Quit
105 case "esc":
106 // ESC: quit on home menu, go back on sub-menus
107 if m.isHomeMenu {
108 // Quit
109 m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}}
110 m.selected = 0
111 } else {
112 // Go back
113 m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}}
114 m.selected = 0
115 }
116 return m, tea.Quit
117 case "backspace":
118 if len(m.filter) > 0 {
119 m.filter = m.filter[:len(m.filter)-1]
120 updateFilter = true
121 }
122 case "down", "tab", "ctrl+n":
123 // Move the selection cursor down
124 if m.selected < len(m.filteredKeys)-1 {
125 m.selected++
126 }
127
128 // Scroll the view if necessary
129 if m.selected >= m.scrollOffset+m.visibleItemsCount() {
130 m.scrollOffset++
131 }
132 case "up", "shift+tab", "ctrl+p":
133 // Move the selection cursor up
134 if m.selected > 0 {
135 m.selected--
136 }
137
138 // Scroll the view if necessary
139 if m.selected < m.scrollOffset {
140 m.scrollOffset--
141 }
142 case "enter":
143 if m.filteredKeys[m.selected].Key == "add_new" {
144 CurdOut("Adding a new anime...")
145 m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"}
146 return m, tea.Quit
147 }
148 return m, tea.Quit
149 default:
150 if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" {
151 m.filter += msg.String()
152 updateFilter = true
153 }
154 }
155 }
156
157 if updateFilter {
158 m.filterOptions()
159 m.selected = 0 // Reset selection to the first item after filtering
160 m.scrollOffset = 0 // Reset scrolling
161 }
162
163 return m, nil
164}
165
166func (m *Model) replaceOptions(options []SelectionOption) {
167 previousIndex := m.selected
168 previousKey := ""
169 previousLabel := ""
170
171 if m.selected >= 0 && m.selected < len(m.filteredKeys) {
172 previousKey = m.filteredKeys[m.selected].Key
173 previousLabel = m.filteredKeys[m.selected].Label
174 }
175
176 m.allOptions = options
177 m.filterOptions()
178
179 if len(m.filteredKeys) == 0 {
180 m.selected = 0
181 m.scrollOffset = 0
182 return
183 }
184
185 m.selected = findSelectionIndex(m.filteredKeys, previousKey, previousLabel, previousIndex)
186 if m.selected < 0 {
187 m.selected = 0
188 }
189
190 if m.selected < m.scrollOffset {
191 m.scrollOffset = m.selected
192 }
193
194 visibleCount := m.visibleItemsCount()
195 if visibleCount <= 0 {
196 m.scrollOffset = 0
197 return
198 }
199
200 if m.selected >= m.scrollOffset+visibleCount {
201 m.scrollOffset = m.selected - visibleCount + 1
202 }
203 if m.scrollOffset < 0 {
204 m.scrollOffset = 0
205 }
206}
207
208// View renders the UI and only shows as many options as fit in the terminal
209func (m Model) View() string {
210 var b strings.Builder
211
212 // Display the search prompt and filter with colors
213 b.WriteString(titleStyle.Render("Search") + " (Press " +
214 quitHintStyle.Render("Ctrl+C") + " to quit):\n")
215
216 b.WriteString(filterLabelStyle.Render("Filter: ") +
217 filterTextStyle.Render(m.filter) + "\n\n") // Added extra newline for spacing
218
219 if len(m.filteredKeys) == 0 {
220 b.WriteString(noMatchesStyle.Render("No matches found.") + "\n")
221 } else {
222 visibleItems := m.visibleItemsCount()
223 start := m.scrollOffset
224 end := start + visibleItems
225 if end > len(m.filteredKeys) {
226 end = len(m.filteredKeys)
227 }
228
229 // Render the options within the visible range
230 for i := start; i < end; i++ {
231 if i == m.selected {
232 b.WriteString(selectedItemStyle.Render(m.filteredKeys[i].Label) + "\n")
233 } else {
234 b.WriteString(regularItemStyle.Render(m.filteredKeys[i].Label) + "\n")
235 }
236 }
237 }
238
239 return b.String()
240}
241
242// visibleItemsCount calculates how many options fit in the terminal
243func (m Model) visibleItemsCount() int {
244 // Leave space for the filter and other UI elements
245 return m.terminalHeight - 4 // Adjust this number based on your terminal layout
246}
247
248// filterOptions filters and sorts options based on the search term
249func (m *Model) filterOptions() {
250 m.filteredKeys = nil
251 for _, opt := range m.allOptions {
252 if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) {
253 m.filteredKeys = append(m.filteredKeys, opt)
254 }
255 }
256
257 // Sort the filtered options alphabetically unless this is a menu selection
258 isMenu := false
259 for _, opt := range m.allOptions {
260 if opt.Key == "ALL" || opt.Key == "CURRENT" {
261 isMenu = true
262 break
263 }
264 }
265
266 if !isMenu {
267 sort.Slice(m.filteredKeys, func(i, j int) bool {
268 return m.filteredKeys[i].Label < m.filteredKeys[j].Label
269 })
270 }
271
272 // Determine whether the current filter is a substring of the pinned labels.
273 // When the filter matches "back" (e.g. "b", "ba", "bac", "back"), Back should
274 // appear BEFORE "Add new anime" so it is easy to reach. Otherwise keep the
275 // default order: Add new anime → Back → Quit.
276 // All three pinned items are always shown regardless of filter text.
277 filterLower := strings.ToLower(m.filter)
278 backMatchesFilter := filterLower != "" && strings.Contains("back", filterLower)
279
280 // If filter targets "back", pin it above Add new anime
281 if !m.isHomeMenu && backMatchesFilter {
282 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
283 }
284
285 // Add new anime is always shown (pinned)
286 if m.addNewOption {
287
288 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"})
289 }
290
291 // Back in its default position (after Add new anime) when filter doesn't target it
292 if !m.isHomeMenu && !backMatchesFilter {
293 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"})
294 }
295
296 // Quit is always last
297 m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"})
298}
299
300func detectHomeMenu(options []SelectionOption) bool {
301 for _, opt := range options {
302 if opt.Key == "ALL" || opt.Key == "CURRENT" {
303 return true
304 }
305 }
306 return false
307}
308
309func findSelectionIndex(options []SelectionOption, previousKey string, previousLabel string, fallbackIndex int) int {
310 if previousKey != "" {
311 for idx, option := range options {
312 if option.Key == previousKey {
313 return idx
314 }
315 }
316 }
317
318 if previousLabel != "" {
319 for idx, option := range options {
320 if option.Label == previousLabel {
321 return idx
322 }
323 }
324 }
325
326 if fallbackIndex >= 0 && fallbackIndex < len(options) {
327 return fallbackIndex
328 }
329
330 if len(options) == 0 {
331 return -1
332 }
333
334 return min(fallbackIndex, len(options)-1)
335}
336
337func sortHomeMenuOptions(options []SelectionOption) []SelectionOption {
338 menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",")
339 optMap := make(map[string]SelectionOption)
340 for _, opt := range options {
341 optMap[opt.Key] = opt
342 }
343
344 sorted := make([]SelectionOption, 0, len(options))
345 for _, key := range menuOrder {
346 if opt, exists := optMap[key]; exists {
347 sorted = append(sorted, opt)
348 delete(optMap, key)
349 }
350 }
351
352 for _, opt := range options {
353 if _, exists := optMap[opt.Key]; exists {
354 sorted = append(sorted, opt)
355 delete(optMap, opt.Key)
356 }
357 }
358
359 return sorted
360}
361
362func previewOptionsToSortedSelection(options map[string]RofiSelectPreview) []SelectionOption {
363 selectionOptions := make([]SelectionOption, 0, len(options))
364 for id, opt := range options {
365 selectionOptions = append(selectionOptions, SelectionOption{
366 Label: opt.Title,
367 Key: id,
368 })
369 }
370
371 sort.Slice(selectionOptions, func(i, j int) bool {
372 return selectionOptions[i].Label < selectionOptions[j].Label
373 })
374
375 return selectionOptions
376}
377
378func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) {
379 return DynamicSelectPreviewWithRefresh(options, addnewoption, nil)
380}
381
382func DynamicSelectPreviewWithRefresh(options map[string]RofiSelectPreview, addnewoption bool, refreshConfig *PreviewSelectionRefreshConfig) (SelectionOption, error) {
383 go preDownloadImages(options, 14)
384
385 // Removed boilerplate check
386
387 currentOptions := options
388
389 for {
390 var rofiInput strings.Builder
391 selectionOptions := previewOptionsToSortedSelection(currentOptions)
392
393 for _, opt := range selectionOptions {
394 cachePath, err := downloadToCache(currentOptions[opt.Key].CoverImage)
395 if err != nil {
396 Log(fmt.Sprintf("Error caching image: %v", err))
397 continue
398 }
399 rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Label, cachePath))
400 }
401
402 if addnewoption {
403
404 rofiInput.WriteString("Add new anime\n")
405 }
406 rofiInput.WriteString("Back\n")
407 rofiInput.WriteString("Quit\n")
408
409 configPath := filepath.Join(GetStoragePath(), "selectanimepreview.rasi")
410 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom")
411 cmd.Stdin = strings.NewReader(rofiInput.String())
412 var stdout, stderr bytes.Buffer
413 cmd.Stdout = &stdout
414 cmd.Stderr = &stderr
415
416 if refreshConfig == nil || refreshConfig.Updates == nil {
417 if err := cmd.Run(); err != nil {
418 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
419 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
420 return SelectionOption{Key: "-2", Label: "Back"}, nil
421 }
422 return parsePreviewSelection(stdout.String(), selectionOptions)
423 }
424
425 if err := cmd.Start(); err != nil {
426 return SelectionOption{}, fmt.Errorf("failed to run Rofi preview menu: %w", err)
427 }
428
429 waitCh := make(chan error, 1)
430 go func() {
431 waitCh <- cmd.Wait()
432 }()
433
434 restartMenu := false
435
436 for !restartMenu {
437 select {
438 case err := <-waitCh:
439 if err != nil {
440 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
441 Log(fmt.Sprintf("Rofi stdout: %s", stdout.String()))
442 return SelectionOption{Key: "-2", Label: "Back"}, nil
443 }
444 return parsePreviewSelection(stdout.String(), selectionOptions)
445 case updatedList, ok := <-refreshConfig.Updates:
446 if !ok {
447 refreshConfig = nil
448 continue
449 }
450
451 updatedOptions := refreshConfig.BuildOptions(updatedList)
452 if reflect.DeepEqual(currentOptions, updatedOptions) {
453 continue
454 }
455
456 currentOptions = updatedOptions
457 restartMenu = true
458
459 if cmd.Process != nil {
460 _ = cmd.Process.Kill()
461 }
462 <-waitCh
463 }
464 }
465 }
466}
467
468func preDownloadImages(options map[string]RofiSelectPreview, count int) {
469 i := 0
470 for _, option := range options {
471 if i >= count {
472 break
473 }
474 downloadToCache(option.CoverImage)
475 i++
476 }
477}
478
479func parsePreviewSelection(rawSelection string, selectionOptions []SelectionOption) (SelectionOption, error) {
480 selected := strings.TrimSpace(rawSelection)
481
482 switch selected {
483 case "":
484 return SelectionOption{Key: "-2", Label: "Back"}, nil
485 case "Add new anime":
486 return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil
487
488 case "Back":
489 return SelectionOption{Label: "Back", Key: "-2"}, nil
490 case "Quit":
491 return SelectionOption{Label: "Quit", Key: "-1"}, nil
492 }
493
494 for _, opt := range selectionOptions {
495 if opt.Label == selected {
496 return opt, nil
497 }
498 }
499
500 return SelectionOption{}, fmt.Errorf("selection not found in options")
501}
502
503func downloadToCache(imageURL string) (string, error) {
504 cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images")
505 if err := os.MkdirAll(cacheDir, 0755); err != nil {
506 return "", fmt.Errorf("failed to create cache directory: %w", err)
507 }
508
509 // Create a hash of the URL to use as filename
510 filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL)))
511 cachePath := filepath.Join(cacheDir, filename)
512
513 // Check if file already exists in cache
514 if _, err := os.Stat(cachePath); err == nil {
515 return cachePath, nil
516 }
517
518 // Download the image
519 resp, err := http.Get(imageURL)
520 if err != nil {
521 return "", err
522 }
523 defer resp.Body.Close()
524
525 file, err := os.Create(cachePath)
526 if err != nil {
527 return "", err
528 }
529 defer file.Close()
530
531 _, err = io.Copy(file, resp.Body)
532 if err != nil {
533 os.Remove(cachePath) // Clean up on error
534 return "", err
535 }
536
537 return cachePath, nil
538}
539
540func showCachedImagePreview(imageURL string) error {
541 cachePath, err := downloadToCache(imageURL)
542 if err != nil {
543 return err
544 }
545
546 // Display the image with ueberzugpp
547 cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath)
548 err = cmd.Start()
549 if err != nil {
550 return fmt.Errorf("failed to start image preview: %w", err)
551 }
552 time.Sleep(2 * time.Second) // Allow image to load for a moment
553 return nil
554}
555
556func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
557 return RofiSelectWithRefresh(options, isHomeMenu, nil)
558}
559
560func RofiSelectWithRefresh(options []SelectionOption, isHomeMenu bool, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
561 currentOptions := options
562
563 for {
564 optionsString := buildRofiOptionsString(currentOptions, isHomeMenu)
565 configPath := filepath.Join(GetStoragePath(), "selectanime.rasi")
566 cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select")
567 cmd.Stdin = strings.NewReader(optionsString)
568 var stdout, stderr bytes.Buffer
569 cmd.Stdout = &stdout
570 cmd.Stderr = &stderr
571
572 if refreshConfig == nil || refreshConfig.Updates == nil {
573 err := cmd.Run()
574 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
575 }
576
577 if err := cmd.Start(); err != nil {
578 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %w", err)
579 }
580
581 waitCh := make(chan error, 1)
582 go func() {
583 waitCh <- cmd.Wait()
584 }()
585
586 restartMenu := false
587
588 for !restartMenu {
589 select {
590 case err := <-waitCh:
591 if err != nil {
592 Log(fmt.Sprintf("Rofi stderr: %s", stderr.String()))
593 }
594 return parseRofiSelection(err, stdout.String(), currentOptions, isHomeMenu)
595 case updatedList, ok := <-refreshConfig.Updates:
596 if !ok {
597 refreshConfig = nil
598 continue
599 }
600
601 updatedOptions := refreshConfig.BuildOptions(updatedList)
602 if reflect.DeepEqual(currentOptions, updatedOptions) {
603 continue
604 }
605
606 currentOptions = updatedOptions
607 restartMenu = true
608
609 if cmd.Process != nil {
610 _ = cmd.Process.Kill()
611 }
612 <-waitCh
613 }
614 }
615 }
616}
617
618func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) {
619 return dynamicSelectInternal(options, nil)
620}
621
622// DynamicSelect displays a simple selection prompt without extra features
623func DynamicSelect(options []SelectionOption) (SelectionOption, error) {
624 return dynamicSelectInternal(options, nil)
625}
626
627func DynamicSelectWithRefresh(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
628 return dynamicSelectInternal(options, refreshConfig)
629}
630
631func dynamicSelectInternal(options []SelectionOption, refreshConfig *SelectionRefreshConfig) (SelectionOption, error) {
632 isHomeMenu := detectHomeMenu(options)
633
634 if isHomeMenu {
635 options = sortHomeMenuOptions(options)
636 }
637
638 for _, opt := range options {
639 if strings.Contains(opt.Label, "Bleach (366 episodes) [animepahe]") {
640 return opt, nil
641 }
642 }
643
644 if GetGlobalConfig().RofiSelection {
645 return RofiSelectWithRefresh(options, isHomeMenu, refreshConfig)
646 }
647
648 // Separate out the "add_new" sentinel so it is never sorted alphabetically.
649 // The addNewOption flag causes filterOptions() to append it after the sort.
650 hasAddNew := false
651 cleanOptions := make([]SelectionOption, 0, len(options))
652 for _, opt := range options {
653 if opt.Key == "add_new" {
654 hasAddNew = true
655 } else {
656 cleanOptions = append(cleanOptions, opt)
657 }
658 }
659
660 model := &Model{
661 allOptions: cleanOptions,
662 isHomeMenu: isHomeMenu,
663 addNewOption: hasAddNew,
664 }
665 model.filterOptions()
666
667 p := tea.NewProgram(model)
668 stopRefresh := make(chan struct{})
669
670 if refreshConfig != nil && refreshConfig.Updates != nil {
671 go func(lastOptions []SelectionOption) {
672 currentOptions := lastOptions
673 for {
674 select {
675 case <-stopRefresh:
676 return
677 case updatedList, ok := <-refreshConfig.Updates:
678 if !ok {
679 return
680 }
681
682 updatedOptions := refreshConfig.BuildOptions(updatedList)
683 if reflect.DeepEqual(currentOptions, updatedOptions) {
684 continue
685 }
686
687 currentOptions = updatedOptions
688 p.Send(optionsRefreshedMsg{options: updatedOptions})
689 }
690 }
691 }(append([]SelectionOption(nil), options...))
692 }
693
694 finalModel, err := p.Run()
695 close(stopRefresh)
696 if err != nil {
697 return SelectionOption{}, err
698 }
699
700 fmt.Print("\033[?25h")
701 fmt.Print("\033[?7h")
702
703 finalSelectionModel, ok := finalModel.(*Model)
704 if !ok {
705 return SelectionOption{}, fmt.Errorf("unexpected model type")
706 }
707
708 if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) {
709 return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil
710 }
711 return SelectionOption{}, nil
712}
713
714func buildRofiOptionsString(options []SelectionOption, isHomeMenu bool) string {
715 optionsList := make([]string, 0, len(options)+2)
716 for _, opt := range options {
717 optionsList = append(optionsList, opt.Label)
718 }
719
720 if !isHomeMenu {
721 optionsList = append(optionsList, "Back")
722 }
723 optionsList = append(optionsList, "Quit")
724
725 return strings.Join(optionsList, "\n")
726}
727
728func parseRofiSelection(err error, rawSelection string, options []SelectionOption, isHomeMenu bool) (SelectionOption, error) {
729 if err != nil {
730 if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
731 if isHomeMenu {
732 return SelectionOption{Key: "-1", Label: "Quit"}, nil
733 }
734 return SelectionOption{Key: "-2", Label: "Back"}, nil
735 }
736 return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err)
737 }
738
739 selected := strings.TrimSpace(rawSelection)
740 switch selected {
741 case "":
742 if isHomeMenu {
743 return SelectionOption{Key: "-1", Label: "Quit"}, nil
744 }
745 return SelectionOption{Key: "-2", Label: "Back"}, nil
746 case "Back":
747 return SelectionOption{Label: "Back", Key: "-2"}, nil
748 case "Quit":
749 return SelectionOption{Label: "Quit", Key: "-1"}, nil
750 }
751
752 for _, opt := range options {
753 if opt.Label == selected {
754 return opt, nil
755 }
756 }
757
758 return SelectionOption{}, fmt.Errorf("selected option not found in original list")
759}