|
| 1 | +import {execa, execaSync} from 'execa'; |
| 2 | +import linux from './linux.js'; |
| 3 | + |
| 4 | +// Common arguments for text clipboard operations |
| 5 | +const textArgs = ['--type', 'text/plain']; |
| 6 | + |
| 7 | +const makeError = (command, error) => { |
| 8 | + if (error.code === 'ENOENT') { |
| 9 | + return new Error(`Couldn't find the \`${command}\` binary. On Debian/Ubuntu you can install wl-clipboard with: sudo apt install wl-clipboard`); |
| 10 | + } |
| 11 | + |
| 12 | + return new Error(`Command \`${command}\` failed: ${error.message}`); |
| 13 | +}; |
| 14 | + |
| 15 | +const tryWaylandWithFallback = async (command, arguments_, options, fallbackMethod) => { |
| 16 | + try { |
| 17 | + const result = await execa(command, arguments_, options); |
| 18 | + return result.stdout; |
| 19 | + } catch (error) { |
| 20 | + // Handle empty clipboard on wl-paste |
| 21 | + if (command === 'wl-paste' && /nothing is copied|no selection|selection owner/i.test(error.stderr || '')) { |
| 22 | + return ''; |
| 23 | + } |
| 24 | + |
| 25 | + // Fall back to X11 if wl-clipboard not found OR Wayland not available |
| 26 | + if (error.code === 'ENOENT' |
| 27 | + || /wayland|wayland_display|failed to connect|display/i.test(error.stderr || '')) { |
| 28 | + return fallbackMethod(options); |
| 29 | + } |
| 30 | + |
| 31 | + throw makeError(command, error); |
| 32 | + } |
| 33 | +}; |
| 34 | + |
| 35 | +const tryWaylandWithFallbackSync = (command, arguments_, options, fallbackMethod) => { |
| 36 | + try { |
| 37 | + const result = execaSync(command, arguments_, options); |
| 38 | + return result.stdout; |
| 39 | + } catch (error) { |
| 40 | + // Handle empty clipboard on wl-paste |
| 41 | + if (command === 'wl-paste' && /nothing is copied|no selection|selection owner/i.test(error.stderr || '')) { |
| 42 | + return ''; |
| 43 | + } |
| 44 | + |
| 45 | + // Fall back to X11 if wl-clipboard not found OR Wayland not available |
| 46 | + if (error.code === 'ENOENT' |
| 47 | + || /wayland|wayland_display|failed to connect|display/i.test(error.stderr || '')) { |
| 48 | + return fallbackMethod(options); |
| 49 | + } |
| 50 | + |
| 51 | + throw makeError(command, error); |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +const clipboard = { |
| 56 | + async copy(options) { |
| 57 | + await tryWaylandWithFallback('wl-copy', textArgs, options, linux.copy); |
| 58 | + }, |
| 59 | + copySync(options) { |
| 60 | + tryWaylandWithFallbackSync('wl-copy', textArgs, options, linux.copySync); |
| 61 | + }, |
| 62 | + async paste(options) { |
| 63 | + return tryWaylandWithFallback('wl-paste', [...textArgs, '--no-newline'], options, linux.paste); |
| 64 | + }, |
| 65 | + pasteSync(options) { |
| 66 | + return tryWaylandWithFallbackSync('wl-paste', [...textArgs, '--no-newline'], options, linux.pasteSync); |
| 67 | + }, |
| 68 | +}; |
| 69 | + |
| 70 | +export default clipboard; |
0 commit comments