package clipboard import ( "context" "encoding/json" "os" "os/exec" "strconv" "strings" "time" ) // JXA script: returns the pasteboard's change count and, if it changed since the count // passed as argument, its types and text. One osascript call per poll, no cgo needed. const readScript = ` ObjC.import('AppKit'); function run(argv) { const pb = $.NSPasteboard.generalPasteboard; const count = Number(pb.changeCount); if (String(count) === argv[0]) return JSON.stringify({ count: count, same: true }); const types = ObjC.deepUnwrap(pb.types) || []; const text = ObjC.unwrap(pb.stringForType($.NSPasteboardTypeString)) || ''; return JSON.stringify({ count: count, types: types, text: text }); }` type darwinClipboard struct { lastCount int last Content } func New() (Clipboard, error) { return &darwinClipboard{lastCount: -1}, nil } func (c *darwinClipboard) Read() (Content, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() out, err := exec.CommandContext(ctx, "osascript", "-l", "JavaScript", "-e", readScript, strconv.Itoa(c.lastCount)).Output() if err != nil { return Content{}, err } var result struct { Count int `json:"count"` Same bool `json:"same"` Types []string `json:"types"` Text string `json:"text"` } if err := json.Unmarshal(out, &result); err != nil { return Content{}, err } if result.Same { return c.last, nil } c.lastCount = result.Count if isConcealed(result.Types) { c.last = Content{Concealed: true} } else { c.last = Content{Text: result.Text} } return c.last, nil } func (c *darwinClipboard) Write(text string) error { cmd := exec.Command("pbcopy") // pbcopy only keeps non-ASCII text intact with a UTF-8 locale cmd.Env = append(os.Environ(), "LANG=en_US.UTF-8") cmd.Stdin = strings.NewReader(text) return cmd.Run() }