grace/tpb

Tee your Paste Board

git clone https://git.gae.moe/grace/tpb

Grace Yodermisc: cleanup63265d1

0.1.0
2.1 KiB78 linesraw
1const std = @import("std");
2const builtin = @import("builtin");
3
4const os = builtin.target.os.tag;
5const File = std.Io.File;
6const Clip = @import("Clip.zig");
7
8pub fn main(init: std.process.Init) !void {
9    const io = init.io;
10
11    // This program should not be run interactively
12    if (try File.stdin().isTty(io)) {
13        std.debug.print(
14            \\ This program is not meant to be run interactively.
15            \\ Please pipe into this program.
16            \\
17        , .{});
18        std.process.exit(1);
19    }
20
21    // We want to avoid doing as many allocations as possible so having raw
22    // pages with it being larger should be totally fine
23    const alloc = std.heap.page_allocator;
24    const size = std.heap.pageSize();
25
26    const is_ssh =
27        init.environ_map.get("SSH_CONNECTION") != null or
28        init.environ_map.get("SSH_CLIENT") != null or
29        init.environ_map.get("SSH_TTY") != null;
30
31    if (is_ssh) {
32        var clip = try Clip.OSC52.init(alloc, io, size);
33        defer clip.free();
34        try run(io, &clip);
35        return;
36    }
37
38    if (comptime os == .macos) {
39        var clip = try Clip.NSPasteboard.init(alloc, io, size);
40        defer clip.free();
41        try run(io, &clip);
42        return;
43    }
44
45    // Fallback Clipboard
46    var clip = try Clip.OSC52.init(alloc, io, size);
47    defer clip.free();
48    try run(io, &clip);
49}
50
51pub fn run(io: std.Io, clip: anytype) !void {
52    std.debug.print("\x1b[0;32mCopying the following to Pasteboard\x1b[0m\n", .{});
53
54    var buf: [4096]u8 = undefined;
55    while (true) {
56        // Read as much of stdin there is
57        const bytes = File.stdin().readStreaming(io, &.{&buf}) catch |err| {
58            if (err == File.ReadStreamingError.EndOfStream) {
59                break;
60            } else {
61                return err;
62            }
63        };
64        // Passthrough to stdout
65        _ = try File.stdout().writeStreamingAll(io, buf[0..bytes]);
66
67        // Write to clip
68        try clip.writeCopyBuffer(buf[0..bytes]);
69    }
70
71    try clip.writePasteboard();
72
73    std.debug.print("\x1b[0;32mCopied To Pasteboard!\x1b[0m\n", .{});
74}
75
76test {
77    _ = @import("Clip.zig");
78}