liveCopyProgram function

LiveProgram liveCopyProgram(
  1. String file, {
  2. String? os,
  3. LiveProcesses processes = const LiveProcesses(),
})

The program that copies the PNG file to the clipboard on os (as Platform.operatingSystem names it).

On Linux that's wl-copy under Wayland, otherwise xclip. Throws a LiveCommandException saying what to install when neither is there.

Implementation

LiveProgram liveCopyProgram(
  String file, {
  String? os,
  LiveProcesses processes = const LiveProcesses(),
}) {
  switch (os ?? Platform.operatingSystem) {
    case 'macos':
      final String posix = file.replaceAll(r'\', r'\\').replaceAll('"', r'\"');
      return (
        executable: 'osascript',
        arguments: [
          '-e',
          'set the clipboard to (read (POSIX file "$posix") as «class PNGf»)',
        ],
      );
    case 'windows':
      final String path = file.replaceAll("'", "''");
      return (
        executable: 'powershell',
        arguments: [
          '-NoProfile',
          '-STA',
          '-Command',
          'Add-Type -AssemblyName System.Windows.Forms, System.Drawing; '
              '[System.Windows.Forms.Clipboard]::SetImage('
              "[System.Drawing.Image]::FromFile('$path'))",
        ],
      );
    default:
      final bool wayland = processes.environment.containsKey('WAYLAND_DISPLAY');
      final bool wlCopy = processes.find('wl-copy') != null;
      final bool xclip = processes.find('xclip') != null;
      // Both stay running to hand the image over, so their output is let go.
      if (wlCopy && (wayland || !xclip)) {
        return (
          executable: '/bin/sh',
          arguments: [
            '-c',
            r'wl-copy --type image/png < "$1" >/dev/null 2>&1',
            'sh',
            file,
          ],
        );
      }
      if (xclip) {
        return (
          executable: '/bin/sh',
          arguments: [
            '-c',
            r'xclip -selection clipboard -t image/png -i "$1" >/dev/null 2>&1',
            'sh',
            file,
          ],
        );
      }
      throw LiveCommandException(
        'Copying the screenshot needs ${wayland ? 'wl-clipboard' : 'xclip'}. '
        'Install it (e.g. sudo apt install '
        '${wayland ? 'wl-clipboard' : 'xclip'}), then try again.',
      );
  }
}