diff --git a/plugins/ide-open/.gitignore b/plugins/ide-open/.gitignore new file mode 100644 index 000000000..4ee41fe68 --- /dev/null +++ b/plugins/ide-open/.gitignore @@ -0,0 +1,31 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? + +# Test reference project +test/ + +# CI builds on multiple platforms; let npm generate platform-specific lockfile +package-lock.json +.codegraph \ No newline at end of file diff --git a/plugins/ide-open/CHANGELOG.md b/plugins/ide-open/CHANGELOG.md new file mode 100644 index 000000000..d1767e78a --- /dev/null +++ b/plugins/ide-open/CHANGELOG.md @@ -0,0 +1,47 @@ +# Changelog + +## 1.0.5 + +### Changed +- macOS 的八种快速填入预设使用系统 open 命令打开本地项目。 + +## 1.0.4 + +### Fixed +- macOS 缺少 idea 命令时,使用已安装的 IntelliJ IDEA 打开本地项目。 + +## 1.0.3 + +### Changed +- 移除项目列表顶部的操作提示,使用 SVG 绘制复制路径和删除图标。 + +## 1.0.2 + +### Fixed +- macOS 缺少 code 命令时,使用已安装的 VS Code 打开项目。 + +## 1.0.1 + +### Fixed +- 使用 ZTools 内置的 SQLite 读取 WAL 历史并在事务中删除,修复安装包缺少 sql.js 的报错。 +- 支持新版 JetBrains 历史文件和预设路径回退。 +- 修复 IDE 切换后的键盘打开、空列表导航、别名冲突和旧配置迁移。 +- 对齐 utools-ide-open 功能(shell转义、SQL参数化、复制路径、删除确认、UI调整) + +## 1.0.0 + +### Added +- 从 uTools VscodeOpen 插件迁移至 ZTools 平台 +- 支持 VSCode 系编辑器(VS Code、Cursor、VSCodium、Qoder)最近项目读取(SQLite/JSON) +- 支持 JetBrains 系编辑器(IntelliJ IDEA、PyCharm、WebStorm、GoLand)最近项目读取(XML) +- 动态 Feature 注册,输入别名即可进入对应编辑器项目列表 +- setSubInput 搜索 + 键盘导航(↑↓ 选择、Enter 打开、Ctrl+D 删除) +- IDE 配置页面,支持快速填入预设路径 +- 暗色模式支持 + +### Fixed +- 修复命令注入漏洞,添加 escapeShellArg 对参数进行 shell 转义 +- JetBrains 版本目录排序,优先匹配最新版本 +- 添加 safeDecodeURIComponent 防止畸形 URI 导致崩溃 +- 使用 fileURLToPath 替代手动路径转换,修复 Windows 平台路径问题 +- 移除 Settings 页面冗余的 doRegister 逻辑 diff --git a/plugins/ide-open/README.md b/plugins/ide-open/README.md new file mode 100644 index 000000000..7a5aed5ad --- /dev/null +++ b/plugins/ide-open/README.md @@ -0,0 +1,78 @@ +# ide-open + +> 统一管理 VSCode 系及 JetBrains 系编辑器的最近项目 — ZTools 插件 + +## 功能 + +- 从编辑器的本地数据库/配置文件中读取最近项目列表 +- 搜索并快速打开项目,支持键盘导航(↑↓ 选择、Enter 打开) +- 通过项目行的删除按钮或右键菜单移除 SQLite 历史记录 +- 支持动态注册快捷指令,输入别名即可进入对应编辑器的项目列表 + +### 支持的编辑器 + +| 编辑器 | 数据源格式 | 启动命令 | +|---|---|---| +| VS Code | SQLite (.vscdb) / JSON | `code` | +| Cursor | SQLite (.vscdb) / JSON | `cursor` | +| VSCodium | SQLite (.vscdb) / JSON | `codium` | +| Qoder | SQLite (.vscdb) / JSON | `qoder` | +| IntelliJ IDEA | XML (recentProjects.xml) | `idea` | +| PyCharm | XML | `pycharm` | +| WebStorm | XML | `webstorm` | +| GoLand | XML | `goland` | + +## 项目结构 + +``` +├── public/ +│ ├── preload/ +│ │ ├── package.json # preload 依赖(saxes) +│ │ └── services.js # Node.js 能力:SQLite/JSON/XML 读取、项目打开、删除 +│ ├── plugin.json # 插件配置 +│ └── logo.png +├── src/ +│ ├── App.tsx # 入口:onPluginEnter 路由分发 +│ ├── store.ts # 渲染层数据封装 +│ ├── env.d.ts # 类型声明 +│ ├── Settings/ # IDE 配置页面(增删改、快速填入预设) +│ └── ProjectList/ # 项目列表页面(setSubInput 搜索 + 键盘导航) +├── vite.config.js # base: './' +└── tsconfig.json +``` + +## 开发 + +```bash +# 安装依赖(前端 + preload) +npm install +npm ci --prefix public/preload + +# 启动开发服务器 +npm run dev + +# 回归测试(Node.js 22.13 或更新版本) +npm test + +# 构建(自动安装并打包 preload 依赖) +npm run build +``` + +在 ZTools 中配置插件开发地址指向 `http://localhost:5173` 即可热加载调试。 + +## 使用 + +1. 在 ZTools 主搜索框输入 `ideopen` 进入设置页 +2. 点击「+ 新增配置」,可点击「快速填入」按钮自动填充预设路径 +3. 保存后,ZTools 主搜索框输入配置的别名(如 `vsc`、`cursor`)即可进入项目列表 +4. 在项目列表中搜索并打开项目 + +macOS 上的快速填入使用 `/usr/bin/open -a "应用名"` 打开本地项目。VS Code 系预设打开远程项目时,会优先使用对应应用内置的 CLI。 + +## 技术栈 + +React 19 + Vite + TypeScript。SQLite 历史通过 ZTools 内置的 Node.js SQLite 模块读写。 + +## License + +MIT diff --git a/plugins/ide-open/index.html b/plugins/ide-open/index.html new file mode 100644 index 000000000..84b7eb685 --- /dev/null +++ b/plugins/ide-open/index.html @@ -0,0 +1,11 @@ + + + + + + + +
+ + + diff --git a/plugins/ide-open/package.json b/plugins/ide-open/package.json new file mode 100644 index 000000000..e591a415e --- /dev/null +++ b/plugins/ide-open/package.json @@ -0,0 +1,26 @@ +{ + "name": "ide-open", + "version": "1.0.5", + "description": "插件 — 统一管理 VSCode 系及 JetBrains 系编辑器的最近项目。", + "type": "module", + "scripts": { + "dev": "vite", + "prebuild": "npm ci --prefix public/preload --omit=dev", + "build": "tsc && vite build", + "test": "node --test", + "changelog": "node scripts/gen-changelog.mjs", + "release": "npm run changelog && git add CHANGELOG.md && git commit -m \"chore: update CHANGELOG\" && ztools publish" + }, + "dependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "devDependencies": { + "@types/react": "^19.0.8", + "@types/react-dom": "^19.0.3", + "@vitejs/plugin-react": "^4.3.1", + "@ztools-center/ztools-api-types": "^1.0.1", + "typescript": "^5.3.0", + "vite": "^6.0.11" + } +} diff --git a/plugins/ide-open/public/logo.png b/plugins/ide-open/public/logo.png new file mode 100644 index 000000000..ae084fc54 Binary files /dev/null and b/plugins/ide-open/public/logo.png differ diff --git a/plugins/ide-open/public/plugin.json b/plugins/ide-open/public/plugin.json new file mode 100644 index 000000000..6bc66d6c6 --- /dev/null +++ b/plugins/ide-open/public/plugin.json @@ -0,0 +1,29 @@ +{ + "$schema": "node_modules/@ztools-center/ztools-api-types/resource/ztools.schema.json", + "name": "ide-open", + "title": "ide-open", + "description": "统一管理 VSCode 系及 JetBrains 系编辑器的最近项目", + "author": "svenzhao", + "version": "1.0.5", + "main": "index.html", + "preload": "preload/services.js", + "logo": "logo.png", + "development": { + "main": "http://localhost:5173" + }, + "features": [ + { + "code": "ideopen", + "explain": "打开 ideOpen 设置,配置编辑器并注册快捷指令", + "icon": "logo.png", + "cmds": [ + "ideopen" + ] + } + ], + "platform": [ + "darwin", + "win32", + "linux" + ] +} diff --git a/plugins/ide-open/public/preload/package-lock.json b/plugins/ide-open/public/preload/package-lock.json new file mode 100644 index 000000000..669c1860e --- /dev/null +++ b/plugins/ide-open/public/preload/package-lock.json @@ -0,0 +1,30 @@ +{ + "name": "preload", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "saxes": "6.0.0" + } + }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "license": "MIT" + } + } +} diff --git a/plugins/ide-open/public/preload/package.json b/plugins/ide-open/public/preload/package.json new file mode 100644 index 000000000..959822c6b --- /dev/null +++ b/plugins/ide-open/public/preload/package.json @@ -0,0 +1,6 @@ +{ + "type": "commonjs", + "dependencies": { + "saxes": "6.0.0" + } +} diff --git a/plugins/ide-open/public/preload/services.js b/plugins/ide-open/public/preload/services.js new file mode 100644 index 000000000..69dec912a --- /dev/null +++ b/plugins/ide-open/public/preload/services.js @@ -0,0 +1,623 @@ +const fs = require('node:fs') +const path = require('node:path') +const { homedir } = require('node:os') +const { SaxesParser } = require('saxes') +const { exec, execFile } = require('node:child_process') +const { promisify } = require('node:util') +const { fileURLToPath, pathToFileURL } = require('node:url') + +// ─── 文件日志(开发调试) ── + +let _logFile = '' +function getLogFile() { + if (_logFile) return _logFile + try { + const base = window.ztools.getPath('userData') + _logFile = path.join(base, 'ideopen-debug.log') + } catch { + _logFile = path.join(__dirname, 'ideopen-debug.log') + } + return _logFile +} + +function debugLog(message, data) { + let isDev = false + try { isDev = window.ztools.isDev() } catch {} + if (!isDev) return + + const now = new Date().toISOString() + const line = data !== undefined + ? `[${now}] [ideOpen] ${message} ${JSON.stringify(data, null, 2)}` + : `[${now}] [ideOpen] ${message}` + console.log(line) + try { + fs.appendFileSync(getLogFile(), line + '\n') + } catch (e) { + console.warn('[ideOpen] 写入日志文件失败:', e) + } +} + +// ─── glob 路径解析(JetBrains 版本目录含通配符) ── + +function resolveGlobPath(pattern) { + if (!pattern.includes('*')) return pattern + + const starIdx = pattern.indexOf('*') + const before = pattern.substring(0, starIdx) + const after = pattern.substring(starIdx + 1) + const dir = path.dirname(before) + const prefix = path.basename(before) + + if (!fs.existsSync(dir)) return pattern + + try { + const entries = fs.readdirSync(dir).sort((a, b) => b.localeCompare(a, undefined, { numeric: true })) + for (const entry of entries) { + if (entry.startsWith(prefix)) { + const resolved = path.join(dir, entry) + after + if (fs.existsSync(resolved)) return resolved + } + } + } catch {} + + return pattern +} + +// ─── 类型 ── + +// IDEItem: { code, name, command, dbPath, shell } +// ProjectItem: { name, path, uri, type, label } + +// ─── SQLite 读取 ── + +const RECENT_KEYS = [ + 'history.recentlyOpenedPathsList', + 'history.openedPathsList', + 'openedPathsList' +] + +function canDeleteProjects(filePath) { + return ['.vscdb', '.db'].includes(path.extname(filePath).toLowerCase()) +} + +function openDatabase(filePath, readOnly) { + const { DatabaseSync } = require('node:sqlite') + const url = pathToFileURL(filePath) + url.searchParams.set('mode', readOnly ? 'ro' : 'rw') + const db = new DatabaseSync(url.href, { readOnly }) + try { + db.exec('PRAGMA busy_timeout = 500') + return db + } catch (error) { + db.close() + throw error + } +} + +function sqliteCandidates(filePath) { + const normalizedPath = path.resolve(filePath) + const [shared, standard] = vsCodeDatabasePaths() + const paths = [filePath] + if (normalizedPath === shared) paths.push(standard) + if (normalizedPath === standard || + normalizedPath.includes(path.join('Code', 'User', 'globalStorage') + path.sep)) { + paths.push(shared) + } + const existing = paths.filter(candidate => fs.existsSync(candidate)) + if (!existing.length) throw new Error(`文件不存在: ${filePath}`) + return existing +} + +function recentHistory(value) { + const data = typeof value === 'string' ? JSON.parse(value) : value + return Array.isArray(data?.entries) ? data : { entries: [] } +} + +function readProjectsFromSQLite(dbPath) { + for (const filePath of sqliteCandidates(dbPath)) { + debugLog(`读取数据库: ${filePath}`) + const db = openDatabase(filePath, true) + try { + const select = db.prepare('SELECT value FROM ItemTable WHERE key = ?') + for (const key of RECENT_KEYS) { + const { entries } = recentHistory(select.get(key)?.value) + const projects = parseEntries(entries) + if (projects.length) return projects + } + } finally { + db.close() + } + } + return [] +} + +// ─── JSON 读取 ── + +async function readProjectsFromJSON(jsonPath) { + debugLog(`读取 JSON: ${jsonPath}`) + const content = fs.readFileSync(jsonPath, 'utf-8') + const data = JSON.parse(content) + for (const key of RECENT_KEYS) { + const { entries } = recentHistory(data?.[key]) + if (entries.length > 0) { + debugLog(`JSON 命中 key=${key}, entries=${entries.length}`) + return parseEntries(entries) + } + } + debugLog('JSON 未找到项目记录') + return [] +} + +// ─── XML 读取(JetBrains) ── + +function jetBrainsProjectPath(value) { + if (value === '$USER_HOME$') return homedir() + if (/^\$USER_HOME\$[\\/]/.test(value)) { + return path.join(homedir(), value.slice('$USER_HOME$/'.length)) + } + if (/^(?:\/|[a-z]:[\\/]|\\\\)/i.test(value)) return path.normalize(value) + return '' +} + +function projectName(filePath) { + return /^[a-z]:[\\/]|^\\\\/i.test(filePath) + ? path.win32.basename(filePath) + : path.basename(filePath) +} + +function readProjectsFromXML(xmlPath) { + const parser = new SaxesParser() + const stack = [] + const legacyPaths = new Set() + const metadata = new Map() + let project = null + + parser.on('opentag', tag => { + const parent = stack.at(-1) + const { name, key, value } = tag.attributes + if (tag.name === 'entry' && parent?.name === 'map' && + stack.at(-2)?.attributes.name === 'additionalInfo' && key) { + const filePath = jetBrainsProjectPath(key) + if (filePath) { + project = { depth: stack.length, filePath, label: '', activated: 0, opened: 0 } + metadata.set(filePath, project) + } + } else if (tag.name === 'option' && value) { + if (project) { + if (name === 'projectName') project.label = value + if (name === 'activationTimestamp') project.activated = Number(value) || 0 + if (name === 'projectOpenTimestamp') project.opened = Number(value) || 0 + } else if (!name && parent?.name === 'list' && + ['recentPaths', 'openPaths'].includes(stack.at(-2)?.attributes.name)) { + const filePath = jetBrainsProjectPath(value) + if (filePath) legacyPaths.add(filePath) + } + } + stack.push(tag) + }) + + parser.on('closetag', () => { + stack.pop() + if (project?.depth === stack.length) project = null + }) + + parser.write(fs.readFileSync(xmlPath, 'utf8')).close() + const byRecency = Array.from(metadata.values()) + .sort((a, b) => (b.activated || b.opened) - (a.activated || a.opened)) + const paths = new Set([...legacyPaths, ...byRecency.map(item => item.filePath)]) + return Array.from(paths, filePath => { + const label = metadata.get(filePath)?.label || '' + return { + name: label || projectName(filePath) || filePath, + path: filePath, + uri: filePath, + type: 'folder', + label + } + }) +} + +// ─── 统一解析 ── + +function recentUri(entry) { + const uri = typeof entry === 'string' + ? entry + : entry?.folderUri || entry?.fileUri || entry?.workspace?.configPath + return typeof uri === 'string' ? uri : '' +} + +function parseEntries(entries) { + const projects = [] + for (const entry of entries) { + const uri = recentUri(entry) + if (!uri) continue + const remote = /^[a-z]+-remote:\/\//.test(uri) + const localPath = remote ? '' : uriToPath(uri) + const label = typeof entry.label === 'string' ? entry.label : '' + const name = label || projectName(localPath || safeDecodeURIComponent(uri)) || '未命名' + const type = remote ? 'remote' : uri.endsWith('.code-workspace') ? 'workspace' + : entry.fileUri && !entry.folderUri ? 'file' : 'folder' + projects.push({ name, path: localPath, uri, type, label }) + } + return projects +} + +function safeDecodeURIComponent(str) { + try { + return decodeURIComponent(str) + } catch { + return str + } +} + +function uriToPath(uri) { + try { + if (uri.startsWith('file://')) return fileURLToPath(uri) + if (path.isAbsolute(uri) || path.win32.isAbsolute(uri)) return uri + return decodeURIComponent(new URL(uri).pathname) + } catch { + return uri + } +} + +// ─── 主入口 ── + +async function readProjects(filePath) { + debugLog(`readProjects 入口: ${filePath}`) + const resolvedPath = resolveGlobPath(filePath) + if (canDeleteProjects(resolvedPath)) return readProjectsFromSQLite(resolvedPath) + if (!fs.existsSync(resolvedPath)) throw new Error(`文件不存在: ${resolvedPath}`) + + const ext = path.extname(resolvedPath).toLowerCase() + if (ext === '.json') { + const items = await readProjectsFromJSON(resolvedPath) + debugLog(`JSON 解析结果: ${items.length} 个项目`) + return items + } + if (ext === '.xml') { + const items = readProjectsFromXML(resolvedPath) + debugLog(`XML 解析结果: ${items.length} 个项目`) + return items + } + try { + const items = await readProjectsFromSQLite(resolvedPath) + debugLog(`自动探测 SQLite 结果: ${items.length} 个项目`) + return items + } catch { + const items = await readProjectsFromJSON(resolvedPath) + debugLog(`自动探测 JSON 结果: ${items.length} 个项目`) + return items + } +} + +// ─── 删除项目记录 ── + +async function deleteProject(dbPath, uri) { + const resolvedPath = resolveGlobPath(dbPath) + if (!canDeleteProjects(resolvedPath)) throw new Error('该历史格式不支持删除') + + for (const filePath of sqliteCandidates(resolvedPath)) { + const db = openDatabase(filePath, false) + try { + // 先获取写锁,再读取最新历史,防止覆盖编辑器同时提交的记录。 + db.exec('BEGIN IMMEDIATE') + const select = db.prepare('SELECT value FROM ItemTable WHERE key = ?') + for (const key of RECENT_KEYS) { + const data = recentHistory(select.get(key)?.value) + const entries = data.entries.filter(entry => recentUri(entry) !== uri) + if (entries.length === data.entries.length) continue + + db.prepare('UPDATE ItemTable SET value = ? WHERE key = ?') + .run(JSON.stringify({ ...data, entries }), key) + db.exec('COMMIT') + return + } + db.exec('ROLLBACK') + } finally { + db.close() + } + } + throw new Error('未找到匹配的记录') +} + +// ─── IDE 配置管理 ── + +const STORAGE_KEY = 'ide-ides' +const LEGACY_STORAGE_KEY = 'vsc-ides' + +function getIDEs() { + try { + const data = window.ztools.dbStorage.getItem(STORAGE_KEY) + if (Array.isArray(data)) { + debugLog(`getIDEs 从新 key 读取: ${data.length} 个`) + return data + } + const legacy = window.ztools.dbStorage.getItem(LEGACY_STORAGE_KEY) + if (Array.isArray(legacy) && legacy.length > 0) { + debugLog(`getIDEs 从旧 key 迁移: ${legacy.length} 个`) + window.ztools.dbStorage.setItem(STORAGE_KEY, legacy) + return legacy + } + debugLog('getIDEs 未找到配置') + return [] + } catch (e) { + debugLog(`getIDEs 异常: ${e}`) + return [] + } +} + +function saveIDEs(ides) { + debugLog(`saveIDEs: ${ides.length} 个`) + window.ztools.dbStorage.setItem(STORAGE_KEY, ides) +} + +// ─── 打开项目 ── + +const defaultShell = process.platform === 'darwin' ? 'zsh -l -i -c' : process.platform === 'linux' ? 'bash -l -i -c' : '' + +// 转义 shell 特殊字符,防止命令注入 +function escapeShellArg(arg) { + return "'" + arg.replace(/'/g, "'\\''") + "'" +} + +const runShell = promisify(exec) +const runFile = promisify(execFile) +const launchOptions = { windowsHide: true, timeout: 10000 } + +const macEditors = new Map([ + ['code', { apps: ['Visual Studio Code'], bundledCLI: 'code' }], + ['cursor', { apps: ['Cursor'], bundledCLI: 'cursor' }], + ['codium', { apps: ['VSCodium'], bundledCLI: 'codium' }], + ['idea', { apps: ['IntelliJ IDEA', 'IntelliJ IDEA CE', 'IntelliJ IDEA Ultimate'] }], + ['pycharm', { apps: ['PyCharm', 'PyCharm CE'] }], + ['webstorm', { apps: ['WebStorm'] }], + ['goland', { apps: ['GoLand'] }], + ['qoder', { apps: ['Qoder IDE', 'Qoder'], bundledCLI: 'code' }] +]) + +function findMacAppFile(app, ...parts) { + return ['/Applications', path.join(homedir(), 'Applications')] + .map(dir => path.join(dir, `${app}.app`, ...parts)) + .find(filePath => fs.existsSync(filePath)) +} + +function preferredMacApp(editor) { + return editor.apps.length === 1 + ? editor.apps[0] + : editor.apps.find(app => findMacAppFile(app)) || editor.apps[0] +} + +function macOpenCommand(app) { + return `/usr/bin/open -a "${app}"` +} + +function matchMacOpenCommand(command) { + const fullCommand = command.startsWith('open ') ? `/usr/bin/${command}` : command + for (const [launcher, editor] of macEditors) { + const app = editor.apps.find(name => macOpenCommand(name) === fullCommand) + if (app) return { launcher, app, bundledCLI: editor.bundledCLI } + } +} + +function runConfiguredCommand(command, args, shell) { + const cmd = [command, ...args.slice(0, -1), escapeShellArg(args.at(-1))].join(' ') + const fullCmd = shell ? `${shell} ${escapeShellArg(cmd)}` : cmd + debugLog(`执行: ${fullCmd}`) + return runShell(fullCmd, launchOptions) +} + +function findBundledCLI(app, binary) { + return findMacAppFile(app, 'Contents', 'Resources', 'app', 'bin', binary) +} + +async function openProject(command, uri, shell) { + const effectiveShell = shell || defaultShell + const isRemote = /^[a-z]+-remote:\/\//.test(uri) + const args = isRemote ? [uri.endsWith('.code-workspace') ? '--file-uri' : '--folder-uri', uri] : [uriToPath(uri)] + const launcher = command.trim() + const isMac = process.platform === 'darwin' + + try { + // macOS open 只用于本地路径,远程 URI 仍需由编辑器的 CLI 接收。 + const macPreset = isMac && isRemote ? matchMacOpenCommand(launcher) : null + if (macPreset) { + const { app, bundledCLI } = macPreset + if (!bundledCLI) throw new Error(`${app} 的预设无法打开远程项目`) + const cli = findBundledCLI(app, bundledCLI) + if (cli) await runFile(cli, args, launchOptions) + else await runConfiguredCommand(macPreset.launcher, args, effectiveShell) + return + } + + try { + await runConfiguredCommand(command, args, effectiveShell) + } catch (error) { + // 兼容升级前保存的预设命令。 + const editor = isMac ? macEditors.get(launcher) : null + if (error.code !== 127 || !editor) throw error + + const app = preferredMacApp(editor) + if (!isRemote) { + await runFile('/usr/bin/open', ['-a', app, '--', path.resolve(args[0])], launchOptions) + } else { + if (!editor.bundledCLI) throw error + const cli = findBundledCLI(app, editor.bundledCLI) + if (!cli) throw error + await runFile(cli, args, launchOptions) + } + } + } catch (error) { + debugLog(`命令失败: ${error.message}`) + throw new Error(`启动失败: ${error.stderr?.trim() || error.message}`) + } +} + +// ─── 预设 ── + +const jetBrainsDir = () => { + const home = homedir() + if (process.platform === 'darwin') return path.join(home, 'Library', 'Application Support', 'JetBrains') + if (process.platform === 'win32') return path.join(process.env.APPDATA || home, 'JetBrains') + return path.join(home, '.config', 'JetBrains') +} + +function vsCodeDatabasePaths() { + return [ + path.join(homedir(), '.vscode-shared', 'sharedStorage', 'state.vscdb'), + path.join(window.ztools.getPath('appData'), 'Code', 'User', 'globalStorage', 'state.vscdb') + ] +} + +function getPresets() { + const appData = window.ztools.getPath('appData') + const jbDir = jetBrainsDir() + return { + vscode: { + name: 'VS Code', + command: 'code', + dbPaths: [ + ...vsCodeDatabasePaths(), + path.join(appData, 'Code', 'storage.json') + ] + }, + cursor: { + name: 'Cursor', + command: 'cursor', + dbPaths: [ + path.join(appData, 'Cursor', 'User', 'globalStorage', 'state.vscdb'), + path.join(appData, 'Cursor', 'storage.json') + ] + }, + vscodium: { + name: 'VSCodium', + command: 'codium', + dbPaths: [ + path.join(appData, 'VSCodium', 'User', 'globalStorage', 'state.vscdb'), + path.join(appData, 'VSCodium', 'storage.json') + ] + }, + idea: { + name: 'IntelliJ IDEA', + command: 'idea', + dbPaths: [path.join(jbDir, 'IntelliJIdea*', 'options', 'recentProjects.xml')] + }, + pycharm: { + name: 'PyCharm', + command: 'pycharm', + dbPaths: [path.join(jbDir, 'PyCharm*', 'options', 'recentProjects.xml')] + }, + webstorm: { + name: 'WebStorm', + command: 'webstorm', + dbPaths: [path.join(jbDir, 'WebStorm*', 'options', 'recentProjects.xml')] + }, + goland: { + name: 'GoLand', + command: 'goland', + dbPaths: [path.join(jbDir, 'GoLand*', 'options', 'recentProjects.xml')] + }, + qoder: { + name: 'Qoder', + command: 'qoder', + dbPaths: [ + path.join(appData, 'Qoder', 'User', 'globalStorage', 'state.vscdb'), + path.join(appData, 'Qoder', 'storage.json'), + path.join(appData, 'Qoder', 'User', 'globalStorage', 'storage.json') + ] + } + } +} + +function getQuickFillPresets() { + const aliases = { vscode: 'vsc', vscodium: 'codium' } + return Object.entries(getPresets()).map(([key, preset]) => { + const macEditor = process.platform === 'darwin' ? macEditors.get(preset.command) : null + return { + code: aliases[key] || key, + name: preset.name, + command: macEditor ? macOpenCommand(preferredMacApp(macEditor)) : preset.command, + dbPath: preset.dbPaths.find(p => fs.existsSync(resolveGlobPath(p))) || preset.dbPaths[0], + shell: defaultShell + } + }) +} + +function detectPresetPaths() { + const presets = getPresets() + const result = {} + for (const [key, preset] of Object.entries(presets)) { + debugLog(`detectPresetPaths ${key}: 尝试 ${preset.dbPaths.length} 个路径`) + for (const p of preset.dbPaths) { + const resolved = resolveGlobPath(p) + const exists = fs.existsSync(resolved) + debugLog(` ${exists ? '✓' : '✗'} ${resolved}`) + if (exists) { + result[key] = resolved + break + } + } + } + debugLog('detectPresetPaths 结果:', result) + return result +} + +// ─── 动态 Feature 注册 ── + +const REG_CODES_KEY = 'ide-registered-codes' + +function registerFeatures() { + const ides = getIDEs().filter(ide => ide?.code && ide.code.toLowerCase() !== 'ideopen') + const currentCodes = ides.map(ide => ide.code) + debugLog(`registerFeatures: current=${currentCodes.join(',') || '(none)'}`) + const prevCodes = window.ztools.dbStorage.getItem(REG_CODES_KEY) || [] + + for (const ide of ides) { + try { + window.ztools.setFeature({ + code: ide.code, + explain: `打开 ${ide.name || ide.code} 最近项目`, + cmds: [ide.code], + icon: 'logo.png' + }) + debugLog(`✅ 注册 feature: ${ide.code}`) + } catch (e) { + debugLog(`❌ 注册 ${ide.code} 失败: ${e}`) + } + } + + for (const oldCode of prevCodes) { + if (!currentCodes.includes(oldCode)) { + try { + window.ztools.removeFeature(oldCode) + debugLog(`🗑 删除旧 feature: ${oldCode}`) + } catch (e) { + debugLog(`❌ 删除 feature ${oldCode} 失败: ${e}`) + } + } + } + + window.ztools.dbStorage.setItem(REG_CODES_KEY, currentCodes) +} + +// ─── 启动时注册所有已保存 IDE 的动态指令 ── + +registerFeatures() + +// ─── 暴露给渲染进程 ── + +window.services = { + readProjects, + openProject, + deleteProject, + canDeleteProjects, + getIDEs, + saveIDEs, + registerFeatures, + getPresets, + getQuickFillPresets, + detectPresetPaths, + getAppDataPath: () => window.ztools.getPath('appData'), + getDefaultShell: () => defaultShell, + debugLog, + getLogFile +} diff --git a/plugins/ide-open/scripts/gen-changelog.mjs b/plugins/ide-open/scripts/gen-changelog.mjs new file mode 100644 index 000000000..5609ccd57 --- /dev/null +++ b/plugins/ide-open/scripts/gen-changelog.mjs @@ -0,0 +1,77 @@ +#!/usr/bin/env node +/** + * 从 ztools-last-publish tag 之后的 commit 自动生成 CHANGELOG.md 条目 + * 约定 commit 格式: type(scope): message + * feat: → Added + * fix: → Fixed + * refactor: → Changed + * chore: → (跳过,不记入) + * docs: → (跳过) + */ +import { execSync } from 'node:child_process' +import { readFileSync, writeFileSync, existsSync } from 'node:fs' + +const TAG = 'ztools-last-publish' +const VERSION = JSON.parse(readFileSync('package.json', 'utf-8')).version + +// 获取上次发布后的 commit messages +function getCommits() { + let range + try { + // 检查 tag 是否存在 + execSync(`git rev-parse --verify refs/tags/${TAG}`, { stdio: 'pipe' }) + range = `${TAG}..HEAD` + } catch { + // tag 不存在,取所有 commit + range = 'HEAD' + } + + const log = execSync(`git log ${range} --pretty=format:"%s" --no-merges`, { encoding: 'utf-8' }) + return log.trim().split('\n').filter(Boolean) +} + +const TYPE_MAP = { + feat: 'Added', + fix: 'Fixed', + refactor: 'Changed', + perf: 'Changed', +} + +const groups = { Added: [], Fixed: [], Changed: [] } + +for (const line of getCommits()) { + const m = line.match(/^(\w+)(?:\(([^)]+)\))?:\s*(.+)$/) + if (!m) continue + const [, type, scope, msg] = m + const section = TYPE_MAP[type] + if (!section) continue // chore, docs, ci 等跳过 + const prefix = scope ? `**${scope}** ` : '' + groups[section].push(`- ${prefix}${msg}`) +} + +// 检查是否已有该版本条目 +const existing = existsSync('CHANGELOG.md') ? readFileSync('CHANGELOG.md', 'utf-8') : '' +if (existing.includes(`## ${VERSION}`)) { + console.log(`CHANGELOG.md 中已存在 v${VERSION} 条目,跳过生成`) + process.exit(0) +} + +// 生成新条目 +const sections = Object.entries(groups) + .filter(([, items]) => items.length > 0) + .map(([title, items]) => `### ${title}\n${items.join('\n')}`) + .join('\n\n') + +if (!sections) { + console.log('没有可记录的变更(feat/fix/refactor)') + process.exit(0) +} + +const entry = `## ${VERSION}\n\n${sections}\n` +const output = existing + ? existing.replace(/^# Changelog\n/, `# Changelog\n\n${entry}`) + : `# Changelog\n\n${entry}` + +writeFileSync('CHANGELOG.md', output) +console.log(`✓ 已生成 v${VERSION} 的 CHANGELOG 条目:`) +console.log(entry) diff --git a/plugins/ide-open/src/App.tsx b/plugins/ide-open/src/App.tsx new file mode 100644 index 000000000..2a3379794 --- /dev/null +++ b/plugins/ide-open/src/App.tsx @@ -0,0 +1,35 @@ +import { useEffect, useState } from 'react' +import Settings from './Settings' +import ProjectList from './ProjectList' +import { getIDEs, type IDEItem } from './store' + +type View = + | { page: 'settings' } + | { page: 'projects'; ide: IDEItem } + +export default function App() { + const [view, setView] = useState({ page: 'settings' }) + + useEffect(() => { + window.ztools.onPluginEnter((action) => { + window.services?.debugLog('onPluginEnter', action.code) + if (action.code === 'ideopen') { setView({ page: 'settings' }); return } + const ides = getIDEs() + window.services?.debugLog('当前 IDE 列表', ides.map(i => i.code)) + const ide = ides.find(i => i.code === action.code) + if (ide) { + window.services?.debugLog('匹配到 IDE', ide) + setView({ page: 'projects', ide }) + } else { + window.services?.debugLog('未找到匹配的 IDE', action.code) + } + }) + window.ztools.onPluginOut(() => { + setView({ page: 'settings' }) + }) + }, []) + + if (view.page === 'projects') return setView({ page: 'settings' })} /> + + return +} diff --git a/plugins/ide-open/src/ProjectList/index.css b/plugins/ide-open/src/ProjectList/index.css new file mode 100644 index 000000000..47737b7f7 --- /dev/null +++ b/plugins/ide-open/src/ProjectList/index.css @@ -0,0 +1,100 @@ +.project-list { + display: flex; + flex-direction: column; + height: 100vh; + overflow: hidden; +} + +.pl-ide-name { font-weight: 600; font-size: 14px; } +.pl-count { color: var(--fg2); font-size: 12px; } + +.btn-edit-top { + margin-left: auto; + color: var(--blue); + font-size: 12px; + padding: 2px 8px; + border-radius: 4px; + border: 1px solid var(--border); +} +.btn-edit-top:hover { border-color: var(--blue); background: rgba(22,119,255,.04); } + +.pl-loading, .pl-empty { + text-align: center; + padding: 32px; + color: var(--fg2); + font-size: 12px; +} + +.pl-items { + flex: 1; + overflow-y: auto; + padding: 0 12px 12px; +} + +.pl-item { + display: flex; + align-items: center; + gap: 8px; + padding: 5px 8px; + border-radius: 4px; + cursor: pointer; + margin-bottom: 2px; + transition: background .15s; +} + +.pl-item:hover { background: var(--bg2); } +.pl-item-selected { background: rgba(22,119,255,.08) !important; } + +.pl-item-icon { font-size: 16px; flex-shrink: 0; width: 20px; text-align: center; color: var(--blue); } + +.pl-item-info { flex: 1; min-width: 0; } +.pl-item-name { font-size: 13px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.pl-item-path { font-size: 11px; color: var(--fg2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-top: 1px; } + +.pl-item-copy, +.pl-item-del { + display: grid; + place-items: center; + flex: 0 0 24px; + height: 24px; + padding: 0; + border-radius: 4px; + opacity: 0; + pointer-events: none; + transition: opacity .15s, background .15s, color .15s; +} + +.pl-item-del { color: var(--red); } + +.pl-item:hover :is(.pl-item-copy, .pl-item-del), +.pl-item-selected :is(.pl-item-copy, .pl-item-del), +:is(.pl-item-copy, .pl-item-del):focus-visible { + opacity: 1; + pointer-events: auto; +} + +.pl-item-copy:hover { color: var(--blue); background: rgba(22,119,255,.08); } +.pl-item-del:hover { background: rgba(255,77,79,.08); } + +.pl-item-badge { + font-size: 10px; + padding: 0 5px; + line-height: 18px; + border: 1px solid rgba(22,119,255,.25); + color: var(--blue); + border-radius: 3px; + flex-shrink: 0; +} + +.project-error { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100vh; + gap: 8px; + color: var(--red); + font-size: 12px; + padding: 20px; + text-align: center; +} diff --git a/plugins/ide-open/src/ProjectList/index.tsx b/plugins/ide-open/src/ProjectList/index.tsx new file mode 100644 index 000000000..c3c0b0d13 --- /dev/null +++ b/plugins/ide-open/src/ProjectList/index.tsx @@ -0,0 +1,215 @@ +import { useEffect, useState, useRef } from 'react' +import { readProjects, openProject, deleteProject, type IDEItem, type ProjectItem } from '../store' +import './index.css' + +function IconFolder() { + return ( + + + + + ) +} + +function IconFile() { + return ( + + + + + ) +} + +function IconRemote() { + return ( + + + + + + ) +} + +function IconCopy() { + return ( + + ) +} + +function IconTrash() { + return ( + + ) +} + +export default function ProjectList({ ide, onBack, onEdit }: { ide: IDEItem; onBack?: () => void; onEdit?: () => void }) { + const [projects, setProjects] = useState([]) + const [filtered, setFiltered] = useState([]) + const [search, setSearch] = useState('') + const [loading, setLoading] = useState(true) + const [error, setError] = useState('') + const [selected, setSelected] = useState(-1) + const listRef = useRef(null) + const canDelete = window.services?.canDeleteProjects(ide.dbPath) ?? false + + // refs for document-level keydown (避免频繁重新注册) + const filteredRef = useRef(filtered) + const selectedRef = useRef(selected) + filteredRef.current = filtered + selectedRef.current = selected + + const load = () => { + window.services?.debugLog('ProjectList load', { code: ide.code, command: ide.command, dbPath: ide.dbPath, shell: ide.shell }) + if (!ide.command || !ide.dbPath) { + setError(`请先在设置页配置「${ide.name}」的数据文件路径`) + setLoading(false) + return + } + setLoading(true) + setError('') + setProjects([]) + setFiltered([]) + setSelected(-1) + readProjects(ide.dbPath) + .then(items => { + window.services?.debugLog(`ProjectList 加载完成: ${items.length} 个项目`) + setProjects(items); setFiltered(items) + }) + .catch((err: Error) => { + window.services?.debugLog('ProjectList 读取失败', err.message) + setError(`读取失败: ${err.message}`) + }) + .finally(() => setLoading(false)) + } + + // 设置子输入框 + 加载数据 + useEffect(() => { + setSearch('') + window.ztools.setSubInput((input: { text: string }) => setSearch(input.text), '搜索项目 Enter回车', true) + window.ztools.setSubInputValue('') + window.ztools.setExpendHeight(500) + load() + return () => { window.ztools.removeSubInput() } + }, [ide.code]) + + // 过滤 + useEffect(() => { + setSelected(-1) + const q = search.toLowerCase().trim() + if (!q) { setFiltered(projects); return } + const terms = q.split(/\s+/) + setFiltered(projects.filter(p => + terms.every(t => + p.name.toLowerCase().includes(t) || p.path.toLowerCase().includes(t) || p.label.toLowerCase().includes(t) + ) + )) + }, [search, projects]) + + // 滚动到选中项 + useEffect(() => { + if (selected < 0 || !listRef.current) return + const el = listRef.current.children[selected] as HTMLElement + if (el) el.scrollIntoView({ block: 'nearest' }) + }, [selected]) + + const handleOpen = async (project: ProjectItem) => { + window.services?.debugLog('handleOpen', { command: ide.command, uri: project.uri, shell: ide.shell }) + try { + await openProject(ide.command, project.uri, ide.shell) + window.ztools.hideMainWindow() + window.ztools.outPlugin() + } catch (err: any) { + window.services?.debugLog('handleOpen 失败', err.message) + alert(`打开失败: ${err.message}`) + } + } + + const handleDelete = async (project: ProjectItem) => { + if (!canDelete) return + if (!confirm(`确定从历史记录中删除「${project.name}」?`)) return + try { + await deleteProject(ide.dbPath, project.uri) + load() + } catch (err: any) { + alert(`删除失败: ${err.message}`) + } + } + + const handleCopyPath = (project: ProjectItem) => { + const pathToCopy = project.path || project.uri + if (!pathToCopy) return + window.ztools.copyText(pathToCopy) + window.services?.debugLog('复制路径', pathToCopy) + } + + // 键盘导航(document 级,因为焦点在 ZTools 主搜索框上) + useEffect(() => { + const onKeyDown = (e: KeyboardEvent) => { + const f = filteredRef.current + const s = selectedRef.current + if (!f.length) return + if (e.key === 'ArrowDown') { + e.preventDefault(); setSelected(i => i >= f.length - 1 ? 0 : i + 1) + } else if (e.key === 'ArrowUp') { + e.preventDefault(); setSelected(i => i <= 0 ? f.length - 1 : i - 1) + } else if (e.key === 'Enter' && f[s] && !(e.target instanceof HTMLButtonElement)) { + e.preventDefault(); handleOpen(f[s]) + } + } + document.addEventListener('keydown', onKeyDown) + return () => document.removeEventListener('keydown', onKeyDown) + }, []) + + return ( +
+
+ {onBack && } + {ide.name} + {filtered.length} 个项目 + {onEdit && } +
+ + {loading &&
加载中...
} + {error && !loading &&

{error}

} + {!loading && !error && filtered.length === 0 && ( +
{search ? '没有匹配的项目' : '暂无最近项目'}
+ )} + +
+ {filtered.map((p, i) => ( +
handleOpen(p)} + onContextMenu={canDelete ? e => { e.preventDefault(); handleDelete(p) } : undefined} + onMouseEnter={() => setSelected(i)}> +
+ {p.type === 'remote' ? : p.type === 'workspace' || p.type === 'file' ? : } +
+
+
{p.name}
+
{p.path || p.uri}
+
+ + {canDelete && ( + + )} + {p.type === 'remote' && 远程} +
+ ))} +
+
+ ) +} diff --git a/plugins/ide-open/src/Settings/index.css b/plugins/ide-open/src/Settings/index.css new file mode 100644 index 000000000..54b1d8a89 --- /dev/null +++ b/plugins/ide-open/src/Settings/index.css @@ -0,0 +1,121 @@ +.settings { padding: 12px; } + +.settings h2 { + margin: 0 0 2px; + font-size: 14px; + font-weight: 600; +} + +.settings .subtitle { + color: var(--fg2); + font-weight: 400; + font-size: 12px; +} + +.empty-hint { color: var(--fg2); text-align: center; padding: 32px 0; } + +.btn-toggle { + width: 100%; + padding: 4px; + text-align: center; + border: 1px dashed var(--border); + border-radius: 4px; + color: var(--fg2); + font-size: 12px; + margin-bottom: 8px; +} +.btn-toggle:hover { border-color: var(--blue); color: var(--blue); } + +.add-form { + padding: 10px; + border: 1px solid var(--border); + border-radius: 4px; + margin-bottom: 8px; + background: var(--bg2); +} + +.add-form label { + display: block; + margin-bottom: 6px; + font-size: 12px; +} +.add-form label span { color: var(--fg2); margin-bottom: 2px; display: block; } +.add-form input { display: block; width: 100%; } + +.quick-fill { + display: flex; + gap: 4px; + flex-wrap: wrap; + margin-bottom: 8px; +} +.qf-label { color: var(--fg2); line-height: 22px; font-size: 12px; } + +.btn-qf { + padding: 1px 8px; + border: 1px solid var(--border); + border-radius: 4px; + color: var(--fg2); + font-size: 12px; + line-height: 20px; +} +.btn-qf:hover { border-color: var(--blue); color: var(--blue); } + +.btn-submit { + width: 100%; + padding: 4px; + margin-top: 4px; + background: var(--blue); + color: #fff; + border-radius: 4px; + font-size: 12px; + line-height: 22px; +} +.btn-submit:hover { opacity: .85; } + +.ide-table { width: 100%; border-collapse: collapse; font-size: 12px; } + +.ide-table th { + text-align: left; + padding: 5px 8px; + font-weight: 500; + color: var(--fg2); + border-bottom: 1px solid var(--border); + font-size: 11px; +} + +.ide-table td { + padding: 4px 8px; + border-bottom: 1px solid var(--border); + vertical-align: middle; +} + +.ide-table td code { font-weight: 600; font-family: monospace; font-size: 12px; color: var(--blue); } + +.ide-table td input { + width: 100%; + padding: 2px 6px; + border: 1px solid transparent; + background: transparent; + border-radius: 2px; +} +.ide-table td input:focus { border-color: var(--blue); background: var(--bg); } + +.td-path { max-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.td-actions { white-space: nowrap; text-align: right; } + +.btn-edit { + color: var(--blue); + font-size: 12px; + padding: 1px 6px; + border-radius: 3px; +} +.btn-edit:hover { background: rgba(22,119,255,.06); } + +.btn-remove { + color: var(--red); + font-size: 13px; + padding: 1px 4px; + border-radius: 3px; + opacity: .6; +} +.btn-remove:hover { opacity: 1; background: rgba(255,77,79,.06); } diff --git a/plugins/ide-open/src/Settings/index.tsx b/plugins/ide-open/src/Settings/index.tsx new file mode 100644 index 000000000..b7130c341 --- /dev/null +++ b/plugins/ide-open/src/Settings/index.tsx @@ -0,0 +1,149 @@ +import { useEffect, useState } from 'react' +import { getIDEs, saveIDEs, getQuickFillPresets, getDefaultShell, type IDEItem } from '../store' +import './index.css' + +const emptyForm = (): IDEItem => ({ code: '', name: '', command: '', dbPath: '', shell: '' }) + +export default function Settings({ onBack, editIDE }: { onBack?: () => void; editIDE?: IDEItem }) { + const [ides, setIDEs] = useState([]) + const [showForm, setShowForm] = useState(false) + const [form, setForm] = useState(emptyForm()) + const [editingIdx, setEditingIdx] = useState(-1) + const defaultShell = getDefaultShell() + + useEffect(() => { + setIDEs(getIDEs()) + }, []) + + useEffect(() => { + if (!editIDE) return + const idx = ides.findIndex(i => i.code === editIDE.code) + if (idx >= 0) { + setForm({ ...editIDE }) + setEditingIdx(idx) + setShowForm(true) + } + }, [editIDE]) + + const save = () => { + const code = form.code.trim() + const normalizedCode = code.toLowerCase() + if (!code) { alert('请输入别名'); return } + if (normalizedCode === 'ideopen') { alert('ideopen 是设置页的保留别名'); return } + if (ides.some((ide, index) => index !== editingIdx && ide.code.toLowerCase() === normalizedCode)) { + alert('别名已存在') + return + } + if (!form.command.trim()) { alert('请输入启动命令'); return } + if (!form.dbPath.trim()) { alert('请输入历史文件路径'); return } + const entry: IDEItem = { code, name: form.name.trim() || code, command: form.command.trim(), dbPath: form.dbPath.trim(), shell: form.shell.trim() } + let list + if (editingIdx >= 0) { + list = ides.map((item, i) => i === editingIdx ? entry : item) + } else { + list = [...ides, entry] + } + setIDEs(list) + saveIDEs(list) + setForm(emptyForm()) + setEditingIdx(-1) + setShowForm(false) + } + + const del = (idx: number) => { + const removed = ides[idx] + if (!confirm(`确定删除「${removed.name || removed.code}」的配置?`)) return + const list = ides.filter((_, i) => i !== idx) + setIDEs(list) + saveIDEs(list) + } + + const startEdit = (idx: number) => { + const ide = ides[idx] + setForm({ code: ide.code, name: ide.name, command: ide.command, dbPath: ide.dbPath, shell: ide.shell || defaultShell }) + setEditingIdx(idx) + setShowForm(true) + } + + const startAdd = () => { + setForm(emptyForm()) + setEditingIdx(-1) + setShowForm(true) + } + + const fill = (preset: any) => { + setForm({ code: preset.code, name: preset.name, command: preset.command, dbPath: preset.dbPath, shell: preset.shell || '' }) + } + + const isEditing = editingIdx >= 0 + const defaults = getQuickFillPresets() + + return ( +
+
+ {onBack && } +

ideOpen 配置 IDE

+
+ + + + {showForm && ( +
+ {!isEditing && ( +
+ 快速填入: + {defaults.map(p => ( + + ))} +
+ )} + + + + + + +
+ )} + + {ides.length === 0 && ( +

还没有配置,点「+ 新增配置」添加

+ )} + + {ides.length > 0 && ( + + + + + + + + + + + + + {ides.map((ide, idx) => ( + + + + + + + + + ))} + +
别名名称启动命令shell历史文件路径
{ide.code}{ide.name}{ide.command}{ide.shell || '-'}{ide.dbPath} + + +
+ )} +
+ ) +} diff --git a/plugins/ide-open/src/env.d.ts b/plugins/ide-open/src/env.d.ts new file mode 100644 index 000000000..d4b7115e4 --- /dev/null +++ b/plugins/ide-open/src/env.d.ts @@ -0,0 +1,27 @@ +/// +/// + +interface Services { + readProjects: (dbPath: string) => Promise + openProject: (command: string, uri: string, shell?: string) => Promise + deleteProject: (dbPath: string, uri: string) => Promise + canDeleteProjects: (dbPath: string) => boolean + getIDEs: () => any[] + saveIDEs: (ides: any[]) => void + registerFeatures: () => void + getPresets: () => Record + getQuickFillPresets: () => any[] + detectPresetPaths: () => Record + getAppDataPath: () => string + getDefaultShell: () => string + debugLog: (message: string, data?: any) => void + getLogFile: () => string +} + +declare global { + interface Window { + services: Services + } +} + +export {} diff --git a/plugins/ide-open/src/main.css b/plugins/ide-open/src/main.css new file mode 100644 index 000000000..9386e1aa1 --- /dev/null +++ b/plugins/ide-open/src/main.css @@ -0,0 +1,171 @@ +:root { + --blue: #1677ff; + --red: #ff4d4f; + --fg: #333; + --fg2: #999; + --bg: #fff; + --bg2: #fafafa; + --border: #e8e8e8; + --shadow: rgba(0,0,0,.06); +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + padding: 0; + background: var(--bg); + color: var(--fg); + font: 12px/1.6 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; +} + +::-webkit-scrollbar { width: 5px; } +::-webkit-scrollbar-track { background: transparent; } +::-webkit-scrollbar-thumb { background: #d9d9d9; border-radius: 4px; } + +input { + font: inherit; + color: var(--fg); + background: var(--bg); + border: 1px solid var(--border); + border-radius: 4px; + padding: 3px 7px; + outline: none; + transition: border .2s; +} +input:focus { border-color: var(--blue); box-shadow: 0 0 0 2px rgba(22,119,255,.1); } +input::placeholder { color: #bbb; } + +button { + font: inherit; + cursor: pointer; + border: none; + background: none; + color: inherit; +} +button:active { opacity: .7; } + +/* ── 首页 ── */ + +.app-home { padding: 12px; } + +.app-home h2 { + margin: 0 0 8px; + font-size: 14px; + font-weight: 600; +} + +.app-home .subtitle { + color: var(--fg2); + font-weight: 400; + font-size: 12px; +} + +.app-home .empty-hint { + color: var(--fg2); + text-align: center; + padding: 32px 0; +} + +.ide-card { + display: flex; + align-items: center; + justify-content: space-between; + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 4px; + margin-bottom: 6px; + transition: border-color .2s; +} +.ide-card:hover { border-color: var(--blue); } + +.ide-card-body { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; + flex: 1; +} + +.ide-card-body:hover .ide-card-name { color: var(--blue); } + +.ide-card-code { + font-weight: 600; + font-family: monospace; + font-size: 12px; + color: var(--blue); + background: rgba(22,119,255,.06); + padding: 0 6px; + border-radius: 3px; + line-height: 20px; +} + +.ide-card-name { font-size: 13px; transition: color .2s; } + +.ide-card-actions { + display: flex; + align-items: center; + gap: 4px; +} + +.ide-card-btn { + font-size: 11px; + color: var(--fg2); + padding: 1px 6px; + border-radius: 3px; +} +.ide-card-btn:hover { background: rgba(22,119,255,.06); color: var(--blue); } + +.ide-card-arrow { + color: #ccc; + font-size: 14px; + cursor: pointer; + padding: 2px 4px; + border-radius: 3px; +} +.ide-card-arrow:hover { background: var(--bg2); color: var(--blue); } + +.btn-add-ide { + display: block; + width: 100%; + padding: 4px; + text-align: center; + border: 1px dashed var(--border); + border-radius: 4px; + color: var(--fg2); + font-size: 12px; + margin-top: 4px; +} +.btn-add-ide:hover { border-color: var(--blue); color: var(--blue); } + +/* ── 顶部栏 ── */ + +.top-bar { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px 4px; + margin-bottom: 4px; +} + +.btn-back { + color: var(--blue); + font-size: 12px; + padding: 2px 4px; +} +.btn-back:hover { opacity: .75; } + +@media (prefers-color-scheme: dark) { + :root { + --fg: #e0e0e0; + --fg2: #888; + --bg: #1a1a1a; + --bg2: #222; + --border: #333; + --shadow: transparent; + } + input { background: #222; border-color: #444; } + input:focus { border-color: var(--blue); box-shadow: 0 0 0 2px rgba(22,119,255,.15); } + input::placeholder { color: #666; } + .ide-card-code { background: rgba(22,119,255,.12); } +} diff --git a/plugins/ide-open/src/main.tsx b/plugins/ide-open/src/main.tsx new file mode 100644 index 000000000..73fb20139 --- /dev/null +++ b/plugins/ide-open/src/main.tsx @@ -0,0 +1,6 @@ +import React from 'react' +import ReactDOM from 'react-dom/client' +import './main.css' +import App from './App' + +ReactDOM.createRoot(document.getElementById('root')!).render() diff --git a/plugins/ide-open/src/store.ts b/plugins/ide-open/src/store.ts new file mode 100644 index 000000000..5d3f4796a --- /dev/null +++ b/plugins/ide-open/src/store.ts @@ -0,0 +1,74 @@ +export interface IDEItem { + code: string + name: string + command: string + dbPath: string + shell?: string +} + +export interface ProjectItem { + name: string + path: string + uri: string + type: 'folder' | 'file' | 'workspace' | 'remote' + label: string +} + +const STORAGE_KEY = 'ide-ides' + +export function getIDEs(): IDEItem[] { + try { + const data = window.ztools.dbStorage.getItem(STORAGE_KEY) + return Array.isArray(data) ? data : [] + } catch { return [] } +} + +export function saveIDEs(ides: IDEItem[]) { + window.ztools.dbStorage.setItem(STORAGE_KEY, ides) + window.services?.registerFeatures() +} + +export function addIDE(ide: IDEItem) { + const ides = getIDEs() + const idx = ides.findIndex(i => i.code === ide.code) + if (idx >= 0) ides[idx] = ide + else ides.push(ide) + saveIDEs(ides) +} + +export function removeIDE(code: string) { + saveIDEs(getIDEs().filter(i => i.code !== code)) +} + +export function getPresets() { + return window.services?.getPresets() || {} +} + +export function getQuickFillPresets() { + return window.services?.getQuickFillPresets() || [] +} + +export async function detectPresetPaths() { + return window.services?.detectPresetPaths() || {} +} + +export async function readProjects(dbPath: string): Promise { + if (!window.services) throw new Error('preload 未就绪') + return window.services.readProjects(dbPath) +} + +export async function openProject(command: string, uri: string, shell?: string) { + return window.services.openProject(command, uri, shell) +} + +export async function deleteProject(dbPath: string, uri: string) { + return window.services.deleteProject(dbPath, uri) +} + +export function getAppDataPath() { + return window.services?.getAppDataPath() || '' +} + +export function getDefaultShell() { + return window.services?.getDefaultShell() || '' +} diff --git a/plugins/ide-open/tests/launch.test.cjs b/plugins/ide-open/tests/launch.test.cjs new file mode 100644 index 000000000..80502c33c --- /dev/null +++ b/plugins/ide-open/tests/launch.test.cjs @@ -0,0 +1,124 @@ +const assert = require('node:assert/strict') +const childProcess = require('node:child_process') +const fs = require('node:fs') +const path = require('node:path') +const { test, beforeEach, mock } = require('node:test') +const { pathToFileURL } = require('node:url') + +const project = path.resolve("中文项目 with spaces's") +const uri = pathToFileURL(project).href +const macOnly = { skip: process.platform !== 'darwin' } +const missingCode = Object.assign(new Error('code: command not found'), { code: 127 }) +let shellError +const shell = mock.fn((_command, _options, done) => done(shellError, '', '')) +const file = mock.fn((_command, _args, _options, done) => done(null, '', '')) + +global.window = { + ztools: { + getPath: () => '/nonexistent-test-app-data', + dbStorage: { getItem: () => null, setItem: () => {} } + } +} +const { exec, execFile } = childProcess +childProcess.exec = shell +childProcess.execFile = file +require('../public/preload/services.js') +Object.assign(childProcess, { exec, execFile }) +const { openProject, getQuickFillPresets } = window.services + +beforeEach(() => { + shellError = null + shell.mock.resetCalls() + file.mock.resetCalls() +}) + +test('missing code opens the local project in the macOS VS Code app', macOnly, async () => { + shellError = missingCode + await openProject('code', uri) + assert.equal(shell.mock.callCount(), 1) + assert.deepEqual(file.mock.calls[0].arguments.slice(0, 2), [ + '/usr/bin/open', ['-a', 'Visual Studio Code', '--', project] + ]) +}) + +test('missing idea opens the local project in IntelliJ IDEA on macOS', macOnly, async t => { + t.mock.method(fs, 'existsSync', () => false) + shellError = Object.assign(new Error('idea: command not found'), { code: 127 }) + await openProject('idea', uri, 'zsh -l -i -c') + assert.equal(shell.mock.callCount(), 1) + assert.deepEqual(file.mock.calls[0].arguments.slice(0, 2), [ + '/usr/bin/open', ['-a', 'IntelliJ IDEA', '--', project] + ]) +}) + +test('missing code uses the bundled CLI for remote directories and workspaces', macOnly, async t => { + shellError = missingCode + const bundled = '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code' + t.mock.method(fs, 'existsSync', filePath => filePath === bundled) + + const remote = 'vscode-remote://ssh-remote+fixture/projects/demo' + await openProject('code', remote) + await openProject('code', remote + '.code-workspace') + assert.deepEqual(file.mock.calls.map(call => call.arguments.slice(0, 2)), [ + [bundled, ['--folder-uri', remote]], + [bundled, ['--file-uri', remote + '.code-workspace']] + ]) +}) + +test('quick fill exposes all eight macOS app commands and uses them for local paths', macOnly, async t => { + t.mock.method(fs, 'existsSync', () => false) + const apps = ['Visual Studio Code', 'Cursor', 'VSCodium', 'IntelliJ IDEA', 'PyCharm', 'WebStorm', 'GoLand', 'Qoder IDE'] + const presets = getQuickFillPresets() + assert.deepEqual(presets.map(preset => preset.command), apps.map(app => `/usr/bin/open -a "${app}"`)) + + for (const { command } of presets) { + await openProject(command, uri) + } + for (const [i, call] of shell.mock.calls.entries()) { + assert.ok(call.arguments[0].includes(`/usr/bin/open -a "${apps[i]}"`)) + assert.ok(call.arguments[0].includes('中文项目 with spaces')) + } + assert.equal(shell.mock.callCount(), apps.length) + assert.equal(file.mock.callCount(), 0) +}) + +test('quick fill recognizes installed alternate app names on macOS', macOnly, t => { + const installed = new Set(['/Applications/Qoder.app', '/Applications/IntelliJ IDEA CE.app', '/Applications/PyCharm CE.app']) + t.mock.method(fs, 'existsSync', filePath => installed.has(filePath)) + const presets = new Map(getQuickFillPresets().map(({ code, command }) => [code, command])) + assert.equal(presets.get('qoder'), '/usr/bin/open -a "Qoder"') + assert.equal(presets.get('idea'), '/usr/bin/open -a "IntelliJ IDEA CE"') + assert.equal(presets.get('pycharm'), '/usr/bin/open -a "PyCharm CE"') +}) + +test('macOS app presets route remote URIs to the corresponding bundled CLI', macOnly, async t => { + const apps = [['Visual Studio Code', 'code'], ['Cursor', 'cursor'], ['VSCodium', 'codium'], ['Qoder IDE', 'code']] + const binaries = apps.map(([app, cli]) => `/Applications/${app}.app/Contents/Resources/app/bin/${cli}`) + t.mock.method(fs, 'existsSync', filePath => binaries.includes(filePath)) + const remote = 'vscode-remote://ssh-remote+fixture/projects/demo.code-workspace' + for (const [app] of apps) { + await openProject(`/usr/bin/open -a "${app}"`, remote) + } + assert.deepEqual(file.mock.calls.map(call => call.arguments.slice(0, 2)), + binaries.map(cli => [cli, ['--file-uri', remote]])) + assert.equal(shell.mock.callCount(), 0) +}) + +test('a macOS remote app preset can use the existing CLI on PATH', macOnly, async t => { + t.mock.method(fs, 'existsSync', () => false) + const remote = 'vscode-remote://ssh-remote+fixture/projects/demo' + await openProject('open -a "VSCodium"', remote) + assert.ok(shell.mock.calls[0].arguments[0].includes('codium --folder-uri')) + assert.equal(file.mock.callCount(), 0) +}) + +test('configured commands use the shell and report failures without retrying', async () => { + await openProject('code', uri) + assert.equal(file.mock.callCount(), 0) + + shellError = Object.assign(new Error('code failed'), { code: 1 }) + await assert.rejects(openProject('code', uri), /code failed/) + shellError = missingCode + await assert.rejects(openProject('custom-editor', uri), /code: command not found/) + assert.equal(file.mock.callCount(), 0) +}) diff --git a/plugins/ide-open/tests/services.test.cjs b/plugins/ide-open/tests/services.test.cjs new file mode 100644 index 000000000..4bb5edf96 --- /dev/null +++ b/plugins/ide-open/tests/services.test.cjs @@ -0,0 +1,178 @@ +const assert = require('node:assert/strict') +const fs = require('node:fs') +const os = require('node:os') +const path = require('node:path') +const { DatabaseSync } = require('node:sqlite') +const { test, after, mock } = require('node:test') +const { pathToFileURL } = require('node:url') + +const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ide-open-tests-')) +const appData = path.join(root, 'app-data') +const store = new Map() +const features = new Map() +mock.method(os, 'homedir', () => path.join(root, 'home')) + +global.window = { + ztools: { + getPath: () => appData, + isDev: () => false, + dbStorage: { + getItem: key => store.get(key), + setItem: (key, value) => store.set(key, value) + }, + setFeature: feature => features.set(feature.code, feature), + removeFeature: code => features.delete(code) + } +} +require('../public/preload/services.js') +const services = window.services +const historyKey = 'history.recentlyOpenedPathsList' + +after(() => { + fs.rmSync(root, { recursive: true, force: true }) + mock.restoreAll() + delete global.window +}) + +function fixturePath(relativePath) { + const filePath = path.join(root, relativePath) + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + return filePath +} + +function writeFixture(relativePath, content) { + const filePath = fixturePath(relativePath) + fs.writeFileSync(filePath, content) + return filePath +} + +function createDB(filePath) { + const db = new DatabaseSync(filePath) + db.exec('CREATE TABLE ItemTable (key TEXT PRIMARY KEY, value TEXT)') + return db +} + +test('SQLite reads committed WAL records and deletion preserves concurrent IDE history', async () => { + const dbPath = fixturePath('WAL 中文 & %.vscdb') + const first = { folderUri: 'file:///tmp/first' } + const second = { workspace: { configPath: 'file:///tmp/second.code-workspace' } } + const recent = { folderUri: 'vscode-remote://ssh-remote%2Btest/project' } + const writer = createDB(dbPath) + try { + writer.exec('PRAGMA journal_mode = WAL') + const put = writer.prepare('INSERT OR REPLACE INTO ItemTable (key, value) VALUES (?, ?)') + put.run(historyKey, JSON.stringify({ entries: [first], other: 'preserved' })) + writer.exec('PRAGMA wal_checkpoint(TRUNCATE)') + put.run(historyKey, JSON.stringify({ entries: [null, first, second, recent], other: 'preserved' })) + put.run('some-other-setting', 'preserved') + assert.ok(fs.statSync(dbPath + '-wal').size > 0) + + const items = await services.readProjects(dbPath) + assert.deepEqual(items.map(item => item.type), ['folder', 'workspace', 'remote']) + assert.deepEqual(items.map(item => item.uri), [first.folderUri, second.workspace.configPath, recent.folderUri]) + + await services.deleteProject(dbPath, first.folderUri) + const get = writer.prepare('SELECT value FROM ItemTable WHERE key = ?') + assert.deepEqual(JSON.parse(get.get(historyKey).value), { + entries: [null, second, recent], + other: 'preserved' + }) + assert.equal(get.get('some-other-setting').value, 'preserved') + assert.equal(writer.prepare('PRAGMA integrity_check').get().integrity_check, 'ok') + } finally { + writer.close() + } +}) + +test('SQLite deletion leaves another connection’s transaction intact', async () => { + const dbPath = fixturePath('busy.vscdb') + const uri = 'file:///tmp/locked' + const writer = createDB(dbPath) + try { + writer.prepare('INSERT INTO ItemTable VALUES (?, ?)').run(historyKey, JSON.stringify({ entries: [uri] })) + writer.exec('BEGIN IMMEDIATE') + await assert.rejects(services.deleteProject(dbPath, uri), /database is locked/) + writer.exec('COMMIT') + assert.equal((await services.readProjects(dbPath))[0].uri, uri) + } finally { + writer.close() + } +}) + +test('JetBrains XML resolves the latest version, home macros, entities and labels', async () => { + const xml = ` + + ` + writeFixture('JetBrains/IntelliJIdea2025.9/options/recentProjects.xml', '') + writeFixture('JetBrains/IntelliJIdea2025.10/options/recentProjects.xml', xml) + const projects = await services.readProjects(path.join(root, 'JetBrains/IntelliJIdea*/options/recentProjects.xml')) + assert.deepEqual(projects.map(item => item.name), ['newer', 'A & B']) + assert.equal(projects[1].path, path.join(os.homedir(), 'A & B')) +}) + +test('old JetBrains lists and JSON history remain readable without deletion', async () => { + const xml = writeFixture('old.xml', ` + + `) + const localPath = path.join(root, "中文项目's") + const uri = pathToFileURL(localPath).href + const json = writeFixture('history.json', JSON.stringify({ openedPathsList: { entries: [{ fileUri: uri }] } })) + + assert.equal((await services.readProjects(xml))[0].name, 'project') + assert.equal((await services.readProjects(json))[0].path, localPath) + for (const filePath of [xml, json]) { + assert.equal(services.canDeleteProjects(filePath), false) + await assert.rejects(services.deleteProject(filePath, uri), /不支持删除/) + } +}) + +test('quick-fill prefers an existing preset and keeps all eight aliases', () => { + const standard = writeFixture('app-data/Code/User/globalStorage/state.vscdb', '') + const cursor = writeFixture('app-data/Cursor/storage.json', '{}') + const presets = services.getQuickFillPresets() + assert.deepEqual(presets.map(item => item.code), ['vsc', 'cursor', 'codium', 'idea', 'pycharm', 'webstorm', 'goland', 'qoder']) + if (process.platform !== 'darwin') { + assert.deepEqual(presets.map(item => item.command), ['code', 'cursor', 'codium', 'idea', 'pycharm', 'webstorm', 'goland', 'qoder']) + } + assert.equal(presets[0].dbPath, standard) + assert.equal(presets[1].dbPath, cursor) + fs.rmSync(standard) +}) + +test('VS Code presets fall back to the other SQLite location when saved paths are missing', async () => { + const [shared, standard] = services.getPresets().vscode.dbPaths + fs.mkdirSync(path.dirname(shared), { recursive: true }) + fs.mkdirSync(path.dirname(standard), { recursive: true }) + const uri = 'file:///tmp/vs-code-project' + const db = createDB(shared) + try { + db.prepare('INSERT INTO ItemTable VALUES (?, ?)').run(historyKey, JSON.stringify({ entries: [uri] })) + } finally { + db.close() + } + assert.equal((await services.readProjects(standard))[0].uri, uri) + fs.renameSync(shared, standard) + assert.equal((await services.readProjects(shared))[0].uri, uri) +}) + +test('deleting the last migrated IDE leaves the list empty and unregisters its alias', () => { + const saved = [{ code: 'old-ide', name: 'Old IDE' }, { code: 'ideopen', name: 'Reserved' }] + store.set('vsc-ides', saved) + services.registerFeatures() + assert.deepEqual(services.getIDEs(), saved) + assert.ok(features.has('old-ide')) + assert.ok(!features.has('ideopen')) + + services.saveIDEs([]) + services.registerFeatures() + assert.deepEqual(services.getIDEs(), []) + assert.ok(!features.has('old-ide')) +}) diff --git a/plugins/ide-open/tsconfig.json b/plugins/ide-open/tsconfig.json new file mode 100644 index 000000000..d49c64dec --- /dev/null +++ b/plugins/ide-open/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": false, + "noImplicitAny": false, + "types": ["@ztools-center/ztools-api-types"] + }, + "include": ["src"] +} diff --git a/plugins/ide-open/vite.config.js b/plugins/ide-open/vite.config.js new file mode 100644 index 000000000..2d5110981 --- /dev/null +++ b/plugins/ide-open/vite.config.js @@ -0,0 +1,8 @@ +import react from '@vitejs/plugin-react' +import { defineConfig } from 'vite' + +// https://vitejs.dev/config/ +export default defineConfig({ + plugins: [react()], + base: './' +})