grace/tpb

Tee your Paste Board

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

Grace Yoderfeat(NSPasteboard): uses backend when not ssh and on MacOS9a377fa

0.1.3
1.4 KiB53 linesraw
1/// NSPasteBoard Clipboard backend
2/// Fulfills `Clip` interface
3pub const NSPasteboard = @This();
4
5const std = @import("std");
6
7extern fn sendPB(text: [*:0]const u8) void;
8extern fn initPB() void;
9
10alloc: std.mem.Allocator,
11io: std.Io,
12
13buffer: std.ArrayList(u8),
14
15pub fn init(alloc: std.mem.Allocator, io: std.Io, buf_size: usize) !NSPasteboard {
16    return .{
17        .alloc = alloc,
18        .io = io,
19        .buffer = try std.ArrayList(u8).initCapacity(alloc, buf_size),
20    };
21}
22
23pub fn free(self: *NSPasteboard) void {
24    self.buffer.clearAndFree(self.alloc);
25}
26
27pub fn writeCopyBuffer(self: *NSPasteboard, buf: []const u8) anyerror!void {
28    try self.buffer.appendSlice(self.alloc, buf);
29}
30
31pub fn writePasteboard(self: *NSPasteboard) anyerror!void {
32    // Null Terminate string for C function Call
33    if (self.buffer.items[self.buffer.items.len - 1] == '\n') {
34        self.buffer.items[self.buffer.items.len - 1] = '\x00';
35    } else {
36        try self.buffer.append(self.alloc, '\x00');
37    }
38    initPB();
39    sendPB(@ptrCast(self.buffer.items.ptr));
40}
41
42test "objc bridge" {
43    initPB();
44    sendPB("test_string");
45
46    const result = try std.process.run(std.testing.allocator, std.testing.io, .{
47        .argv = &.{"pbpaste"},
48    });
49    defer std.testing.allocator.free(result.stdout);
50    defer std.testing.allocator.free(result.stderr);
51
52    try std.testing.expectEqualStrings("test_string", std.mem.trim(u8, result.stdout, "\n"));
53}