UNPKG

bytefun

Version:

一个打通了原型设计、UI设计与代码转换、跨平台原生代码开发等的平台

121 lines (95 loc) 3.71 kB
import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import { exec } from 'child_process'; import { promisify } from 'util'; const execAsync = promisify(exec); /** * 模拟用户操作:直接在Finder中选择指定的多个图片文件并复制 * * @param folderPath 文件夹路径 * @param fileNames 要复制的文件名数组 * @returns Promise<boolean> */ export async function copyImagesBySimulatingUserAction(folderPath: string, fileNames: string[]): Promise<boolean> { try { // 检查文件夹是否存在 if (!fs.existsSync(folderPath)) { vscode.window.showErrorMessage(`文件夹不存在: ${folderPath}`); return false; } // 验证文件名数组 if (!fileNames || fileNames.length === 0) { vscode.window.showWarningMessage('没有提供要复制的文件名'); return false; } // 检查指定的文件是否存在 const existingFiles: string[] = []; const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']; for (const fileName of fileNames) { const filePath = path.join(folderPath, fileName); if (fs.existsSync(filePath)) { const ext = path.extname(fileName).toLowerCase(); if (imageExtensions.includes(ext)) { existingFiles.push(fileName); } else { console.warn(`⚠️ [copyData] 跳过非图片文件: ${fileName}`); } } else { console.warn(`⚠️ [copyData] 文件不存在: ${fileName}`); } } if (existingFiles.length === 0) { vscode.window.showWarningMessage('没有找到可复制的图片文件'); return false; } if (process.platform === 'darwin') { // 构建AppleScript来选择指定的文件 const fileSelections = existingFiles.map(fileName => `file "${fileName.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" of targetFolder` ).join(', '); const simpleScript = ` tell application "Finder" -- 打开文件夹 set targetFolder to POSIX file "${folderPath.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}" as alias open targetFolder activate -- 等待窗口打开 delay 0.7 -- 选择指定的文件 try select {${fileSelections}} delay 0.2 -- 复制选中的文件 tell application "System Events" tell process "Finder" keystroke "c" using {command down} delay 0.2 end tell end tell -- 复制完成后切换回VS Code tell application "Visual Studio Code" activate end tell return "success" on error errMsg return "error: " & errMsg end try end tell`; await execAsync(`osascript -e '${simpleScript}'`); vscode.window.showInformationMessage( `已复制 ${existingFiles.length} 个图片文件到剪贴板!可以按Command+V粘贴。`, '好的' ); return true; } else { // 非macOS系统的处理 vscode.window.showErrorMessage('此功能目前仅支持macOS系统'); return false; } } catch (error) { console.error('❌ [copyData] 模拟用户操作失败:', error); vscode.window.showErrorMessage(`复制失败: ${error instanceof Error ? error.message : '未知错误'}`); return false; } }