diff --git a/next/doc/java-parity-migration-plan.md b/next/doc/java-parity-migration-plan.md index 6d4eb965..01a07221 100644 --- a/next/doc/java-parity-migration-plan.md +++ b/next/doc/java-parity-migration-plan.md @@ -286,7 +286,7 @@ type AppSettings = { | 开发 | `java` | 代码运行 | Java/Python/Node.js 三个 Tab、编辑器、格式化、运行结果、历史;Java Tab 兼容旧版 Java/Groovy | P6 | 待对齐验收 | | 开发 | `ymlProperties` | 配置转换 | 转换 Tab、校验、历史 | P3 | 待对齐验收 | | 开发 | `protobuf` | Protobuf | JSON/二进制、Wire、Hex/Base64 三个 Tab | P4 | 待对齐验收 | -| 开发 | `variables` | 环境变量 | 系统变量/Java Properties Tab、表格、导出 | P5 | 待对齐验收 | +| 开发 | `variables` | 环境变量 | 用户/系统变量直接修改、Java Properties Tab、表格、导出 | P5 | 待对齐验收 | | 网络 | `http` | HTTP 请求 | 请求列表、请求编辑、响应 Body/Header/Cookie、历史 | P5 | 待对齐验收 | | 网络 | `host` | Host | Host 列表、编辑器、查找替换、导入导出 | P5 | 待对齐验收 | | 网络 | `net` | 网络/IP | 功能选择、参数区、结果区 | P5 | 待对齐验收 | diff --git a/next/doc/parity/p5-network-system.md b/next/doc/parity/p5-network-system.md index 56b19963..83e66769 100644 --- a/next/doc/parity/p5-network-system.md +++ b/next/doc/parity/p5-network-system.md @@ -13,7 +13,7 @@ | 翻译 | 翻译/单词本/历史三 Tab、源/目标语言、翻译器、自动翻译 | 500 ms 自动翻译、Google/Bing 轻量双实现与 fallback、代理/超时/取消、单词本 CRUD/重译和历史 | 待对齐验收 | | Host | 方案列表、文本编辑、查找替换、导入导出、当前系统 Hosts、切换 | 方案 CRUD、编辑/查找替换、文件导入导出、系统 Hosts 查看、按平台提权写入和 DNS 刷新 | 待对齐验收 | | 网络/IP | 命令输出与 IPv4、ping、DNS、地址解析、WHOIS、本机地址 | 白名单系统命令、IPv4/Long 双向转换、DNS 解析、WHOIS、本机 IPv4/IPv6、停止与错误码 | 待对齐验收 | -| 环境变量 | 系统变量/Java Properties Tab、搜索、表格、导出 | 系统环境变量/Electron 运行属性 Tab、搜索、逐项复制、刷新和完整导出 | 待对齐验收 | +| 环境变量 | 用户/系统变量直接新增、编辑、删除;Java Properties Tab、表格、导出 | 用户/系统变量直接新增、编辑、删除;当前进程/Electron 运行属性只读视图、搜索、复制、刷新和完整导出 | 待对齐验收 | | 系统信息 | 系统/CPU/内存/存储/网络五 Tab | `systeminformation` 结构化采集、五 Tab、刷新、复制、序列号脱敏 | 待对齐验收 | ## 2. 主进程与设置边界 @@ -33,7 +33,7 @@ - [x] 翻译保留翻译/单词本/历史 Tab 顺序,单词本或历史回填不会触发重复在线翻译。 - [x] Host 保留“左侧方案 + 右侧工具栏/编辑器”,系统 Hosts 通过独立对话框查看。 - [x] 网络/IP 保留“左侧命令结果 + 右侧功能区”的桌面宽屏结构。 -- [x] 环境变量和系统信息保留 Java 版 Tab、表格/键值结构与刷新、复制、导出操作。 +- [x] 环境变量和系统信息保留 Java 版 Tab、表格/键值结构与刷新、复制、导出操作;两版均支持直接修改用户/系统环境变量。 - [x] 所有页面具有简体中文、英文、日文文案,并跟随系统明暗主题。 - [x] 1440 x 920 浅色与 1080 x 720 深色共 12 张页面截图已建立。 - [x] 两组视口下六页均无窗口级或工作区级横向溢出、控件遮挡和空白渲染。 diff --git a/next/electron/main/index.ts b/next/electron/main/index.ts index fdfcf806..1b97a54e 100644 --- a/next/electron/main/index.ts +++ b/next/electron/main/index.ts @@ -92,6 +92,8 @@ import { QuickNoteVaultRepository } from './quickNoteVaultRepository' import { RuntimeExecutionService } from './runtimeExecutionService' import { normalizeHostInput, + normalizeDeleteEnvironmentVariableInput, + normalizeEnvironmentVariableInput, normalizeHttpRequest, normalizeHttpResponse, normalizeHttpSendInput, @@ -699,6 +701,8 @@ function registerIpc(): void { ipcMain.handle('system:network-command', (_event, value: unknown) => systemService.runNetwork(normalizeNetworkInput(value))) ipcMain.handle('system:cancel', (_event, requestId: unknown) => systemService.cancel(normalizeRequestId(requestId))) ipcMain.handle('system:environment', () => systemService.getEnvironment()) + ipcMain.handle('system:environment-set', (_event, value: unknown) => systemService.setEnvironmentVariable(normalizeEnvironmentVariableInput(value))) + ipcMain.handle('system:environment-delete', (_event, value: unknown) => systemService.deleteEnvironmentVariable(normalizeDeleteEnvironmentVariableInput(value))) ipcMain.handle('system:local-addresses', () => systemService.getLocalAddresses()) ipcMain.handle('system:info', () => systemService.getSystemInfo()) ipcMain.handle('runtime:run', (event, value: unknown) => { diff --git a/next/electron/main/p5Validation.ts b/next/electron/main/p5Validation.ts index abccc029..f74df31e 100644 --- a/next/electron/main/p5Validation.ts +++ b/next/electron/main/p5Validation.ts @@ -1,5 +1,5 @@ import { httpMethods, normalizeTranslationLanguagePair, type HttpCookieEntry, type HttpRequestDraft, type HttpResponseResult, type HttpSendInput, type KeyValueEntry, type SaveTranslationHistoryInput, type SaveTranslationWordInput, type TranslationInput } from '../../src/shared/contracts/network' -import type { NetworkCommandInput, SaveHostProfileInput } from '../../src/shared/contracts/system' +import type { DeleteEnvironmentVariableInput, EnvironmentVariableInput, NetworkCommandInput, SaveHostProfileInput } from '../../src/shared/contracts/system' const networkActions = ['interfaces', 'connections', 'ping', 'ping-range', 'port-scan', 'flush-dns', 'resolve', 'whois'] as const @@ -88,10 +88,44 @@ export function normalizeNetworkInput(value: unknown): NetworkCommandInput { } } +export function normalizeEnvironmentVariableInput(value: unknown): EnvironmentVariableInput { + const record = objectValue(value, 'Invalid environment variable') + return { + scope: environmentScope(record.scope), + key: environmentKey(record.key), + value: environmentValue(record.value) + } +} + +export function normalizeDeleteEnvironmentVariableInput(value: unknown): DeleteEnvironmentVariableInput { + const record = objectValue(value, 'Invalid environment variable') + return { + scope: environmentScope(record.scope), + key: environmentKey(record.key) + } +} + export function normalizeKeyword(value: unknown): string { return typeof value === 'string' ? value.slice(0, 200) : '' } +function environmentScope(value: unknown): EnvironmentVariableInput['scope'] { + if (value !== 'user' && value !== 'system') throw new Error('Invalid environment variable scope') + return value +} + +function environmentKey(value: unknown): string { + const key = stringValue(value, 256) + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error('Invalid environment variable name') + return key +} + +function environmentValue(value: unknown): string { + const result = stringValue(value, 65_535) + if (/[\0\r\n]/.test(result)) throw new Error('Environment variable values cannot contain line breaks') + return result +} + export function normalizePositiveId(value: unknown): number { const id = optionalId(value) if (!id) throw new Error('Invalid id') diff --git a/next/electron/main/systemService.ts b/next/electron/main/systemService.ts index 8cfce9d9..fa75de7a 100644 --- a/next/electron/main/systemService.ts +++ b/next/electron/main/systemService.ts @@ -1,14 +1,17 @@ import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process' -import { access, readFile, unlink, writeFile } from 'node:fs/promises' +import { access, mkdir, readFile, unlink, writeFile } from 'node:fs/promises' import { constants } from 'node:fs' import { lookup } from 'node:dns/promises' import { createConnection, type Socket } from 'node:net' -import { networkInterfaces } from 'node:os' -import { join } from 'node:path' +import { homedir, networkInterfaces } from 'node:os' +import { dirname, join } from 'node:path' import si from 'systeminformation' import type { + DeleteEnvironmentVariableInput, EnvironmentEntry, + EnvironmentScope, EnvironmentSnapshot, + EnvironmentVariableInput, NetworkAction, NetworkCommandInput, NetworkCommandResult, @@ -22,6 +25,8 @@ const maxCommandOutput = 2 * 1024 * 1024 const maxCustomPorts = 4096 const ipRangeConcurrency = 32 const portScanConcurrency = 96 +const environmentAssignment = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/ +const environmentProfileMarker = '# >>> MooTool environment >>>' const commonPorts = new Map([ [20, 'ftp-data'], [21, 'ftp'], [22, 'ssh'], [23, 'telnet'], [25, 'smtp'], [53, 'dns'], [67, 'dhcp'], [68, 'dhcp'], [69, 'tftp'], [80, 'http'], [110, 'pop3'], [123, 'ntp'], @@ -96,7 +101,7 @@ export class SystemService { return true } - getEnvironment(): EnvironmentSnapshot { + async getEnvironment(): Promise { const environment = Object.entries(process.env) .map(([key, value]) => ({ key, value: value ?? '' })) .sort(compareEntries) @@ -112,7 +117,29 @@ export class SystemService { ['process.locale', Intl.DateTimeFormat().resolvedOptions().locale], ['process.timeZone', Intl.DateTimeFormat().resolvedOptions().timeZone] ].map(([key, value]) => ({ key, value })).sort(compareEntries) - return { environment, runtime } + const [user, system] = await Promise.all([ + this.listPersistentEnvironment('user'), + this.listPersistentEnvironment('system') + ]) + return { environment, runtime, user, system } + } + + async setEnvironmentVariable(input: EnvironmentVariableInput): Promise { + if (process.platform === 'win32') { + await writeWindowsEnvironment(input.scope, input.key, input.value) + } else { + await this.writeUnixEnvironment(input.scope, input.key, input.value) + } + await this.syncCurrentProcessEnvironment(input.key) + } + + async deleteEnvironmentVariable(input: DeleteEnvironmentVariableInput): Promise { + if (process.platform === 'win32') { + await writeWindowsEnvironment(input.scope, input.key) + } else { + await this.writeUnixEnvironment(input.scope, input.key) + } + await this.syncCurrentProcessEnvironment(input.key) } getLocalAddresses(): LocalAddressSnapshot { @@ -283,12 +310,165 @@ export class SystemService { const script = `Copy-Item -LiteralPath '${psQuote(temporary)}' -Destination '${psQuote(destination)}' -Force` await execFilePromise('powershell.exe', ['-NoProfile', '-Command', `Start-Process powershell.exe -Verb RunAs -Wait -ArgumentList @('-NoProfile','-Command',${psString(script)})`], 120_000) } else { - await execFilePromise('pkexec', ['/bin/cp', temporary, destination], 120_000) + await execFilePromise('pkexec', ['/bin/sh', '-c', '/bin/cp "$1" "$2" && /bin/chmod 644 "$2"', 'mootool', temporary, destination], 120_000) } } finally { await unlink(temporary).catch(() => undefined) } } + + private async listPersistentEnvironment(scope: EnvironmentScope): Promise { + if (process.platform === 'win32') return readWindowsEnvironment(scope) + const path = unixEnvironmentPath(scope) + const content = await readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return '' + throw error + }) + return parseEnvironmentContent(content) + } + + private async writeUnixEnvironment(scope: EnvironmentScope, key: string, value?: string): Promise { + const destination = unixEnvironmentPath(scope) + const current = await readFile(destination, 'utf8').catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return '' + throw error + }) + const content = updateEnvironmentContent(current, key, value, scope === 'user' || process.platform === 'darwin') + if (scope === 'user') { + await mkdir(dirname(destination), { recursive: true }) + await writeFile(destination, content, { encoding: 'utf8', mode: 0o600 }) + await ensureUnixEnvironmentProfile(destination) + if (process.platform === 'darwin') { + const args = value === undefined ? ['unsetenv', key] : ['setenv', key, value] + await execFilePromise('/bin/launchctl', args, 30_000).catch(() => undefined) + } + return + } + try { + await writeFile(destination, content, 'utf8') + } catch (error) { + if (!isPermissionError(error)) throw error + await this.writeEnvironmentElevated(destination, content) + } + } + + private async syncCurrentProcessEnvironment(key: string): Promise { + const [user, system] = await Promise.all([ + this.listPersistentEnvironment('user'), + this.listPersistentEnvironment('system') + ]) + const matches = (entry: EnvironmentEntry): boolean => process.platform === 'win32' + ? entry.key.toLowerCase() === key.toLowerCase() + : entry.key === key + const effective = user.find(matches) ?? system.find(matches) + if (effective) process.env[key] = effective.value + else delete process.env[key] + } + + private async writeEnvironmentElevated(destination: string, content: string): Promise { + const temporary = join(this.tempDirectory, `mootool-environment-${process.pid}-${Date.now()}`) + await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600 }) + try { + if (process.platform === 'darwin') { + const command = `/bin/cp ${shellQuote(temporary)} ${shellQuote(destination)} && /bin/chmod 644 ${shellQuote(destination)}` + await execFilePromise('/usr/bin/osascript', ['-e', `do shell script ${appleScriptString(command)} with administrator privileges`], 120_000) + } else { + await execFilePromise('pkexec', ['/bin/sh', '-c', '/bin/cp "$1" "$2" && /bin/chmod 644 "$2"', 'mootool', temporary, destination], 120_000) + } + } finally { + await unlink(temporary).catch(() => undefined) + } + } +} + +export function parseEnvironmentContent(content: string): EnvironmentEntry[] { + const values = new Map() + for (const line of content.split(/\r?\n/)) { + const match = line.match(environmentAssignment) + if (!match) continue + values.set(match[1], unquoteEnvironmentValue(match[2].trim())) + } + return [...values].map(([key, value]) => ({ key, value })).sort(compareEntries) +} + +export function updateEnvironmentContent(content: string, key: string, value: string | undefined, shellExport: boolean): string { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) throw new Error('Invalid environment variable name') + if (value !== undefined && (value.length > 65_535 || /[\0\r\n]/.test(value))) throw new Error('Invalid environment variable value') + const replacement = value === undefined ? undefined : serializeEnvironmentValue(key, value, shellExport) + const lines = content.split(/\r?\n/) + const result: string[] = [] + let replaced = false + for (const line of lines) { + const match = line.match(environmentAssignment) + if (match?.[1] === key) { + if (!replaced && replacement !== undefined) { + result.push(replacement) + replaced = true + } + continue + } + result.push(line) + } + while (result.at(-1) === '') result.pop() + if (replacement !== undefined && !replaced) result.push(replacement) + return result.length ? `${result.join('\n')}\n` : '' +} + +async function readWindowsEnvironment(scope: EnvironmentScope): Promise { + const target = scope === 'user' ? 'User' : 'Machine' + const script = `[Console]::OutputEncoding=[Text.Encoding]::UTF8; ` + + `[Environment]::GetEnvironmentVariables([EnvironmentVariableTarget]::${target}).GetEnumerator() ` + + `| Sort-Object Name | ForEach-Object { [PSCustomObject]@{ key=[string]$_.Key; value=[string]$_.Value } } ` + + '| ConvertTo-Json -Compress' + const output = (await execFileText('powershell.exe', ['-NoProfile', '-Command', script], 30_000)).trim() + if (!output) return [] + const parsed = JSON.parse(output) as EnvironmentEntry | EnvironmentEntry[] + return (Array.isArray(parsed) ? parsed : [parsed]).sort(compareEntries) +} + +async function writeWindowsEnvironment(scope: EnvironmentScope, key: string, value?: string): Promise { + const target = scope === 'user' ? 'User' : 'Machine' + const psValue = value === undefined ? '$null' : `'${psQuote(value)}'` + const script = `[Environment]::SetEnvironmentVariable('${psQuote(key)}',${psValue},[EnvironmentVariableTarget]::${target})` + const encoded = Buffer.from(script, 'utf16le').toString('base64') + if (scope === 'user') { + await execFilePromise('powershell.exe', ['-NoProfile', '-EncodedCommand', encoded], 30_000) + return + } + const elevated = `$p=Start-Process -FilePath powershell.exe -Verb RunAs -Wait -PassThru -ArgumentList @('-NoProfile','-EncodedCommand','${encoded}'); exit $p.ExitCode` + await execFilePromise('powershell.exe', ['-NoProfile', '-Command', elevated], 120_000) +} + +function unixEnvironmentPath(scope: EnvironmentScope): string { + if (scope === 'user') return join(homedir(), '.MooTool', 'environment') + return process.platform === 'darwin' ? '/etc/zshenv' : '/etc/environment' +} + +async function ensureUnixEnvironmentProfile(environmentPath: string): Promise { + const profile = join(homedir(), process.platform === 'darwin' ? '.zshenv' : '.profile') + const current = await readFile(profile, 'utf8').catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') return '' + throw error + }) + if (current.includes(environmentProfileMarker)) return + const separator = !current || current.endsWith('\n') ? '' : '\n' + const block = `${environmentProfileMarker}\n[ -f ${shellQuote(environmentPath)} ] && . ${shellQuote(environmentPath)}\n# <<< MooTool environment <<<\n` + await writeFile(profile, `${current}${separator}${block}`, 'utf8') +} + +function serializeEnvironmentValue(key: string, value: string, shellExport: boolean): string { + if (shellExport) return `export ${key}='${value.replace(/'/g, `'\\''`)}'` + return `${key}="${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"` +} + +function unquoteEnvironmentValue(value: string): string { + if (value.length >= 2 && value.startsWith("'") && value.endsWith("'")) { + return value.slice(1, -1).replace(/'\\''/g, "'") + } + if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) { + return value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\') + } + return value } export function ipv4ToLong(value: string): number { @@ -534,6 +714,10 @@ function execFilePromise(file: string, args: string[], timeout: number): Promise return new Promise((resolve, reject) => execFile(file, args, { timeout, windowsHide: true }, (error) => error ? reject(error) : resolve())) } +function execFileText(file: string, args: string[], timeout: number): Promise { + return new Promise((resolve, reject) => execFile(file, args, { timeout, windowsHide: true, encoding: 'utf8' }, (error, stdout) => error ? reject(error) : resolve(stdout))) +} + function shellQuote(value: string): string { return `'${value.replace(/'/g, `'"'"'`)}'` } diff --git a/next/electron/preload/index.ts b/next/electron/preload/index.ts index 4fb1183d..93c0bffb 100644 --- a/next/electron/preload/index.ts +++ b/next/electron/preload/index.ts @@ -21,7 +21,7 @@ import type { CreateQuickNoteInput, MoveQuickNoteEntryInput, QuickNoteAttachment import type { VaultGitActionInput, VaultGitActionResult, VaultGitCommit, VaultGitDiffInput, VaultGitDiffResult, VaultGitStatus } from '../../src/shared/contracts/vaultGit' import type { FavoriteKind, FavoriteRecord, SaveFavoriteInput } from '../../src/shared/contracts/favorites' import type { HttpRequestDraft, HttpRequestHistory, HttpResponseResult, HttpSendInput, SaveTranslationHistoryInput, SaveTranslationWordInput, SavedHttpRequest, TranslationHistory, TranslationInput, TranslationResult, TranslationWord } from '../../src/shared/contracts/network' -import type { EnvironmentSnapshot, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from '../../src/shared/contracts/system' +import type { DeleteEnvironmentVariableInput, EnvironmentSnapshot, EnvironmentVariableInput, HostProfile, HostProfileListInput, LocalAddressSnapshot, NetworkCommandInput, NetworkCommandResult, SaveHostProfileInput, SystemHostsFile, SystemInfoSnapshot } from '../../src/shared/contracts/system' import type { RuntimeExecutionInput, RuntimeExecutionResult, RuntimeOutputEvent } from '../../src/shared/contracts/runtime' import type { BackupExportResult, BackupInfo, BackupKind, BackupLocation } from '../../src/shared/contracts/backup' import type { LegacyMigrationInput, LegacyMigrationPreview, LegacyMigrationResult } from '../../src/shared/contracts/migration' @@ -83,6 +83,8 @@ contextBridge.exposeInMainWorld('mootool', { runNetworkCommand: (input: NetworkCommandInput): Promise => ipcRenderer.invoke('system:network-command', input), cancelSystemCommand: (requestId: string): Promise => ipcRenderer.invoke('system:cancel', requestId), getEnvironmentSnapshot: (): Promise => ipcRenderer.invoke('system:environment'), + setEnvironmentVariable: (input: EnvironmentVariableInput): Promise => ipcRenderer.invoke('system:environment-set', input), + deleteEnvironmentVariable: (input: DeleteEnvironmentVariableInput): Promise => ipcRenderer.invoke('system:environment-delete', input), getLocalAddresses: (): Promise => ipcRenderer.invoke('system:local-addresses'), getSystemInfo: (): Promise => ipcRenderer.invoke('system:info'), chooseDirectory: (initialPath?: string): Promise => ipcRenderer.invoke('dialog:choose-directory', initialPath), diff --git a/next/src/features/variables/VariablesTool.tsx b/next/src/features/variables/VariablesTool.tsx index c27fa5d4..4ac12d24 100644 --- a/next/src/features/variables/VariablesTool.tsx +++ b/next/src/features/variables/VariablesTool.tsx @@ -1,50 +1,215 @@ -import { ClipboardCopy, Download, RefreshCw, Search } from 'lucide-react' +import { ClipboardCopy, Download, Pencil, Plus, RefreshCw, Search, Trash2 } from 'lucide-react' import { useEffect, useMemo, useState } from 'react' +import { Dialog } from '@/shared/components/Dialog' import { ToolPageHeader, ToolTabs } from '@/shared/components/ToolPage' -import type { EnvironmentEntry, EnvironmentSnapshot } from '@/shared/contracts/system' +import type { EnvironmentEntry, EnvironmentScope, EnvironmentSnapshot } from '@/shared/contracts/system' import { useToolActions } from '@/shared/hooks/useToolActions' import { useI18n } from '@/shared/i18n/I18nProvider' type VariableTab = 'environment' | 'runtime' +type DisplayScope = 'process' | EnvironmentScope + +const emptySnapshot: EnvironmentSnapshot = { environment: [], runtime: [], user: [], system: [] } export function VariablesTool() { const { t } = useI18n() const actions = useToolActions('variables') const [tab, setTab] = useState('environment') - const [snapshot, setSnapshot] = useState({ environment: [], runtime: [] }) + const [scope, setScope] = useState('process') + const [targetScope, setTargetScope] = useState('user') + const [snapshot, setSnapshot] = useState(emptySnapshot) const [query, setQuery] = useState('') const [loading, setLoading] = useState(false) - const entries = useMemo(() => snapshot[tab].filter((entry) => !query || `${entry.key}\n${entry.value}`.toLowerCase().includes(query.toLowerCase())), [query, snapshot, tab]) + const [saving, setSaving] = useState(false) + const [editing, setEditing] = useState(undefined) + const [keyValue, setKeyValue] = useState('') + const [value, setValue] = useState('') + const sourceEntries = tab === 'runtime' + ? snapshot.runtime + : scope === 'process' ? snapshot.environment : snapshot[scope] + const entries = useMemo( + () => sourceEntries.filter((entry) => !query || `${entry.key}\n${entry.value}`.toLowerCase().includes(query.toLowerCase())), + [query, sourceEntries] + ) + const canEdit = tab === 'environment' + const canDelete = tab === 'environment' && scope !== 'process' async function refresh(): Promise { setLoading(true) - try { setSnapshot(await window.mootool.getEnvironmentSnapshot()) } catch (error) { actions.reportError(error) } finally { setLoading(false) } + try { + setSnapshot(await window.mootool.getEnvironmentSnapshot()) + } catch (error) { + actions.reportError(error) + } finally { + setLoading(false) + } } useEffect(() => { void refresh() }, []) async function exportValues(): Promise { - const content = formatEnvironment(snapshot.environment, snapshot.runtime) - try { await window.mootool.saveTextFile({ kind: 'text', defaultName: 'mootool-environment.txt', content }) } catch (error) { actions.reportError(error) } + const content = formatEnvironment(snapshot) + try { + await window.mootool.saveTextFile({ kind: 'text', defaultName: 'mootool-environment.txt', content }) + } catch (error) { + actions.reportError(error) + } + } + + function openEditor(entry?: EnvironmentEntry): void { + setEditing(entry ?? null) + setKeyValue(entry?.key ?? '') + setValue(entry?.value ?? '') + setTargetScope(scope === 'process' ? 'user' : scope) + } + + async function saveVariable(): Promise { + setSaving(true) + try { + await window.mootool.setEnvironmentVariable({ scope: targetScope, key: keyValue.trim(), value }) + setEditing(undefined) + await refresh() + actions.toast.success(t('variables.saved')) + } catch (error) { + actions.reportError(error) + } finally { + setSaving(false) + } + } + + async function deleteVariable(entry: EnvironmentEntry): Promise { + if (scope === 'process' || !window.confirm(t('variables.confirmDelete', { key: entry.key }))) return + setSaving(true) + try { + await window.mootool.deleteEnvironmentVariable({ scope, key: entry.key }) + await refresh() + actions.toast.success(t('variables.deleted')) + } catch (error) { + actions.reportError(error) + } finally { + setSaving(false) + } } return (
- } /> + + {tab === 'environment' && } + + + } + />
-
({ id, label: t(`variables.tab.${id}` as 'variables.tab.environment') }))} active={tab} onChange={setTab} />
setQuery(event.target.value)} />
- { void actions.copy(`${entry.key}=${entry.value}`) }} /> -
{t('variables.count', { count: String(entries.length), total: String(snapshot[tab].length) })}
+
+ ({ id, label: t(`variables.tab.${id}` as 'variables.tab.environment') }))} active={tab} onChange={setTab} /> + {tab === 'environment' && ( + + )} +
setQuery(event.target.value)} />
+
+ { void actions.copy(`${entry.key}=${entry.value}`) }} + onEdit={openEditor} + onDelete={(entry) => { void deleteVariable(entry) }} + /> +
+ {t('variables.count', { count: String(entries.length), total: String(sourceEntries.length) })} + {tab === 'environment' && {t(`variables.scopeHint.${scope}` as 'variables.scopeHint.user')}} +
+ setEditing(undefined)} + footer={<> + + + } + > +
+ +