|
| 1 | +import { spawn } from 'child_process' |
| 2 | +import crypto from 'crypto' |
| 3 | +import { promises as fs } from 'fs' |
| 4 | +import { tmpdir } from 'os' |
| 5 | +import * as path from 'path' |
| 6 | +import * as vscode from 'vscode' |
| 7 | + |
| 8 | +import { t } from './i18n' |
| 9 | +import { logger } from './logger' |
| 10 | + |
| 11 | +const getClipboardImageAsBase64Url = async (): Promise<string | null> => { |
| 12 | + const osPlatform = process.platform |
| 13 | + const tempDir = tmpdir() |
| 14 | + const randomString = crypto.randomBytes(8).toString('hex') |
| 15 | + let command: string |
| 16 | + let args: string[] |
| 17 | + let fileExtension: string |
| 18 | + let mimeType: string |
| 19 | + let filePath: string |
| 20 | + |
| 21 | + switch (osPlatform) { |
| 22 | + case 'win32': |
| 23 | + fileExtension = '.bmp' |
| 24 | + mimeType = 'image/bmp' |
| 25 | + filePath = path.win32.join( |
| 26 | + tempDir, |
| 27 | + `clipboard_image_${randomString}${fileExtension}` |
| 28 | + ) |
| 29 | + command = 'powershell' |
| 30 | + args = [ |
| 31 | + '-command', |
| 32 | + `Add-Type -AssemblyName System.Windows.Forms; |
| 33 | + Add-Type -AssemblyName System.Drawing; |
| 34 | + $img = [System.Windows.Forms.Clipboard]::GetImage(); |
| 35 | + if ($img -ne $null) { |
| 36 | + $img.Save('${filePath}', [System.Drawing.Imaging.ImageFormat]::Bmp); |
| 37 | + $img.Dispose(); |
| 38 | + } else { |
| 39 | + Write-Error "No image found in clipboard" |
| 40 | + }` |
| 41 | + ] |
| 42 | + break |
| 43 | + case 'darwin': |
| 44 | + fileExtension = '.png' |
| 45 | + mimeType = 'image/png' |
| 46 | + filePath = path.join( |
| 47 | + tempDir, |
| 48 | + `clipboard_image_${randomString}${fileExtension}` |
| 49 | + ) |
| 50 | + command = 'osascript' |
| 51 | + args = [ |
| 52 | + '-e', |
| 53 | + `set imgFile to (POSIX file "${filePath}") |
| 54 | + try |
| 55 | + set imgData to the clipboard as «class PNGf» |
| 56 | + set fileRef to open for access imgFile with write permission |
| 57 | + write imgData to fileRef |
| 58 | + close access fileRef |
| 59 | + on error |
| 60 | + try |
| 61 | + close access imgFile |
| 62 | + end try |
| 63 | + error "No image found in clipboard" |
| 64 | + end try` |
| 65 | + ] |
| 66 | + break |
| 67 | + case 'linux': |
| 68 | + fileExtension = '.png' |
| 69 | + mimeType = 'image/png' |
| 70 | + filePath = path.join( |
| 71 | + tempDir, |
| 72 | + `clipboard_image_${randomString}${fileExtension}` |
| 73 | + ) |
| 74 | + await checkXclipInstalled() |
| 75 | + command = 'sh' |
| 76 | + args = [ |
| 77 | + '-c', |
| 78 | + `xclip -selection clipboard -t image/png -o > "${filePath}"` |
| 79 | + ] |
| 80 | + break |
| 81 | + default: |
| 82 | + logger.warn(`Unsupported platform: ${osPlatform}`) |
| 83 | + return null |
| 84 | + } |
| 85 | + |
| 86 | + try { |
| 87 | + await executeCommand(command, args) |
| 88 | + const base64 = await readFileAsBase64(filePath) |
| 89 | + return `data:${mimeType};base64,${base64}` |
| 90 | + } catch (error) { |
| 91 | + logger.warn( |
| 92 | + 'getClipboardImageAsBase64Url Failed to get clipboard image', |
| 93 | + error |
| 94 | + ) |
| 95 | + return null |
| 96 | + } finally { |
| 97 | + await safeDeleteFile(filePath) |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +const checkXclipInstalled = async (): Promise<void> => { |
| 102 | + try { |
| 103 | + await executeCommand('which', ['xclip']) |
| 104 | + } catch (error) { |
| 105 | + throw new Error(t('error.xclipNotFound')) |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +const executeCommand = (command: string, args: string[]): Promise<void> => |
| 110 | + new Promise((resolve, reject) => { |
| 111 | + const childProcess = spawn(command, args) |
| 112 | + let stderr = '' |
| 113 | + |
| 114 | + childProcess.stderr.on('data', data => { |
| 115 | + stderr += data.toString() |
| 116 | + }) |
| 117 | + |
| 118 | + childProcess.on('close', code => { |
| 119 | + if (code === 0) { |
| 120 | + resolve() |
| 121 | + } else { |
| 122 | + reject(new Error(`Command failed with code ${code}. Error: ${stderr}`)) |
| 123 | + } |
| 124 | + }) |
| 125 | + }) |
| 126 | + |
| 127 | +const readFileAsBase64 = async (filePath: string): Promise<string | null> => { |
| 128 | + try { |
| 129 | + const data = await fs.readFile(filePath) |
| 130 | + return data.toString('base64') |
| 131 | + } catch (error) { |
| 132 | + logger.warn('readFileAsBase64 Failed to read file as base64', error) |
| 133 | + return null |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +const safeDeleteFile = async (filePath: string): Promise<void> => { |
| 138 | + try { |
| 139 | + await fs.unlink(filePath) |
| 140 | + } catch (error) { |
| 141 | + // File doesn't exist or can't be accessed, no need to do anything |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +type SafeReadClipboardOptions = { |
| 146 | + readImg?: boolean |
| 147 | +} |
| 148 | + |
| 149 | +type ClipboardResult = { |
| 150 | + text: string |
| 151 | + img?: string |
| 152 | +} |
| 153 | + |
| 154 | +export const safeReadClipboard = async ( |
| 155 | + options: SafeReadClipboardOptions = {} |
| 156 | +): Promise<ClipboardResult> => { |
| 157 | + const clipboardResult: ClipboardResult = { text: '' } |
| 158 | + |
| 159 | + if (options.readImg) { |
| 160 | + const img = await getClipboardImageAsBase64Url() |
| 161 | + if (img) { |
| 162 | + clipboardResult.img = img |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + try { |
| 167 | + const text = await vscode.env.clipboard.readText() |
| 168 | + if (text) { |
| 169 | + clipboardResult.text = text |
| 170 | + } |
| 171 | + } catch (error) { |
| 172 | + logger.warn('safeReadClipboard Failed to read clipboard text', error) |
| 173 | + } |
| 174 | + |
| 175 | + return clipboardResult |
| 176 | +} |
0 commit comments