-
Notifications
You must be signed in to change notification settings - Fork 4
/
darwin.ts
105 lines (94 loc) · 2.31 KB
/
darwin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { Buffer, streams } from "../deps.ts";
import { decode, encode, writeTmp } from "./helper.ts";
export async function read_text(): Promise<string> {
const p = Deno.run({
cmd: ["pbpaste"],
stdout: "piped",
stderr: "piped",
});
try {
const status = await p.status();
if (!status.success) {
p.stdout.close();
const cause = decode(await p.stderrOutput());
throw new Error(
`cannot read text: exit code: ${status.code}, error: ${cause}`,
);
}
p.stderr.close();
return decode(await p.output());
} finally {
p.close();
}
}
export async function write_text(text: string): Promise<void> {
const p = Deno.run({
cmd: ["pbcopy"],
stdin: "piped",
stderr: "piped",
stdout: "null",
});
const buf = new Buffer(encode(text));
await streams.copy(buf, p.stdin);
p.stdin.close();
try {
const status = await p.status();
if (!status.success) {
throw new Error(decode(await p.stderrOutput()));
}
p.stderr.close();
} finally {
p.close();
}
}
export async function read_image(): Promise<Deno.Reader> {
const tmp = await Deno.makeTempFile();
const p = Deno.run({
cmd: [
"osascript",
"-e",
`write (the clipboard as «class PNGf») to (open for access "${tmp}" with write permission)`,
],
stderr: "piped",
});
try {
const status = await p.status();
if (!status.success) {
const cause = decode(await p.stderrOutput());
throw new Error(
`cannot read text: exit code: ${status.code}, error: ${cause}`,
);
}
p.stderr.close();
const dst = new Buffer();
const src = await Deno.open(tmp);
await streams.copy(src, dst);
src.close();
return dst;
} finally {
p.close();
}
}
export async function write_image(data: Uint8Array): Promise<void> {
const tmp = await writeTmp(new Buffer(data));
const p = Deno.run({
cmd: [
"osascript",
"-e",
`set the clipboard to (read "${tmp}" as TIFF picture)`,
],
stderr: "piped",
});
try {
const status = await p.status();
if (!status.success) {
const cause = decode(await p.stderrOutput());
throw new Error(
`cannot read text: exit code: ${status.code}, error: ${cause}`,
);
}
p.stderr.close();
} finally {
p.close();
}
}