diff --git a/clipboardsafe/clipboardsafe.go b/clipboardsafe/clipboardsafe.go new file mode 100644 index 0000000..c884ff7 --- /dev/null +++ b/clipboardsafe/clipboardsafe.go @@ -0,0 +1,86 @@ +package clipboardsafe + +import ( + "context" + "fmt" + "io" + "os/exec" + "runtime" + "time" + + "github.com/atotto/clipboard" +) + +const ( + MaxClipboardBytes = 4 << 20 // 4 MiB + MaxClipboardStr = "4 MiB" + ClipboardTimeout = 1 * time.Second +) + +// ReadAllLimited reads clipboard content with a hard byte ceiling and timeout. +func ReadAllLimited() (string, error) { + // On Windows, atotto/clipboard uses direct Win32 API calls (user32.dll), + // which is non-streaming and already capped to a fixed memory buffer. + if runtime.GOOS == "windows" { + return limitedAtotto() + } + + if clipboard.Unsupported { + return "", fmt.Errorf("clipboard unsupported") + } + + ctx, cancel := context.WithTimeout(context.Background(), ClipboardTimeout) + defer cancel() + + var cmd *exec.Cmd + switch { + case runtime.GOOS == "darwin" && lookpath("pbpaste"): // macOS + cmd = exec.CommandContext(ctx, "pbpaste") + case lookpath("wl-paste"): // Wayland + cmd = exec.CommandContext(ctx, "wl-paste", "--no-newline") + case lookpath("xclip"): // X11 xclip + cmd = exec.CommandContext(ctx, "xclip", "-out", "-selection", "clipboard") + case lookpath("xsel"): // X11 xsel + cmd = exec.CommandContext(ctx, "xsel", "--output", "--clipboard") + default: + return limitedAtotto() + } + + out, err := cmd.StdoutPipe() + if err != nil { + return "", err + } + if err := cmd.Start(); err != nil { + return "", err + } + + limited := io.LimitReader(out, MaxClipboardBytes+1) + data, err := io.ReadAll(limited) + _ = cmd.Process.Kill() + _ = cmd.Wait() + + if err != nil { + return "", err + } + if int64(len(data)) > MaxClipboardBytes { + return "", fmt.Errorf("clipboard data exceeds %s limit", MaxClipboardStr) + } + + return string(data), nil +} + +func limitedAtotto() (string, error) { + s, err := clipboard.ReadAll() + if err != nil { + return "", err + } + if len(s) > MaxClipboardBytes { + return "", fmt.Errorf("clipboard data exceeds %s limit", MaxClipboardStr) + } + return s, nil +} + +func lookpath(bin string) bool { + _, err := exec.LookPath(bin) + return err == nil +} diff --git a/go.mod b/go.mod index a3ea95f..e004dde 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/hyuricane/cmdpp go 1.27.1 require ( + github.com/atotto/clipboard v0.1.4 github.com/charmbracelet/bubbles v1.0.0 github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 @@ -10,7 +11,6 @@ require ( ) require ( - github.com/atotto/clipboard v0.1.4 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/charmbracelet/colorprofile v0.4.1 // indirect github.com/charmbracelet/x/ansi v0.11.6 // indirect diff --git a/tui/app.go b/tui/app.go index 3d8cfe1..1fd8767 100644 --- a/tui/app.go +++ b/tui/app.go @@ -1,3 +1,4 @@ +// Package tui handles everyting TUI package tui import ( @@ -5,10 +6,12 @@ import ( "strings" "time" + "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/hyuricane/cmdpp/cli" + "github.com/hyuricane/cmdpp/clipboardsafe" "github.com/hyuricane/cmdpp/store" ) @@ -46,6 +49,7 @@ type Model struct { // NewModel initializes the TUI model. func NewModel(s *store.Store) Model { ti := textinput.New() + ti.KeyMap.Paste = key.NewBinding() ti.Placeholder = "Type to filter commands... (press / to search)" ti.CharLimit = 100 ti.Width = 60 @@ -128,6 +132,44 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case tea.KeyMsg: + // Global Paste inteceptor (ctrl+v) + if msg.String() == "ctrl+v" { + var inputModel *textinput.Model + if m.paramModal != nil { + if len(m.paramModal.Inputs) > m.paramModal.FocusIndex { + inputModel = &m.paramModal.Inputs[m.paramModal.FocusIndex] + } + } else if m.modal != nil { + if len(m.modal.Inputs) > m.modal.FocusIndex { + inputModel = &m.modal.Inputs[m.modal.FocusIndex] + } + } else if m.searchFocused { + inputModel = &m.searchInput + } else { + return m, nil + } + if inputModel == nil { + return m, nil + } + pasteText, err := clipboardsafe.ReadAllLimited() + if err != nil { + return m, m.setToast(fmt.Sprintf("Paste failed: %s", err.Error()), true) + } + if len(pasteText) == 0 { + return m, nil + } + err = insertAtCursor(inputModel, pasteText) + if err != nil { + return m, m.setToast(fmt.Sprintf("Paste failed: %s", err.Error()), true) + } + if m.searchFocused { + m.filterCommands() + } else if m.modal != nil { + m.modal.updateSuggestions() + } + return m, nil + } + // 1. If Parameter Modal is active if m.paramModal != nil { var cmd tea.Cmd @@ -369,7 +411,9 @@ func (m Model) View() string { logo := LogoStyle.Render("cmdpp") title := TitleStyle.Render("Command Launcher") count := CountBadgeStyle.Render(fmt.Sprintf("(%d/%d commands)", len(m.filtered), len(m.commands))) - b.WriteString(lipgloss.JoinHorizontal(lipgloss.Center, logo, title, count) + "\n\n") + b.WriteString(lipgloss.JoinHorizontal(lipgloss.Center, logo, title, count)) + b.WriteRune('\n') + b.WriteRune('\n') // 2. Search Input searchStyle := SearchBoxStyle @@ -377,7 +421,8 @@ func (m Model) View() string { searchStyle = SearchBoxFocusedStyle } searchBox := searchStyle.Render("🔍 " + m.searchInput.View()) - b.WriteString(searchBox + "\n") + b.WriteString(searchBox) + b.WriteRune('\n') // 3. Command List if len(m.filtered) == 0 { @@ -430,15 +475,17 @@ func (m Model) View() string { } if isSelected { - b.WriteString(SelectedItemStyle.Render(line) + "\n") + b.WriteString(SelectedItemStyle.Render(line)) } else { - b.WriteString(NormalItemStyle.Render(line) + "\n") + b.WriteString(NormalItemStyle.Render(line)) } + b.WriteRune('\n') } if len(m.filtered) > m.maxVisibleRows { scrollInfo := fmt.Sprintf(" Showing %d-%d of %d ", m.viewportTop+1, visibleEnd, len(m.filtered)) - b.WriteString(ItemMetaStyle.Render(scrollInfo) + "\n") + b.WriteString(ItemMetaStyle.Render(scrollInfo)) + b.WriteRune('\n') } } @@ -446,7 +493,9 @@ func (m Model) View() string { if len(m.filtered) > 0 && m.cursor < len(m.filtered) { selected := m.filtered[m.cursor] var detailContent strings.Builder - detailContent.WriteString(DetailLabelStyle.Render("Command: ") + DetailCmdStyle.Render(selected.Cmd) + "\n") + detailContent.WriteString(DetailLabelStyle.Render("Command: ")) + detailContent.WriteString(DetailCmdStyle.Render(selected.Cmd)) + detailContent.WriteRune('\n') params := store.ExtractParams(selected.Cmd) if len(params) > 0 { var pList []string @@ -457,10 +506,14 @@ func (m Model) View() string { pList = append(pList, p.Name) } } - detailContent.WriteString(DetailLabelStyle.Render("Params: ") + DetailParamStyle.Render(strings.Join(pList, ", ")) + "\n") + detailContent.WriteString(DetailLabelStyle.Render("Params: ")) + detailContent.WriteString(DetailParamStyle.Render(strings.Join(pList, ", "))) + detailContent.WriteRune('\n') } if selected.Description != "" { - detailContent.WriteString(DetailLabelStyle.Render("About: ") + DetailValueStyle.Render(selected.Description) + "\n") + detailContent.WriteString(DetailLabelStyle.Render("About: ")) + detailContent.WriteString(DetailValueStyle.Render(selected.Description)) + detailContent.WriteRune('\n') } lastRun := "Never" if selected.LastRunAt != nil { @@ -476,19 +529,27 @@ func (m Model) View() string { paneWidth := max(40, m.width-4) detailPane := DetailPaneStyle.Width(paneWidth).Render(detailContent.String()) - b.WriteString("\n" + detailPane + "\n") + b.WriteRune('\n') + b.WriteString(detailPane) + b.WriteRune('\n') } // 5. Toast / Notification / Confirm Delete if m.isConfirmingDel && len(m.filtered) > 0 { sel := m.filtered[m.cursor] prompt := fmt.Sprintf("⚠️ Are you sure you want to delete %q? [y] Yes [n/Esc] Cancel", sel.Name) - b.WriteString("\n" + ToastDangerStyle.Render(prompt) + "\n") + b.WriteRune('\n') + b.WriteString(ToastDangerStyle.Render(prompt)) + b.WriteRune('\n') } else if m.toastMsg != "" { if m.toastIsErr { - b.WriteString("\n" + ToastDangerStyle.Render("⚠️ "+m.toastMsg) + "\n") + b.WriteRune('\n') + b.WriteString(ToastDangerStyle.Render("⚠️ " + m.toastMsg)) + b.WriteRune('\n') } else { - b.WriteString("\n" + ToastSuccessStyle.Render(m.toastMsg) + "\n") + b.WriteRune('\n') + b.WriteString(ToastSuccessStyle.Render(m.toastMsg)) + b.WriteRune('\n') } } @@ -513,7 +574,8 @@ func (m Model) View() string { HelpKeyStyle.Render("[q]"), HelpDescStyle.Render(" Quit"), ) } - b.WriteString("\n" + HelpBarStyle.Render(helpBar)) + b.WriteString("\n") + b.WriteString(HelpBarStyle.Render(helpBar)) return b.String() } @@ -528,16 +590,19 @@ func (m Model) ChosenCommand() *store.Command { return m.chosenCommand } -func min(a, b int) int { - if a < b { - return a +func insertAtCursor(input *textinput.Model, txt string) error { + runes := []rune(input.Value()) + insertRunes := []rune(txt) + cursorPos := min(max(0, input.Position()), len(runes)) + if input.CharLimit > 0 && len(runes)+len(insertRunes) > input.CharLimit { + return fmt.Errorf("input length exceeds %d characters", input.CharLimit) } - return b -} -func max(a, b int) int { - if a > b { - return a - } - return b + newvalue := make([]rune, 0, len(runes)+len(insertRunes)) + newvalue = append(newvalue, runes[:cursorPos]...) + newvalue = append(newvalue, insertRunes...) + newvalue = append(newvalue, runes[cursorPos:]...) + input.SetValue(string(newvalue)) + input.SetCursor(cursorPos + len(insertRunes)) + return nil } diff --git a/tui/modal.go b/tui/modal.go index 75cf62c..d348c34 100644 --- a/tui/modal.go +++ b/tui/modal.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" @@ -44,6 +45,7 @@ func NewModal(mode ModalMode, initialName, initialCmd, initialDesc string, sugge // 1. Name input inputs[0] = textinput.New() + inputs[0].KeyMap.Paste = key.NewBinding() inputs[0].Placeholder = "tunnel-one" inputs[0].Focus() inputs[0].CharLimit = 64 @@ -52,6 +54,7 @@ func NewModal(mode ModalMode, initialName, initialCmd, initialDesc string, sugge // 2. Command input inputs[1] = textinput.New() + inputs[1].KeyMap.Paste = key.NewBinding() inputs[1].Placeholder = "ssh -N -L user@ssh.example.org" inputs[1].CharLimit = 1024 inputs[1].Width = 50 @@ -59,6 +62,7 @@ func NewModal(mode ModalMode, initialName, initialCmd, initialDesc string, sugge // 3. Description input inputs[2] = textinput.New() + inputs[2].KeyMap.Paste = key.NewBinding() inputs[2].Placeholder = "Optional description or notes" inputs[2].CharLimit = 256 inputs[2].Width = 50 @@ -325,7 +329,8 @@ func (m *ModalModel) renderDropdown() string { } else { headerText = fmt.Sprintf("▾ Suggestions (%d matches):", total) } - sb.WriteString(DropdownHeaderStyle.Render(headerText) + "\n") + sb.WriteString(DropdownHeaderStyle.Render(headerText)) + sb.WriteRune('\n') maxCmdWidth := max(30, m.Width-16) start := m.DropdownViewportTop @@ -360,7 +365,8 @@ func (m *ModalModel) renderDropdown() string { scrollHints = append(scrollHints, fmt.Sprintf("▼ %d more", total-end)) } if len(scrollHints) > 0 { - sb.WriteString("\n" + DropdownHintStyle.Render(strings.Join(scrollHints, " "))) + sb.WriteRune('\n') + sb.WriteString(DropdownHintStyle.Render(strings.Join(scrollHints, " "))) } } @@ -377,7 +383,9 @@ func (m *ModalModel) View() string { } var b strings.Builder - b.WriteString(title + "\n\n") + b.WriteString(title) + b.WriteRune('\n') + b.WriteRune('\n') labels := []string{"Name:", "Command:", "Description:"} for i, input := range m.Inputs { @@ -386,18 +394,23 @@ func (m *ModalModel) View() string { if i == m.FocusIndex && (i != 1 || m.SelectedSugIndex == -1) { boxStyle = ModalInputActive } - b.WriteString(label + "\n") - b.WriteString(boxStyle.Render(input.View()) + "\n") + b.WriteString(label) + b.WriteRune('\n') + b.WriteString(boxStyle.Render(input.View())) + b.WriteRune('\n') if i == 1 && m.FocusIndex == 1 && len(m.FilteredSuggestions) > 0 { - b.WriteString(m.renderDropdown() + "\n") + b.WriteString(m.renderDropdown()) + b.WriteRune('\n') } else { - b.WriteString("\n") + b.WriteRune('\n') } } if m.ErrMessage != "" { - b.WriteString(ToastDangerStyle.Render("⚠️ "+m.ErrMessage) + "\n\n") + b.WriteString(ToastDangerStyle.Render("⚠️ " + m.ErrMessage)) + b.WriteRune('\n') + b.WriteRune('\n') } var controls string diff --git a/tui/param_modal.go b/tui/param_modal.go index 874008f..6a8f654 100644 --- a/tui/param_modal.go +++ b/tui/param_modal.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" @@ -27,6 +28,7 @@ func NewParamModal(cmd *store.Command, params []store.Param) ParamModalModel { inputs := make([]textinput.Model, len(params)) for i, p := range params { ti := textinput.New() + ti.KeyMap.Paste = key.NewBinding() ti.CharLimit = 256 ti.Width = 46 if p.HasDefault { @@ -147,7 +149,9 @@ func (m ParamModalModel) View() string { // Header / Title title := ModalTitleStyle.Render(fmt.Sprintf("Parameters: %s", m.Command.Name)) - b.WriteString(title + "\n\n") + b.WriteString(title) + b.WriteRune('\n') + b.WriteRune('\n') // Render parameter inputs for i, p := range m.Params { @@ -161,23 +165,32 @@ func (m ParamModalModel) View() string { } labelRendered := ModalFieldLabelStyle.Render(label) - b.WriteString(labelRendered + "\n") + b.WriteString(labelRendered) + b.WriteRune('\n') inputBoxStyle := ModalInputInactive if isFocused { inputBoxStyle = ModalInputActive } - b.WriteString(inputBoxStyle.Render(m.Inputs[i].View()) + "\n\n") + b.WriteString(inputBoxStyle.Render(m.Inputs[i].View())) + b.WriteRune('\n') + b.WriteRune('\n') } // Live preview previewLabel := lipgloss.NewStyle().Bold(true).Foreground(PrimaryColor).Render("Preview:") previewCmd := lipgloss.NewStyle().Foreground(TextColor).Italic(true).Render(m.Preview()) - b.WriteString(previewLabel + "\n" + previewCmd + "\n\n") + b.WriteString(previewLabel) + b.WriteRune('\n') + b.WriteString(previewCmd) + b.WriteRune('\n') + b.WriteRune('\n') // Error message if m.ErrMessage != "" { - b.WriteString(ToastDangerStyle.Render("⚠️ "+m.ErrMessage) + "\n\n") + b.WriteString(ToastDangerStyle.Render("⚠️ " + m.ErrMessage)) + b.WriteRune('\n') + b.WriteRune('\n') } // Footer / Keybindings