grace/tpb

Tee your Paste Board

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

Grace Yoderfeat(OSC52): added tmux autodetect2178c4d

0.1.3
5.9 KiB177 linesraw
1/// OSC52 Clipboard backend
2/// Fullfils `Clip` interface
3pub const OSC52 = @This();
4
5const std = @import("std");
6
7alloc: std.mem.Allocator,
8io: std.Io,
9
10base64buffer: std.ArrayList(u8),
11
12leftover_bytes: [3]u8,
13leftover_count: u8,
14
15/// This is to wrap the OSC buffer in the tmux passthrough sequence. This lets
16/// OSC52 clipboard requests go directly to the host instead of going to a tmux
17/// buffer.
18/// https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it
19/// Since tmux v3.7, there is a `get-clipboard` option and when it is set to
20/// `request` any OSC52 query that comes to it will cause the tmux buffer to
21/// update before sending the information.
22/// https://raw.githubusercontent.com/tmux/tmux/3.7b/CHANGES
23/// This still wraps the tmux session in an escape whenever one is detected
24/// since this option is still incredibly new.
25is_tmux: bool,
26
27const base64encoder =
28    std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '=');
29
30pub fn init(alloc: std.mem.Allocator, io: std.Io, buf_size: usize, is_tmux: bool) !OSC52 {
31    return .{
32        .alloc = alloc,
33        .io = io,
34        .base64buffer = try std.ArrayList(u8).initCapacity(alloc, buf_size),
35        .leftover_bytes = undefined,
36        .leftover_count = 0,
37        .is_tmux = is_tmux,
38    };
39}
40
41pub fn free(self: *OSC52) void {
42    self.base64buffer.clearAndFree(self.alloc);
43}
44
45pub fn writeCopyBuffer(self: *OSC52, buf: []const u8) anyerror!void {
46    if (buf.len == 0) return;
47
48    // Start of buffer after dealing with leftover bytes
49    const buf_idx = 3 - self.leftover_count;
50
51    // When we dont fill the leftover buffer, just copy data
52    if (buf_idx > buf.len) {
53        const end = self.leftover_count + buf.len;
54        @memcpy(self.leftover_bytes[self.leftover_count..end], buf[0..buf.len]);
55        self.leftover_count = @intCast(end);
56        return;
57    }
58
59    @memcpy(self.leftover_bytes[self.leftover_count..3], buf[0..buf_idx]);
60    var temp: [5]u8 = undefined;
61    var s = OSC52.base64encoder.encode(&temp, &self.leftover_bytes);
62    try self.base64buffer.appendSlice(self.alloc, s);
63
64    const chunkable_length = buf.len - ((buf.len - buf_idx) % 3);
65    var chunker = std.mem.window(u8, buf[buf_idx..chunkable_length], 3, 3);
66    while (chunker.next()) |chunk| {
67        s = OSC52.base64encoder.encode(&temp, chunk);
68        try self.base64buffer.appendSlice(self.alloc, s);
69    }
70
71    self.leftover_count = @intCast(buf.len - chunkable_length);
72    if (self.leftover_count != 0) {
73        @memmove(self.leftover_bytes[0..self.leftover_count], buf[chunkable_length..]);
74    }
75}
76
77pub fn encodeRemaining(self: *OSC52) anyerror!void {
78    var temp: [5]u8 = undefined;
79    const s = OSC52.base64encoder.encode(&temp, self.leftover_bytes[0..self.leftover_count]);
80    try self.base64buffer.appendSlice(self.alloc, s);
81}
82
83pub fn writePasteboard(self: *OSC52) anyerror!void {
84    try self.encodeRemaining();
85
86    // https://ghostty.org/docs/vt/osc/52
87
88    // Write data to stdout
89    const stdout = std.Io.File.stdout();
90    try stdout.writeStreamingAll(self.io, self.osc_header());
91    try stdout.writeStreamingAll(self.io, self.base64buffer.items);
92    try stdout.writeStreamingAll(self.io, self.osc_footer());
93}
94
95fn osc_header(self: *OSC52) []const u8 {
96    if (self.is_tmux) {
97        return &[_]u8{
98            0x1b, // ESC
99            'P', 't', 'm', 'u', 'x', ';', // tmux escape
100            0x1b, 0x1b, // ESC ESC
101            0x5d, // ']'
102            0x35, 0x32, // Code 52
103            0x3b, // ';'
104            // 0x70, // 'p' Primary Clipboard
105            0x63, // 'c' Standard Clipboard
106            0x3b, // ';'
107        };
108    } else {
109        return &[_]u8{
110            0x1b, // ESC
111            0x5d, // ']'
112            0x35, 0x32, // Code 52
113            0x3b, // ';'
114            // 0x70, // 'p' Primary Clipboard
115            0x63, // 'c' Standard Clipboard
116            0x3b, // ';'
117        };
118    }
119}
120
121fn osc_footer(self: *OSC52) []const u8 {
122    if (self.is_tmux) {
123        return &[_]u8{
124            0x1b, 0x1b, // ESC ESC
125            0x5c, // '\'
126            0x1b, // ESC
127            0x5c, // '\'
128        };
129    } else {
130        return &[_]u8{
131            0x1b, // ESC
132            0x5c, // '\'
133        };
134    }
135}
136
137test "basic base64 encode" {
138    var osc = try OSC52.init(std.testing.allocator, std.testing.io, 1024, false);
139    defer osc.free();
140    try osc.writeCopyBuffer("part1");
141    try osc.encodeRemaining();
142    try std.testing.expectEqualSlices(u8, "cGFydDE=", osc.base64buffer.items);
143}
144
145test "multi part base64 encode" {
146    var osc = try OSC52.init(std.testing.allocator, std.testing.io, 1024, false);
147    defer osc.free();
148    try osc.writeCopyBuffer("part1");
149    try osc.writeCopyBuffer("part2");
150    try osc.encodeRemaining();
151    try std.testing.expectEqualSlices(u8, "cGFydDFwYXJ0Mg==", osc.base64buffer.items);
152}
153
154test "tiny buffers base64 encode" {
155    var osc = try OSC52.init(std.testing.allocator, std.testing.io, 1024, false);
156    defer osc.free();
157    try osc.writeCopyBuffer("part1");
158    try osc.writeCopyBuffer("part2");
159    try osc.writeCopyBuffer("1");
160    try osc.writeCopyBuffer("2");
161    try osc.writeCopyBuffer("3");
162    try osc.writeCopyBuffer("45");
163    try osc.writeCopyBuffer("6");
164    try osc.writeCopyBuffer("78");
165    try osc.writeCopyBuffer("90fin");
166    try osc.encodeRemaining();
167    try std.testing.expectEqualSlices(u8, "cGFydDFwYXJ0MjEyMzQ1Njc4OTBmaW4=", osc.base64buffer.items);
168}
169
170test "big buffers base64 encode" {
171    var osc = try OSC52.init(std.testing.allocator, std.testing.io, 1024, false);
172    defer osc.free();
173    try osc.writeCopyBuffer("part1part1part1part1part1part1part1part1part1|");
174    try osc.writeCopyBuffer("part2part2part2part2part2part2part2part2part2");
175    try osc.encodeRemaining();
176    try std.testing.expectEqualSlices(u8, "cGFydDFwYXJ0MXBhcnQxcGFydDFwYXJ0MXBhcnQxcGFydDFwYXJ0MXBhcnQxfHBhcnQycGFydDJwYXJ0MnBhcnQycGFydDJwYXJ0MnBhcnQycGFydDJwYXJ0Mg==", osc.base64buffer.items);
177}