/* The system clipboard for Ctrl+V; see clipboard.h. Pi reads it through a
* native module and, on Linux, wl-paste and xclip (utils/clipboard-image.ts,
* clipboard.ts); pic uses what the OS ships: JavaScript for Automation on
* macOS, wl-paste, xclip and xsel on Linux. Everything is read in memory. */
#ifndef _DEFAULT_SOURCE
#define _DEFAULT_SOURCE 1
#endif
#include "tui/clipboard.h"
#include "image.h"
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#define CLIP_MAX ((size_t)32 << 20) /* far above what an image may be (4.5MB of base64) */
static long cb_now_ms(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return (long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
/* Runs ARGV (PATH search) with stdin and stderr on /dev/null and returns its
* stdout (malloc'd, NUL-terminated, *len bytes), or NULL when it cannot run,
* fails, outputs over CLIP_MAX, or takes over MS milliseconds (it is killed). */
static unsigned char *capture(char *const *argv, int ms, size_t *len)
{
int p[2];
pid_t pid;
unsigned char *buf = NULL;
size_t n = 0, cap = 0;
long end = cb_now_ms() + ms;
int status, ok = 1;
*len = 0;
if (pipe(p) != 0)
return NULL;
pid = fork();
if (pid < 0) {
close(p[0]);
close(p[1]);
return NULL;
}
if (pid == 0) {
int null = open("/dev/null", O_RDWR);
if (null >= 0) {
(void)dup2(null, STDIN_FILENO);
(void)dup2(null, STDERR_FILENO);
}
(void)dup2(p[1], STDOUT_FILENO);
close(p[0]);
close(p[1]);
execvp(argv[0], argv);
_exit(127);
}
close(p[1]);
for (;;) {
struct pollfd pf = {p[0], POLLIN, 0};
long left = end - cb_now_ms();
ssize_t r;
if (left <= 0) {
ok = 0;
break;
}
if (poll(&pf, 1, (int)left) < 0 && errno != EINTR)
ok = 0;
if (!ok)
break;
if (!(pf.revents & (POLLIN | POLLHUP)))
continue;
if (n + 65536 + 1 > cap) {
unsigned char *q;
cap = cap ? cap * 2 : 65536 + 1;
if (!(q = realloc(buf, cap))) {
ok = 0;
break;
}
buf = q;
}
r = read(p[0], buf + n, cap - n - 1);
if (r == 0)
break;
if (r < 0) {
if (errno != EINTR && errno != EAGAIN)
ok = 0;
if (!ok)
break;
continue;
}
n += (size_t)r;
if (n > CLIP_MAX) {
ok = 0;
break;
}
}
close(p[0]);
if (!ok)
(void)kill(pid, SIGKILL);
while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
;
if (!ok || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
free(buf);
return NULL;
}
if (!buf && !(buf = malloc(1)))
return NULL;
buf[n] = '\0';
*len = n;
return buf;
}
/* A file's bytes (malloc'd, NUL-terminated), or NULL when it is missing, empty or too big. */
static unsigned char *slurp(const char *path, size_t *len)
{
struct stat st;
unsigned char *b;
size_t got = 0;
int fd = open(path, O_RDONLY | O_CLOEXEC);
*len = 0;
if (fd < 0)
return NULL;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || st.st_size <= 0 || (size_t)st.st_size > CLIP_MAX ||
!(b = malloc((size_t)st.st_size + 1))) {
close(fd);
return NULL;
}
while (got < (size_t)st.st_size) {
ssize_t r = read(fd, b + got, (size_t)st.st_size - got);
if (r <= 0)
break;
got += (size_t)r;
}
close(fd);
if (got != (size_t)st.st_size) {
free(b);
return NULL;
}
b[got] = '\0';
*len = got;
return b;
}
#ifdef __APPLE__
/* One script for the whole pasteboard: "files" and the paths, else "image"
* and the base64 of a PNG, JPEG, GIF or WebP (a TIFF, which is what some
* apps copy, converted to PNG), else "none". */
static const char macos_script[] =
"ObjC.import('AppKit');"
"var pb=$.NSPasteboard.generalPasteboard;"
"var urls=pb.readObjectsForClassesOptions($.NSArray.arrayWithObject($.NSURL),"
"$({NSPasteboardURLReadingFileURLsOnlyKey:true}));"
"var out='none';"
"if(urls&&urls.count>0){var ps=[];for(var i=0;i<urls.count;i++){ps.push(ObjC.unwrap(urls.objectAtIndex(i).path));}"
"out='files\\n'+ps.join('\\n');}"
"else{var ts=['public.png','public.jpeg','com.compuserve.gif','org.webmproject.webp'];var d=null;"
"for(var j=0;j<ts.length&&!d;j++){d=pb.dataForType(ts[j]);}"
"if(!d||d.isNil()){var t=pb.dataForType('public.tiff');"
"if(t&&!t.isNil()){var r=$.NSBitmapImageRep.imageRepWithData(t);"
"if(r&&!r.isNil()){d=r.representationUsingTypeProperties($.NSBitmapImageFileTypePNG,$());}}}"
"if(d&&!d.isNil()&&d.length>0){out='image\\n'+ObjC.unwrap(d.base64EncodedStringWithOptions(0));}}"
"out;";
static int read_native(tui_clip *c)
{
char *const av[] = {"osascript", "-l", "JavaScript", "-e", (char *)(uintptr_t)macos_script, NULL};
size_t n;
unsigned char *o = capture(av, 8000, &n);
char *s = (char *)o, *nl;
int kind = TUI_CLIP_NONE;
if (o && (nl = strchr(s, '\n')) != NULL) {
*nl++ = '\0';
n -= (size_t)(nl - s);
while (n > 0 && (nl[n - 1] == '\n' || nl[n - 1] == '\r'))
nl[--n] = '\0';
if (strcmp(s, "files") == 0 && n > 0 && (c->text = strdup(nl)) != NULL) {
kind = TUI_CLIP_FILES;
} else if (strcmp(s, "image") == 0 && n > 0) {
unsigned char *img = malloc(n / 4 * 3 + 3);
size_t m = img ? pic_base64_decode(nl, n, img) : (size_t)-1;
if (m == (size_t)-1 || m == 0) {
free(img);
} else {
c->image = img;
c->image_len = m;
kind = TUI_CLIP_IMAGE;
}
}
}
free(o);
if (kind != TUI_CLIP_NONE)
return kind;
{
char *const pv[] = {"pbpaste", NULL};
unsigned char *t = capture(pv, 5000, &n);
if (t && n > 0) {
c->text = (char *)t;
return TUI_CLIP_TEXT;
}
free(t);
}
return TUI_CLIP_NONE;
}
#else
/* The first of the types (a list, one per line) that the pic can take. */
static const char *pick_type(const char *list)
{
static const char *const want[] = {"image/png", "image/jpeg", "image/webp", "image/gif"};
for (size_t w = 0; w < sizeof want / sizeof *want; w++) {
for (const char *p = list; *p;) {
size_t n = strcspn(p, "\r\n;");
if (n == strlen(want[w]) && memcmp(p, want[w], n) == 0)
return want[w];
p += n;
p += strspn(p, "\r\n; ");
}
}
return NULL;
}
static int read_image_via(char *const *list_argv, char *const *data_argv, int type_slot, tui_clip *c)
{
size_t n;
unsigned char *types = capture(list_argv, 1000, &n);
const char *type = types ? pick_type((const char *)types) : NULL;
char *argv[8];
unsigned char *img;
int i = 0;
if (!type) {
free(types);
return -1;
}
for (; data_argv[i] && i < 7; i++)
argv[i] = data_argv[i];
argv[i] = NULL;
argv[type_slot] = (char *)(uintptr_t)type;
img = capture(argv, 5000, &n);
free(types);
if (!img || n == 0) {
free(img);
return -1;
}
c->image = img;
c->image_len = n;
return 0;
}
static int read_native(tui_clip *c)
{
size_t n;
unsigned char *t;
if (getenv("WAYLAND_DISPLAY") || (getenv("XDG_SESSION_TYPE") && strcmp(getenv("XDG_SESSION_TYPE"), "wayland") == 0)) {
char *const lt[] = {"wl-paste", "--list-types", NULL};
char *const dt[] = {"wl-paste", "--type", "", "--no-newline", NULL};
if (read_image_via(lt, dt, 2, c) == 0)
return TUI_CLIP_IMAGE;
}
if (getenv("DISPLAY")) {
char *const lt[] = {"xclip", "-selection", "clipboard", "-t", "TARGETS", "-o", NULL};
char *const dt[] = {"xclip", "-selection", "clipboard", "-t", "", "-o", NULL};
if (read_image_via(lt, dt, 4, c) == 0)
return TUI_CLIP_IMAGE;
}
if (getenv("WAYLAND_DISPLAY")) {
char *const av[] = {"wl-paste", "--no-newline", "--type", "text", NULL};
if ((t = capture(av, 5000, &n)) && n > 0) {
c->text = (char *)t;
return TUI_CLIP_TEXT;
}
free(t);
}
if (getenv("DISPLAY")) {
char *const xc[] = {"xclip", "-selection", "clipboard", "-out", NULL};
char *const xs[] = {"xsel", "--clipboard", "--output", NULL};
if ((t = capture(xc, 5000, &n)) && n > 0) {
c->text = (char *)t;
return TUI_CLIP_TEXT;
}
free(t);
if ((t = capture(xs, 5000, &n)) && n > 0) {
c->text = (char *)t;
return TUI_CLIP_TEXT;
}
free(t);
}
return TUI_CLIP_NONE;
}
#endif
int tui_clipboard_read(tui_clip *c)
{
const char *files = getenv("PIC_CLIPBOARD_FILES_FILE"), *image = getenv("PIC_CLIPBOARD_IMAGE_FILE"),
*text = getenv("PIC_CLIPBOARD_TEXT_FILE");
size_t n;
memset(c, 0, sizeof *c);
if (files || image || text) { /* the test clipboard, in files */
unsigned char *b;
if (files && (b = slurp(files, &n)) != NULL) {
while (n > 0 && b[n - 1] == '\n')
b[--n] = '\0';
if (n > 0) {
c->text = (char *)b;
return TUI_CLIP_FILES;
}
free(b);
}
if (image && (b = slurp(image, &n)) != NULL) {
c->image = b;
c->image_len = n;
return TUI_CLIP_IMAGE;
}
if (text && (b = slurp(text, &n)) != NULL) {
c->text = (char *)b;
return TUI_CLIP_TEXT;
}
return TUI_CLIP_NONE;
}
if (getenv("PIC_NO_NATIVE_CLIPBOARD"))
return TUI_CLIP_NONE;
return read_native(c);
}
void tui_clip_free(tui_clip *c)
{
free(c->text);
free(c->image);
memset(c, 0, sizeof *c);
}
/* Runs ARGV (PATH search) with T[0..n) on its stdin and its output dropped; 0 when it exited 0. A tool that
* stays to serve the selection (wl-copy, xclip) forks into the background and the first process exits. */
static int feed(char *const *argv, const char *t, size_t n)
{
int p[2], status;
pid_t pid;
if (pipe(p) != 0)
return -1;
if ((pid = fork()) < 0) {
close(p[0]);
close(p[1]);
return -1;
}
if (pid == 0) {
int null = open("/dev/null", O_RDWR);
(void)dup2(p[0], STDIN_FILENO);
if (null >= 0) {
(void)dup2(null, STDOUT_FILENO);
(void)dup2(null, STDERR_FILENO);
}
close(p[0]);
close(p[1]);
execvp(argv[0], argv);
_exit(127);
}
close(p[0]);
{
void (*was)(int) = signal(SIGPIPE, SIG_IGN);
for (size_t off = 0; off < n;) {
ssize_t w = write(p[1], t + off, n - off);
if (w < 0 && errno == EINTR)
continue;
if (w <= 0)
break;
off += (size_t)w;
}
(void)signal(SIGPIPE, was);
}
close(p[1]);
while (waitpid(pid, &status, 0) < 0 && errno == EINTR)
;
return WIFEXITED(status) && WEXITSTATUS(status) == 0 ? 0 : -1;
}
int tui_clipboard_write(const char *t, size_t n)
{
#ifdef PIC_FAULTS
{
char *fake = getenv("PIC_TEST_CLIPBOARD_CMD");
if (fake && *fake) {
char *const av[] = {fake, NULL};
return feed(av, t, n);
}
}
#endif
if (getenv("PIC_NO_NATIVE_CLIPBOARD"))
return -1;
#ifdef __APPLE__
{
char *const av[] = {"/usr/bin/pbcopy", NULL};
return access(av[0], X_OK) == 0 ? feed(av, t, n) : -1;
}
#else
if (getenv("WAYLAND_DISPLAY")) {
char *const av[] = {"wl-copy", NULL};
if (feed(av, t, n) == 0)
return 0;
}
if (getenv("DISPLAY")) {
char *const xc[] = {"xclip", "-selection", "clipboard", "-in", NULL};
char *const xs[] = {"xsel", "--clipboard", "--input", NULL};
if (feed(xc, t, n) == 0 || feed(xs, t, n) == 0)
return 0;
}
return -1;
#endif
}