Something went wrong. Try again.
Charm-like tui library
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576//! OS clipboard reader. Spawns the platform tool (xclip, wl-paste, pbpaste,//! powershell) and emits a `paste` Msg with the captured text.//!//! The paste Msg payload is heap-allocated with the gpa supplied to the Cmd//! at run time; `Program.run` frees it after the model dispatches the msg//! (see the lifecycle note on `Msg.paste`).const std = @import("std");const Allocator = std.mem.Allocator;const Io = std.Io;
const builtin = @import("builtin");const Cmd = @import("Cmd.zig");const Msg = @import("msg/root.zig").Msg;
/// Returns a Cmd that, when run, reads the system clipboard and emits a/// `paste` Msg. On any failure (tool missing, non-zero exit, empty buffer)/// the Cmd produces no Msg.pub fn pasteCmd() Cmd { return .{ .run_fn = pasteRun };}
fn pasteRun(allocator: Allocator, io: Io, _: ?*anyopaque) ?Msg { const text = readClipboard(allocator, io) catch return null; if (text.len == 0) { allocator.free(text); return null; } return .{ .paste = text };}
const ToolList = []const []const []const u8;
fn pickTools() ToolList { return switch (builtin.os.tag) { .linux => &[_][]const []const u8{ &.{ "wl-paste", "-n" }, &.{ "xclip", "-selection", "clipboard", "-o" }, &.{ "xsel", "--clipboard", "--output" }, }, .macos => &[_][]const []const u8{&.{"pbpaste"}}, .windows => &[_][]const []const u8{ &.{ "powershell.exe", "-NoProfile", "-Command", "Get-Clipboard" }, }, else => &[_][]const []const u8{}, };}
fn readClipboard(allocator: Allocator, io: Io) ![]u8 { for (pickTools()) |argv| { const result = std.process.run(allocator, io, .{ .argv = argv, .stdout_limit = .limited(1 << 20), .stderr_limit = .limited(1 << 16), }) catch continue; defer allocator.free(result.stderr); switch (result.term) { .exited => |code| if (code != 0) { allocator.free(result.stdout); continue; }, else => { allocator.free(result.stdout); continue; }, } // Strip a single trailing newline (most tools add one). var len = result.stdout.len; if (len > 0 and result.stdout[len - 1] == '\n') len -= 1; if (len > 0 and result.stdout[len - 1] == '\r') len -= 1; if (len == result.stdout.len) return result.stdout; const out = try allocator.realloc(result.stdout, len); return out; } return error.ClipboardUnavailable;}