Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions clipboardsafe/clipboardsafe.go
Original file line number Diff line number Diff line change
@@ -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
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ 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
github.com/mattn/go-isatty v0.0.20
)

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
Expand Down
111 changes: 88 additions & 23 deletions tui/app.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
// Package tui handles everyting TUI
package tui

import (
"fmt"
"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"
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -369,15 +411,18 @@ 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
if m.searchFocused {
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 {
Expand Down Expand Up @@ -430,23 +475,27 @@ 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')
}
}

// 4. Details Box (for selected command)
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
Expand All @@ -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 {
Expand All @@ -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')
}
}

Expand All @@ -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()
}
Expand All @@ -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
}
Loading
Loading