package internal import ( "bytes" "crypto/md5" "fmt" "io" "net/http" "os" "os/exec" "path/filepath" "sort" "strings" "time" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" ) // Model represents the application state for the selection prompt type Model struct { filter string filteredKeys []SelectionOption allOptions []SelectionOption selected int terminalWidth int terminalHeight int scrollOffset int addNewOption bool isHomeMenu bool // If true, ESC quits; if false, ESC goes back } func isAndroidTerminalMode() bool { config := GetGlobalConfig() return config != nil && config.IsAndroid() } var ( // Style definitions titleStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#7CB9E8")). // Light blue Bold(true) filterLabelStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#FF69B4")). // Hot pink Bold(true) filterTextStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#98FB98")) // Pale green selectedItemStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#FFFFFF")). // White text Background(lipgloss.Color("#4A90E2")). // Softer blue background Bold(true). Padding(0, 1). Border(lipgloss.NormalBorder(), false, false, false, true). // Left border only BorderForeground(lipgloss.Color("#FFFFFF")) // White border regularItemStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#E6E6FA")). // Light lavender Padding(0, 1) noMatchesStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#FF6B6B")). // Coral red Italic(true) quitHintStyle = lipgloss.NewStyle(). Foreground(lipgloss.Color("#FFD700")) // Gold ) // Init initializes the model func (m Model) Init() tea.Cmd { return nil } // Update handles user input and updates the model func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // Handle terminal resize messages if wsm, ok := msg.(tea.WindowSizeMsg); ok { m.terminalWidth = wsm.Width m.terminalHeight = wsm.Height } updateFilter := false switch msg := msg.(type) { case tea.KeyMsg: switch msg.String() { case "ctrl+c": // Return quit selection option directly return m, tea.Quit case "esc": // ESC: quit on home menu, go back on sub-menus if m.isHomeMenu { // Quit m.filteredKeys = []SelectionOption{{Key: "-1", Label: "Quit"}} m.selected = 0 } else { // Go back m.filteredKeys = []SelectionOption{{Key: "-2", Label: "Back"}} m.selected = 0 } return m, tea.Quit case "backspace": if len(m.filter) > 0 { m.filter = m.filter[:len(m.filter)-1] updateFilter = true } case "down", "tab", "ctrl+n": // Move the selection cursor down if m.selected < len(m.filteredKeys)-1 { m.selected++ } // Scroll the view if necessary if m.selected >= m.scrollOffset+m.visibleItemsCount() { m.scrollOffset++ } case "up", "shift+tab", "ctrl+p": // Move the selection cursor up if m.selected > 0 { m.selected-- } // Scroll the view if necessary if m.selected < m.scrollOffset { m.scrollOffset-- } case "enter": if m.filteredKeys[m.selected].Key == "add_new" { CurdOut("Adding a new anime...") m.filteredKeys[m.selected] = SelectionOption{Label: "add_new", Key: "0"} return m, tea.Quit } return m, tea.Quit default: if len(msg.String()) == 1 && msg.String() >= " " && msg.String() <= "~" { m.filter += msg.String() updateFilter = true } } } if updateFilter { m.filterOptions() m.selected = 0 // Reset selection to the first item after filtering m.scrollOffset = 0 // Reset scrolling } return m, nil } // View renders the UI and only shows as many options as fit in the terminal func (m Model) View() string { var b strings.Builder androidMode := isAndroidTerminalMode() title := "Search" if androidMode { title = "Search Anime" } b.WriteString(titleStyle.Render(title) + "\n") if androidMode { b.WriteString(filterLabelStyle.Render("Query: ") + filterTextStyle.Render(m.filter) + "\n") } else { b.WriteString(filterLabelStyle.Render("Filter: ") + filterTextStyle.Render(m.filter) + "\n") } b.WriteString("\n") if len(m.filteredKeys) == 0 { b.WriteString(noMatchesStyle.Render("No matches found.") + "\n") } else { visibleItems := m.visibleItemsCount() start := m.scrollOffset end := start + visibleItems if end > len(m.filteredKeys) { end = len(m.filteredKeys) } // Render the options within the visible range for i := start; i < end; i++ { label := m.filteredKeys[i].Label if androidMode { label = " " + label } if i == m.selected { b.WriteString(selectedItemStyle.Render(label) + "\n") } else { b.WriteString(regularItemStyle.Render(label) + "\n") } if androidMode { b.WriteString("\n") } } } if androidMode { footer := "Enter select Esc back Ctrl+C quit Type to search" if m.isHomeMenu { footer = "Enter select Esc quit Ctrl+C quit Type to search" } b.WriteString("\n" + quitHintStyle.Render(footer)) } return b.String() } // visibleItemsCount calculates how many options fit in the terminal func (m Model) visibleItemsCount() int { // Leave space for the filter and other UI elements if isAndroidTerminalMode() { return max(1, (m.terminalHeight-6)/2) } return max(1, m.terminalHeight-4) } // filterOptions filters and sorts options based on the search term func (m *Model) filterOptions() { m.filteredKeys = nil for _, opt := range m.allOptions { if strings.Contains(strings.ToLower(opt.Label), strings.ToLower(m.filter)) { m.filteredKeys = append(m.filteredKeys, opt) } } // Sort the filtered options alphabetically unless this is a menu selection isMenu := false for _, opt := range m.allOptions { if opt.Key == "ALL" || opt.Key == "CURRENT" { isMenu = true break } } if !isMenu { sort.Slice(m.filteredKeys, func(i, j int) bool { return m.filteredKeys[i].Label < m.filteredKeys[j].Label }) } // Add "Add new anime" option if enabled if m.addNewOption { m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Add new anime", Key: "add_new"}) } // Add Back option before Quit (only for non-home menus) if !m.isHomeMenu { m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Back", Key: "-2"}) } m.filteredKeys = append(m.filteredKeys, SelectionOption{Label: "Quit", Key: "-1"}) } func DynamicSelectPreview(options map[string]RofiSelectPreview, addnewoption bool) (SelectionOption, error) { go preDownloadImages(options, 14) userCurdConfig := GetGlobalConfig() if userCurdConfig.StoragePath == "" { userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") } var rofiInput strings.Builder selectionOptions := make([]SelectionOption, 0, len(options)) // Prepare options and rofi input for id, opt := range options { cachePath, err := downloadToCache(opt.CoverImage) if err != nil { Log(fmt.Sprintf("Error caching image: %v", err)) continue } rofiInput.WriteString(fmt.Sprintf("%s\x00icon\x1f%s\n", opt.Title, cachePath)) selectionOptions = append(selectionOptions, SelectionOption{ Label: opt.Title, Key: id, }) } if addnewoption { rofiInput.WriteString("Add new anime\n") } // Add Back option before Quit (this is always a sub-menu when using preview) rofiInput.WriteString("Back\n") rofiInput.WriteString("Quit\n") // Run rofi configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanimepreview.rasi") cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-show-icons", "-p", "Select Anime", "-i", "-no-custom") cmd.Stdin = strings.NewReader(rofiInput.String()) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr if err := cmd.Run(); err != nil { Log(fmt.Sprintf("Rofi stderr: %s", stderr.String())) Log(fmt.Sprintf("Rofi stdout: %s", stdout.String())) // ESC pressed or rofi closed - return back return SelectionOption{Key: "-2", Label: "Back"}, nil } selected := strings.TrimSpace(stdout.String()) // Handle special cases switch selected { case "": // Empty selection - go back return SelectionOption{Key: "-2", Label: "Back"}, nil case "Add new anime": return SelectionOption{Label: "Add new anime", Key: "add_new"}, nil case "Back": return SelectionOption{Label: "Back", Key: "-2"}, nil case "Quit": return SelectionOption{Label: "Quit", Key: "-1"}, nil } // Find matching option for _, opt := range selectionOptions { if opt.Label == selected { return opt, nil } } return SelectionOption{}, fmt.Errorf("selection not found in options") } func preDownloadImages(options map[string]RofiSelectPreview, count int) { i := 0 for _, option := range options { if i >= count { break } downloadToCache(option.CoverImage) i++ } } func downloadToCache(imageURL string) (string, error) { cacheDir := os.ExpandEnv("${HOME}/.cache/curd/images") if err := os.MkdirAll(cacheDir, 0755); err != nil { return "", fmt.Errorf("failed to create cache directory: %w", err) } // Create a hash of the URL to use as filename filename := fmt.Sprintf("%x.jpg", md5.Sum([]byte(imageURL))) cachePath := filepath.Join(cacheDir, filename) // Check if file already exists in cache if _, err := os.Stat(cachePath); err == nil { return cachePath, nil } // Download the image resp, err := http.Get(imageURL) if err != nil { return "", err } defer resp.Body.Close() file, err := os.Create(cachePath) if err != nil { return "", err } defer file.Close() _, err = io.Copy(file, resp.Body) if err != nil { os.Remove(cachePath) // Clean up on error return "", err } return cachePath, nil } func showCachedImagePreview(imageURL string) error { cachePath, err := downloadToCache(imageURL) if err != nil { return err } // Display the image with ueberzugpp cmd := exec.Command("ueberzugpp", "layer", "--silent", "add", "preview", "--path", cachePath) err = cmd.Start() if err != nil { return fmt.Errorf("failed to start image preview: %w", err) } time.Sleep(2 * time.Second) // Allow image to load for a moment return nil } func RofiSelect(options []SelectionOption, isHomeMenu bool) (SelectionOption, error) { userCurdConfig := GetGlobalConfig() if userCurdConfig.StoragePath == "" { userCurdConfig.StoragePath = os.ExpandEnv("${HOME}/.local/share/curd") } // Create ordered list of options var optionsList []string for _, opt := range options { optionsList = append(optionsList, opt.Label) } // Add "Back" option before "Quit" (only for non-home menus) if !isHomeMenu { optionsList = append(optionsList, "Back") } // Add "Quit" option at the end optionsList = append(optionsList, "Quit") optionsString := strings.Join(optionsList, "\n") // Prepare and run rofi configPath := filepath.Join(os.ExpandEnv(userCurdConfig.StoragePath), "selectanime.rasi") cmd := exec.Command("rofi", "-dmenu", "-theme", configPath, "-i", "-p", "Select") cmd.Stdin = strings.NewReader(optionsString) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() if err != nil { if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 { // ESC pressed or rofi closed: go back on sub-menus, quit on home menu if isHomeMenu { return SelectionOption{Key: "-1", Label: "Quit"}, nil } return SelectionOption{Key: "-2", Label: "Back"}, nil } return SelectionOption{}, fmt.Errorf("failed to run Rofi: %v", err) } selected := strings.TrimSpace(stdout.String()) // Handle special cases switch selected { case "": // Empty selection: go back on sub-menus, quit on home menu if isHomeMenu { return SelectionOption{Key: "-1", Label: "Quit"}, nil } return SelectionOption{Key: "-2", Label: "Back"}, nil case "Back": return SelectionOption{Label: "Back", Key: "-2"}, nil case "Quit": return SelectionOption{Label: "Quit", Key: "-1"}, nil } // Find the matching SelectionOption for _, opt := range options { if opt.Label == selected { return opt, nil } } return SelectionOption{}, fmt.Errorf("selected option not found in original list") } func DynamicSelectFromSlice(options []SelectionOption) (SelectionOption, error) { // Detect if this is a home menu by checking for category keys isHomeMenu := false for _, opt := range options { if opt.Key == "ALL" || opt.Key == "CURRENT" { isHomeMenu = true break } } if GetGlobalConfig().RofiSelection { return RofiSelect(options, isHomeMenu) } model := &Model{ allOptions: options, isHomeMenu: isHomeMenu, } model.filterOptions() // Initialize filtered options p := tea.NewProgram(model) finalModel, err := p.Run() if err != nil { return SelectionOption{}, err } // resetting terminal state fmt.Print("\033[?25h") // show cursor fmt.Print("\033[?7h") // line wrapping finalSelectionModel, ok := finalModel.(*Model) if !ok { return SelectionOption{}, fmt.Errorf("unexpected model type") } if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) { return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil } return SelectionOption{}, nil } // DynamicSelect displays a simple selection prompt without extra features func DynamicSelect(options []SelectionOption) (SelectionOption, error) { // Detect if this is a home menu by checking for category keys isHomeMenu := false for _, opt := range options { if opt.Key == "ALL" || opt.Key == "CURRENT" { isHomeMenu = true break } } if GetGlobalConfig().RofiSelection { return RofiSelect(options, isHomeMenu) } // Sort options if this contains menu categories if isHomeMenu { menuOrder := strings.Split(GetGlobalConfig().MenuOrder, ",") optMap := make(map[string]SelectionOption) for _, opt := range options { optMap[opt.Key] = opt } sorted := make([]SelectionOption, 0, len(options)) for _, key := range menuOrder { if opt, exists := optMap[key]; exists { sorted = append(sorted, opt) } } options = sorted } model := &Model{ allOptions: options, isHomeMenu: isHomeMenu, } model.filterOptions() // Initialize filtered options p := tea.NewProgram(model) finalModel, err := p.Run() if err != nil { return SelectionOption{}, err } fmt.Print("\033[?25h") // Show cursor fmt.Print("\033[?7h") // Enable line wrapping finalSelectionModel, ok := finalModel.(*Model) if !ok { return SelectionOption{}, fmt.Errorf("unexpected model type") } // Check if the program was quit with Ctrl+C if err != nil { return SelectionOption{Key: "-1", Label: "Quit"}, nil } if finalSelectionModel.selected < len(finalSelectionModel.filteredKeys) { return finalSelectionModel.filteredKeys[finalSelectionModel.selected], nil } return SelectionOption{}, nil }