Files
voicepaste/internal/paste/paste.go

56 lines
1.3 KiB
Go

// Package paste handles writing text to the system clipboard and simulating
// Ctrl+V / Cmd+V to paste into the currently focused application.
package paste
import (
"fmt"
"log/slog"
"runtime"
"time"
"github.com/go-vgo/robotgo"
"golang.design/x/clipboard"
)
const keyDelay = 50 * time.Millisecond
// Init initializes the clipboard subsystem. Must be called once at startup.
func Init() error {
return clipboard.Init()
}
// Paste writes text to the clipboard and simulates a paste keystroke.
// Falls back to clipboard-only if key simulation fails.
func Paste(text string) error {
// Write to clipboard
clipboard.Write(clipboard.FmtText, []byte(text))
// Small delay to ensure clipboard is ready
time.Sleep(keyDelay)
// Simulate paste keystroke
if err := simulatePaste(); err != nil {
slog.Warn("key simulation failed, text is in clipboard", "err", err)
return fmt.Errorf("key simulation failed (text is in clipboard): %w", err)
}
return nil
}
// ClipboardOnly writes text to clipboard without simulating a keystroke.
func ClipboardOnly(text string) {
clipboard.Write(clipboard.FmtText, []byte(text))
}
func simulatePaste() error {
switch runtime.GOOS {
case "darwin":
robotgo.KeyTap("v", "command")
case "linux", "windows":
robotgo.KeyTap("v", "control")
default:
return fmt.Errorf("unsupported platform: %s", runtime.GOOS)
}
return nil
}