|
| 1 | +#include "includes/copyclip.h" |
| 2 | +#include "includes/colors.h" |
| 3 | +#include "includes/os_detect.h" |
| 4 | +#include <stdio.h> |
| 5 | +#include <stdlib.h> |
| 6 | +#include <string.h> |
| 7 | + |
| 8 | +#ifdef OS_WINDOWS |
| 9 | +#include <windows.h> |
| 10 | +#endif |
| 11 | + |
| 12 | +void copy_to_clipboard_any(const char *text) { |
| 13 | + |
| 14 | +#ifdef OS_LINUX |
| 15 | + const char *wayland = getenv("WAYLAND_DISPLAY"); |
| 16 | + const char *x11 = getenv("DISPLAY"); |
| 17 | + FILE *pipe = NULL; |
| 18 | + |
| 19 | + if (wayland) { |
| 20 | + pipe = popen("wl-copy", "w"); |
| 21 | + if (!pipe) { |
| 22 | + fprintf(stderr, RED "Error: no command wl-copy (Wayland)\n" RESET); |
| 23 | + exit(1); |
| 24 | + } |
| 25 | + fwrite(text, sizeof(char), strlen(text), pipe); |
| 26 | + pclose(pipe); |
| 27 | + } else if (x11) { |
| 28 | + // X11 |
| 29 | + pipe = popen("xclip -selection clipboard", "w"); |
| 30 | + if (!pipe) { |
| 31 | + fprintf(stderr, RED "Error: no command xclip (X11)\n" RESET); |
| 32 | + exit(1); |
| 33 | + } |
| 34 | + fwrite(text, sizeof(char), strlen(text), pipe); |
| 35 | + pclose(pipe); |
| 36 | + } else { |
| 37 | + fprintf(stderr, RED "Error: no display environment detected (not Wayland or X11)\n" RESET); |
| 38 | + exit(1); |
| 39 | + } |
| 40 | + |
| 41 | +#elif defined(OS_MAC) |
| 42 | + FILE *pipe = popen("pbcopy", "w"); |
| 43 | + if (!pipe) { |
| 44 | + fprintf(stderr, RED "Error: command pbcopy not found.\n" RESET); |
| 45 | + exit(1); |
| 46 | + } |
| 47 | + fwrite(text, sizeof(char), strlen(text), pipe); |
| 48 | + pclose(pipe); |
| 49 | + |
| 50 | +#elif defined(OS_WINDOWS) |
| 51 | + const size_t len = strlen(text) + 1; |
| 52 | + HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len); |
| 53 | + if (!hMem) { |
| 54 | + fprintf(stderr, RED "Error: unable to allocate memory for clipboard.\n" RESET); |
| 55 | + return; |
| 56 | + } |
| 57 | + memcpy(GlobalLock(hMem), text, len); |
| 58 | + GlobalUnlock(hMem); |
| 59 | + if (OpenClipboard(NULL)) { |
| 60 | + EmptyClipboard(); |
| 61 | + SetClipboardData(CF_TEXT, hMem); |
| 62 | + CloseClipboard(); |
| 63 | + } else { |
| 64 | + fprintf(stderr, RED "Error: could not open clipboard.\n" RESET); |
| 65 | + GlobalFree(hMem); |
| 66 | + } |
| 67 | + |
| 68 | +#else |
| 69 | + fprintf(stderr, RED "Clipboard not supported on this platform.\n" RESET); |
| 70 | +#endif |
| 71 | +} |
| 72 | + |
0 commit comments