Debian Codegraph @

clipboard_darwin.go

raw symbols SCIP
1 // Copyright 2013 @atotto. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build darwin
6 // +build darwin
7
8 package clipboard
9
10 import (
11 "context"
12 "encoding/base64"
13 "fmt"
14 "os/exec"
15 "strings"
16 )
17
18 var (
19 pasteCmdArgs = "pbpaste"
20 copyCmdArgs = "pbcopy"
21 osascriptPath = "osascript"
22 )
23
24 func readAll(ctx context.Context) ([]byte, error) {
25 pasteCmd := exec.CommandContext(ctx, pasteCmdArgs)
26 out, err := pasteCmd.Output()
27 if err != nil {
28 return nil, err
29 }
30
31 return out, nil
32 }
33
34 func writeAll(ctx context.Context, text []byte, secret bool) error {
35 if secret {
36 // Use osascript to set the clipboard contents, if that fails
37 // just use pbcopy as a fallback.
38 if err := copyViaOsascript(ctx, string(text)); err == nil {
39 return nil
40 }
41 }
42
43 // If osascript fails or we're not dealing with a secret, use pbcopy.
44 copyCmd := exec.CommandContext(ctx, copyCmdArgs)
45 in, err := copyCmd.StdinPipe()
46 if err != nil {
47 return err
48 }
49
50 if err := copyCmd.Start(); err != nil {
51 return err
52 }
53 if _, err := in.Write(text); err != nil {
54 return err
55 }
56 if err := in.Close(); err != nil {
57 return err
58 }
59
60 return copyCmd.Wait()
61 }
62
63 func copyViaOsascript(ctx context.Context, password string) error {
64 // Base64-encode the password so it can be safely embedded in the AppleScript
65 // source without any special escaping — the base64 alphabet [A-Za-z0-9+/=]
66 // contains no characters that are special inside AppleScript string literals.
67 b64 := base64.StdEncoding.EncodeToString([]byte(password))
68
69 // The entire script is piped to "osascript -" via stdin, which avoids the
70 // fd#3 inheritance issue introduced in macOS 15 (Sequoia) where subprocesses
71 // spawned by "do shell script" no longer reliably inherit extra file
72 // descriptors from the osascript process.
73 script := fmt.Sprintf(`use framework "Foundation"
74 use scripting additions
75 set pw to do shell script "printf '%%s' '%s' | base64 -D"
76 set type to current application's NSPasteboardTypeString
77 set pb to current application's NSPasteboard's generalPasteboard()
78 pb's clearContents()
79 pb's setString:"" forType:"org.nspasteboard.ConcealedType"
80 pb's setString:pw forType:type
81 `, b64)
82
83 cmd := exec.CommandContext(ctx, osascriptPath, "-")
84 cmd.Stdin = strings.NewReader(script)
85
86 out, err := cmd.Output()
87 if err != nil {
88 return fmt.Errorf("osascript: %w", err)
89 }
90
91 // osascript prints the return value of the last expression; setString:forType:
92 // returns a BOOL which AppleScript renders as "true" on success.
93 if string(out) != "true\n" {
94 return fmt.Errorf("osascript failed to set password: %s", string(out))
95 }
96
97 return nil
98 }
99
100 func unsupported() bool {
101 return false
102 }