/
linux.ts
84 lines (76 loc) · 2.31 KB
/
linux.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
import { toText } from "../deps.ts";
import { decode } from "./helper.ts";
export async function readText(): Promise<string> {
const cmd = new Deno.Command("xclip", {
args: ["-selection", "clipboard", "-o"],
stdin: "null",
stdout: "piped",
stderr: "piped",
});
const { success, code, stdout, stderr } = await cmd.output();
if (!success) {
const cause = decode(stderr);
throw new Error(
`cannot read text: exit code: ${code}, error: ${cause}`,
);
}
return decode(stdout);
}
export async function writeText(text: string): Promise<void> {
const cmd = new Deno.Command("xclip", {
args: ["-selection", "clipboard"],
stdin: "piped",
stderr: "piped",
stdout: "null",
});
const child = cmd.spawn();
const r = new Blob([text]).stream();
await r.pipeTo(child.stdin);
// It seems we must not wait `stderr` unless there are actual errors.
// Thus we cannot use `await child.output()` here.
const { success, code } = await child.status;
if (!success) {
const cause = await toText(child.stderr);
throw new Error(
`cannot write text: exit code: ${code}, error: ${cause}`,
);
}
await child.stderr.cancel();
}
export async function readImage(): Promise<Uint8Array> {
const cmd = new Deno.Command("xclip", {
args: ["-selection", "clipboard", "-t", "image/png", "-o"],
stdin: "null",
stdout: "piped",
stderr: "piped",
});
const { success, code, stdout, stderr } = await cmd.output();
if (!success) {
const cause = decode(stderr);
throw new Error(
`cannot read image: exit code: ${code}, error: ${cause}`,
);
}
return stdout;
}
export async function writeImage(data: Uint8Array): Promise<void> {
const cmd = new Deno.Command("xclip", {
args: ["-selection", "clipboard", "-t", "image/png"],
stdin: "piped",
stderr: "piped",
stdout: "null",
});
const child = cmd.spawn();
const r = new Blob([data]).stream();
await r.pipeTo(child.stdin);
// It seems we must not wait `stderr` unless there are actual errors.
// Thus we cannot use `await child.output()` here.
const { success, code } = await child.status;
if (!success) {
const cause = await toText(child.stderr);
throw new Error(
`cannot write image: exit code: ${code}, error: ${cause}`,
);
}
await child.stderr.cancel();
}