Compare commits
6
Commits
e09b0567d6
...
v26.8.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a19b4b38a | ||
|
|
7d49a7395f | ||
|
|
d0705b1ffe | ||
|
|
6c7897bf47 | ||
|
|
2f20161010 | ||
|
|
d09599fa95 |
@@ -7,6 +7,9 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# 发布暂存目录
|
||||
release_stage/
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
|
||||
@@ -100,7 +100,7 @@ Thing/
|
||||
#### 📸 截图
|
||||
- [x] 截图及相关
|
||||
- [ ] 滚动截图(后续支持)
|
||||
- [ ] 贴图(后续支持)
|
||||
- [x] 贴图
|
||||
|
||||
#### 📊 硬件监控
|
||||
- [x] 悬浮窗显示
|
||||
@@ -127,8 +127,8 @@ Thing/
|
||||
- [x] 性能优化(P1/P2:轮询随窗口可见性暂停、批量测速限并发、渲染 memo 化等,见 MODULE_REVIEW.md)
|
||||
- [x] 错误处理与日志完善(B5 进程级全局日志器、异常兜底)
|
||||
- [x] 用户体验优化(混合 DPI 定位、rAF 节流、UI 细节)
|
||||
- [ ] 自动更新机制
|
||||
- [ ] 打包发布
|
||||
- [x] 自动更新机制
|
||||
- [x] 打包发布
|
||||
|
||||
## 模块管理架构
|
||||
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "thing",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"version": "26.8.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
@echo off
|
||||
chcp 65001 >nul
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
set "SCRIPT=%~dp0release.ps1"
|
||||
|
||||
echo ================================================
|
||||
echo Thing Build Pubilsh
|
||||
echo 发布目标:https://gitea.atie.fun/LFeng/Thing
|
||||
echo ================================================
|
||||
echo.
|
||||
|
||||
:: ---------- 版本号 ----------
|
||||
set "VERSION="
|
||||
set /p "VERSION=请输入版本号(如 26.8.1,直接回车沿用当前版本): "
|
||||
set "VER_ARG="
|
||||
if not "%VERSION%"=="" set "VER_ARG=-Version %VERSION%"
|
||||
|
||||
:: ---------- 发布模式 ----------
|
||||
echo.
|
||||
echo [1] Build + Pubilsh Gitea
|
||||
echo [2] Build Only
|
||||
echo [3] Pubilsh Gitea
|
||||
set "MODE="
|
||||
set /p "MODE=请输入数字选择(回车默认 1): "
|
||||
if "%MODE%"=="" set "MODE=1"
|
||||
|
||||
set "EXTRA="
|
||||
if "%MODE%"=="2" (
|
||||
set "EXTRA=-SkipPush"
|
||||
) else if "%MODE%"=="3" (
|
||||
set "EXTRA=-SkipBuild"
|
||||
)
|
||||
|
||||
:: ---------- Gitea Token(仅完整发布模式需要) ----------
|
||||
if "%MODE%"=="1" if not defined GITEA_TOKEN (
|
||||
echo.
|
||||
echo 未检测到环境变量 GITEA_TOKEN,上传到 Gitea 需要它。
|
||||
echo 可在此临时输入(仅本次会话生效),留空则自动改为"只构建不上传"。
|
||||
set /p "GITEA_TOKEN=请输入 Gitea Token: "
|
||||
if "!GITEA_TOKEN!"=="" (
|
||||
set "EXTRA=-SkipPush"
|
||||
set "MODE=2"
|
||||
echo [提示] 已切换为"只构建并整理产物,不上传"。
|
||||
)
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Start:release.ps1 %VER_ARG% %EXTRA%
|
||||
echo ------------------------------------------------
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %VER_ARG% %EXTRA%
|
||||
set "RESULT=%ERRORLEVEL%"
|
||||
|
||||
echo.
|
||||
if "%RESULT%"=="0" (
|
||||
echo 执行完成。
|
||||
) else (
|
||||
echo 执行出错,请查看上方日志。
|
||||
)
|
||||
echo.
|
||||
pause
|
||||
@@ -0,0 +1,166 @@
|
||||
# ============================================================
|
||||
# Thing 构建发布脚本(目标:自建 Gitea release)
|
||||
#
|
||||
# 用法:
|
||||
# .\scripts\release.ps1 -Version 0.2.0 # 同步版本号 + 构建 + 发布
|
||||
# .\scripts\release.ps1 -Version 0.2.0 -SkipBuild # 复用现有构建产物,直接发布
|
||||
# .\scripts\release.ps1 -Version 0.2.0 -SkipPush # 只构建+整理产物,不上传
|
||||
#
|
||||
# 发布产物(上传到 https://gitea.atie.fun/LFeng/Thing 的 v{Version} release):
|
||||
# thing_{v}_x64.exe 便携免安装版(无内核)
|
||||
# thing_{v}_x64.msi 安装版 MSI(去掉 tauri 默认的 _en-US 后缀)
|
||||
# thing_{v}_x64-setup.exe 安装版 NSIS
|
||||
# thing-hk_{v}.zip ThingHK 硬件监控内核(mihomo 继续走代理模块内置的 GitHub 下载)
|
||||
#
|
||||
# 前提:
|
||||
# - Gitea token 已配置为环境变量 GITEA_TOKEN(-SkipPush 时不需要)
|
||||
# - 可选 -NotesPath 指定 release notes 文件(Markdown 文本),
|
||||
# 缺省时使用 scripts/release-notes.md(若存在),否则用简单占位文本
|
||||
# ============================================================
|
||||
|
||||
param(
|
||||
[string]$Version = '',
|
||||
[switch]$SkipBuild,
|
||||
[switch]$SkipPush,
|
||||
[string]$NotesPath = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$Root = Split-Path -Parent $PSScriptRoot
|
||||
$TargetDir = Join-Path $Root 'src-tauri\target\release'
|
||||
$BundleDir = Join-Path $TargetDir 'bundle'
|
||||
$RepoOwner = 'LFeng'
|
||||
$RepoName = 'Thing'
|
||||
$ApiBase = 'https://gitea.atie.fun/api/v1'
|
||||
$Product = 'thing'
|
||||
|
||||
function Write-Step([string]$msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||
|
||||
# ---------- 0. 版本号 ----------
|
||||
if ([string]::IsNullOrWhiteSpace($Version)) {
|
||||
$conf = Get-Content (Join-Path $Root 'src-tauri\tauri.conf.json') -Raw | ConvertFrom-Json
|
||||
$Version = $conf.version
|
||||
Write-Step "未指定 -Version,沿用现有版本 $Version"
|
||||
}
|
||||
# 校验 X.Y.Z 格式
|
||||
if ($Version -notmatch '^\d+\.\d+\.\d+$') {
|
||||
throw "版本号格式错误(应为 X.Y.Z):$Version"
|
||||
}
|
||||
Write-Step "发布版本:v$Version"
|
||||
|
||||
# ---------- 1. 同步版本号到三处 ----------
|
||||
$tauriConf = Join-Path $Root 'src-tauri\tauri.conf.json'
|
||||
$cargoToml = Join-Path $Root 'src-tauri\Cargo.toml'
|
||||
$pkgJson = Join-Path $Root 'package.json'
|
||||
|
||||
$t = Get-Content $tauriConf -Raw
|
||||
$t = $t -replace '("version"\s*:\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||
[System.IO.File]::WriteAllText($tauriConf, $t, (New-Object System.Text.UTF8Encoding($false)))
|
||||
|
||||
$c = Get-Content $cargoToml -Raw
|
||||
$c = $c -replace '(?m)^(version\s*=\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||
[System.IO.File]::WriteAllText($cargoToml, $c, (New-Object System.Text.UTF8Encoding($false)))
|
||||
|
||||
$p = Get-Content $pkgJson -Raw
|
||||
$p = $p -replace '("version"\s*:\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||
[System.IO.File]::WriteAllText($pkgJson, $p, (New-Object System.Text.UTF8Encoding($false)))
|
||||
Write-Step "版本号已同步:tauri.conf.json / Cargo.toml / package.json"
|
||||
|
||||
# ---------- 2. 构建 ----------
|
||||
if (-not $SkipBuild) {
|
||||
Write-Step '开始构建(bun run tauri build)...'
|
||||
Push-Location $Root
|
||||
try { bun run tauri build }
|
||||
finally { Pop-Location }
|
||||
if ($LASTEXITCODE -ne 0) { throw 'tauri build 失败' }
|
||||
} else {
|
||||
Write-Step '跳过构建,复用现有产物'
|
||||
}
|
||||
|
||||
# ---------- 3. 整理产物 ----------
|
||||
# 版本号此时已解析,再确定暂存目录
|
||||
$StageDir = Join-Path $Root "release_stage\$Version"
|
||||
New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
|
||||
|
||||
$exeSrc = Join-Path $TargetDir "$Product.exe"
|
||||
$msiSrc = Join-Path $BundleDir "msi\${Product}_${Version}_x64_en-US.msi"
|
||||
$nsisSrc = Join-Path $BundleDir "nsis\${Product}_${Version}_x64-setup.exe"
|
||||
$hkSrc = Join-Path $Root 'src-tauri\binaries\ThingHK.exe'
|
||||
|
||||
$exeOut = Join-Path $StageDir "${Product}_${Version}_x64.exe"
|
||||
$msiOut = Join-Path $StageDir "${Product}_${Version}_x64.msi"
|
||||
$nsisOut = Join-Path $StageDir "${Product}_${Version}_x64-setup.exe"
|
||||
$hkZip = Join-Path $StageDir "thing-hk_${Version}.zip"
|
||||
|
||||
if (Test-Path $exeSrc) { Copy-Item $exeSrc $exeOut } else { Write-Warning "缺少便携版:$exeSrc" }
|
||||
if (Test-Path $msiSrc) { Copy-Item $msiSrc $msiOut } else { Write-Warning "缺少 MSI(已跳过重命名):$msiSrc" }
|
||||
if (Test-Path $nsisSrc) { Copy-Item $nsisSrc $nsisOut } else { Write-Warning "缺少 NSIS:$nsisSrc" }
|
||||
|
||||
if (Test-Path $hkSrc) {
|
||||
$tmp = Join-Path $env:TEMP "thinghk_$([guid]::NewGuid().ToString('N'))"
|
||||
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
|
||||
Copy-Item $hkSrc (Join-Path $tmp 'ThingHK.exe')
|
||||
Compress-Archive -Path (Join-Path $tmp 'ThingHK.exe') -DestinationPath $hkZip -Force
|
||||
Remove-Item -Recurse -Force $tmp
|
||||
Write-Step "ThingHK 内核包:$hkZip"
|
||||
} else {
|
||||
Write-Warning "缺少 ThingHK.exe:$hkSrc"
|
||||
}
|
||||
|
||||
Write-Step "产物已整理到:$StageDir"
|
||||
Get-ChildItem $StageDir | Select-Object Name, @{n='Size(MB)';e={[math]::Round($_.Length/1MB,1)}} | Format-Table -AutoSize
|
||||
|
||||
# ---------- 4. 上传到 Gitea ----------
|
||||
if ($SkipPush) {
|
||||
Write-Step '已跳过上传(-SkipPush)'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$token = $env:GITEA_TOKEN
|
||||
if ([string]::IsNullOrWhiteSpace($token)) {
|
||||
throw '未设置环境变量 GITEA_TOKEN,无法发布到 Gitea(或使用 -SkipPush 跳过上传)'
|
||||
}
|
||||
$auth = @{ Authorization = "token $token" }
|
||||
|
||||
# 4.1 release notes
|
||||
if (-not [string]::IsNullOrWhiteSpace($NotesPath)) {
|
||||
$body = Get-Content $NotesPath -Raw
|
||||
} elseif (Test-Path (Join-Path $PSScriptRoot 'release-notes.md')) {
|
||||
$body = Get-Content (Join-Path $PSScriptRoot 'release-notes.md') -Raw
|
||||
} else {
|
||||
$body = "Thing v$Version"
|
||||
}
|
||||
|
||||
# 4.2 创建 release(已存在同名 tag 则复用)
|
||||
Write-Step "创建 release v$Version ..."
|
||||
$releaseUrl = "$ApiBase/repos/$RepoOwner/$RepoName/releases"
|
||||
$releasePayload = @{
|
||||
tag_name = "v$Version"
|
||||
name = "Thing v$Version"
|
||||
body = $body
|
||||
draft = $false
|
||||
prerelease = $false
|
||||
} | ConvertTo-Json
|
||||
|
||||
try {
|
||||
$release = Invoke-RestMethod -Method Post -Uri $releaseUrl -Headers $auth -ContentType 'application/json' -Body $releasePayload
|
||||
} catch {
|
||||
# tag 已存在:尝试用该 tag 查找现有 release,后续资产上传会追加
|
||||
Write-Warning "创建 release 失败,尝试复用已有 release:$_"
|
||||
$release = Invoke-RestMethod -Method Get -Uri "$releaseUrl/tags/v$Version" -Headers $auth
|
||||
}
|
||||
$releaseId = $release.id
|
||||
Write-Step "release id=$releaseId"
|
||||
|
||||
# 4.3 逐个上传资产
|
||||
$assets = @($exeOut, $msiOut, $nsisOut, $hkZip) | Where-Object { Test-Path $_ }
|
||||
foreach ($file in $assets) {
|
||||
$name = Split-Path $file -Leaf
|
||||
Write-Step "上传 $name ..."
|
||||
$assetUrl = "$releaseUrl/$releaseId/assets?name=$([uri]::EscapeDataString($name))"
|
||||
$resp = Invoke-RestMethod -Method Post -Uri $assetUrl -Headers $auth -ContentType 'application/octet-stream' -InFile $file
|
||||
Write-Host " -> $($resp.browser_download_url)" -ForegroundColor Green
|
||||
}
|
||||
|
||||
Write-Step "发布完成:https://gitea.atie.fun/$RepoOwner/$RepoName/releases/tag/v$Version"
|
||||
Generated
+22
-1
@@ -4743,7 +4743,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "thing"
|
||||
version = "0.1.0"
|
||||
version = "26.8.1"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
@@ -4753,6 +4753,7 @@ dependencies = [
|
||||
"image",
|
||||
"notify",
|
||||
"raw-window-handle",
|
||||
"regex",
|
||||
"reqwest 0.12.28",
|
||||
"rusqlite",
|
||||
"serde",
|
||||
@@ -4773,6 +4774,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"url",
|
||||
"walkdir",
|
||||
"windows 0.52.0",
|
||||
"windows-sys 0.52.0",
|
||||
"winreg 0.52.0",
|
||||
"zip",
|
||||
@@ -5590,6 +5592,16 @@ dependencies = [
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be"
|
||||
dependencies = [
|
||||
"windows-core 0.52.0",
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.57.0"
|
||||
@@ -5622,6 +5634,15 @@ dependencies = [
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-core"
|
||||
version = "0.57.0"
|
||||
|
||||
+11
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "thing"
|
||||
version = "0.1.0"
|
||||
version = "26.8.1"
|
||||
description = "A Tauri App"
|
||||
authors = ["you"]
|
||||
edition = "2021"
|
||||
@@ -26,6 +26,7 @@ tauri-plugin-global-shortcut = "2"
|
||||
tauri-plugin-notification = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
regex = "1"
|
||||
serde_yaml = "0.9"
|
||||
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
|
||||
specta-typescript = "0.0.12"
|
||||
@@ -65,6 +66,15 @@ windows-sys = { version = "0.52", features = [
|
||||
"Win32_Storage_Xps",
|
||||
"Win32_Storage_FileSystem",
|
||||
] }
|
||||
# Explorer 前台目录检测(IShellWindows COM):仅引入用到的 feature,控制编译体积
|
||||
windows = { version = "0.52", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_Ole",
|
||||
"Win32_System_Variant",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
|
||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||
tauri-plugin-autostart = "2"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "screenshot",
|
||||
"description": "Capability for screenshot overlay and editor windows",
|
||||
"windows": ["screenshot-overlay*", "screenshot-editor-*"],
|
||||
"description": "Capability for screenshot overlay, editor and pin windows",
|
||||
"windows": ["screenshot-overlay*", "screenshot-editor-*", "screenshot-pin"],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-hide",
|
||||
@@ -11,6 +11,7 @@
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-set-position",
|
||||
"core:window:allow-set-size",
|
||||
"core:window:allow-set-resizable",
|
||||
"core:window:allow-set-always-on-top",
|
||||
"core:window:allow-set-skip-taskbar",
|
||||
"core:window:allow-set-decorations",
|
||||
|
||||
@@ -16,7 +16,6 @@ const DEFAULT_CONFIG = {
|
||||
interceptDownload: true,
|
||||
minSize: 0,
|
||||
excludeDomains: [],
|
||||
showNotifications: true,
|
||||
// 嗅探开关
|
||||
sniffEnabled: true,
|
||||
// 嗅探的资源类型:只保留视频/音频/图片/压缩包/种子/安装包
|
||||
@@ -386,28 +385,13 @@ async function handleDownloadCreated(downloadItem) {
|
||||
const filename = downloadItem.filename || ''
|
||||
|
||||
try {
|
||||
const id = await addDownload(url, filename, downloadItem.referrer, '')
|
||||
await notify('已添加到 Thing', `${filename || url}`)
|
||||
await addDownload(url, filename, downloadItem.referrer, '')
|
||||
} catch (e) {
|
||||
await notify('Thing 添加失败', `${filename || url}\n${e.message}`)
|
||||
// 添加失败:回退到浏览器自带下载,不弹通知
|
||||
try { await chrome.downloads.download({ url }) } catch { /* ignore */ }
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 通知 =====
|
||||
async function notify(title, message) {
|
||||
const config = await getConfig()
|
||||
if (!config.showNotifications) return
|
||||
try {
|
||||
await chrome.notifications.create({
|
||||
type: 'basic',
|
||||
iconUrl: 'icons/icon-128.png',
|
||||
title,
|
||||
message
|
||||
})
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
// ===== 右键菜单 =====
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.contextMenus.create({
|
||||
@@ -428,10 +412,7 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
const filename = url.split('/').pop()?.split('?')[0] || ''
|
||||
try {
|
||||
await addDownload(url, filename, info.pageUrl, '')
|
||||
await notify('已添加到 Thing', `${filename || url}`)
|
||||
} catch (e) {
|
||||
await notify('Thing 添加失败', `${e.message}`)
|
||||
}
|
||||
} catch (e) { /* 忽略:添加失败时不打扰用户 */ }
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -11,9 +11,7 @@
|
||||
"permissions": [
|
||||
"downloads",
|
||||
"storage",
|
||||
"notifications",
|
||||
"webRequest",
|
||||
"webNavigation",
|
||||
"contextMenus",
|
||||
"tabs",
|
||||
"scripting"
|
||||
|
||||
@@ -87,11 +87,6 @@
|
||||
<span>启用资源嗅探</span>
|
||||
</label>
|
||||
|
||||
<label class="checkbox">
|
||||
<input type="checkbox" id="showNotifications" />
|
||||
<span>显示桌面通知</span>
|
||||
</label>
|
||||
|
||||
<label class="field">
|
||||
<span>下载最小文件大小(字节,0=全部)</span>
|
||||
<input type="number" id="minSize" min="0" placeholder="0" />
|
||||
|
||||
@@ -12,7 +12,6 @@ const DEFAULT_CONFIG = {
|
||||
interceptDownload: true,
|
||||
minSize: 0,
|
||||
excludeDomains: [],
|
||||
showNotifications: true,
|
||||
sniffEnabled: true,
|
||||
sniffTypes: ['video', 'audio', 'image', 'archive', 'torrent', 'installer'],
|
||||
sniffMaxItems: 200,
|
||||
@@ -57,7 +56,6 @@ function fillForm(config) {
|
||||
$('secret').value = config.secret || ''
|
||||
$('interceptDownload').checked = config.interceptDownload !== false
|
||||
$('sniffEnabled').checked = config.sniffEnabled !== false
|
||||
$('showNotifications').checked = config.showNotifications !== false
|
||||
$('minSize').value = config.minSize || 0
|
||||
$('sniffMinSize').value = config.sniffMinSize ?? DEFAULT_CONFIG.sniffMinSize
|
||||
$('excludeDomains').value = (config.excludeDomains || []).join(',')
|
||||
@@ -69,7 +67,6 @@ function readForm() {
|
||||
secret: $('secret').value.trim(),
|
||||
interceptDownload: $('interceptDownload').checked,
|
||||
sniffEnabled: $('sniffEnabled').checked,
|
||||
showNotifications: $('showNotifications').checked,
|
||||
minSize: parseInt($('minSize').value, 10) || 0,
|
||||
sniffMinSize: parseInt($('sniffMinSize').value, 10) || 0,
|
||||
excludeDomains: $('excludeDomains').value
|
||||
|
||||
Binary file not shown.
@@ -10,6 +10,8 @@ pub mod windows {
|
||||
pub const OSD_OVERLAY: &str = "osd-overlay";
|
||||
#[allow(dead_code)]
|
||||
pub const SCREENSHOT_OVERLAY: &str = "screenshot-overlay";
|
||||
#[allow(dead_code)]
|
||||
pub const SCREENSHOT_PIN: &str = "screenshot-pin";
|
||||
}
|
||||
|
||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||
@@ -27,6 +29,7 @@ pub mod events {
|
||||
// 快速面板
|
||||
pub const QUICKPANEL_SHOW: &str = "quickpanel-show";
|
||||
pub const QUICKPANEL_HIDE: &str = "quickpanel-hide";
|
||||
pub const QUICKPANEL_EXTRACT_PROGRESS: &str = "quickpanel-extract-progress";
|
||||
// 监控
|
||||
pub const MONITOR_DATA: &str = "monitor-data";
|
||||
pub const MONITOR_NETWORK: &str = "monitor-network";
|
||||
@@ -41,9 +44,14 @@ pub mod events {
|
||||
pub const OSD_END_DRAG: &str = "osd-end-drag";
|
||||
// 截图
|
||||
pub const SCREENSHOT_SHORTCUT: &str = "screenshot-shortcut";
|
||||
pub const SCREENSHOT_PIN_SHORTCUT: &str = "screenshot-pin-shortcut";
|
||||
// 内核安装进度
|
||||
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
||||
// 应用更新进度
|
||||
pub const UPDATE_PROGRESS: &str = "update-progress";
|
||||
// 进程与下载
|
||||
pub const PROCESS_STATUS_CHANGED: &str = "process-status-changed";
|
||||
pub const DOWNLOAD_ADDED: &str = "download-added";
|
||||
/// 浏览器扩展通过 HTTP API 新增下载(前端需置前主窗口并跳到下载画面)
|
||||
pub const DOWNLOAD_EXTENSION_ADDED: &str = "download-extension-added";
|
||||
}
|
||||
|
||||
@@ -761,7 +761,7 @@ impl DownloadEngine {
|
||||
last_time = now;
|
||||
|
||||
// 更新任务状态 + 发送进度事件
|
||||
let total_size = {
|
||||
let (total_size, live_status) = {
|
||||
let mut tasks = engine.inner.tasks.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(task) = tasks.get_mut(&id_monitor) {
|
||||
task.completed_size = completed;
|
||||
@@ -771,7 +771,10 @@ impl DownloadEngine {
|
||||
seg.completed = prog.load(Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
task.total_size
|
||||
// 读取任务实时状态而非硬编码 Active:
|
||||
// 暂停后监控循环 break 前可能发出的最后一次事件
|
||||
// 必须携带 Paused,否则前端会把任务状态覆盖回"下载中"
|
||||
(task.total_size, task.status.clone())
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
@@ -784,7 +787,7 @@ impl DownloadEngine {
|
||||
completed_size: completed,
|
||||
total_size,
|
||||
speed,
|
||||
status: TaskStatus::Active,
|
||||
status: live_status,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use axum::{
|
||||
Router,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use super::engine::DownloadEngine;
|
||||
use super::task::DownloadTask;
|
||||
@@ -45,14 +46,18 @@ struct ErrorResponse {
|
||||
|
||||
impl ExtensionServer {
|
||||
/// 启动 HTTP API 服务器(绑定到 127.0.0.1:port)
|
||||
pub async fn start(engine: DownloadEngine, port: u16, secret: String) {
|
||||
pub async fn start(engine: DownloadEngine, port: u16, secret: String, app_handle: AppHandle) {
|
||||
let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().expect("无效端口");
|
||||
|
||||
let app = Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/api/downloads", post(create_download).get(list_downloads))
|
||||
.route("/api/downloads/:id", axum::routing::delete(remove_download))
|
||||
.with_state(AppState { engine, secret });
|
||||
.with_state(AppState {
|
||||
engine,
|
||||
secret,
|
||||
app_handle,
|
||||
});
|
||||
|
||||
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
||||
Ok(l) => l,
|
||||
@@ -74,6 +79,7 @@ impl ExtensionServer {
|
||||
struct AppState {
|
||||
engine: DownloadEngine,
|
||||
secret: String,
|
||||
app_handle: AppHandle,
|
||||
}
|
||||
|
||||
/// 鉴权检查:如果配置了 secret,校验 Bearer token
|
||||
@@ -109,7 +115,14 @@ async fn create_download(
|
||||
}
|
||||
|
||||
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true).await {
|
||||
Ok(id) => Ok(Json(CreateDownloadResponse { id })),
|
||||
Ok(id) => {
|
||||
// 浏览器扩展发起下载:置前主窗口并通知前端跳到下载画面(替代原桌面通知)
|
||||
crate::tray_menu::focus_main_window(&state.app_handle);
|
||||
let _ = state
|
||||
.app_handle
|
||||
.emit(crate::constants::events::DOWNLOAD_EXTENSION_ADDED, ());
|
||||
Ok(Json(CreateDownloadResponse { id }))
|
||||
}
|
||||
Err(e) => Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e }))),
|
||||
}
|
||||
}
|
||||
|
||||
+43
-19
@@ -15,6 +15,7 @@ mod setup;
|
||||
mod shortcut;
|
||||
mod snap_fix;
|
||||
mod tray_menu;
|
||||
mod updater;
|
||||
mod win32_util;
|
||||
|
||||
use download_engine::{
|
||||
@@ -34,10 +35,10 @@ use mihomo_manager::{
|
||||
proxy_test_delay, proxy_update_kernel, proxy_update_profile, proxy_version, MihomoManager,
|
||||
};
|
||||
use monitor_kernel::{
|
||||
monitor_elevate_self, monitor_get_elevate_on_launch, monitor_get_hardware_config,
|
||||
monitor_get_snapshot, monitor_get_status, monitor_kernel_info, monitor_set_elevate_on_launch,
|
||||
monitor_set_hardware_config, monitor_start, monitor_start_elevated, monitor_status,
|
||||
monitor_stop, MonitorKernel,
|
||||
monitor_elevate_self, monitor_get_auto_start, monitor_get_elevate_on_launch,
|
||||
monitor_get_hardware_config, monitor_get_snapshot, monitor_get_status, monitor_kernel_info,
|
||||
monitor_set_auto_start, monitor_set_elevate_on_launch, monitor_set_hardware_config,
|
||||
monitor_start, monitor_start_elevated, monitor_status, monitor_stop, MonitorKernel,
|
||||
};
|
||||
use network_monitor::network_status;
|
||||
use osd_window::{
|
||||
@@ -54,8 +55,9 @@ use screenshot::commands::{
|
||||
screenshot_crop_stored, screenshot_cursor_pos, screenshot_delete_cache,
|
||||
screenshot_disable_transitions, screenshot_enum_windows, screenshot_fullscreen_png,
|
||||
screenshot_get_editor_image, screenshot_get_fullscreen_bmp, screenshot_load_cache,
|
||||
screenshot_register_shortcut, screenshot_save_cache, screenshot_save_png,
|
||||
screenshot_set_editor_image, screenshot_unregister_shortcut, screenshot_window_from_point,
|
||||
screenshot_register_pin_shortcut, screenshot_register_shortcut, screenshot_save_cache,
|
||||
screenshot_save_png, screenshot_set_editor_image, screenshot_unregister_pin_shortcut,
|
||||
screenshot_unregister_shortcut, screenshot_window_from_point,
|
||||
};
|
||||
use clipboard::{
|
||||
ClipboardManager,
|
||||
@@ -66,16 +68,18 @@ use clipboard::{
|
||||
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
||||
};
|
||||
use quickpanel::{
|
||||
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
||||
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_build_file_index,
|
||||
quickpanel_clear_app_icon_cache, quickpanel_delete_file, quickpanel_delete_files,
|
||||
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
||||
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
|
||||
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
|
||||
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
|
||||
quickpanel_unregister_shortcut,
|
||||
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
|
||||
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
|
||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
|
||||
};
|
||||
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
|
||||
use updater::{app_version, update_check, update_install, update_thinghk};
|
||||
|
||||
#[tauri::command]
|
||||
fn quit_app(app: tauri::AppHandle) {
|
||||
@@ -100,6 +104,8 @@ fn export_bindings() {
|
||||
// 生成命令失败时直接 throw,与原生 invoke 一致,前端无需解包 helper
|
||||
.error_handling(ErrorHandlingMode::Throw)
|
||||
.commands(collect_commands![
|
||||
// 应用更新(4)
|
||||
app_version, update_check, update_install, update_thinghk,
|
||||
// proxy(20)
|
||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||
proxy_close_connection, proxy_delete_profile, proxy_get_settings,
|
||||
@@ -115,7 +121,9 @@ fn export_bindings() {
|
||||
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
||||
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
|
||||
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command,
|
||||
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
|
||||
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
|
||||
quickpanel_delete_files, quickpanel_focus_main_window,
|
||||
// clipboard(20)
|
||||
clipboard_get_history, clipboard_get_pinned, clipboard_search, clipboard_get_item,
|
||||
clipboard_set_pinned, clipboard_delete, clipboard_clear, clipboard_copy_back,
|
||||
@@ -127,13 +135,14 @@ fn export_bindings() {
|
||||
downloader_get_tasks, downloader_check_url, downloader_add_task, downloader_pause_task,
|
||||
downloader_resume_task, downloader_remove_task, downloader_get_settings,
|
||||
downloader_save_settings, downloader_open_dir, downloader_open_url,
|
||||
// screenshot(19,豁免 2:get_fullscreen_bmp 返回 ipc::Response、compose_copy 接收 ipc::Request)
|
||||
// screenshot(21,豁免 2:get_fullscreen_bmp 返回 ipc::Response、compose_copy 接收 ipc::Request)
|
||||
screenshot_disable_transitions, screenshot_register_shortcut,
|
||||
screenshot_unregister_shortcut, screenshot_capture_fullscreen, screenshot_fullscreen_png,
|
||||
screenshot_clear_fullscreen, screenshot_crop_stored, screenshot_crop_copy_stored,
|
||||
screenshot_window_from_point, screenshot_cursor_pos, screenshot_enum_windows,
|
||||
screenshot_capture_window, screenshot_set_editor_image, screenshot_get_editor_image,
|
||||
screenshot_copy_image, screenshot_save_png,
|
||||
screenshot_unregister_shortcut, screenshot_register_pin_shortcut,
|
||||
screenshot_unregister_pin_shortcut, screenshot_capture_fullscreen,
|
||||
screenshot_fullscreen_png, screenshot_clear_fullscreen, screenshot_crop_stored,
|
||||
screenshot_crop_copy_stored, screenshot_window_from_point, screenshot_cursor_pos,
|
||||
screenshot_enum_windows, screenshot_capture_window, screenshot_set_editor_image,
|
||||
screenshot_get_editor_image, screenshot_copy_image, screenshot_save_png,
|
||||
screenshot_save_cache, screenshot_load_cache, screenshot_delete_cache,
|
||||
])
|
||||
.export(Typescript::default(), "../src/lib/bindings.ts")
|
||||
@@ -161,6 +170,10 @@ pub fn run() {
|
||||
.manage(ProcessManager::new())
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
quit_app,
|
||||
app_version,
|
||||
update_check,
|
||||
update_install,
|
||||
update_thinghk,
|
||||
process_start,
|
||||
process_stop,
|
||||
process_status,
|
||||
@@ -204,6 +217,8 @@ pub fn run() {
|
||||
monitor_get_snapshot,
|
||||
monitor_get_elevate_on_launch,
|
||||
monitor_set_elevate_on_launch,
|
||||
monitor_get_auto_start,
|
||||
monitor_set_auto_start,
|
||||
monitor_get_hardware_config,
|
||||
monitor_set_hardware_config,
|
||||
network_status,
|
||||
@@ -264,10 +279,17 @@ pub fn run() {
|
||||
quickpanel_reveal_in_explorer,
|
||||
quickpanel_open_file,
|
||||
quickpanel_delete_file,
|
||||
quickpanel_delete_files,
|
||||
quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command,
|
||||
quickpanel_get_special_locations,
|
||||
quickpanel_open_special,
|
||||
quickpanel_list_archives,
|
||||
quickpanel_list_dir,
|
||||
quickpanel_batch_extract,
|
||||
quickpanel_preview_rename,
|
||||
quickpanel_apply_rename,
|
||||
quickpanel_focus_main_window,
|
||||
tray_menu_action,
|
||||
tray_menu_hide,
|
||||
tray_menu_ready,
|
||||
@@ -291,6 +313,8 @@ pub fn run() {
|
||||
screenshot_delete_cache,
|
||||
screenshot_register_shortcut,
|
||||
screenshot_unregister_shortcut,
|
||||
screenshot_register_pin_shortcut,
|
||||
screenshot_unregister_pin_shortcut,
|
||||
screenshot_disable_transitions,
|
||||
screenshot_compose_copy
|
||||
])
|
||||
|
||||
@@ -14,6 +14,7 @@ mod system_proxy;
|
||||
mod types;
|
||||
|
||||
pub use pseudo::is_pseudo_node;
|
||||
pub use system_proxy::get_system_proxy_windows;
|
||||
pub use types::{InstallProgress, KernelInfo, KernelUpdateInfo, ProfileMeta, ProxySettings, ProxyStatus};
|
||||
pub use commands::{
|
||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy, proxy_close_connection,
|
||||
|
||||
@@ -38,7 +38,7 @@ pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn get_system_proxy_windows() -> bool {
|
||||
pub fn get_system_proxy_windows() -> bool {
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||
@@ -67,7 +67,7 @@ pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
||||
Err("系统代理仅支持 Windows".into())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
pub(crate) fn get_system_proxy_windows() -> bool {
|
||||
pub fn get_system_proxy_windows() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
|
||||
@@ -132,6 +132,41 @@ pub fn is_thing_elevated() -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
// ===================== 监控设置持久化 =====================
|
||||
|
||||
/// 监控模块设置(存储于 {app_data_dir}/monitor/settings.json)
|
||||
/// 参照代理模块 ProxySettings 的模式,仅包含需要持久化的运行时开关。
|
||||
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MonitorSettings {
|
||||
/// 应用启动时自动启动监控内核(默认 false)
|
||||
#[serde(default)]
|
||||
pub auto_start: bool,
|
||||
}
|
||||
|
||||
/// 监控设置文件路径: {app_data_dir}/monitor/settings.json
|
||||
fn settings_path(app_data_dir: &std::path::Path) -> PathBuf {
|
||||
app_data_dir.join("monitor").join("settings.json")
|
||||
}
|
||||
|
||||
/// 读取监控设置(文件不存在或解析失败时返回默认值)
|
||||
pub fn load_monitor_settings(app_data_dir: &std::path::Path) -> MonitorSettings {
|
||||
fs::read_to_string(settings_path(app_data_dir))
|
||||
.ok()
|
||||
.and_then(|s| serde_json::from_str::<MonitorSettings>(&s).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 写入监控设置
|
||||
pub fn save_monitor_settings(app_data_dir: &std::path::Path, settings: &MonitorSettings) -> Result<(), String> {
|
||||
let path = settings_path(app_data_dir);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {}", e))?;
|
||||
}
|
||||
let content = serde_json::to_string_pretty(settings).map_err(|e| format!("序列化设置失败: {}", e))?;
|
||||
fs::write(path, content).map_err(|e| format!("写入设置失败: {}", e))
|
||||
}
|
||||
|
||||
// ===================== 永久提权标志持久化 =====================
|
||||
|
||||
/// 永久提权标志文件路径: {app_data_dir}/monitor/elevate.json
|
||||
@@ -295,6 +330,32 @@ impl MonitorKernel {
|
||||
write_elevate_flag(&self.root.join("elevate.json"), enabled)
|
||||
}
|
||||
|
||||
/// 读取监控设置(auto_start 等)
|
||||
pub fn load_settings(&self) -> MonitorSettings {
|
||||
load_monitor_settings(&self.root.parent().unwrap_or(&self.root).to_path_buf())
|
||||
}
|
||||
|
||||
/// 写入监控设置
|
||||
pub fn save_settings(&self, settings: &MonitorSettings) -> Result<(), String> {
|
||||
save_monitor_settings(&self.root.parent().unwrap_or(&self.root).to_path_buf(), settings)
|
||||
}
|
||||
|
||||
/// 应用启动时检查是否需要自动启动监控内核
|
||||
pub fn auto_start_on_launch(&self, app: &AppHandle) {
|
||||
let settings = self.load_settings();
|
||||
if !settings.auto_start {
|
||||
return;
|
||||
}
|
||||
let monitor = self.clone();
|
||||
let app_handle = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match monitor.start_with_subscription(&app_handle).await {
|
||||
Ok(info) => crate::logger::log_info("monitor", &format!("自动启动成功, pid={:?}", info.pid)),
|
||||
Err(e) => crate::logger::log_warn("monitor", &format!("自动启动跳过: {}", e)),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn cores_dir(&self) -> PathBuf {
|
||||
self.root.join("cores")
|
||||
}
|
||||
@@ -950,6 +1011,25 @@ pub fn monitor_set_elevate_on_launch(
|
||||
state.set_elevate_on_launch(enabled)
|
||||
}
|
||||
|
||||
/// 查询"应用启动时自动启动监控内核"是否已启用
|
||||
#[tauri::command]
|
||||
pub fn monitor_get_auto_start(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
) -> bool {
|
||||
state.load_settings().auto_start
|
||||
}
|
||||
|
||||
/// 设置/清除"应用启动时自动启动监控内核"开关
|
||||
#[tauri::command]
|
||||
pub fn monitor_set_auto_start(
|
||||
state: tauri::State<'_, MonitorKernel>,
|
||||
enabled: bool,
|
||||
) -> Result<(), String> {
|
||||
let mut settings = state.load_settings();
|
||||
settings.auto_start = enabled;
|
||||
state.save_settings(&settings)
|
||||
}
|
||||
|
||||
/// 查询硬件监控配置(透传 Kernel GET /config/hardware)。
|
||||
/// 返回当前配置 + 可用硬件/传感器类型清单,供前端 Dialog 渲染。
|
||||
#[tauri::command]
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! 快速面板:基于 7-Zip(binaries/7z.exe)的批量文件操作。
|
||||
//!
|
||||
//! - 批量解压:逐文件调用 7z 控制台,支持一次传入统一密码(`-p`),
|
||||
//! 每完成一个文件通过事件推送进度,前端可实时展示。
|
||||
//! - 批量重命名:`regex` 匹配文件名生成预览,确认后执行 `fs::rename`。
|
||||
//! - 目录列表:供前端展示当前目录的压缩包 / 文件列表。
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use crate::constants::events::QUICKPANEL_EXTRACT_PROGRESS;
|
||||
|
||||
/// 7z 可执行文件名(与 7z.dll 同目录,位于 resources/binaries)。
|
||||
const _7Z_EXE: &str = "binaries/7z.exe";
|
||||
|
||||
/// 支持的压缩包扩展名(解压面板中列出)。
|
||||
const ARCHIVE_EXTS: &[&str] = &[
|
||||
".zip", ".7z", ".rar", ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".xz", ".txz", ".zst",
|
||||
".tzst", ".cab", ".lzma",
|
||||
];
|
||||
|
||||
/// 定位 7z 可执行文件(resources/binaries/7z.exe)。
|
||||
fn locate_7z(app: &AppHandle) -> Option<PathBuf> {
|
||||
let path = app
|
||||
.path()
|
||||
.resolve(_7Z_EXE, tauri::path::BaseDirectory::Resource)
|
||||
.ok()?;
|
||||
if path.exists() {
|
||||
Some(path)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ArchiveInfo {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct FileEntry {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub is_dir: bool,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExtractResult {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub ok: bool,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ExtractProgress {
|
||||
pub done: usize,
|
||||
pub total: usize,
|
||||
pub current: String,
|
||||
pub ok: bool,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RenamePreview {
|
||||
pub path: String,
|
||||
pub old_name: String,
|
||||
pub new_name: String,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RenameItem {
|
||||
pub path: String,
|
||||
pub old_name: String,
|
||||
pub new_name: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RenameResult {
|
||||
pub old_name: String,
|
||||
pub new_name: String,
|
||||
pub ok: bool,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
fn is_archive(name: &str) -> bool {
|
||||
let lower = name.to_lowercase();
|
||||
ARCHIVE_EXTS.iter().any(|ext| lower.ends_with(ext))
|
||||
}
|
||||
|
||||
/// 列出目录下的压缩包文件(供批量解压面板使用)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_list_archives(dir: String) -> Result<Vec<ArchiveInfo>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let d = Path::new(&dir);
|
||||
if !d.is_dir() {
|
||||
return Err(format!("目录不存在: {dir}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
|
||||
let Ok(entry) = entry else { continue };
|
||||
let path = entry.path();
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if is_archive(&name) {
|
||||
let size = path.metadata().map(|m| m.len()).unwrap_or(0);
|
||||
out.push(ArchiveInfo {
|
||||
name,
|
||||
path: path.to_string_lossy().to_string(),
|
||||
size,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("读取压缩包失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_list_dir(dir: String) -> Result<Vec<FileEntry>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let d = Path::new(&dir);
|
||||
if !d.is_dir() {
|
||||
return Err(format!("目录不存在: {dir}"));
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
|
||||
let Ok(entry) = entry else { continue };
|
||||
let path = entry.path();
|
||||
let is_dir = path.is_dir();
|
||||
let name = path
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
let size = if is_dir {
|
||||
0
|
||||
} else {
|
||||
path.metadata().map(|m| m.len()).unwrap_or(0)
|
||||
};
|
||||
out.push(FileEntry {
|
||||
name,
|
||||
path: path.to_string_lossy().to_string(),
|
||||
is_dir,
|
||||
size,
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| {
|
||||
b.is_dir
|
||||
.cmp(&a.is_dir)
|
||||
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
||||
});
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("读取目录失败: {e}"))?
|
||||
}
|
||||
|
||||
fn extract_one(
|
||||
exe: &Path,
|
||||
archive: &str,
|
||||
dest: &str,
|
||||
password: Option<&str>,
|
||||
into_subfolder: bool,
|
||||
) -> Result<(), String> {
|
||||
let archive_path = Path::new(archive);
|
||||
let mut cmd = Command::new(exe);
|
||||
cmd.arg("x").arg(archive_path);
|
||||
if into_subfolder {
|
||||
// 解压到「压缩包同名子文件夹」,避免文件散落在当前目录。
|
||||
let sub = archive_path
|
||||
.file_stem()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| "extracted".into());
|
||||
let sub_dir = Path::new(dest).join(&sub);
|
||||
std::fs::create_dir_all(&sub_dir).map_err(|e| format!("创建目录 {sub} 失败: {e}"))?;
|
||||
cmd.arg(format!("-o{}", sub_dir.display()));
|
||||
} else {
|
||||
cmd.arg(format!("-o{}", dest));
|
||||
}
|
||||
cmd.arg("-y"); // 全自动覆盖确认
|
||||
if let Some(p) = password.filter(|p| !p.is_empty()) {
|
||||
cmd.arg(format!("-p{p}"));
|
||||
}
|
||||
// 静默普通输出,仅错误进 stderr,逐文件粒度足够时无需 -bsp1 进度。
|
||||
cmd.arg("-bso0").arg("-bse1").arg("-bsp0");
|
||||
// 以 7z.exe 所在目录为工作目录,确保同目录的 7z.dll 可被加载。
|
||||
if let Some(dir) = exe.parent() {
|
||||
cmd.current_dir(dir);
|
||||
}
|
||||
let output = cmd.output().map_err(|e| format!("启动 7-Zip 失败: {e}"))?;
|
||||
if output.status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
let msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
let code = output.status.code().unwrap_or(-1);
|
||||
Err(if msg.is_empty() {
|
||||
format!("退出码 {code}")
|
||||
} else {
|
||||
msg
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
|
||||
/// `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
|
||||
/// 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_batch_extract(
|
||||
app: AppHandle,
|
||||
files: Vec<String>,
|
||||
dest_dir: String,
|
||||
password: Option<String>,
|
||||
into_subfolder: bool,
|
||||
) -> Result<Vec<ExtractResult>, String> {
|
||||
let exe = locate_7z(&app).ok_or("未找到 7-Zip 组件(binaries/7z.exe),请重新安装")?;
|
||||
let total = files.len();
|
||||
let results = tauri::async_runtime::spawn_blocking(move || {
|
||||
let mut results = Vec::with_capacity(total);
|
||||
for (idx, file) in files.iter().enumerate() {
|
||||
let err = extract_one(&exe, file, &dest_dir, password.as_deref(), into_subfolder);
|
||||
let name = Path::new(file)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| file.clone());
|
||||
let (ok, error) = match err {
|
||||
Ok(()) => (true, String::new()),
|
||||
Err(e) => (false, e),
|
||||
};
|
||||
results.push(ExtractResult {
|
||||
name,
|
||||
path: file.clone(),
|
||||
ok,
|
||||
error: error.clone(),
|
||||
});
|
||||
let _ = app.emit(
|
||||
QUICKPANEL_EXTRACT_PROGRESS,
|
||||
ExtractProgress {
|
||||
done: idx + 1,
|
||||
total,
|
||||
current: results[idx].name.clone(),
|
||||
ok,
|
||||
error,
|
||||
},
|
||||
);
|
||||
}
|
||||
results
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("解压任务异常终止: {e}"))?;
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
/// 正则批量重命名预览:对每个文件名应用 `pattern → replacement`,
|
||||
/// 仅返回有匹配的文件,`newName` 为替换结果。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_preview_rename(
|
||||
files: Vec<String>,
|
||||
pattern: String,
|
||||
replacement: String,
|
||||
) -> Result<Vec<RenamePreview>, String> {
|
||||
let re = regex::Regex::new(&pattern).map_err(|e| format!("正则表达式无效: {e}"))?;
|
||||
let mut out = Vec::new();
|
||||
for file in files {
|
||||
let name = Path::new(&file)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_default();
|
||||
if !re.is_match(&name) {
|
||||
continue;
|
||||
}
|
||||
let new_name = re.replace_all(&name, replacement.as_str()).to_string();
|
||||
let error = if new_name.is_empty() || new_name == name {
|
||||
"名称未变化".to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
out.push(RenamePreview {
|
||||
path: file,
|
||||
old_name: name,
|
||||
new_name,
|
||||
error,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// 执行重命名。同一目录下若目标已存在则跳过该项。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_apply_rename(items: Vec<RenameItem>) -> Result<Vec<RenameResult>, String> {
|
||||
let mut out = Vec::new();
|
||||
for item in items {
|
||||
let result = (|| -> Result<(), String> {
|
||||
if item.new_name.is_empty() {
|
||||
return Err("新文件名为空".into());
|
||||
}
|
||||
if item.new_name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||
return Err("文件名包含非法字符".into());
|
||||
}
|
||||
let old = Path::new(&item.path);
|
||||
let parent = old.parent().unwrap_or(Path::new("."));
|
||||
let new_path = parent.join(&item.new_name);
|
||||
if new_path.exists() {
|
||||
return Err("目标已存在".into());
|
||||
}
|
||||
std::fs::rename(old, &new_path).map_err(|e| format!("重命名失败: {e}"))?;
|
||||
Ok(())
|
||||
})();
|
||||
out.push(RenameResult {
|
||||
old_name: item.old_name,
|
||||
new_name: item.new_name,
|
||||
ok: result.is_ok(),
|
||||
error: result.err().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -1,10 +1,20 @@
|
||||
//! Tauri 命令:快速面板模块
|
||||
|
||||
use tauri::AppHandle;
|
||||
use tauri::{AppHandle, Manager};
|
||||
|
||||
use super::popup::{self, QuickPanelSettings};
|
||||
use super::{file_index, app_scanner, icon_extractor};
|
||||
|
||||
/// 批量删除单个条目的结果。
|
||||
#[derive(serde::Serialize, serde::Deserialize, specta::Type, Clone)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeleteResult {
|
||||
pub name: String,
|
||||
pub path: String,
|
||||
pub ok: bool,
|
||||
pub error: String,
|
||||
}
|
||||
|
||||
/// 读取快速面板设置(快捷键等)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -76,6 +86,26 @@ pub async fn quickpanel_show_window(app: AppHandle) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 显示主窗口并强制置为前台。
|
||||
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_focus_main_window(app: AppHandle) -> Result<(), String> {
|
||||
use crate::constants::windows::MAIN;
|
||||
if let Some(window) = app.get_webview_window(MAIN) {
|
||||
window.show().map_err(|e| e.to_string())?;
|
||||
window.unminimize().map_err(|e| e.to_string())?;
|
||||
match window.hwnd() {
|
||||
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
window.set_focus().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗)
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -95,11 +125,19 @@ pub fn quickpanel_lock_screen() -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 初始化文件索引数据库(应用启动时调用)
|
||||
/// 初始化文件索引数据库(应用启动时调用)。
|
||||
/// 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
|
||||
/// 无需重建即可继续自动同步文件变更。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_init_file_index(app: AppHandle) -> Result<(), String> {
|
||||
tauri::async_runtime::spawn_blocking(move || file_index::init(&app))
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
file_index::init(&app);
|
||||
let stats = file_index::stats();
|
||||
if stats.last_built_at > 0 && !stats.last_built_dirs.is_empty() {
|
||||
file_index::start_watcher(&stats.last_built_dirs);
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("索引初始化任务失败: {}", e))
|
||||
}
|
||||
@@ -114,6 +152,8 @@ pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String>
|
||||
} else {
|
||||
settings.index_dirs
|
||||
};
|
||||
// 懒加载:首次构建时自动初始化 DB 连接
|
||||
file_index::ensure_initialized(&app);
|
||||
// 阻塞操作放到 spawn_blocking
|
||||
tauri::async_runtime::spawn_blocking(move || file_index::build_index(&dirs))
|
||||
.await
|
||||
@@ -126,7 +166,10 @@ pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String>
|
||||
pub async fn quickpanel_search_files(
|
||||
query: String,
|
||||
limit: Option<i64>,
|
||||
app: AppHandle,
|
||||
) -> Result<Vec<file_index::FileRecord>, String> {
|
||||
// 懒加载:首次搜索时自动初始化 DB 连接
|
||||
file_index::ensure_initialized(&app);
|
||||
tauri::async_runtime::spawn_blocking(move || file_index::search(&query, limit.unwrap_or(50)))
|
||||
.await
|
||||
.map_err(|e| format!("搜索任务失败: {}", e))
|
||||
@@ -135,7 +178,9 @@ pub async fn quickpanel_search_files(
|
||||
/// 获取索引状态
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn quickpanel_file_index_stats() -> file_index::IndexStats {
|
||||
pub async fn quickpanel_file_index_stats(app: AppHandle) -> file_index::IndexStats {
|
||||
// 懒加载:查询状态前确保 DB 已初始化(未初始化时 stats 返回全 0)
|
||||
file_index::ensure_initialized(&app);
|
||||
file_index::stats()
|
||||
}
|
||||
|
||||
@@ -298,6 +343,69 @@ fn delete_file_impl(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
|
||||
/// 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
|
||||
/// 锁定的文件仍会失败并返回原因)。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn quickpanel_delete_files(
|
||||
paths: Vec<String>,
|
||||
force: bool,
|
||||
) -> Result<Vec<DeleteResult>, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let mut out = Vec::new();
|
||||
for path in paths {
|
||||
let name = std::path::Path::new(&path)
|
||||
.file_name()
|
||||
.map(|s| s.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| path.clone());
|
||||
let result = if force {
|
||||
delete_force_impl(&path)
|
||||
} else {
|
||||
delete_file_impl(&path)
|
||||
};
|
||||
out.push(DeleteResult {
|
||||
name,
|
||||
path: path.clone(),
|
||||
ok: result.is_ok(),
|
||||
error: result.err().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("删除任务失败: {e}"))?
|
||||
}
|
||||
|
||||
/// 强行删除:递归清除只读属性后永久删除(不经过回收站)。
|
||||
fn delete_force_impl(path: &str) -> Result<(), String> {
|
||||
let p = std::path::Path::new(path);
|
||||
clear_readonly(p);
|
||||
if p.is_dir() {
|
||||
std::fs::remove_dir_all(p).map_err(|e| format!("删除失败: {e}"))
|
||||
} else {
|
||||
std::fs::remove_file(p).map_err(|e| format!("删除失败: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
/// 递归清除只读属性(只读文件/目录无法直接删除)。
|
||||
fn clear_readonly(path: &std::path::Path) {
|
||||
if let Ok(meta) = std::fs::metadata(path) {
|
||||
if meta.permissions().readonly() {
|
||||
let mut perms = meta.permissions();
|
||||
perms.set_readonly(false);
|
||||
let _ = std::fs::set_permissions(path, perms);
|
||||
}
|
||||
if meta.is_dir() {
|
||||
if let Ok(rd) = std::fs::read_dir(path) {
|
||||
for entry in rd.flatten() {
|
||||
clear_readonly(&entry.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 运行自定义命令(执行可执行文件 + 参数)
|
||||
/// .lnk 快捷方式不能直接 spawn(os error 193),需通过 cmd /C 启动
|
||||
#[tauri::command]
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
//! 快速面板:检测前台 Explorer 窗口的当前目录。
|
||||
//!
|
||||
//! 必须在快捷键回调(`show_popup`)内调用:此时前台窗口仍是资源管理器,
|
||||
//! 面板尚未取得焦点,`GetForegroundWindow` 拿到的才是 Explorer 主窗口;
|
||||
//! 若等面板显示后再调用,前台就变成面板自身了。
|
||||
//!
|
||||
//! 思路(Listary / PowerToys Run 同款):前台窗口 HWND 匹配 `IShellWindows`
|
||||
//! 中某个 Shell 窗口 → 取其 `LocationURL`(file:///...)→ 转成本地路径。
|
||||
//!
|
||||
//! Win11 多选项卡:同一顶层窗口下每个选项卡都是独立的 `IShellWindows` 条目,
|
||||
//! 共享顶层 HWND。活动选项卡的内容窗口(`ShellTabWindowClass`)在子窗口
|
||||
//! z-order 顶层,用 `IID_IShellBrowser` 作为 `QueryService` 的 service ID 获取
|
||||
//! 每个选项卡自己的 `IShellBrowser`(而非 `SID_STopLevelBrowser` 返回的顶层
|
||||
//! browser),再通过 `GetWindow()` 拿到该选项卡的内容窗口句柄,与活动选项卡
|
||||
//! 的内容窗口比对,从而定位当前正在浏览的选项卡(`IsWindowVisible` 对所有
|
||||
//! 选项卡都成立,不可用)。
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
#[cfg(windows)]
|
||||
use windows::core::ComInterface;
|
||||
#[cfg(windows)]
|
||||
use windows::Win32::Foundation::HWND;
|
||||
#[cfg(windows)]
|
||||
use windows::Win32::System::Com::{
|
||||
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
||||
IServiceProvider,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
use windows::Win32::System::Variant::{VARIANT, VT_I4};
|
||||
#[cfg(windows)]
|
||||
use windows::Win32::UI::Shell::{
|
||||
IWebBrowserApp, IShellBrowser, IShellWindows, ShellWindows,
|
||||
};
|
||||
#[cfg(windows)]
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
GetClassNameW, GetForegroundWindow, GetWindow, GW_CHILD, GW_HWNDNEXT,
|
||||
};
|
||||
|
||||
/// 检测前台 Explorer 窗口的当前目录。
|
||||
/// 返回 `None`:前台不是 Explorer / COM 初始化失败 / URL 无法转路径。
|
||||
#[cfg(windows)]
|
||||
pub fn detect_explorer_folder() -> Option<String> {
|
||||
// 首次 COM 初始化失败(例如已在 MTA 线程)时,后续 COM 调用一般仍可用,忽略错误继续。
|
||||
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||
let fg = unsafe { GetForegroundWindow() };
|
||||
let result = if fg.0 == 0 {
|
||||
None
|
||||
} else {
|
||||
unsafe { find_folder_for_hwnd(fg) }
|
||||
};
|
||||
unsafe { CoUninitialize() };
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
unsafe fn find_folder_for_hwnd(fg: HWND) -> Option<String> {
|
||||
let shell: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL).ok()?;
|
||||
let count = shell.Count().ok()?;
|
||||
// Win11 多选项卡:活动选项卡的内容窗口(ShellTabWindowClass)在子窗口 z-order
|
||||
// 顶层。在 IShellWindows 条目中,用 IShellBrowser::GetWindow() 取到的内容窗口
|
||||
// HWND 与它比对,即可定位当前正在浏览的选项卡(IsWindowVisible 对所有选项卡
|
||||
// 都成立,不可用)。
|
||||
let active_tab = find_active_shell_tab(fg);
|
||||
for i in 0..count {
|
||||
// 索引过期的窗口会返回失败,跳过继续即可,不能 `?` 提前结束整个循环。
|
||||
// 0.52 的 Win32 VARIANT 无 From<i32>,手动构造 VT_I4 变体。
|
||||
let mut index = VARIANT::default();
|
||||
{
|
||||
let value = &mut *index.Anonymous.Anonymous;
|
||||
value.vt = VT_I4;
|
||||
value.Anonymous.lVal = i;
|
||||
}
|
||||
let Ok(dispatch) = shell.Item(index) else { continue };
|
||||
let Ok(app) = dispatch.cast::<IWebBrowserApp>() else { continue };
|
||||
// 只考虑前台顶层窗口对应的条目;同一窗口的多个选项卡条目共享顶层句柄。
|
||||
let Ok(hwnd) = app.HWND() else { continue };
|
||||
if HWND(hwnd.0) != fg {
|
||||
continue;
|
||||
}
|
||||
// 有选项卡时,必须匹配活动选项卡的内容窗口;否则退化为任意条目(旧版无选项卡)。
|
||||
if let Some(active) = active_tab {
|
||||
let Ok(svc) = app.cast::<IServiceProvider>() else { continue };
|
||||
let Ok(browser) = svc.QueryService::<IShellBrowser>(&IShellBrowser::IID) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(this_tab) = browser.GetWindow() else { continue };
|
||||
if this_tab != active {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Ok(url) = app.LocationURL() {
|
||||
return url_to_path(&url.to_string());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 枚举前台窗口的子窗口(z-order 自上而下),返回第一个类名为 `ShellTabWindowClass`
|
||||
/// 的窗口句柄,即 Win11 资源管理器活动选项卡的内容窗口;无选项卡时返回 `None`。
|
||||
#[cfg(windows)]
|
||||
unsafe fn find_active_shell_tab(fg: HWND) -> Option<HWND> {
|
||||
const CLASS: &str = "ShellTabWindowClass";
|
||||
let mut hwnd = GetWindow(fg, GW_CHILD);
|
||||
while hwnd.0 != 0 {
|
||||
let mut buf = [0u16; 64];
|
||||
let len = GetClassNameW(hwnd, &mut buf);
|
||||
if len > 0 {
|
||||
let name = String::from_utf16_lossy(&buf[..len as usize]);
|
||||
if name == CLASS {
|
||||
return Some(hwnd);
|
||||
}
|
||||
}
|
||||
hwnd = GetWindow(hwnd, GW_HWNDNEXT);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 把 `file:///C:/xxx`(可能带百分号编码)转成本地路径,仅接受目录。
|
||||
#[cfg(windows)]
|
||||
fn url_to_path(url: &str) -> Option<String> {
|
||||
if !url.starts_with("file:") {
|
||||
return None;
|
||||
}
|
||||
let parsed = url::Url::parse(url).ok()?;
|
||||
let path = parsed.to_file_path().ok()?;
|
||||
let path = Path::new(&path);
|
||||
if path.is_dir() {
|
||||
Some(path.to_string_lossy().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 非 Windows 平台占位:保持模块可编译。
|
||||
#[cfg(not(windows))]
|
||||
pub fn detect_explorer_folder() -> Option<String> {
|
||||
None
|
||||
}
|
||||
@@ -93,6 +93,17 @@ pub fn init(app: &AppHandle) {
|
||||
crate::logger::log_info("quickpanel", &format!("文件索引 DB 已就绪: {}", path.display()));
|
||||
}
|
||||
|
||||
/// 懒加载:首次访问文件索引时自动初始化(若尚未初始化)。
|
||||
/// 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。
|
||||
pub fn ensure_initialized(app: &AppHandle) {
|
||||
let guard = index_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||
if guard.is_some() {
|
||||
return;
|
||||
}
|
||||
drop(guard);
|
||||
init(app);
|
||||
}
|
||||
|
||||
/// 判断索引是否已初始化
|
||||
fn with_conn<F, R>(f: F) -> Option<R>
|
||||
where
|
||||
@@ -333,16 +344,51 @@ pub fn start_watcher(dirs: &[String]) {
|
||||
crate::logger::log_info("quickpanel", &format!("notify 监听已启动,监听 {} 个目录", dirs.len()));
|
||||
}
|
||||
|
||||
/// 处理文件系统事件:创建/修改 → upsert,删除 → remove,重命名 → remove + upsert
|
||||
/// 处理文件系统事件:
|
||||
/// - 创建/数据或元数据修改 → upsert
|
||||
/// - 重命名:旧路径(From) → remove,新路径(To) → upsert
|
||||
/// - 删除 → remove
|
||||
fn handle_fs_event(event: ¬ify::Event) {
|
||||
use notify::event::{ModifyKind, RenameMode};
|
||||
|
||||
match event.kind {
|
||||
EventKind::Create(_) | EventKind::Modify(_) => {
|
||||
// 创建、数据/元数据修改、类型未知 → upsert
|
||||
EventKind::Create(_)
|
||||
| EventKind::Modify(ModifyKind::Data(_))
|
||||
| EventKind::Modify(ModifyKind::Metadata(_))
|
||||
| EventKind::Modify(ModifyKind::Other)
|
||||
| EventKind::Modify(ModifyKind::Any) => {
|
||||
for path in &event.paths {
|
||||
if path.exists() {
|
||||
upsert_path(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 重命名旧路径 → 删除旧记录(含目录子项,避免索引残留失效路径)
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
|
||||
for path in &event.paths {
|
||||
remove_path(path);
|
||||
}
|
||||
}
|
||||
// 重命名新路径 → 写入新记录
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
|
||||
for path in &event.paths {
|
||||
if path.exists() {
|
||||
upsert_path(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 重命名模式未知:存在则写入,不存在则删除(幂等兜底)
|
||||
EventKind::Modify(ModifyKind::Name(RenameMode::Any | RenameMode::Both)) => {
|
||||
for path in &event.paths {
|
||||
if path.exists() {
|
||||
upsert_path(path);
|
||||
} else {
|
||||
remove_path(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 删除 → remove(含子项)
|
||||
EventKind::Remove(_) => {
|
||||
for path in &event.paths {
|
||||
remove_path(path);
|
||||
|
||||
@@ -4,21 +4,27 @@
|
||||
//! Phase 2:fuzzy + 拼音引擎,command/calc/web/system Provider
|
||||
//! Phase 3:文件索引(walkdir + rusqlite)、应用扫描、剪贴板历史复用
|
||||
|
||||
pub mod actions;
|
||||
pub mod app_scanner;
|
||||
pub mod commands;
|
||||
pub mod explorer;
|
||||
pub mod file_index;
|
||||
pub mod icon_extractor;
|
||||
pub mod popup;
|
||||
pub mod special_locations;
|
||||
|
||||
pub use actions::{
|
||||
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_list_archives,
|
||||
quickpanel_list_dir, quickpanel_preview_rename,
|
||||
};
|
||||
pub use commands::{
|
||||
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
||||
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
||||
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
|
||||
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
|
||||
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
|
||||
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
|
||||
quickpanel_unregister_shortcut,
|
||||
quickpanel_delete_files, quickpanel_file_index_stats, quickpanel_focus_main_window,
|
||||
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
|
||||
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
|
||||
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||
quickpanel_show_window, quickpanel_unregister_shortcut,
|
||||
};
|
||||
pub use popup::{ensure_window, load_settings};
|
||||
|
||||
@@ -20,6 +20,8 @@ use tauri::window::{Effect, EffectsBuilder};
|
||||
|
||||
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
||||
|
||||
use super::explorer;
|
||||
|
||||
use specta::Type;
|
||||
|
||||
/// 弹窗窗口标签
|
||||
@@ -29,6 +31,24 @@ pub const POPUP_LABEL: &str = "quick-panel";
|
||||
const WIN_W: f64 = 600.0;
|
||||
const WIN_H: f64 = 420.0;
|
||||
|
||||
/// `quickpanel-show` 事件负载:携带快捷键按下时检测到的 Explorer 当前目录,
|
||||
/// 前端据此渲染"当前目录"文件操作分组。
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct QuickPanelShowPayload {
|
||||
pub dir: Option<String>,
|
||||
}
|
||||
|
||||
/// 检测前台 Explorer 目录并连同 show 事件一起下发。
|
||||
/// 必须在快捷键回调内调用:此时前台窗口仍是 Explorer,面板尚未抢焦点。
|
||||
fn emit_show(app: &AppHandle) {
|
||||
let dir = explorer::detect_explorer_folder();
|
||||
crate::logger::log_info("quickpanel", &format!("show_popup: explorer_dir={:?}", dir));
|
||||
let _ = app.emit(
|
||||
crate::constants::events::QUICKPANEL_SHOW,
|
||||
QuickPanelShowPayload { dir },
|
||||
);
|
||||
}
|
||||
|
||||
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
||||
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
||||
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||
@@ -226,14 +246,15 @@ pub fn show_popup(app: &AppHandle) {
|
||||
|
||||
// 窗口已存在:移动 + 显示 + 请求焦点
|
||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||
// 必须先于窗口显示/聚焦检测 Explorer 目录:show/set_focus 会立即抢走前台焦点,
|
||||
// 之后调用 GetForegroundWindow 拿到的就是面板自身了。
|
||||
emit_show(app);
|
||||
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition {
|
||||
x: x as i32,
|
||||
y: y as i32,
|
||||
}));
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -261,10 +282,10 @@ pub fn show_window(app: &AppHandle) {
|
||||
y: y as i32,
|
||||
}));
|
||||
}
|
||||
// 同样先检测 Explorer 目录再显示,避免面板抢焦点导致检测失败。
|
||||
emit_show(app);
|
||||
let _ = win.show();
|
||||
let _ = win.set_focus();
|
||||
// 通知前端刷新数据
|
||||
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -67,6 +67,27 @@ pub async fn screenshot_unregister_shortcut(app: tauri::AppHandle) -> Result<(),
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 注册(或切换)贴图全局快捷键。传入空字符串则禁用快捷键。
|
||||
/// 按下时 emit 'screenshot-pin-shortcut',由前端切换贴图窗口显示/隐藏。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn screenshot_register_pin_shortcut(
|
||||
app: tauri::AppHandle,
|
||||
shortcut: String,
|
||||
) -> Result<(), String> {
|
||||
crate::shortcut::register_shortcut(&app, "贴图", &shortcut, |a| {
|
||||
let _ = a.emit(crate::constants::events::SCREENSHOT_PIN_SHORTCUT, ());
|
||||
})
|
||||
}
|
||||
|
||||
/// 注销贴图全局快捷键
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn screenshot_unregister_pin_shortcut(app: tauri::AppHandle) -> Result<(), String> {
|
||||
crate::shortcut::unregister_shortcut(&app, "贴图");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
@@ -349,17 +370,17 @@ pub async fn screenshot_save_png(png_base64: String, path: String) -> Result<(),
|
||||
.map_err(|e| format!("保存任务失败: {}", e))?
|
||||
}
|
||||
|
||||
// ===== 截图历史缓存:完整 PNG 落盘缓存目录,内存只保留缩略图 =====
|
||||
// ===== 截图历史缓存:完整 PNG 落盘到应用数据目录(持久化,随历史保留数量清理),内存只保留缩略图 =====
|
||||
|
||||
/// 历史缓存根目录(app_cache_dir/screenshot/history)
|
||||
/// 历史根目录(app_data_dir/screenshot/history)
|
||||
fn history_cache_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {
|
||||
let dir = app
|
||||
.path()
|
||||
.app_cache_dir()
|
||||
.map_err(|e| format!("获取缓存目录失败: {}", e))?
|
||||
.app_data_dir()
|
||||
.map_err(|e| format!("获取应用数据目录失败: {}", e))?
|
||||
.join("screenshot")
|
||||
.join("history");
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建缓存目录失败: {}", e))?;
|
||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建历史目录失败: {}", e))?;
|
||||
Ok(dir)
|
||||
}
|
||||
|
||||
|
||||
+7
-13
@@ -66,8 +66,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let server_engine = engine.clone();
|
||||
let server_port = settings.extension_port;
|
||||
let server_secret = settings.extension_secret.clone();
|
||||
let server_app = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
ExtensionServer::start(server_engine, server_port, server_secret).await;
|
||||
ExtensionServer::start(server_engine, server_port, server_secret, server_app).await;
|
||||
});
|
||||
|
||||
// ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 =====
|
||||
@@ -90,8 +91,10 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
app.manage(clipboard);
|
||||
|
||||
// ===== 快速面板:快捷键 + 预创建弹窗 + 文件索引 =====
|
||||
// ===== 快速面板:快捷键 + 预创建弹窗 =====
|
||||
// defaultEnabled:true 假设启用;用户在设置页禁用模块时由前端 onDisable 钩子注销快捷键。
|
||||
// 文件索引 DB 连接改为懒加载(首次搜索/构建时由 commands 中的 ensure_initialized 触发),
|
||||
// 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。
|
||||
let qp_settings = crate::quickpanel::load_settings(&app.handle());
|
||||
if !qp_settings.shortcut.trim().is_empty() {
|
||||
let app_handle = app.handle().clone();
|
||||
@@ -106,8 +109,6 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
||||
crate::quickpanel::ensure_window(&app_handle);
|
||||
}
|
||||
// 初始化文件索引数据库(不立即构建,由前端设置页或首次唤起时触发)
|
||||
crate::quickpanel::file_index::init(&app.handle());
|
||||
|
||||
// ===== 托盘菜单 =====
|
||||
crate::tray_menu::create_tray_menu(app.handle())?;
|
||||
@@ -123,16 +124,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
}
|
||||
|
||||
// monitor Kernel:硬件监控默认启用,被动读取无副作用
|
||||
// monitor Kernel:用户在设置中开启"自动启动"时随应用启动
|
||||
if let Some(monitor) = app.try_state::<MonitorKernel>() {
|
||||
let monitor = monitor.inner().clone();
|
||||
let app_handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
match monitor.start_with_subscription(&app_handle).await {
|
||||
Ok(info) => crate::logger::log_info("monitor", &format!("自动启动成功, pid={:?}", info.pid)),
|
||||
Err(e) => crate::logger::log_warn("monitor", &format!("自动启动跳过: {}", e)),
|
||||
}
|
||||
});
|
||||
monitor.auto_start_on_launch(app.handle());
|
||||
}
|
||||
|
||||
// 截图快捷键由前端 screenshotStore 启动时调用 screenshot_register_shortcut 注册
|
||||
|
||||
+95
-45
@@ -21,10 +21,10 @@ use tauri::{
|
||||
static LAST_SHOW_TIME: Mutex<Option<Instant>> = Mutex::new(None);
|
||||
|
||||
/// 保存最近一次右键时计算出的定位参数(物理坐标),供 `tray_menu_ready` 使用
|
||||
/// (x, tray_top, wa_top, wa_bottom, scale)
|
||||
/// (x, cursor_y, screen_top, screen_bottom, scale)
|
||||
static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(None);
|
||||
|
||||
use crate::win32_util::{get_work_area, get_work_area_at_point, get_dpi_for_point};
|
||||
use crate::win32_util::{get_work_area, get_monitor_bounds_at_point, get_dpi_for_point};
|
||||
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
|
||||
use crate::monitor_kernel::MonitorKernel;
|
||||
use crate::process_manager::{ProcessManager, ProcessStatus};
|
||||
@@ -46,6 +46,7 @@ pub struct ProxyNodeInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct TrayMenuState {
|
||||
pub proxy_running: bool,
|
||||
pub system_proxy: bool,
|
||||
pub monitor_running: bool,
|
||||
pub proxy_group: Option<String>,
|
||||
pub proxy_nodes: Vec<ProxyNodeInfo>,
|
||||
@@ -147,9 +148,29 @@ async fn fetch_proxy_nodes(app: &AppHandle) -> Option<(String, Vec<(String, Opti
|
||||
|
||||
// ===== 获取菜单状态 =====
|
||||
|
||||
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
||||
/// 基础状态(不含代理节点)。托盘菜单显示不应受 mihomo API 慢/卡死影响,
|
||||
/// 因此先秒发基础状态让菜单立即出现,代理节点随后异步补充。
|
||||
fn get_base_tray_state(app: &AppHandle) -> TrayMenuState {
|
||||
let proxy_running = is_proxy_running(app);
|
||||
let monitor_running = is_monitor_running(app);
|
||||
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
|
||||
let system_proxy = crate::mihomo_manager::get_system_proxy_windows();
|
||||
TrayMenuState {
|
||||
proxy_running,
|
||||
system_proxy,
|
||||
monitor_running,
|
||||
proxy_group: None,
|
||||
proxy_nodes: vec![],
|
||||
proxy_current: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 完整状态(含代理节点)。可能因调用 mihomo /proxies 而耗时(最长 10s)。
|
||||
async fn get_full_tray_state(app: &AppHandle) -> TrayMenuState {
|
||||
let proxy_running = is_proxy_running(app);
|
||||
let monitor_running = is_monitor_running(app);
|
||||
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
|
||||
let system_proxy = crate::mihomo_manager::get_system_proxy_windows();
|
||||
|
||||
let (proxy_group, proxy_nodes, proxy_current) = if proxy_running {
|
||||
match fetch_proxy_nodes(app).await {
|
||||
@@ -172,6 +193,7 @@ pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
||||
|
||||
TrayMenuState {
|
||||
proxy_running,
|
||||
system_proxy,
|
||||
monitor_running,
|
||||
proxy_group,
|
||||
proxy_nodes,
|
||||
@@ -179,6 +201,10 @@ pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
||||
get_full_tray_state(app).await
|
||||
}
|
||||
|
||||
// ===== 显示/隐藏托盘菜单窗口 =====
|
||||
|
||||
/// 托盘菜单窗口尺寸(逻辑像素)
|
||||
@@ -245,29 +271,30 @@ pub fn precreate_tray_menu_window(app: &AppHandle) {
|
||||
}
|
||||
|
||||
/// 右键托盘时调用:计算定位参数、发送状态给前端,但不立即显示窗口。
|
||||
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部精确对齐托盘图标。
|
||||
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部对齐鼠标点击位置。
|
||||
///
|
||||
/// `cursor_pos`: 事件报告的鼠标物理坐标;`tray_rect`: 托盘图标区域(物理像素)。
|
||||
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64, f64, f64, f64)) {
|
||||
/// `cursor_pos`: 事件报告的鼠标物理坐标。
|
||||
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64)) {
|
||||
let (mx, my) = (cursor_pos.0, cursor_pos.1);
|
||||
let tray_top = tray_rect.1;
|
||||
|
||||
// 获取光标所在显示器的工作区(物理像素)
|
||||
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(mx as i32, my as i32)
|
||||
.unwrap_or((0, 0, 1920, 1040));
|
||||
// 获取光标所在显示器的完整边界(含任务栏,物理像素)。
|
||||
// 托盘图标位于任务栏上,菜单需在鼠标位置弹出,因此用屏幕边界而非工作区做 clamp,
|
||||
// 否则会被工作区底部(任务栏顶部)截断,导致菜单整体被推到任务栏上方。
|
||||
let (scr_left, scr_top, scr_right, scr_bottom) = get_monitor_bounds_at_point(mx as i32, my as i32)
|
||||
.unwrap_or((0, 0, 1920, 1080));
|
||||
|
||||
// 光标所在显示器的 DPI:菜单宽度按物理像素换算
|
||||
let dpi = get_dpi_for_point(mx as i32, my as i32).unwrap_or(96);
|
||||
let scale = dpi as f64 / 96.0;
|
||||
let menu_w_px = MENU_W * scale;
|
||||
|
||||
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出右边界则左移(物理坐标)
|
||||
let x = mx.max(wa_left as f64).min(wa_right as f64 - menu_w_px);
|
||||
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出屏幕右边界则左移(物理坐标)
|
||||
let x = mx.max(scr_left as f64).min(scr_right as f64 - menu_w_px);
|
||||
|
||||
// 保存布局参数(全部物理坐标 + scale,供 tray_menu_ready 换算前端上报的逻辑高度)
|
||||
{
|
||||
let mut layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*layout = Some((x, tray_top, wa_top as f64, wa_bottom as f64, scale));
|
||||
*layout = Some((x, my, scr_top as f64, scr_bottom as f64, scale));
|
||||
}
|
||||
|
||||
// 记录显示时间,用于失焦防抖
|
||||
@@ -281,10 +308,20 @@ pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64,
|
||||
precreate_tray_menu_window(app);
|
||||
}
|
||||
|
||||
// 发送状态给前端(前端测量内容高度后调用 tray_menu_ready 显示窗口)
|
||||
// 发送状态给前端(前端测量内容高度后调用 tray_menu_ready 显示窗口)。
|
||||
// 代理节点拉取默认最长 10s;这里用 1.5s 短超时兜底,避免 mihomo API 卡死时
|
||||
// 菜单迟迟不出现(超时则退回基础状态,节点区留空,后续 refresh 可补)。
|
||||
let app_clone = app.clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let state = get_tray_menu_state(&app_clone).await;
|
||||
let state = match tokio::time::timeout(
|
||||
Duration::from_millis(1500),
|
||||
get_full_tray_state(&app_clone),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(s) => s,
|
||||
Err(_) => get_base_tray_state(&app_clone),
|
||||
};
|
||||
let _ = app_clone.emit(crate::constants::events::TRAY_MENU_SHOW, state);
|
||||
});
|
||||
}
|
||||
@@ -302,6 +339,22 @@ async fn refresh_and_emit_state(app: &AppHandle) {
|
||||
let _ = app.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
|
||||
}
|
||||
|
||||
/// 显示主窗口并强制置为前台。
|
||||
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||
pub fn focus_main_window(app: &AppHandle) {
|
||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
||||
let _ = window.show();
|
||||
let _ = window.unminimize();
|
||||
match window.hwnd() {
|
||||
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||
Err(_) => {
|
||||
window.set_focus().ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== Tauri 命令 =====
|
||||
|
||||
/// 执行菜单项动作(统一入口)
|
||||
@@ -338,6 +391,21 @@ pub async fn tray_menu_action(
|
||||
}
|
||||
}
|
||||
}
|
||||
"system_proxy_toggle" => {
|
||||
// 根据注册表当前真实状态切换(不依赖 settings.json 缓存,避免与主界面不同步)
|
||||
let mihomo = app.state::<MihomoManager>();
|
||||
if crate::mihomo_manager::get_system_proxy_windows() {
|
||||
if let Err(e) = mihomo.disable_system_proxy() {
|
||||
crate::logger::log_error("tray", &format!("关闭系统代理失败: {}", e));
|
||||
send_notification(&app, "系统代理关闭失败", &e);
|
||||
}
|
||||
} else {
|
||||
if let Err(e) = mihomo.enable_system_proxy() {
|
||||
crate::logger::log_error("tray", &format!("开启系统代理失败: {}", e));
|
||||
send_notification(&app, "系统代理开启失败", &e);
|
||||
}
|
||||
}
|
||||
}
|
||||
"osd_toggle" => {
|
||||
let _ = app.emit(crate::constants::events::TRAY_TOGGLE_OSD, ());
|
||||
}
|
||||
@@ -348,18 +416,12 @@ pub async fn tray_menu_action(
|
||||
}
|
||||
}
|
||||
"download_new" => {
|
||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
||||
window.show().ok();
|
||||
window.set_focus().ok();
|
||||
}
|
||||
focus_main_window(&app);
|
||||
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
|
||||
hide_tray_menu(&app);
|
||||
}
|
||||
"settings" => {
|
||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
||||
window.show().ok();
|
||||
window.set_focus().ok();
|
||||
}
|
||||
focus_main_window(&app);
|
||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
|
||||
hide_tray_menu(&app);
|
||||
}
|
||||
@@ -392,9 +454,9 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
||||
let win = app.get_webview_window(TRAY_MENU_LABEL)
|
||||
.ok_or("tray-menu window not found")?;
|
||||
|
||||
let (x, tray_top, wa_top, wa_bottom, scale) = {
|
||||
let (x, cursor_y, scr_top, scr_bottom, scale) = {
|
||||
let layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
layout.unwrap_or((0.0, 1040.0, 0.0, 1040.0, 1.0))
|
||||
layout.unwrap_or((0.0, 1040.0, 0.0, 1080.0, 1.0))
|
||||
};
|
||||
|
||||
// 将内容高度限制在合理范围内(前端上报为逻辑像素)
|
||||
@@ -408,8 +470,10 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
||||
height: win_h_px as u32,
|
||||
}));
|
||||
|
||||
// 垂直:菜单下边缘紧贴托盘图标顶部(向上弹出,物理坐标)
|
||||
let y = (tray_top - win_h_px).max(wa_top).min(wa_bottom - win_h_px);
|
||||
// 垂直:菜单底部对齐鼠标点击位置(向上弹出,物理坐标)。
|
||||
// 用屏幕边界而非工作区 clamp,使菜单贴近/覆盖任务栏上的鼠标位置,
|
||||
// 而不是被工作区底部(任务栏顶部)截断后整体出现在任务栏上方。
|
||||
let y = (cursor_y - win_h_px).max(scr_top).min(scr_bottom - win_h_px);
|
||||
|
||||
let pos = tauri::Position::Physical(tauri::PhysicalPosition {
|
||||
x: x as i32,
|
||||
@@ -647,31 +711,17 @@ pub fn create_tray_menu(app: &AppHandle) -> Result<(), tauri::Error> {
|
||||
button: MouseButton::Left,
|
||||
..
|
||||
} => {
|
||||
// 左键:显示主窗口
|
||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
||||
window.show().ok();
|
||||
window.set_focus().ok();
|
||||
}
|
||||
// 左键:显示主窗口(强制置前,绕过前台锁定)
|
||||
focus_main_window(&app);
|
||||
}
|
||||
TrayIconEvent::Click {
|
||||
button: MouseButton::Right,
|
||||
position,
|
||||
rect,
|
||||
..
|
||||
} => {
|
||||
// 右键:显示自定义菜单窗口(使用事件中的精确坐标)
|
||||
// 右键:显示自定义菜单窗口(使用事件中的鼠标坐标)
|
||||
let cursor = (position.x, position.y);
|
||||
// 从 Rect 的 Position/Size 枚举中提取物理像素值
|
||||
let (rx, ry) = match rect.position {
|
||||
tauri::Position::Physical(p) => (p.x as f64, p.y as f64),
|
||||
tauri::Position::Logical(p) => (p.x, p.y),
|
||||
};
|
||||
let (_rw, rh) = match rect.size {
|
||||
tauri::Size::Physical(s) => (s.width as f64, s.height as f64),
|
||||
tauri::Size::Logical(s) => (s.width, s.height),
|
||||
};
|
||||
let tray_r = (rx, ry, _rw, rh);
|
||||
show_tray_menu(&app, cursor, tray_r);
|
||||
show_tray_menu(&app, cursor);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
//! 应用自更新模块。
|
||||
//! 更新源为自建 Gitea:`https://gitea.atie.fun/LFeng/Thing` 的 release 资产。
|
||||
//! - 便携版(无 unins000.exe 且不在 Program Files):下载新 thing.exe → update.bat 覆盖重启
|
||||
//! - 安装版(NSIS):下载新 setup.exe → 提权静默安装 /S
|
||||
//! - ThingHK 内核:下载 thing-hk_{v}.zip → 停止监控内核 → 覆盖 {app_data}/monitor/cores/ThingHK.exe
|
||||
//! mihomo 内核更新继续复用代理模块已有的 GitHub 下载机制,不在此模块处理。
|
||||
use futures_util::StreamExt;
|
||||
use serde::Serialize;
|
||||
use specta::Type;
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use tauri::{AppHandle, Emitter, Manager};
|
||||
|
||||
use crate::constants::events::UPDATE_PROGRESS;
|
||||
|
||||
/// 发布仓库(Gitea)
|
||||
const GITEA_REPO: &str = "LFeng/Thing";
|
||||
const GITEA_BASE: &str = "https://gitea.atie.fun";
|
||||
|
||||
/// release 中的一个资产
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateAsset {
|
||||
pub name: String,
|
||||
pub size: u64,
|
||||
pub browser_download_url: String,
|
||||
}
|
||||
|
||||
/// 检查更新的结果
|
||||
#[derive(Debug, Clone, Serialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateCheckResult {
|
||||
pub current_version: String,
|
||||
pub latest_version: String,
|
||||
pub has_update: bool,
|
||||
/// portable | installed
|
||||
pub install_type: String,
|
||||
pub release_name: String,
|
||||
pub release_body: String,
|
||||
pub assets: Vec<UpdateAsset>,
|
||||
}
|
||||
|
||||
/// 更新进度事件载荷(与内核安装进度同构,独立事件便于 UI 区分)
|
||||
#[derive(Serialize, Clone, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct UpdateProgress {
|
||||
pub stage: String,
|
||||
pub percent: u8,
|
||||
#[specta(type = f64)]
|
||||
pub downloaded_bytes: u64,
|
||||
#[specta(type = Option<f64>)]
|
||||
pub total_bytes: Option<u64>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
// ---------- 版本比较 ----------
|
||||
|
||||
/// 解析 vX.Y.Z 为数字元组用于比较;解析失败返回 (0,0,0)
|
||||
fn parse_version(v: &str) -> (u32, u32, u32) {
|
||||
let s = v.trim().trim_start_matches('v');
|
||||
let mut parts = s.split('.');
|
||||
let major = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
|
||||
let minor = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
|
||||
let patch = parts
|
||||
.next()
|
||||
.map(|p| p.chars().take_while(|c| c.is_ascii_digit()).collect::<String>())
|
||||
.and_then(|p| p.parse().ok())
|
||||
.unwrap_or(0);
|
||||
(major, minor, patch)
|
||||
}
|
||||
|
||||
fn version_gt(a: &str, b: &str) -> bool {
|
||||
parse_version(a) > parse_version(b)
|
||||
}
|
||||
|
||||
// ---------- Gitea API ----------
|
||||
|
||||
struct LatestRelease {
|
||||
tag_name: String,
|
||||
name: String,
|
||||
body: String,
|
||||
assets: Vec<UpdateAsset>,
|
||||
}
|
||||
|
||||
async fn fetch_latest_release() -> Result<LatestRelease, String> {
|
||||
let url = format!("{}/api/v1/repos/{}/releases/latest", GITEA_BASE, GITEA_REPO);
|
||||
let client = reqwest::Client::builder()
|
||||
.timeout(std::time::Duration::from_secs(15))
|
||||
.build()
|
||||
.map_err(|e| format!("创建 HTTP 客户端失败: {}", e))?;
|
||||
let resp = client
|
||||
.get(&url)
|
||||
.header("User-Agent", "thing-app")
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求 Gitea API 失败: {}", e))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("Gitea API 返回 HTTP {}", resp.status()));
|
||||
}
|
||||
let json: serde_json::Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 Gitea 响应失败: {}", e))?;
|
||||
let mut assets = Vec::new();
|
||||
if let Some(list) = json.get("assets").and_then(|v| v.as_array()) {
|
||||
for a in list {
|
||||
if let (Some(name), Some(url)) = (
|
||||
a.get("name").and_then(|v| v.as_str()),
|
||||
a.get("browser_download_url").and_then(|v| v.as_str()),
|
||||
) {
|
||||
assets.push(UpdateAsset {
|
||||
name: name.to_string(),
|
||||
size: a.get("size").and_then(|v| v.as_u64()).unwrap_or(0),
|
||||
browser_download_url: url.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(LatestRelease {
|
||||
tag_name: json.get("tag_name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||
name: json.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||
body: json.get("body").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||
assets,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- 下载 / 解压 ----------
|
||||
|
||||
/// 下载文件到 dest,期间通过 UPDATE_PROGRESS 事件上报进度
|
||||
async fn download_with_progress(app: &AppHandle, url: &str, dest: &Path) -> Result<(), String> {
|
||||
let client = reqwest::Client::new();
|
||||
let resp = client
|
||||
.get(url)
|
||||
.header("User-Agent", "thing-app")
|
||||
.timeout(std::time::Duration::from_secs(30))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("下载请求失败: {}", e))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("下载失败: HTTP {}", resp.status()));
|
||||
}
|
||||
let total = resp.content_length();
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {}", e))?;
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut last_percent: u8 = 0;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|e| format!("读取下载流失败: {}", e))?;
|
||||
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {}", e))?;
|
||||
downloaded += chunk.len() as u64;
|
||||
let percent = match total {
|
||||
Some(t) if t > 0 => ((downloaded as f64 / t as f64) * 100.0) as u8,
|
||||
_ => 0,
|
||||
};
|
||||
if percent >= last_percent + 1 {
|
||||
last_percent = percent;
|
||||
let _ = app.emit(
|
||||
UPDATE_PROGRESS,
|
||||
UpdateProgress {
|
||||
stage: "downloading".into(),
|
||||
percent,
|
||||
downloaded_bytes: downloaded,
|
||||
total_bytes: total,
|
||||
message: format!(
|
||||
"已下载 {:.2} MB / {:.2} MB",
|
||||
downloaded as f64 / 1024.0 / 1024.0,
|
||||
total.unwrap_or(0) as f64 / 1024.0 / 1024.0
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
file.flush().map_err(|e| format!("flush 失败: {}", e))?;
|
||||
let _ = app.emit(
|
||||
UPDATE_PROGRESS,
|
||||
UpdateProgress {
|
||||
stage: "downloaded".into(),
|
||||
percent: 100,
|
||||
downloaded_bytes: downloaded,
|
||||
total_bytes: total,
|
||||
message: "下载完成".into(),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 用 zip crate 解压(纯 Rust,避免 PowerShell 执行策略问题)
|
||||
fn extract_zip(zip_path: &Path, dest: &Path) -> Result<(), String> {
|
||||
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {}", e))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive
|
||||
.by_index(i)
|
||||
.map_err(|e| format!("读取条目失败: {}", e))?;
|
||||
let outpath = match entry.enclosed_name() {
|
||||
Some(p) => dest.join(p),
|
||||
None => continue,
|
||||
};
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(parent) = outpath.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------- 安装类型 / ShellExecute ----------
|
||||
|
||||
/// 判断当前是便携版还是安装版。
|
||||
/// NSIS 安装会在程序目录生成 unins000.exe;MSI 通常安装到 Program Files。
|
||||
fn is_installed_version() -> bool {
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(dir) = exe.parent() {
|
||||
if dir.join("unins000.exe").exists() {
|
||||
return true;
|
||||
}
|
||||
let p = dir.to_string_lossy().to_lowercase();
|
||||
if p.contains("program files") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 通过 ShellExecuteW 启动程序/文档(绕过 Job Object,脱离主进程生命周期)
|
||||
fn shell_execute(verb: &str, file: &Path, params: &str, show: i32) -> Result<(), String> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use windows_sys::Win32::UI::Shell::ShellExecuteW;
|
||||
let file_w: Vec<u16> = file.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||
let verb_w: Vec<u16> = verb.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
let params_w: Vec<u16> = params.encode_utf16().chain(std::iter::once(0)).collect();
|
||||
let res = unsafe {
|
||||
ShellExecuteW(
|
||||
0 as isize,
|
||||
verb_w.as_ptr(),
|
||||
file_w.as_ptr(),
|
||||
params_w.as_ptr(),
|
||||
std::ptr::null(),
|
||||
show,
|
||||
)
|
||||
};
|
||||
if (res as isize) <= 32 {
|
||||
return Err(format!("ShellExecuteW 失败 (code={})", res));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let _ = (verb, file, params, show);
|
||||
Err("仅支持 Windows".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// 便携版:写 update.bat 等待主进程退出 → 覆盖 exe → 重新启动
|
||||
fn apply_portable_update(new_exe: &Path) -> Result<(), String> {
|
||||
let cur_exe = std::env::current_exe().map_err(|e| format!("获取当前程序路径失败: {}", e))?;
|
||||
let cur_dir = cur_exe.parent().ok_or("无法确定程序目录".to_string())?;
|
||||
let bat_path = cur_dir.join("update.bat");
|
||||
let script = format!(
|
||||
"@echo off\r\n\
|
||||
:wait\r\n\
|
||||
tasklist /FI \"IMAGENAME eq thing.exe\" 2>nul | findstr /i \"thing.exe\" >nul\r\n\
|
||||
if not errorlevel 1 (\r\n\
|
||||
ping -n 2 127.0.0.1 >nul\r\n\
|
||||
goto wait\r\n\
|
||||
)\r\n\
|
||||
copy /y \"{new}\" \"{cur}\" >nul\r\n\
|
||||
if errorlevel 1 exit /b 1\r\n\
|
||||
start \"\" \"{cur}\"\r\n\
|
||||
del \"{new}\" >nul 2>nul\r\n\
|
||||
del \"%~f0\" >nul 2>nul\r\n",
|
||||
new = new_exe.display(),
|
||||
cur = cur_exe.display()
|
||||
);
|
||||
fs::write(&bat_path, script).map_err(|e| format!("写入更新脚本失败: {}", e))?;
|
||||
// 用 cmd /c 启动 bat 并隐藏窗口;ShellExecute 启动的进程不属于本进程 Job,
|
||||
// 主进程退出后 update.bat 仍能继续执行
|
||||
let windir = std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into());
|
||||
let cmd_exe = Path::new(&windir).join("System32").join("cmd.exe");
|
||||
shell_execute("open", &cmd_exe, &format!("/c \"{}\"", bat_path.display()), 0)
|
||||
}
|
||||
|
||||
// ---------- 命令 ----------
|
||||
|
||||
/// 获取当前应用版本
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn app_version(app: AppHandle) -> String {
|
||||
app.package_info().version.to_string()
|
||||
}
|
||||
|
||||
/// 检查 Gitea 最新 release,返回版本对比与可用资产
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn update_check(app: AppHandle) -> Result<UpdateCheckResult, String> {
|
||||
let latest = fetch_latest_release().await?;
|
||||
let latest_version = latest.tag_name.trim_start_matches('v').to_string();
|
||||
let current_version = app.package_info().version.to_string();
|
||||
let has_update = version_gt(&latest_version, ¤t_version);
|
||||
Ok(UpdateCheckResult {
|
||||
current_version,
|
||||
latest_version,
|
||||
has_update,
|
||||
install_type: if is_installed_version() { "installed".into() } else { "portable".into() },
|
||||
release_name: latest.name,
|
||||
release_body: latest.body,
|
||||
assets: latest.assets,
|
||||
})
|
||||
}
|
||||
|
||||
/// 更新应用本体。
|
||||
/// 便携版:下载 thing_{v}_x64.exe → update.bat 覆盖重启;
|
||||
/// 安装版:下载 thing_{v}_x64-setup.exe → 提权静默安装 /S。
|
||||
/// 下载进度通过 UPDATE_PROGRESS 事件上报,调用方返回前会触发应用退出。
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn update_install(app: AppHandle) -> Result<(), String> {
|
||||
let latest = fetch_latest_release().await?;
|
||||
let installed = is_installed_version();
|
||||
let (target_name, target_url) = if installed {
|
||||
latest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|a| a.name.ends_with("-setup.exe"))
|
||||
.map(|a| (a.name.clone(), a.browser_download_url.clone()))
|
||||
.ok_or("未在 release 中找到安装包 (setup.exe)".to_string())?
|
||||
} else {
|
||||
latest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|a| a.name.ends_with(".exe") && !a.name.contains("setup"))
|
||||
.map(|a| (a.name.clone(), a.browser_download_url.clone()))
|
||||
.ok_or("未在 release 中找到便携版程序 (thing.exe)".to_string())?
|
||||
};
|
||||
let temp_dir = std::env::temp_dir().join("thing-update");
|
||||
fs::create_dir_all(&temp_dir).map_err(|e| format!("创建临时目录失败: {}", e))?;
|
||||
let dest = temp_dir.join(&target_name);
|
||||
download_with_progress(&app, &target_url, &dest).await?;
|
||||
let _ = app.emit(
|
||||
UPDATE_PROGRESS,
|
||||
UpdateProgress {
|
||||
stage: "applying".into(),
|
||||
percent: 100,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: if installed { "正在启动安装程序...".into() } else { "正在替换程序文件...".into() },
|
||||
},
|
||||
);
|
||||
if installed {
|
||||
// 提权静默安装 /S;UAC 确认期间主进程已退出,安装器可正常覆盖
|
||||
shell_execute("runas", &dest, "/S", 0)?;
|
||||
} else {
|
||||
apply_portable_update(&dest)?;
|
||||
}
|
||||
// 延迟退出,确保 ShellExecute 已拉起子进程
|
||||
app.exit(0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 更新 ThingHK 内核:下载 thing-hk_{v}.zip → 停止监控内核 → 覆盖内核文件
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn update_thinghk(app: AppHandle) -> Result<(), String> {
|
||||
let latest = fetch_latest_release().await?;
|
||||
let asset = latest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|a| a.name.starts_with("thing-hk_") && a.name.ends_with(".zip"))
|
||||
.ok_or("未在 release 中找到 ThingHK 内核包".to_string())?;
|
||||
// 停止监控内核(含提权模式的 /shutdown 兜底由前端先停模块),避免 exe 被占用
|
||||
if let Some(monitor) = app.try_state::<crate::monitor_kernel::MonitorKernel>() {
|
||||
monitor.stop_subscription(&app).await;
|
||||
}
|
||||
if let Some(pm) = app.try_state::<crate::process_manager::ProcessManager>() {
|
||||
let _ = pm.stop("monitor");
|
||||
}
|
||||
// 等待进程退出释放文件句柄
|
||||
tokio::time::sleep(std::time::Duration::from_millis(600)).await;
|
||||
let temp_dir = std::env::temp_dir().join("thing-update");
|
||||
fs::create_dir_all(&temp_dir).map_err(|e| format!("创建临时目录失败: {}", e))?;
|
||||
let zip_path = temp_dir.join(&asset.name);
|
||||
download_with_progress(&app, &asset.browser_download_url, &zip_path).await?;
|
||||
let _ = app.emit(
|
||||
UPDATE_PROGRESS,
|
||||
UpdateProgress {
|
||||
stage: "extracting".into(),
|
||||
percent: 95,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: "正在解压内核...".into(),
|
||||
},
|
||||
);
|
||||
let extract_dir = temp_dir.join("thinghk_extract");
|
||||
let _ = fs::remove_dir_all(&extract_dir);
|
||||
extract_zip(&zip_path, &extract_dir)?;
|
||||
// 在解压目录中查找 ThingHK.exe
|
||||
let exe_path = find_thinghk_exe(&extract_dir).ok_or("内核包中未找到 ThingHK.exe".to_string())?;
|
||||
let app_data = app
|
||||
.path()
|
||||
.app_data_dir()
|
||||
.map_err(|e| format!("获取数据目录失败: {}", e))?;
|
||||
let cores_dir = app_data.join("monitor").join("cores");
|
||||
fs::create_dir_all(&cores_dir).map_err(|e| format!("创建内核目录失败: {}", e))?;
|
||||
fs::copy(&exe_path, cores_dir.join("ThingHK.exe"))
|
||||
.map_err(|e| format!("覆盖内核文件失败(请确认监控模块已停止): {}", e))?;
|
||||
// 清理临时文件
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
let _ = fs::remove_dir_all(&extract_dir);
|
||||
let _ = app.emit(
|
||||
UPDATE_PROGRESS,
|
||||
UpdateProgress {
|
||||
stage: "done".into(),
|
||||
percent: 100,
|
||||
downloaded_bytes: 0,
|
||||
total_bytes: None,
|
||||
message: "ThingHK 内核更新完成".into(),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn find_thinghk_exe(dir: &Path) -> Option<PathBuf> {
|
||||
if let Ok(entries) = fs::read_dir(dir) {
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
if let Some(found) = find_thinghk_exe(&path) {
|
||||
return Some(found);
|
||||
}
|
||||
} else if path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.map(|s| s.eq_ignore_ascii_case("ThingHK.exe"))
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return Some(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -60,6 +60,30 @@ pub fn get_work_area_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取指定点所在显示器的完整边界(含任务栏),返回 (left, top, right, bottom) 物理像素。
|
||||
/// 与 get_work_area_at_point 不同,这里用 rcMonitor 而非 rcWork,
|
||||
/// 用于需要在鼠标位置弹出、允许贴近/覆盖任务栏的场景(如托盘菜单)。
|
||||
#[cfg(windows)]
|
||||
pub fn get_monitor_bounds_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
|
||||
use windows_sys::Win32::Foundation::POINT;
|
||||
use windows_sys::Win32::Graphics::Gdi::{
|
||||
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST,
|
||||
};
|
||||
|
||||
let pt = POINT { x, y };
|
||||
let hmon = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
|
||||
let mut mi: MONITORINFO = unsafe { std::mem::zeroed() };
|
||||
mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
|
||||
unsafe {
|
||||
if GetMonitorInfoW(hmon, &mut mi) != 0 {
|
||||
let rc = mi.rcMonitor;
|
||||
Some((rc.left, rc.top, rc.right, rc.bottom))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取指定点所在显示器的有效 DPI。
|
||||
/// scale factor = dpi / 96。
|
||||
#[cfg(windows)]
|
||||
@@ -81,6 +105,24 @@ pub fn get_dpi_for_point(x: i32, y: i32) -> Option<u32> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 强制将窗口置为前台(绕过 Windows 前台锁定限制)。
|
||||
/// Tauri 的 set_focus 内部调用 SetForegroundWindow,受前台锁定(foreground lock)限制:
|
||||
/// 本进程不拥有前台时调用会被系统忽略,导致已打开但被遮挡的窗口无法到前台。
|
||||
/// 先模拟 Alt 键释放以重置前台锁定,再 SetForegroundWindow + BringWindowToTop。
|
||||
#[cfg(windows)]
|
||||
pub fn force_foreground(hwnd: isize) {
|
||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
|
||||
keybd_event, KEYEVENTF_KEYUP, VK_MENU,
|
||||
};
|
||||
use windows_sys::Win32::UI::WindowsAndMessaging::{BringWindowToTop, SetForegroundWindow};
|
||||
|
||||
unsafe {
|
||||
keybd_event(VK_MENU as u8, 0, KEYEVENTF_KEYUP, 0);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
let _ = BringWindowToTop(hwnd);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 非 Windows 平台空实现 =====
|
||||
|
||||
#[cfg(not(windows))]
|
||||
@@ -94,3 +136,9 @@ pub fn get_work_area_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)>
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn get_dpi_for_point(_x: i32, _y: i32) -> Option<u32> { None }
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn get_monitor_bounds_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)> { None }
|
||||
|
||||
#[cfg(not(windows))]
|
||||
pub fn force_foreground(_hwnd: isize) {}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "thing",
|
||||
"version": "0.1.0",
|
||||
"version": "26.8.1",
|
||||
"identifier": "thing.lfeng.me",
|
||||
"build": {
|
||||
"beforeDevCommand": "bun run dev",
|
||||
@@ -37,6 +37,11 @@
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"resources": ["binaries/*", "resources/thing-extension/**/*"]
|
||||
"resources": ["binaries/*", "resources/thing-extension/**/*"],
|
||||
"windows": {
|
||||
"nsis": {
|
||||
"compression": "lzma"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+33
-2
@@ -10,16 +10,19 @@ import { useAppStore } from '@/stores/appStore'
|
||||
import { useScreenshotStore } from '@/stores/screenshotStore'
|
||||
import { useQuickPanelStore } from '@/stores/quickpanelStore'
|
||||
import { useMonitorStore } from '@/stores/monitorStore'
|
||||
import { useProcessStore } from '@/stores/processStore'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { moduleRegistry } from '@/modules/registry'
|
||||
import type { ModuleMeta } from '@/types/module'
|
||||
import { pendingNewDownload } from '@/lib/trayEvents'
|
||||
import { pendingNewDownload, pendingShowDownloadTasks } from '@/lib/trayEvents'
|
||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
||||
import { commands } from '@/lib/bindings'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const screenshotStore = useScreenshotStore()
|
||||
const quickpanelStore = useQuickPanelStore()
|
||||
const monitorStore = useMonitorStore()
|
||||
const processStore = useProcessStore()
|
||||
|
||||
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
|
||||
interface NavModule {
|
||||
@@ -41,6 +44,9 @@ const activeModule = ref('')
|
||||
|
||||
const activeComponent = shallowRef<Component | null>(null)
|
||||
|
||||
/** 模块组件加载中(异步 import 未完成)标志,避免切换期间仍显示上一个模块内容 */
|
||||
const moduleLoading = ref(false)
|
||||
|
||||
/** 当前可显示的模块(内置模块 + 已启用的用户模块),按用户排序显示 */
|
||||
const availableModules = computed<NavModule[]>(() => {
|
||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||
@@ -65,10 +71,15 @@ const availableModules = computed<NavModule[]>(() => {
|
||||
let moduleLoadSeq = 0
|
||||
const loadModule = async (moduleId: string) => {
|
||||
const seq = ++moduleLoadSeq
|
||||
// 立即清空旧组件并进入加载态,避免异步 import 期间仍渲染上一个模块内容
|
||||
// (否则 ModuleContainer 以 :key="activeModule" 重挂载旧组件,用户误以为切换失败)
|
||||
activeComponent.value = null
|
||||
moduleLoading.value = true
|
||||
const component = await moduleRegistry.loadComponent(moduleId)
|
||||
// 过期请求(期间用户又切换了模块)直接丢弃,不覆盖 activeComponent 也不触发钩子
|
||||
if (seq !== moduleLoadSeq) return
|
||||
activeComponent.value = component
|
||||
moduleLoading.value = false
|
||||
|
||||
// 调用模块的 onActivate 生命周期钩子
|
||||
const config = moduleRegistry.getConfig(moduleId)
|
||||
@@ -149,9 +160,16 @@ onMounted(async () => {
|
||||
// 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取
|
||||
quickpanelStore.syncCommands()
|
||||
quickpanelStore.syncSettings()
|
||||
// 初始化文件索引 DB 并恢复增量监听(上次构建过索引时自动恢复,不重建)
|
||||
commands.quickpanelInitFileIndex().catch(e => console.error('文件索引初始化失败:', e))
|
||||
// 监听快速面板执行命令事件:显示主窗口 + 切换模块
|
||||
trayUnlisteners.push(
|
||||
await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => {
|
||||
// Rust 端强制置前(绕过 Windows 前台锁定,主窗口被遮挡时也能到前台)
|
||||
try {
|
||||
await commands.quickpanelFocusMainWindow()
|
||||
} catch {
|
||||
// 回退:前端 show + setFocus
|
||||
const win = getCurrentWindow()
|
||||
try {
|
||||
await win.show()
|
||||
@@ -160,6 +178,7 @@ onMounted(async () => {
|
||||
} catch {
|
||||
/* 忽略窗口操作失败 */
|
||||
}
|
||||
}
|
||||
handleSearch(e.payload.moduleId)
|
||||
})
|
||||
)
|
||||
@@ -177,6 +196,16 @@ onMounted(async () => {
|
||||
}
|
||||
})
|
||||
)
|
||||
// 浏览器扩展新增下载:直接切到下载模块的任务列表页(主窗口已由 Rust 端置前)
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.downloadExtensionAdded, () => {
|
||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||
if (enabledIds.includes('downloader') || moduleRegistry.getConfig('downloader')?.builtin) {
|
||||
pendingShowDownloadTasks.value = true
|
||||
handleModuleChange('downloader')
|
||||
}
|
||||
})
|
||||
)
|
||||
trayUnlisteners.push(
|
||||
await listen(EVENTS.trayOpenSettings, () => {
|
||||
handleModuleChange('settings')
|
||||
@@ -193,6 +222,8 @@ onUnmounted(() => {
|
||||
screenshotStore.destroyExportListener()
|
||||
// 释放 OSD 事件监听与配置 watcher
|
||||
monitorStore.disposeOsd()
|
||||
// 释放进程状态事件监听
|
||||
processStore.destroyListener()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -206,7 +237,7 @@ onUnmounted(() => {
|
||||
:active-module="activeModule"
|
||||
@change="handleModuleChange"
|
||||
/>
|
||||
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" />
|
||||
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" :loading="moduleLoading" />
|
||||
</div>
|
||||
</div>
|
||||
<Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" />
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
import type { Component } from 'vue'
|
||||
import { ref, watch } from 'vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
activeComponent: Component | null
|
||||
activeModule: string
|
||||
loading: boolean
|
||||
}>()
|
||||
|
||||
const containerRef = ref<HTMLElement | null>(null)
|
||||
|
||||
// 切换模块时重置主滚动区位置,避免新模块沿用上一个模块的滚动距离
|
||||
watch(
|
||||
() => props.activeModule,
|
||||
() => {
|
||||
const viewport = containerRef.value?.querySelector<HTMLElement>(
|
||||
'[data-slot="scroll-area-viewport"]'
|
||||
)
|
||||
if (viewport) viewport.scrollTop = 0
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main
|
||||
ref="containerRef"
|
||||
class="flex-1"
|
||||
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
||||
>
|
||||
@@ -22,6 +39,30 @@ defineProps<{
|
||||
>
|
||||
<component :is="activeComponent" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="loading"
|
||||
key="loading"
|
||||
class="h-full w-full p-6"
|
||||
>
|
||||
<!-- 模块加载骨架:撑起画面,避免空白闪屏 -->
|
||||
<div class="h-full max-w-5xl mx-auto space-y-5">
|
||||
<div class="flex items-center gap-3">
|
||||
<Skeleton class="h-8 w-40" />
|
||||
<Skeleton class="h-6 w-24 ml-auto" />
|
||||
</div>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div v-for="n in 4" :key="n" class="rounded-lg border p-5 space-y-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<Skeleton class="h-5 w-32" />
|
||||
<Skeleton class="h-5 w-16" />
|
||||
</div>
|
||||
<Skeleton class="h-4 w-full" />
|
||||
<Skeleton class="h-4 w-5/6" />
|
||||
<Skeleton class="h-4 w-2/3" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
key="empty"
|
||||
|
||||
@@ -31,14 +31,14 @@ const displayModules = computed(() => {
|
||||
<Button
|
||||
:variant="activeModule === module.id ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="h-10 w-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
|
||||
'hover:bg-secondary/50': activeModule !== module.id
|
||||
}"
|
||||
@click="emit('change', module.id)"
|
||||
@click="activeModule !== module.id && emit('change', module.id)"
|
||||
>
|
||||
<component :is="getModuleIcon(module.icon)" class="h-5 w-5" />
|
||||
<component :is="getModuleIcon(module.icon)" class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
@@ -55,14 +55,14 @@ const displayModules = computed(() => {
|
||||
<Button
|
||||
:variant="activeModule === 'settings' ? 'default' : 'ghost'"
|
||||
size="icon"
|
||||
class="h-10 w-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||
:class="{
|
||||
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
|
||||
'hover:bg-secondary/50': activeModule !== 'settings'
|
||||
}"
|
||||
@click="emit('change', 'settings')"
|
||||
@click="activeModule !== 'settings' && emit('change', 'settings')"
|
||||
>
|
||||
<Settings class="h-5 w-5" />
|
||||
<Settings class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="right" class="w-fit">
|
||||
|
||||
@@ -42,6 +42,11 @@ const hasSearchContent = computed(() => {
|
||||
return searchQuery.value.trim().length > 0
|
||||
})
|
||||
|
||||
/** 模块 id → 名称 查找表(用于搜索结果中标注所属模块) */
|
||||
const moduleNameById = computed(() => {
|
||||
return new Map(props.modules.map(m => [m.id, m.name]))
|
||||
})
|
||||
|
||||
const handleSearchSelect = (moduleId: string) => {
|
||||
emit('search', moduleId)
|
||||
searchQuery.value = ''
|
||||
@@ -50,6 +55,10 @@ const handleSearchSelect = (moduleId: string) => {
|
||||
|
||||
const handleSettingSelect = (item: SearchItem) => {
|
||||
emit('search', item.moduleId)
|
||||
// 记录待跳转 tab:模块挂载后由 useModuleTabs 自动切换(模块已挂载时同样生效)
|
||||
if (item.tab) {
|
||||
tabsStore.setPendingTab(item.moduleId, item.tab)
|
||||
}
|
||||
if (item.action) {
|
||||
item.action()
|
||||
}
|
||||
@@ -259,8 +268,7 @@ const handleBlur = () => {
|
||||
<Transition name="floating-tabs">
|
||||
<button
|
||||
v-if="showScrollTop"
|
||||
class="flex items-center justify-center h-6 w-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||
title="回到顶部"
|
||||
class="flex items-center justify-center size-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||
@click="scrollToTop"
|
||||
@mousedown.stop
|
||||
>
|
||||
@@ -276,7 +284,6 @@ const handleBlur = () => {
|
||||
v-if="tabsStore.saveVisible"
|
||||
class="flex items-center gap-1.5 h-7 px-3 mr-1 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-60 disabled:pointer-events-none transition-colors pointer-events-auto"
|
||||
:disabled="tabsStore.saving"
|
||||
title="保存当前模块设置"
|
||||
@click="tabsStore.runSave"
|
||||
@mousedown.stop
|
||||
>
|
||||
@@ -287,7 +294,7 @@ const handleBlur = () => {
|
||||
</Transition>
|
||||
<div class="relative max-w-xs mr-3 pointer-events-auto">
|
||||
<Search
|
||||
class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"
|
||||
class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground"
|
||||
/>
|
||||
<Input
|
||||
v-model="searchQuery"
|
||||
@@ -325,14 +332,19 @@ const handleBlur = () => {
|
||||
class="w-full px-3 py-2 text-left text-sm hover:bg-accent transition-colors flex items-center gap-2"
|
||||
@click="handleSettingSelect(item)"
|
||||
>
|
||||
<Settings class="h-4 w-4 text-muted-foreground" />
|
||||
<Settings class="size-4 text-muted-foreground shrink-0" />
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="truncate">{{ item.title }}</span>
|
||||
<span class="shrink-0 text-[10px] text-muted-foreground/70 px-1 py-px rounded bg-muted">
|
||||
{{ moduleNameById.get(item.moduleId) || item.moduleId }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="item.description" class="block text-xs text-muted-foreground truncate">
|
||||
{{ item.description }}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronRight class="h-4 w-4 text-muted-foreground" />
|
||||
<ChevronRight class="size-4 text-muted-foreground shrink-0" />
|
||||
</button>
|
||||
</template>
|
||||
|
||||
@@ -347,7 +359,7 @@ const handleBlur = () => {
|
||||
|
||||
<div class="flex items-center pointer-events-auto" :class="{ 'hover-suppressed': hoverSuppressed }">
|
||||
<button
|
||||
class="h-10 w-10 flex items-center justify-center hover:bg-foreground/5 transition-colors rounded-sm"
|
||||
class="size-10 flex items-center justify-center hover:bg-foreground/5 transition-colors rounded-sm"
|
||||
@click="minimize"
|
||||
@mousedown.stop
|
||||
>
|
||||
@@ -358,7 +370,7 @@ const handleBlur = () => {
|
||||
</button>
|
||||
<button
|
||||
id="titlebar-maximize"
|
||||
class="h-10 w-10 flex items-center justify-center transition-colors rounded-sm titlebar-maximize-btn"
|
||||
class="size-10 flex items-center justify-center transition-colors rounded-sm titlebar-maximize-btn"
|
||||
@click="maximize"
|
||||
@mousedown.stop
|
||||
>
|
||||
@@ -375,7 +387,7 @@ const handleBlur = () => {
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
class="h-10 w-10 flex items-center justify-center hover:bg-red-500 hover:text-white text-foreground transition-colors rounded-sm"
|
||||
class="size-10 flex items-center justify-center hover:bg-red-500 hover:text-white text-foreground transition-colors rounded-sm"
|
||||
@click="close"
|
||||
@mousedown.stop
|
||||
>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="empty"
|
||||
:class="cn(
|
||||
'flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance rounded-lg border-dashed p-6 text-center md:p-12',
|
||||
props.class,
|
||||
)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="empty-content"
|
||||
:class="cn(
|
||||
'flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm',
|
||||
props.class,
|
||||
)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p
|
||||
data-slot="empty-description"
|
||||
:class="cn(
|
||||
'text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4',
|
||||
$attrs.class ?? '',
|
||||
)"
|
||||
>
|
||||
<slot />
|
||||
</p>
|
||||
</template>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="empty-header"
|
||||
:class="cn(
|
||||
'flex max-w-sm flex-col items-center gap-2 text-center',
|
||||
props.class,
|
||||
)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import type { EmptyMediaVariants } from "."
|
||||
import { cn } from "@/lib/utils"
|
||||
import { emptyMediaVariants } from "."
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
variant?: EmptyMediaVariants["variant"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="empty-icon"
|
||||
:data-variant="variant"
|
||||
:class="cn(emptyMediaVariants({ variant }), props.class)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="empty-title"
|
||||
:class="cn('text-lg font-medium tracking-tight', props.class)"
|
||||
>
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { VariantProps } from "class-variance-authority"
|
||||
import { cva } from "class-variance-authority"
|
||||
|
||||
export { default as Empty } from "./Empty.vue"
|
||||
export { default as EmptyContent } from "./EmptyContent.vue"
|
||||
export { default as EmptyDescription } from "./EmptyDescription.vue"
|
||||
export { default as EmptyHeader } from "./EmptyHeader.vue"
|
||||
export { default as EmptyMedia } from "./EmptyMedia.vue"
|
||||
export { default as EmptyTitle } from "./EmptyTitle.vue"
|
||||
|
||||
export const emptyMediaVariants = cva(
|
||||
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
export type EmptyMediaVariants = VariantProps<typeof emptyMediaVariants>
|
||||
@@ -0,0 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import type { HTMLAttributes } from "vue"
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const props = defineProps<{
|
||||
class?: HTMLAttributes["class"]
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
:class="cn('animate-pulse rounded-md bg-muted', props.class)"
|
||||
/>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Skeleton } from "./Skeleton.vue"
|
||||
@@ -24,7 +24,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||
data-slot="switch"
|
||||
v-bind="forwarded"
|
||||
:class="cn(
|
||||
'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer hover:data-[state=checked]:bg-primary/90 hover:data-[state=unchecked]:bg-input/70 active:scale-95',
|
||||
props.class,
|
||||
)"
|
||||
>
|
||||
|
||||
@@ -24,7 +24,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||
<TooltipContent
|
||||
data-slot="tooltip-content"
|
||||
v-bind="{ ...forwarded, ...$attrs }"
|
||||
:class="cn('bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit rounded-md px-3 py-1.5 text-xs text-balance', props.class)"
|
||||
:class="cn('bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit max-w-[calc(100vw-2rem)] rounded-md px-3 py-1.5 text-xs', props.class)"
|
||||
>
|
||||
<slot />
|
||||
|
||||
|
||||
+121
-1
@@ -4,6 +4,19 @@ import { invoke as __TAURI_INVOKE } from "@tauri-apps/api/core";
|
||||
|
||||
/** Commands */
|
||||
export const commands = {
|
||||
/** 获取当前应用版本 */
|
||||
appVersion: () => __TAURI_INVOKE<string>("app_version"),
|
||||
/** 检查 Gitea 最新 release,返回版本对比与可用资产 */
|
||||
updateCheck: () => __TAURI_INVOKE<UpdateCheckResult>("update_check"),
|
||||
/**
|
||||
* 更新应用本体。
|
||||
* 便携版:下载 thing_{v}_x64.exe → update.bat 覆盖重启;
|
||||
* 安装版:下载 thing_{v}_x64-setup.exe → 提权静默安装 /S。
|
||||
* 下载进度通过 UPDATE_PROGRESS 事件上报,调用方返回前会触发应用退出。
|
||||
*/
|
||||
updateInstall: () => __TAURI_INVOKE<null>("update_install"),
|
||||
/** 更新 ThingHK 内核:下载 thing-hk_{v}.zip → 停止监控内核 → 覆盖内核文件 */
|
||||
updateThinghk: () => __TAURI_INVOKE<null>("update_thinghk"),
|
||||
proxyActivateProfile: (id: string) => __TAURI_INVOKE<null>("proxy_activate_profile", { id }),
|
||||
proxyCheckKernelUpdate: () => __TAURI_INVOKE<KernelUpdateInfo>("proxy_check_kernel_update"),
|
||||
proxyClearSystemProxy: () => __TAURI_INVOKE<null>("proxy_clear_system_proxy"),
|
||||
@@ -41,7 +54,11 @@ export const commands = {
|
||||
quickpanelShowWindow: () => __TAURI_INVOKE<null>("quickpanel_show_window"),
|
||||
/** 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗) */
|
||||
quickpanelLockScreen: () => __TAURI_INVOKE<null>("quickpanel_lock_screen"),
|
||||
/** 初始化文件索引数据库(应用启动时调用) */
|
||||
/**
|
||||
* 初始化文件索引数据库(应用启动时调用)。
|
||||
* 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
|
||||
* 无需重建即可继续自动同步文件变更。
|
||||
*/
|
||||
quickpanelInitFileIndex: () => __TAURI_INVOKE<null>("quickpanel_init_file_index"),
|
||||
/** 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用) */
|
||||
quickpanelBuildFileIndex: () => __TAURI_INVOKE<number>("quickpanel_build_file_index"),
|
||||
@@ -83,6 +100,35 @@ export const commands = {
|
||||
* 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
||||
*/
|
||||
quickpanelRunSystemCommand: (command: string, args: string[]) => __TAURI_INVOKE<null>("quickpanel_run_system_command", { command, args }),
|
||||
/** 列出目录下的压缩包文件(供批量解压面板使用)。 */
|
||||
quickpanelListArchives: (dir: string) => __TAURI_INVOKE<ArchiveInfo[]>("quickpanel_list_archives", { dir }),
|
||||
/** 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。 */
|
||||
quickpanelListDir: (dir: string) => __TAURI_INVOKE<FileEntry[]>("quickpanel_list_dir", { dir }),
|
||||
/**
|
||||
* 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
|
||||
* `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
|
||||
* 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
|
||||
*/
|
||||
quickpanelBatchExtract: (files: string[], destDir: string, password: string | null, intoSubfolder: boolean) => __TAURI_INVOKE<ExtractResult[]>("quickpanel_batch_extract", { files, destDir, password, intoSubfolder }),
|
||||
/**
|
||||
* 正则批量重命名预览:对每个文件名应用 `pattern → replacement`,
|
||||
* 仅返回有匹配的文件,`newName` 为替换结果。
|
||||
*/
|
||||
quickpanelPreviewRename: (files: string[], pattern: string, replacement: string) => __TAURI_INVOKE<RenamePreview[]>("quickpanel_preview_rename", { files, pattern, replacement }),
|
||||
/** 执行重命名。同一目录下若目标已存在则跳过该项。 */
|
||||
quickpanelApplyRename: (items: RenameItem[]) => __TAURI_INVOKE<RenameResult[]>("quickpanel_apply_rename", { items }),
|
||||
/**
|
||||
* 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
|
||||
* 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
|
||||
* 锁定的文件仍会失败并返回原因)。
|
||||
*/
|
||||
quickpanelDeleteFiles: (paths: string[], force: boolean) => __TAURI_INVOKE<DeleteResult[]>("quickpanel_delete_files", { paths, force }),
|
||||
/**
|
||||
* 显示主窗口并强制置为前台。
|
||||
* Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||
* 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||
*/
|
||||
quickpanelFocusMainWindow: () => __TAURI_INVOKE<null>("quickpanel_focus_main_window"),
|
||||
clipboardGetHistory: (limit: number | null, offset: number | null, kind: string | null) => __TAURI_INVOKE<HistoryPage>("clipboard_get_history", { limit, offset, kind }),
|
||||
clipboardGetPinned: () => __TAURI_INVOKE<ClipboardItem[]>("clipboard_get_pinned"),
|
||||
clipboardSearch: (query: string, limit: number | null, offset: number | null) => __TAURI_INVOKE<HistoryPage>("clipboard_search", { query, limit, offset }),
|
||||
@@ -140,6 +186,13 @@ export const commands = {
|
||||
screenshotRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("screenshot_register_shortcut", { shortcut }),
|
||||
/** 注销截图全局快捷键 */
|
||||
screenshotUnregisterShortcut: () => __TAURI_INVOKE<null>("screenshot_unregister_shortcut"),
|
||||
/**
|
||||
* 注册(或切换)贴图全局快捷键。传入空字符串则禁用快捷键。
|
||||
* 按下时 emit 'screenshot-pin-shortcut',由前端切换贴图窗口显示/隐藏。
|
||||
*/
|
||||
screenshotRegisterPinShortcut: (shortcut: string) => __TAURI_INVOKE<null>("screenshot_register_pin_shortcut", { shortcut }),
|
||||
/** 注销贴图全局快捷键 */
|
||||
screenshotUnregisterPinShortcut: () => __TAURI_INVOKE<null>("screenshot_unregister_pin_shortcut"),
|
||||
/** 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码 */
|
||||
screenshotCaptureFullscreen: () => __TAURI_INVOKE<null>("screenshot_capture_fullscreen"),
|
||||
/** 全屏捕获编码为 PNG base64 并清除(全屏截图直接进编辑器) */
|
||||
@@ -186,6 +239,12 @@ export type AppRecord = {
|
||||
path: string,
|
||||
};
|
||||
|
||||
export type ArchiveInfo = {
|
||||
name: string,
|
||||
path: string,
|
||||
size: number,
|
||||
};
|
||||
|
||||
/** 前端可见的捕获数据 */
|
||||
export type CaptureData = {
|
||||
pngBase64: string,
|
||||
@@ -260,6 +319,14 @@ export type CustomCommand = {
|
||||
args?: string[],
|
||||
};
|
||||
|
||||
/** 批量删除单个条目的结果。 */
|
||||
export type DeleteResult = {
|
||||
name: string,
|
||||
path: string,
|
||||
ok: boolean,
|
||||
error: string,
|
||||
};
|
||||
|
||||
/** 下载任务 */
|
||||
export type DownloadTask = {
|
||||
/** 任务 ID(自增 hex 字符串) */
|
||||
@@ -330,6 +397,20 @@ export type ExistingTaskInfo = {
|
||||
status: TaskStatus,
|
||||
};
|
||||
|
||||
export type ExtractResult = {
|
||||
name: string,
|
||||
path: string,
|
||||
ok: boolean,
|
||||
error: string,
|
||||
};
|
||||
|
||||
export type FileEntry = {
|
||||
name: string,
|
||||
path: string,
|
||||
isDir: boolean,
|
||||
size: number,
|
||||
};
|
||||
|
||||
/** 单个文件记录(返回给前端) */
|
||||
export type FileRecord = {
|
||||
path: string,
|
||||
@@ -429,6 +510,26 @@ export type QuickPanelSettings = {
|
||||
customCommands?: CustomCommand[],
|
||||
};
|
||||
|
||||
export type RenameItem = {
|
||||
path: string,
|
||||
oldName: string,
|
||||
newName: string,
|
||||
};
|
||||
|
||||
export type RenamePreview = {
|
||||
path: string,
|
||||
oldName: string,
|
||||
newName: string,
|
||||
error: string,
|
||||
};
|
||||
|
||||
export type RenameResult = {
|
||||
oldName: string,
|
||||
newName: string,
|
||||
ok: boolean,
|
||||
error: string,
|
||||
};
|
||||
|
||||
export type ScreenRect = {
|
||||
x: number,
|
||||
y: number,
|
||||
@@ -473,6 +574,25 @@ export type TaskStatus =
|
||||
/** 错误 */
|
||||
"error";
|
||||
|
||||
/** release 中的一个资产 */
|
||||
export type UpdateAsset = {
|
||||
name: string,
|
||||
size: number,
|
||||
browserDownloadUrl: string,
|
||||
};
|
||||
|
||||
/** 检查更新的结果 */
|
||||
export type UpdateCheckResult = {
|
||||
currentVersion: string,
|
||||
latestVersion: string,
|
||||
hasUpdate: boolean,
|
||||
/** portable | installed */
|
||||
installType: string,
|
||||
releaseName: string,
|
||||
releaseBody: string,
|
||||
assets: UpdateAsset[],
|
||||
};
|
||||
|
||||
/** 窗口信息(窗口拾取 / 枚举) */
|
||||
export type WindowInfo = {
|
||||
hwnd: number,
|
||||
|
||||
@@ -9,6 +9,7 @@ export const WINDOWS = {
|
||||
main: 'main',
|
||||
osdOverlay: 'osd-overlay',
|
||||
screenshotOverlay: 'screenshot-overlay',
|
||||
screenshotPin: 'screenshot-pin',
|
||||
} as const
|
||||
|
||||
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
|
||||
@@ -27,13 +28,19 @@ export const EVENTS = {
|
||||
quickpanelShow: 'quickpanel-show',
|
||||
quickpanelHide: 'quickpanel-hide',
|
||||
quickpanelExecuteCommand: 'quickpanel-execute-command',
|
||||
quickpanelExtractProgress: 'quickpanel-extract-progress',
|
||||
// 截图
|
||||
screenshotBegin: 'screenshot-begin',
|
||||
screenshotOverlayReady: 'screenshot-overlay-ready',
|
||||
screenshotShortcut: 'screenshot-shortcut',
|
||||
screenshotPinShortcut: 'screenshot-pin-shortcut',
|
||||
screenshotPinReady: 'screenshot-pin-ready',
|
||||
screenshotPinShow: 'screenshot-pin-show',
|
||||
screenshotExported: 'screenshot-exported',
|
||||
// 内核安装进度
|
||||
kernelInstallProgress: 'kernel-install-progress',
|
||||
// 应用更新进度
|
||||
updateProgress: 'update-progress',
|
||||
// 监控 OSD
|
||||
osdStateUpdate: 'osd-state-update',
|
||||
osdContentSize: 'osd-content-size',
|
||||
@@ -50,6 +57,8 @@ export const EVENTS = {
|
||||
// 其他
|
||||
processStatusChanged: 'process-status-changed',
|
||||
downloadAdded: 'download-added',
|
||||
/** 浏览器扩展通过 HTTP API 新增下载(置前主窗口并跳到下载画面) */
|
||||
downloadExtensionAdded: 'download-extension-added',
|
||||
} as const
|
||||
|
||||
/** localStorage 存储键 */
|
||||
@@ -60,6 +69,16 @@ export const STORAGE_KEYS = {
|
||||
quickpanelSettings: 'thing_quickpanel_settings',
|
||||
quickpanelHistory: 'thing_quickpanel_history',
|
||||
quickpanelHistoryItems: 'thing_quickpanel_history_items',
|
||||
quickpanelPwdHistory: 'thing_quickpanel_pwd_history',
|
||||
quickpanelPwdFavs: 'thing_quickpanel_pwd_favs',
|
||||
quickpanelRenameMatchHistory: 'thing_quickpanel_rename_match_history',
|
||||
quickpanelRenameMatchFavs: 'thing_quickpanel_rename_match_favs',
|
||||
quickpanelRenameReplaceHistory: 'thing_quickpanel_rename_replace_history',
|
||||
quickpanelRenameReplaceFavs: 'thing_quickpanel_rename_replace_favs',
|
||||
quickpanelDeleteFilterHistory: 'thing_quickpanel_delete_filter_history',
|
||||
quickpanelDeleteFilterFavs: 'thing_quickpanel_delete_filter_favs',
|
||||
currencyRates: 'thing_quickpanel_currency_rates',
|
||||
monitorOsdConfig: 'thing_monitor_osd_config',
|
||||
screenshotHistory: 'thing_screenshot_history',
|
||||
screenshotPinIndex: 'thing_screenshot_pin_index',
|
||||
} as const
|
||||
|
||||
@@ -10,3 +10,6 @@ import { ref } from 'vue'
|
||||
|
||||
/** 待打开新建下载对话框(由托盘"新建下载"触发) */
|
||||
export const pendingNewDownload = ref(false)
|
||||
|
||||
/** 待切换到下载任务列表页(由浏览器扩展新增下载触发,不弹对话框直接看任务) */
|
||||
export const pendingShowDownloadTasks = ref(false)
|
||||
|
||||
@@ -12,12 +12,15 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
||||
* ```ts
|
||||
* // 模块 <script setup> 顶部
|
||||
* const activeTab = ref('overview')
|
||||
* const tabsListRef = useModuleTabs(activeTab, [
|
||||
* const tabsListRef = useModuleTabs('proxy', activeTab, [
|
||||
* { value: 'overview', label: '概览' },
|
||||
* { value: 'settings', label: '设置' }
|
||||
* ])
|
||||
* ```
|
||||
*
|
||||
* 第一个参数为模块 id:搜索导航跳转时,模块挂载后会自动
|
||||
* 消费 moduleTabsStore 中对应的待跳转 tab(pendingTab)。
|
||||
*
|
||||
* ```vue
|
||||
* <!-- 模板中给 TabsList 包一层带 ref 的 div -->
|
||||
* <div ref="tabsListRef">
|
||||
@@ -29,7 +32,8 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
||||
* 1. onMounted 时注册标签到 moduleTabsStore,TitleBar 据此渲染浮动切换器
|
||||
* 2. 用 IntersectionObserver 监听 TabsList 可见性(rootMargin 裁剪 TitleBar 高度)
|
||||
* 3. 双向 watch 同步本地 activeTab 与 store.activeTab
|
||||
* 4. onUnmounted 时清理 observer 并注销标签
|
||||
* 4. 消费搜索导航的待跳转 tab(模块尚未挂载的场景)
|
||||
* 5. onUnmounted 时清理 observer 并注销标签
|
||||
*
|
||||
* ## 约束
|
||||
* - TitleBar 高度固定为 40px (h-10),composable 内部已用 44px 裁剪(含缓冲)
|
||||
@@ -37,6 +41,7 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
||||
* - 模块卸载时务必让 composable 的 onUnmounted 执行(已自动处理,无需手动调用)
|
||||
*/
|
||||
export function useModuleTabs(
|
||||
moduleId: string,
|
||||
activeTab: Ref<string>,
|
||||
tabs: ModuleTab[]
|
||||
): Ref<HTMLElement | null> {
|
||||
@@ -45,6 +50,15 @@ export function useModuleTabs(
|
||||
|
||||
let observer: IntersectionObserver | null = null
|
||||
|
||||
/** 应用待跳转 tab(若属于当前模块的 tab 列表) */
|
||||
const applyPendingTab = () => {
|
||||
const pending = tabsStore.consumePendingTab(moduleId)
|
||||
if (pending && tabs.some(t => t.value === pending)) {
|
||||
activeTab.value = pending
|
||||
tabsStore.setActiveTab(pending)
|
||||
}
|
||||
}
|
||||
|
||||
const setupObserver = () => {
|
||||
const el = tabsListRef.value
|
||||
if (!el || observer) return
|
||||
@@ -75,10 +89,19 @@ export function useModuleTabs(
|
||||
}
|
||||
})
|
||||
|
||||
// 模块已挂载时(搜索结果选中同一模块),pendingTab 变化 → 直接切换 tab
|
||||
watch(() => tabsStore.pendingTab, (p) => {
|
||||
if (p?.moduleId === moduleId) {
|
||||
applyPendingTab()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
tabsStore.registerTabs(tabs, activeTab.value)
|
||||
await nextTick()
|
||||
setupObserver()
|
||||
// 搜索导航跳转:模块刚挂载,消费待跳转 tab
|
||||
applyPendingTab()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
|
||||
+8
-1
@@ -6,6 +6,9 @@ import 'vue-sonner/style.css'
|
||||
import { createLogger } from './lib/logger'
|
||||
const logger = createLogger('main')
|
||||
|
||||
// 禁用 WebView 默认右键菜单(桌面应用体验,主窗口与独立窗口共用)
|
||||
document.addEventListener('contextmenu', (e) => e.preventDefault())
|
||||
|
||||
// 全局未捕获异常日志
|
||||
window.addEventListener('error', (event) => {
|
||||
logger.error(`全局JS错误: ${event.message} @ ${event.filename}:${event.lineno}`)
|
||||
@@ -26,6 +29,7 @@ const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Pr
|
||||
['#tray-menu', '托盘菜单', () => import('./modules/tray/TrayMenu.vue')],
|
||||
['#screenshot-overlay', '截图覆盖层', () => import('./modules/screenshot/ScreenshotOverlay.vue')],
|
||||
['#screenshot-editor', '截图编辑器', () => import('./modules/screenshot/ScreenshotEditor.vue')],
|
||||
['#screenshot-pin', '贴图窗口', () => import('./modules/screenshot/ScreenshotPin.vue')],
|
||||
]
|
||||
|
||||
const winHash = window.location.hash
|
||||
@@ -77,14 +81,17 @@ if (matched) {
|
||||
useProcessStore().initListener().catch(e => console.error('Process listener init error:', e))
|
||||
})
|
||||
|
||||
// 截图模块:加载设置 + 预创建常驻覆盖层窗口 + 监听导出事件(历史/自动保存)+ 注册并监听全局快捷键
|
||||
// 截图模块:加载设置 + 恢复持久化历史 + 预创建常驻覆盖层窗口 + 监听导出事件(历史/自动保存)+ 注册并监听全局快捷键(截图/贴图)
|
||||
void import('./stores/screenshotStore').then(({ useScreenshotStore }) => {
|
||||
const screenshotStore = useScreenshotStore()
|
||||
screenshotStore.loadSettings()
|
||||
screenshotStore.loadHistory()
|
||||
screenshotStore.initOverlay().catch(e => console.error('Screenshot overlay init error:', e))
|
||||
screenshotStore.initExportListener().catch(e => console.error('Screenshot export listener init error:', e))
|
||||
screenshotStore.initShortcutListener().catch(e => console.error('Screenshot shortcut listener init error:', e))
|
||||
screenshotStore.initShortcutRegistration().catch(e => console.error('Screenshot shortcut registration init error:', e))
|
||||
screenshotStore.initPinShortcutListener().catch(e => console.error('Screenshot pin shortcut listener init error:', e))
|
||||
screenshotStore.initPinShortcutRegistration().catch(e => console.error('Screenshot pin shortcut registration init error:', e))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -26,12 +26,16 @@ import {
|
||||
import {
|
||||
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
||||
} from '@/components/ui/pagination'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import {
|
||||
Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,
|
||||
} from '@/components/ui/empty'
|
||||
|
||||
const store = useClipboardStore()
|
||||
|
||||
const activeTab = ref('history')
|
||||
const tabsStore = useModuleTabsStore()
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
const tabsListRef = useModuleTabs('clipboard', activeTab, [
|
||||
{ value: 'history', label: '历史' },
|
||||
{ value: 'pinned', label: '固定' },
|
||||
{ value: 'settings', label: '设置' },
|
||||
@@ -73,6 +77,12 @@ const detailOpen = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<ClipboardItemDetail | null>(null)
|
||||
const openDetail = async (item: ClipboardItem) => {
|
||||
// reka-ui Dialog 打开时会把当前活动元素记为 triggerElement,关闭时对其无 preventScroll 地 focus,
|
||||
// 导致历史列表的 ScrollAreaViewport(tabindex=0) 被聚焦并滚回顶部。打开前 blur,避免记录滚动容器。
|
||||
const active = document.activeElement
|
||||
if (active instanceof HTMLElement) {
|
||||
active.blur()
|
||||
}
|
||||
detailOpen.value = true
|
||||
detailLoading.value = true
|
||||
detail.value = null
|
||||
@@ -282,9 +292,17 @@ const historyList = computed(() => store.history)
|
||||
const pinnedList = computed(() => store.pinned)
|
||||
|
||||
onMounted(async () => {
|
||||
await store.init()
|
||||
await Promise.all([loadPage(), store.refreshPinned()])
|
||||
// 首次进入:异步加载并显示骨架屏。再次进入时 store 已缓存历史/固定/设置,
|
||||
// 直接即时渲染缓存数据,后台并行静默刷新,避免每次切换都出现骨架屏/空态闪烁。
|
||||
const isFirst = !store.initialized
|
||||
if (isFirst) store.loading = true
|
||||
try {
|
||||
await Promise.all([store.init(), loadPage(), store.refreshPinned()])
|
||||
store.initialized = true
|
||||
form.value = { ...store.settings }
|
||||
} finally {
|
||||
store.loading = false
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
@@ -308,7 +326,7 @@ onUnmounted(() => {
|
||||
<TabsContent value="history" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||
<div class="flex items-center gap-2 mb-3 shrink-0">
|
||||
<div class="relative flex-1 max-w-sm">
|
||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input v-model="searchQuery" placeholder="搜索历史..." class="pl-8" />
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
@@ -327,7 +345,7 @@ onUnmounted(() => {
|
||||
{{ store.historyTotal }} 条
|
||||
</Badge>
|
||||
<Button variant="outline" size="sm" @click="clearOpen = true" :disabled="!historyList.length">
|
||||
<Eraser class="h-4 w-4 mr-1" />清空
|
||||
<Eraser class="size-4 mr-1" />清空
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -368,22 +386,42 @@ onUnmounted(() => {
|
||||
|
||||
<ScrollArea class="flex-1 min-h-0">
|
||||
<div class="space-y-1.5 pr-2">
|
||||
<!-- 加载骨架:数据异步返回前撑起画面,避免误显示"暂无历史" -->
|
||||
<div v-if="store.loading" class="space-y-1.5">
|
||||
<div
|
||||
v-if="!historyList.length"
|
||||
class="flex flex-col items-center justify-center text-muted-foreground py-12"
|
||||
v-for="n in 8" :key="n"
|
||||
class="flex items-center gap-3 rounded-lg border p-3"
|
||||
>
|
||||
<ClipboardList class="h-12 w-12 mb-3 opacity-40" />
|
||||
<p class="text-sm">暂无历史记录,复制内容后将自动收录</p>
|
||||
<Skeleton class="size-4 shrink-0" />
|
||||
<div class="flex-1 space-y-2">
|
||||
<Skeleton class="h-3.5 w-3/4" />
|
||||
<Skeleton class="h-2.5 w-1/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Empty
|
||||
v-else-if="!historyList.length"
|
||||
class="py-12"
|
||||
>
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<ClipboardList class="size-6" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>暂无历史记录</EmptyTitle>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<EmptyDescription>复制内容后将自动收录,图片与文件也会被记录</EmptyDescription>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
<Card
|
||||
v-for="item in historyList"
|
||||
:key="item.id"
|
||||
class="group hover:shadow-md transition-shadow py-0"
|
||||
>
|
||||
<CardContent class="flex items-center gap-3 px-3 py-2">
|
||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-muted-foreground shrink-0" />
|
||||
<component :is="kindIcon(item.kind)" class="size-4 text-muted-foreground shrink-0" />
|
||||
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
||||
<p class="text-sm break-all line-clamp-1">{{ item.preview }}</p>
|
||||
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
||||
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
||||
<span>{{ formatTime(item.createdAt) }}</span>
|
||||
@@ -391,13 +429,13 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="复制" @click.stop="handleCopy(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" :title="item.pinned ? '取消固定' : '固定'" @click.stop="handlePin(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7" :title="item.pinned ? '取消固定' : '固定'" @click.stop="handlePin(item)">
|
||||
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -410,19 +448,22 @@ onUnmounted(() => {
|
||||
<!-- 固定 -->
|
||||
<TabsContent value="pinned" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||
<div class="flex-1 min-h-0 overflow-y-auto space-y-1.5 pr-1">
|
||||
<div
|
||||
v-if="!pinnedList.length"
|
||||
class="flex flex-col items-center justify-center h-full text-muted-foreground"
|
||||
>
|
||||
<Pin class="h-12 w-12 mb-3 opacity-40" />
|
||||
<p class="text-sm">暂无固定条目</p>
|
||||
<p class="text-xs mt-1">鼠标悬停历史条目,点击图钉按钮即可固定</p>
|
||||
</div>
|
||||
<Empty v-if="!pinnedList.length" class="h-full py-8">
|
||||
<EmptyHeader>
|
||||
<EmptyMedia variant="icon">
|
||||
<Pin class="size-6" />
|
||||
</EmptyMedia>
|
||||
<EmptyTitle>暂无固定条目</EmptyTitle>
|
||||
</EmptyHeader>
|
||||
<EmptyContent>
|
||||
<EmptyDescription>鼠标悬停历史条目,点击图钉按钮即可固定</EmptyDescription>
|
||||
</EmptyContent>
|
||||
</Empty>
|
||||
<Card v-for="item in pinnedList" :key="item.id" class="group hover:shadow-md transition-shadow py-0">
|
||||
<CardContent class="flex items-center gap-3 px-3 py-2">
|
||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-primary shrink-0" />
|
||||
<component :is="kindIcon(item.kind)" class="size-4 text-primary shrink-0" />
|
||||
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
||||
<p class="text-sm break-all line-clamp-1">{{ item.preview }}</p>
|
||||
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
||||
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
||||
<span>{{ formatTime(item.createdAt) }}</span>
|
||||
@@ -430,13 +471,13 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="复制" @click.stop="handleCopy(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="取消固定" @click.stop="handlePin(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7" title="取消固定" @click.stop="handlePin(item)">
|
||||
<PinOff class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-7 w-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
@@ -450,7 +491,7 @@ onUnmounted(() => {
|
||||
<div class="max-w-xl space-y-4">
|
||||
<div class="flex items-center">
|
||||
<h3 class="text-base font-medium flex items-center gap-2">
|
||||
<SettingsIcon class="h-4 w-4" />基本设置
|
||||
<SettingsIcon class="size-4" />基本设置
|
||||
</h3>
|
||||
</div>
|
||||
|
||||
@@ -519,7 +560,7 @@ onUnmounted(() => {
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<Label class="flex items-center gap-2">
|
||||
<Keyboard class="h-4 w-4" />快捷弹窗快捷键
|
||||
<Keyboard class="size-4" />快捷弹窗快捷键
|
||||
</Label>
|
||||
<p class="text-xs text-muted-foreground mt-1">全局快捷键触发鼠标位置历史弹窗,留空禁用</p>
|
||||
</div>
|
||||
@@ -563,7 +604,7 @@ onUnmounted(() => {
|
||||
</DialogHeader>
|
||||
<div class="flex-1 min-h-0 overflow-auto">
|
||||
<div v-if="detailLoading" class="flex items-center justify-center py-12">
|
||||
<Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<Loader2 class="size-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
<template v-else-if="detail">
|
||||
<img
|
||||
|
||||
@@ -8,13 +8,14 @@ import { Effect, EffectState } from '@tauri-apps/api/window'
|
||||
import { commands } from '@/lib/bindings'
|
||||
import {
|
||||
ClipboardList, Pin, PinOff, Trash2, Search, Image as ImageIcon,
|
||||
FileText, Files, Loader2,
|
||||
FileText, Files,
|
||||
} from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
||||
} from '@/components/ui/pagination'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
|
||||
// ===== 与 Rust 端对应的数据结构(bindings 提供,camelCase) =====
|
||||
// kind 为 bindings 生成的 string,前端按字符串比较即可
|
||||
@@ -366,7 +367,7 @@ onUnmounted(() => {
|
||||
<!-- 搜索栏(与剪切板主页统一样式) -->
|
||||
<div class="flex items-center gap-2 px-3 py-2 border-b border-border shrink-0">
|
||||
<div class="relative flex-1 max-w-sm">
|
||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
ref="searchInputRef"
|
||||
v-model="searchQuery"
|
||||
@@ -388,11 +389,21 @@ onUnmounted(() => {
|
||||
<!-- 列表 -->
|
||||
<ScrollArea class="popup-list flex-1 min-h-0">
|
||||
<div class="space-y-1.5 p-2">
|
||||
<div v-if="loading && !hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||
<Loader2 class="h-6 w-6 animate-spin" />
|
||||
<div v-if="loading && !hasItems" class="space-y-1.5">
|
||||
<div
|
||||
v-for="n in 8"
|
||||
:key="n"
|
||||
class="flex items-start gap-3 rounded-lg border px-3 py-2"
|
||||
>
|
||||
<Skeleton class="size-4 shrink-0 mt-0.5" />
|
||||
<div class="flex-1 space-y-1.5">
|
||||
<Skeleton class="h-3.5 w-3/4" />
|
||||
<Skeleton class="h-2.5 w-1/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="!hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||
<ClipboardList class="h-10 w-10 mb-2 opacity-40" />
|
||||
<ClipboardList class="size-10 mb-2 opacity-40" />
|
||||
<p class="text-sm">
|
||||
{{ searchQuery ? '无匹配结果' : '暂无历史记录' }}
|
||||
</p>
|
||||
@@ -406,19 +417,19 @@ onUnmounted(() => {
|
||||
@mouseenter="onItemHover(idx, item)"
|
||||
@mouseleave="onItemLeave"
|
||||
>
|
||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<component :is="kindIcon(item.kind)" class="size-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||
<div class="flex-1 min-w-0">
|
||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
||||
<p class="text-sm break-all line-clamp-1">{{ item.preview }}</p>
|
||||
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
||||
<span class="popup-item-kind px-1.5 py-0 text-[10px] border rounded-sm" :class="kindBadgeClass(item.kind)">{{ kindLabel(item.kind) }}</span>
|
||||
<span>{{ formatTime(item.createdAt) }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="popup-item-actions shrink-0">
|
||||
<button class="popup-action-btn h-7 w-7" title="固定" @click="togglePin(item, $event)">
|
||||
<button class="popup-action-btn size-7" :title="item.pinned ? '取消固定' : '固定'" @click="togglePin(item, $event)">
|
||||
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
<button class="popup-action-btn h-7 w-7 hover:text-destructive" title="删除" @click="deleteItem(item, $event)">
|
||||
<button class="popup-action-btn size-7 hover:text-destructive" title="删除" @click="deleteItem(item, $event)">
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,44 @@ const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '剪贴板历史',
|
||||
description: '查看和管理剪贴板记录',
|
||||
keywords: ['剪贴板', '复制', '粘贴', 'clipboard', 'copy', 'paste']
|
||||
keywords: ['剪贴板', '复制', '粘贴', 'clipboard', 'copy', 'paste'],
|
||||
tab: 'history'
|
||||
},
|
||||
{
|
||||
title: '固定记录',
|
||||
description: '查看固定的剪贴板条目',
|
||||
keywords: ['固定', '收藏', 'pin', '置顶'],
|
||||
tab: 'pinned'
|
||||
},
|
||||
{
|
||||
title: '剪贴板设置',
|
||||
description: '历史数量、图片收录与快捷弹窗快捷键',
|
||||
keywords: ['设置', 'setting', '选项', '配置'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '快捷弹窗快捷键',
|
||||
description: '配置全局快捷键唤起剪贴板弹窗',
|
||||
keywords: ['快捷键', '热键', 'shortcut', 'hotkey', '弹窗', 'popup'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '最大历史条数',
|
||||
description: '设置剪贴板历史记录数量上限',
|
||||
keywords: ['历史', '数量', '上限', '条数', 'max', 'limit'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '图片大小上限',
|
||||
description: '设置收录图片的大小上限 (KB)',
|
||||
keywords: ['图片', '大小', '上限', 'image', 'kb', '体积'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '记录图片',
|
||||
description: '是否收录复制/截图的图片',
|
||||
keywords: ['图片', '截图', '收录', 'image', 'capture'],
|
||||
tab: 'settings'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import { useDownloaderStore, type DownloadTask, type TaskStatus, type CheckUrlRe
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { pendingNewDownload } from '@/lib/trayEvents'
|
||||
import { pendingNewDownload, pendingShowDownloadTasks } from '@/lib/trayEvents'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -45,7 +45,7 @@ const logger = createLogger('downloader')
|
||||
// ===== 主 Tab 状态 =====
|
||||
const activeTab = ref('tasks')
|
||||
const tabsStore = useModuleTabsStore()
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
const tabsListRef = useModuleTabs('downloader', activeTab, [
|
||||
{ value: 'tasks', label: '下载任务' },
|
||||
{ value: 'settings', label: '设置' },
|
||||
{ value: 'extension', label: '浏览器扩展' }
|
||||
@@ -536,6 +536,11 @@ onMounted(async () => {
|
||||
pendingNewDownload.value = false
|
||||
addDialogOpen.value = true
|
||||
}
|
||||
// 消费浏览器扩展新增下载标志位:直接显示任务列表页
|
||||
if (pendingShowDownloadTasks.value) {
|
||||
pendingShowDownloadTasks.value = false
|
||||
activeTab.value = 'tasks'
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
@@ -616,15 +621,15 @@ const toggleSortOrder = () => {
|
||||
<div ref="tabsListRef">
|
||||
<TabsList class="grid w-full grid-cols-3 max-w-md !bg-transparent !p-0 !shadow-none">
|
||||
<TabsTrigger value="tasks" class="gap-1.5">
|
||||
<ListChecks class="h-4 w-4" />
|
||||
<ListChecks class="size-4" />
|
||||
下载任务
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="settings" class="gap-1.5">
|
||||
<SettingsIcon class="h-4 w-4" />
|
||||
<SettingsIcon class="size-4" />
|
||||
设置
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="extension" class="gap-1.5">
|
||||
<Puzzle class="h-4 w-4" />
|
||||
<Puzzle class="size-4" />
|
||||
浏览器扩展
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
@@ -650,19 +655,19 @@ const toggleSortOrder = () => {
|
||||
<Separator orientation="vertical" class="h-5" />
|
||||
<div v-if="running" class="flex items-center gap-2 text-xs">
|
||||
<Badge variant="secondary" class="gap-1">
|
||||
<Download class="h-3 w-3" />
|
||||
<Download class="size-3" />
|
||||
下载中 {{ statusCounts.active }}
|
||||
</Badge>
|
||||
<Badge variant="secondary" class="gap-1">
|
||||
<Clock class="h-3 w-3" />
|
||||
<Clock class="size-3" />
|
||||
等待 {{ statusCounts.queued }}
|
||||
</Badge>
|
||||
<Badge v-if="statusCounts.paused > 0" variant="secondary" class="gap-1">
|
||||
<Pause class="h-3 w-3" />
|
||||
<Pause class="size-3" />
|
||||
已暂停 {{ statusCounts.paused }}
|
||||
</Badge>
|
||||
<Badge variant="secondary" class="gap-1">
|
||||
<Check class="h-3 w-3" />
|
||||
<Check class="size-3" />
|
||||
已完成 {{ statusCounts.complete }}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -673,7 +678,7 @@ const toggleSortOrder = () => {
|
||||
variant="ghost"
|
||||
@click="store.refreshTasks()"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
<RefreshCw class="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -683,20 +688,15 @@ const toggleSortOrder = () => {
|
||||
<!-- 工具栏:筛选 / 排序 / 搜索 -->
|
||||
<div class="shrink-0 flex items-center gap-2 flex-wrap">
|
||||
<!-- 新建下载按钮 -->
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
size="sm"
|
||||
class="h-8 gap-1.5"
|
||||
:disabled="addingTask"
|
||||
@click="addDialogOpen = true"
|
||||
>
|
||||
<Plus class="h-4 w-4" />
|
||||
<Plus class="size-4" />
|
||||
新建下载
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>添加下载链接</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<!-- 状态筛选 -->
|
||||
<Select v-model="statusFilter">
|
||||
@@ -736,11 +736,11 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 w-8 p-0 bg-transparent"
|
||||
class="size-8 p-0 bg-transparent"
|
||||
@click="toggleSortOrder"
|
||||
>
|
||||
<ArrowUp v-if="sortOrder === 'asc'" class="h-4 w-4" />
|
||||
<ArrowDown v-else class="h-4 w-4" />
|
||||
<ArrowUp v-if="sortOrder === 'asc'" class="size-4" />
|
||||
<ArrowDown v-else class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ sortOrder === 'asc' ? '升序(点击切换降序)' : '降序(点击切换升序)' }}</TooltipContent>
|
||||
@@ -748,7 +748,7 @@ const toggleSortOrder = () => {
|
||||
|
||||
<!-- 搜索框 -->
|
||||
<div class="relative flex-1 min-w-[180px] max-w-xs">
|
||||
<Search class="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Search class="absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="searchText"
|
||||
placeholder="搜索文件名..."
|
||||
@@ -756,20 +756,15 @@ const toggleSortOrder = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 gap-1.5 bg-transparent"
|
||||
@click="downloadSettingsOpen = true"
|
||||
>
|
||||
<SettingsIcon class="h-4 w-4" />
|
||||
<SettingsIcon class="size-4" />
|
||||
下载设置
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>下载设置</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<span class="text-xs text-muted-foreground ml-auto">
|
||||
共 {{ sortedTasks.length }} 个任务
|
||||
@@ -779,10 +774,10 @@ const toggleSortOrder = () => {
|
||||
<!-- 任务列表 -->
|
||||
<ScrollArea class="flex-1 min-h-0">
|
||||
<div v-if="pagedTasks.length === 0" key="empty" class="h-full flex flex-col items-center justify-center text-muted-foreground gap-2 pt-10">
|
||||
<CheckCircle2 class="h-16 w-16 opacity-30" />
|
||||
<CheckCircle2 class="size-16 opacity-30" />
|
||||
<p>暂无符合条件的任务</p>
|
||||
<Button size="sm" class="mt-2" @click="addDialogOpen = true">
|
||||
<Plus class="h-4 w-4" />
|
||||
<Plus class="size-4" />
|
||||
新建下载
|
||||
</Button>
|
||||
</div>
|
||||
@@ -792,19 +787,14 @@ const toggleSortOrder = () => {
|
||||
<div class="flex items-start justify-between gap-3 mb-3">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-2 mb-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="font-medium truncate cursor-default">
|
||||
{{ getFileName(task) }}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ getFileName(task) }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<Badge
|
||||
:variant="getTaskStatusBadge(task).variant"
|
||||
class="shrink-0"
|
||||
>
|
||||
<component :is="getTaskStatusBadge(task).icon" class="h-3 w-3" />
|
||||
<component :is="getTaskStatusBadge(task).icon" class="size-3" />
|
||||
{{ getTaskStatusBadge(task).text }}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -813,7 +803,7 @@ const toggleSortOrder = () => {
|
||||
{{ formatSize(task.completedSize) }} / {{ formatSize(task.totalSize) }}
|
||||
</span>
|
||||
<span v-if="task.status === 'active'" class="flex items-center gap-1 text-green-600 dark:text-green-400">
|
||||
<Download class="h-3 w-3" />
|
||||
<Download class="size-3" />
|
||||
{{ formatSpeed(task.speed) }}
|
||||
</span>
|
||||
<Badge v-if="task.status === 'active' && task.segments.length > 1" variant="outline" class="gap-1 py-0 px-1.5 text-[10px]">
|
||||
@@ -826,7 +816,7 @@ const toggleSortOrder = () => {
|
||||
{{ truncatePath(task.dir) }}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[400px] break-all">{{ task.dir }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">{{ task.dir }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span v-if="task.error" class="text-destructive">
|
||||
{{ task.error }}
|
||||
@@ -839,10 +829,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="handlePause(task.id)"
|
||||
>
|
||||
<Pause class="h-4 w-4" />
|
||||
<Pause class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ task.status === 'queued' ? '取消排队' : '暂停' }}</TooltipContent>
|
||||
@@ -852,10 +842,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="handleResume(task.id)"
|
||||
>
|
||||
<Play class="h-4 w-4" />
|
||||
<Play class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>继续</TooltipContent>
|
||||
@@ -865,10 +855,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="handleShowDetail(task)"
|
||||
>
|
||||
<Info class="h-4 w-4" />
|
||||
<Info class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>详细信息</TooltipContent>
|
||||
@@ -878,10 +868,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="handleOpenDir(task)"
|
||||
>
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>打开目录</TooltipContent>
|
||||
@@ -891,10 +881,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8 text-destructive hover:text-destructive"
|
||||
class="size-8 text-destructive hover:text-destructive"
|
||||
@click="handleRemove(task)"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
<Trash2 class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>删除</TooltipContent>
|
||||
@@ -919,12 +909,12 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 w-8 p-0"
|
||||
class="size-8 p-0"
|
||||
:disabled="currentPage <= 1"
|
||||
@click="currentPage = 1"
|
||||
>
|
||||
<ChevronLeft class="h-4 w-4" />
|
||||
<ChevronLeft class="h-4 w-4 -ml-2" />
|
||||
<ChevronLeft class="size-4" />
|
||||
<ChevronLeft class="size-4 -ml-2" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>第一页</TooltipContent>
|
||||
@@ -934,11 +924,11 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 w-8 p-0"
|
||||
class="size-8 p-0"
|
||||
:disabled="currentPage <= 1"
|
||||
@click="currentPage--"
|
||||
>
|
||||
<ChevronLeft class="h-4 w-4" />
|
||||
<ChevronLeft class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>上一页</TooltipContent>
|
||||
@@ -951,11 +941,11 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 w-8 p-0"
|
||||
class="size-8 p-0"
|
||||
:disabled="currentPage >= totalPages"
|
||||
@click="currentPage++"
|
||||
>
|
||||
<ChevronRight class="h-4 w-4" />
|
||||
<ChevronRight class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>下一页</TooltipContent>
|
||||
@@ -965,12 +955,12 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="h-8 w-8 p-0"
|
||||
class="size-8 p-0"
|
||||
:disabled="currentPage >= totalPages"
|
||||
@click="currentPage = totalPages"
|
||||
>
|
||||
<ChevronRight class="h-4 w-4" />
|
||||
<ChevronRight class="h-4 w-4 -ml-2" />
|
||||
<ChevronRight class="size-4" />
|
||||
<ChevronRight class="size-4 -ml-2" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>最后一页</TooltipContent>
|
||||
@@ -988,7 +978,7 @@ const toggleSortOrder = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<FolderOpen class="h-4 w-4 text-primary" />
|
||||
<FolderOpen class="size-4 text-primary" />
|
||||
下载设置
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -1004,7 +994,7 @@ const toggleSortOrder = () => {
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="outline" size="icon" @click="handleSelectSettingsDir">
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>选择目录</TooltipContent>
|
||||
@@ -1079,7 +1069,7 @@ const toggleSortOrder = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Zap class="h-4 w-4 text-primary" />
|
||||
<Zap class="size-4 text-primary" />
|
||||
扩展 API
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -1121,7 +1111,7 @@ const toggleSortOrder = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2 text-base">
|
||||
<Puzzle class="h-4 w-4 text-primary" />
|
||||
<Puzzle class="size-4 text-primary" />
|
||||
Thing Extension
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -1142,7 +1132,7 @@ const toggleSortOrder = () => {
|
||||
{{ store.extensionInfo.url }}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[400px] break-all">{{ store.extensionInfo.url }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">{{ store.extensionInfo.url }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<Tooltip>
|
||||
@@ -1150,10 +1140,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8 shrink-0"
|
||||
class="size-8 shrink-0"
|
||||
@click="handleCopy(store.extensionInfo.url, 'API 地址')"
|
||||
>
|
||||
<Copy class="h-4 w-4" />
|
||||
<Copy class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>复制 API 地址</TooltipContent>
|
||||
@@ -1173,11 +1163,11 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="showSecret = !showSecret"
|
||||
>
|
||||
<Eye v-if="!showSecret" class="h-4 w-4" />
|
||||
<EyeOff v-else class="h-4 w-4" />
|
||||
<Eye v-if="!showSecret" class="size-4" />
|
||||
<EyeOff v-else class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ showSecret ? '隐藏' : '显示' }}</TooltipContent>
|
||||
@@ -1187,10 +1177,10 @@ const toggleSortOrder = () => {
|
||||
<Button
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
class="h-8 w-8"
|
||||
class="size-8"
|
||||
@click="handleCopy(store.extensionInfo.secret, '密钥')"
|
||||
>
|
||||
<Copy class="h-4 w-4" />
|
||||
<Copy class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>复制密钥</TooltipContent>
|
||||
@@ -1205,7 +1195,7 @@ const toggleSortOrder = () => {
|
||||
<Label class="text-xs text-muted-foreground">安装扩展</Label>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" @click="handleInstallExtensionOnline">
|
||||
<ExternalLink class="h-4 w-4" />
|
||||
<ExternalLink class="size-4" />
|
||||
在线安装
|
||||
</Button>
|
||||
</div>
|
||||
@@ -1235,7 +1225,7 @@ const toggleSortOrder = () => {
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2">
|
||||
<SettingsIcon class="h-4 w-4 text-primary" />
|
||||
<SettingsIcon class="size-4 text-primary" />
|
||||
下载设置
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
@@ -1256,7 +1246,7 @@ const toggleSortOrder = () => {
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="outline" size="icon" @click="handleSelectSettingsDir">
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>选择目录</TooltipContent>
|
||||
@@ -1328,7 +1318,7 @@ const toggleSortOrder = () => {
|
||||
<Button variant="outline">取消</Button>
|
||||
</DialogClose>
|
||||
<Button @click="handleDialogSave">
|
||||
<Check class="h-4 w-4" />
|
||||
<Check class="size-4" />
|
||||
保存
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
@@ -1340,7 +1330,7 @@ const toggleSortOrder = () => {
|
||||
<DialogContent class="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2">
|
||||
<Link2 class="h-4 w-4 text-primary" />
|
||||
<Link2 class="size-4 text-primary" />
|
||||
新建下载
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
@@ -1371,7 +1361,7 @@ const toggleSortOrder = () => {
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="outline" size="icon" @click="handleSelectDir">
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>选择目录</TooltipContent>
|
||||
@@ -1389,8 +1379,8 @@ const toggleSortOrder = () => {
|
||||
<Button variant="outline">取消</Button>
|
||||
</DialogClose>
|
||||
<Button :disabled="addingTask || !addUriText.trim()" @click="handleAddDownload">
|
||||
<Loader2 v-if="addingTask" class="h-4 w-4 animate-spin" />
|
||||
<Plus v-else class="h-4 w-4" />
|
||||
<Loader2 v-if="addingTask" class="size-4 animate-spin" />
|
||||
<Plus v-else class="size-4" />
|
||||
添加下载
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
@@ -1402,7 +1392,7 @@ const toggleSortOrder = () => {
|
||||
<AlertDialogContent class="max-w-md">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle class="flex items-center gap-2">
|
||||
<AlertCircle class="h-4 w-4 text-amber-500" />
|
||||
<AlertCircle class="size-4 text-amber-500" />
|
||||
下载重复提醒
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription class="text-xs">
|
||||
@@ -1423,7 +1413,7 @@ const toggleSortOrder = () => {
|
||||
<AlertDialogCancel @click="onDuplicateCancel">取消全部</AlertDialogCancel>
|
||||
<Button variant="outline" @click="onDuplicateSkip">跳过此链接</Button>
|
||||
<AlertDialogAction @click="onDuplicateConfirm">
|
||||
<Download class="h-4 w-4" />
|
||||
<Download class="size-4" />
|
||||
仍然下载
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
@@ -1469,7 +1459,7 @@ const toggleSortOrder = () => {
|
||||
<DialogContent class="max-w-xl max-h-[80vh]">
|
||||
<DialogHeader>
|
||||
<DialogTitle class="flex items-center gap-2">
|
||||
<Info class="h-4 w-4 text-primary" />
|
||||
<Info class="size-4 text-primary" />
|
||||
任务详情
|
||||
</DialogTitle>
|
||||
<DialogDescription class="text-xs">
|
||||
@@ -1487,7 +1477,7 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button size="icon" variant="ghost" class="h-7 w-7 shrink-0" @click="handleCopyText(detailTask.filename, '文件名')">
|
||||
<Button size="icon" variant="ghost" class="size-7 shrink-0" @click="handleCopyText(detailTask.filename, '文件名')">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
@@ -1501,7 +1491,7 @@ const toggleSortOrder = () => {
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-xs text-muted-foreground">状态</span>
|
||||
<Badge :variant="getTaskStatusBadge(detailTask).variant" class="gap-1">
|
||||
<component :is="getTaskStatusBadge(detailTask).icon" class="h-3 w-3" />
|
||||
<component :is="getTaskStatusBadge(detailTask).icon" class="size-3" />
|
||||
{{ getTaskStatusBadge(detailTask).text }}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -1514,7 +1504,7 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button size="icon" variant="ghost" class="h-7 w-7 shrink-0" @click="handleCopyText(detailTask.url, '下载链接')">
|
||||
<Button size="icon" variant="ghost" class="size-7 shrink-0" @click="handleCopyText(detailTask.url, '下载链接')">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
@@ -1532,13 +1522,13 @@ const toggleSortOrder = () => {
|
||||
<TooltipTrigger as-child>
|
||||
<span class="font-mono text-xs break-all cursor-default">{{ detailTask.dir }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[400px] break-all">{{ detailTask.dir }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">{{ detailTask.dir }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span class="font-mono text-xs text-muted-foreground break-all">{{ detailTask.filename }}</span>
|
||||
</div>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button size="icon" variant="ghost" class="h-7 w-7 shrink-0" @click="handleCopyText(detailTask.dir + '\\' + detailTask.filename, '完整路径')">
|
||||
<Button size="icon" variant="ghost" class="size-7 shrink-0" @click="handleCopyText(detailTask.dir + '\\' + detailTask.filename, '完整路径')">
|
||||
<Copy class="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
@@ -1643,7 +1633,7 @@ const toggleSortOrder = () => {
|
||||
<Button variant="outline">关闭</Button>
|
||||
</DialogClose>
|
||||
<Button v-if="detailTask?.dir" variant="outline" @click="handleOpenDir(detailTask)">
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
打开目录
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -5,22 +5,44 @@ const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '下载任务',
|
||||
description: '查看与管理下载任务',
|
||||
keywords: ['下载', 'download', '任务', 'task']
|
||||
keywords: ['下载', 'download', '任务', 'task'],
|
||||
tab: 'tasks'
|
||||
},
|
||||
{
|
||||
title: '添加下载',
|
||||
description: '添加 HTTP/HTTPS 直链下载',
|
||||
keywords: ['添加', '链接', 'url', 'add', '新建']
|
||||
keywords: ['添加', '链接', 'url', 'add', '新建'],
|
||||
tab: 'tasks'
|
||||
},
|
||||
{
|
||||
title: '下载设置',
|
||||
description: '配置下载目录、并发数与速度限制',
|
||||
keywords: ['设置', 'setting', '速度', '目录', '并发']
|
||||
keywords: ['设置', 'setting', '速度', '目录', '并发'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '下载目录',
|
||||
description: '设置任务默认保存目录',
|
||||
keywords: ['目录', '保存', '路径', 'dir', 'folder', '下载位置'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '并发下载数',
|
||||
description: '设置同时下载的任务数量上限',
|
||||
keywords: ['并发', '数量', 'concurrent', '线程'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '速度限制',
|
||||
description: '设置全局下载/上传限速',
|
||||
keywords: ['限速', '速度', '速率', 'rate', 'limit', '带宽'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '浏览器扩展',
|
||||
description: '安装 Thing Extension 接管浏览器下载',
|
||||
keywords: ['扩展', 'extension', '浏览器', 'chrome', 'edge']
|
||||
keywords: ['扩展', 'extension', '浏览器', 'chrome', 'edge'],
|
||||
tab: 'extension'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ const store = useMonitorStore()
|
||||
|
||||
// ===== Tab 配置(注册到 TitleBar 浮动切换器) =====
|
||||
const activeTab = ref('overview')
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
const tabsListRef = useModuleTabs('monitor', activeTab, [
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'details', label: '详细' },
|
||||
{ value: 'osd', label: 'OSD 显示' },
|
||||
@@ -1102,8 +1102,9 @@ onUnmounted(() => {
|
||||
// 不 dispose store:SSE 订阅保持,确保切走监控模块后 OSD 仍有数据
|
||||
// store.subscribe() 内部有守卫(if unlistenFns.length return),重复 init 不会重复订阅
|
||||
// 不关闭 OSD 窗口:切走监控模块时保持 OSD 显示,由模块禁用或应用退出时统一清理
|
||||
// 释放 OSD 事件监听(App 启动或模块重新挂载时会重新注册)
|
||||
store.disposeOsd()
|
||||
// 不调用 store.disposeOsd():tray:toggle-osd 监听与 OSD 配置 watcher 由 App.vue 的
|
||||
// initOsd() 注册,属应用级常驻(与模块生命周期解耦);若在此释放,切走监控模块后
|
||||
// 托盘菜单的 OSD 开关会失效。OSD 事件监听仅在 App 卸载(应用退出)时统一释放。
|
||||
})
|
||||
|
||||
// 当 Kernel 从未就绪变成就绪时,主动拉一次快照填充 UI
|
||||
@@ -1145,7 +1146,12 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center justify-between text-sm">
|
||||
<span class="flex items-center gap-1.5"><Cpu class="size-4 text-primary" />CPU</span>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="cpuModel ?? ''">{{ cpuModel ?? '--' }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2">{{ cpuModel ?? '--' }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ cpuModel ?? '' }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
@@ -1178,7 +1184,12 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center justify-between text-sm">
|
||||
<span class="flex items-center gap-1.5"><Gauge class="size-4 text-primary" />GPU</span>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="gpuModel ?? ''">{{ gpuModel ?? '--' }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2">{{ gpuModel ?? '--' }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ gpuModel ?? '' }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
@@ -1211,9 +1222,14 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center justify-between text-sm">
|
||||
<span class="flex items-center gap-1.5"><MemoryStick class="size-4 text-primary" />内存</span>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="memModuleModels.join(', ')">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2">
|
||||
{{ memTotalGB != null ? fmt(memTotalGB, 0) + ' GB' : '--' }}
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ memModuleModels.join(', ') }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
@@ -1275,7 +1291,12 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<div v-if="storageDrives.length" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
|
||||
<div v-for="drive in storageDrives" :key="drive.name" class="border rounded-md p-2 space-y-1">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="text-xs font-medium truncate" :title="drive.name">{{ drive.name }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs font-medium truncate">{{ drive.name }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ drive.name }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span :class="['text-xs font-mono tabular-nums shrink-0', tempColor(drive.temp)]">{{ fmt(drive.temp, 0) }}°C</span>
|
||||
</div>
|
||||
<div>
|
||||
@@ -1330,14 +1351,24 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<Play class="size-3" />启动
|
||||
</Button>
|
||||
<!-- 提权按钮(标志未启用时显示:设置标志 + 以管理员权限重启 Thing) -->
|
||||
<Button v-if="!store.elevateOnLaunch" size="xs" variant="outline" class="gap-1 text-emerald-600 dark:text-emerald-400 border-emerald-500/40 hover:bg-emerald-500/10" :disabled="store.starting" title="以管理员权限重启 Thing(弹 UAC,ThingHK 子进程继承权限,后续启动自动提权,崩溃自动重启)" @click="handleElevateSelf">
|
||||
<Tooltip v-if="!store.elevateOnLaunch">
|
||||
<TooltipTrigger as-child>
|
||||
<Button size="xs" variant="outline" class="gap-1 text-emerald-600 dark:text-emerald-400 border-emerald-500/40 hover:bg-emerald-500/10" :disabled="store.starting" @click="handleElevateSelf">
|
||||
<Loader2 v-if="store.starting" class="size-3 animate-spin" />
|
||||
<ShieldCheck v-else class="size-3" />提权
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[480px] break-words">以管理员权限重启 Thing(弹 UAC,ThingHK 子进程继承权限,后续启动自动提权,崩溃自动重启)</TooltipContent>
|
||||
</Tooltip>
|
||||
<!-- 取消提权按钮(标志已启用时显示:清除标志,下次启动不触发 UAC) -->
|
||||
<Button v-else size="xs" variant="outline" class="gap-1 text-muted-foreground hover:text-foreground" title="取消提权,下次启动将以普通权限运行(不影响当前会话)" @click="handleCancelElevation">
|
||||
<Tooltip v-else>
|
||||
<TooltipTrigger as-child>
|
||||
<Button size="xs" variant="outline" class="gap-1 text-muted-foreground hover:text-foreground" @click="handleCancelElevation">
|
||||
<ShieldOff class="size-3" />取消提权
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[480px] break-words">取消提权,下次启动将以普通权限运行(不影响当前会话)</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button size="xs" variant="outline" :disabled="store.starting || store.stopping || store.connState === 'idle'" @click="handleRefresh">
|
||||
<RefreshCw class="size-3" />刷新
|
||||
</Button>
|
||||
@@ -1420,7 +1451,12 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<div class="text-[11px] uppercase tracking-wide text-muted-foreground/70 mb-1">{{ typeLabel(typeGroup.type) }}</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-0.5 text-xs">
|
||||
<div v-for="s in typeGroup.items" :key="s.id" class="flex justify-between items-center py-0.5">
|
||||
<span class="text-muted-foreground truncate pr-2" :title="s.name">{{ s.name }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-muted-foreground truncate pr-2">{{ s.name }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ s.name }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span class="font-mono tabular-nums shrink-0" :class="{ 'text-muted-foreground/50': s.value == null }">
|
||||
{{ s.value == null ? 'N/A' : s.value.toFixed(s.type === 'voltage' || s.type === 'power' ? 2 : 1) }}
|
||||
<span class="text-muted-foreground ml-0.5">{{ s.unit }}</span>
|
||||
@@ -2074,7 +2110,18 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
</Button>
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground">
|
||||
Kernel 由 ProcessManager 统一管理,应用启动时自动拉起,崩溃自动重启。
|
||||
Kernel 由 ProcessManager 统一管理,崩溃自动重启。
|
||||
</div>
|
||||
<!-- 应用启动时自动启动 toggle(参照代理模块) -->
|
||||
<div class="flex items-center justify-between rounded-md border p-3">
|
||||
<div>
|
||||
<p class="text-sm">应用启动时自动启动监控内核</p>
|
||||
<p class="text-xs text-muted-foreground">软件启动时自动运行 ThingHK 内核</p>
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="store.autoStart"
|
||||
@update:model-value="(v: boolean) => store.setAutoStart(v)"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -2108,7 +2155,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
>{{ pathDisplay || pathShort }}</span>
|
||||
<span v-else class="font-mono text-xs text-right cursor-default">{{ pathShort }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[400px] break-all">{{ store.kernelInfo.path ?? '' }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">{{ store.kernelInfo.path ?? '' }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<template v-if="store.kernelInfo.exists">
|
||||
<Tooltip>
|
||||
|
||||
@@ -6,7 +6,56 @@ const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '硬件监控',
|
||||
description: '查看系统硬件状态',
|
||||
keywords: ['监控', '硬件', 'cpu', '内存', 'monitor', 'hardware']
|
||||
keywords: ['监控', '硬件', 'cpu', '内存', 'monitor', 'hardware'],
|
||||
tab: 'overview'
|
||||
},
|
||||
{
|
||||
title: '详细数据',
|
||||
description: '查看各传感器详细读数',
|
||||
keywords: ['详细', '数据', '传感器', 'sensor', '温度', '转速'],
|
||||
tab: 'details'
|
||||
},
|
||||
{
|
||||
title: 'OSD 显示',
|
||||
description: '配置悬浮窗显示项、位置与外观',
|
||||
keywords: ['osd', '悬浮窗', '小窗', '显示', 'overlay'],
|
||||
tab: 'osd'
|
||||
},
|
||||
{
|
||||
title: 'OSD 悬浮窗位置',
|
||||
description: '设置悬浮窗在屏幕中的位置',
|
||||
keywords: ['位置', '悬浮窗', '屏幕', 'position', 'osd'],
|
||||
tab: 'osd'
|
||||
},
|
||||
{
|
||||
title: '警告阈值',
|
||||
description: '设置传感器告警阈值与颜色',
|
||||
keywords: ['阈值', '告警', '警告', 'threshold', '颜色'],
|
||||
tab: 'osd'
|
||||
},
|
||||
{
|
||||
title: '监控设置',
|
||||
description: '内核控制、自动启动与监控项配置',
|
||||
keywords: ['设置', 'setting', '配置', '选项'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '启动监控内核',
|
||||
description: '启动或停止 ThingHK 监控内核',
|
||||
keywords: ['内核', '启动', '停止', 'kernel', 'thinghk', '控制'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '自动启动监控内核',
|
||||
description: '应用启动时自动运行监控内核',
|
||||
keywords: ['自动启动', '开机', '内核', 'autoStart'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '监控项配置',
|
||||
description: '选择要监控的传感器分组与项目',
|
||||
keywords: ['监控项', '传感器', '分组', 'sensor', '配置'],
|
||||
tab: 'settings'
|
||||
}
|
||||
]
|
||||
|
||||
@@ -30,9 +79,12 @@ export const moduleConfig: ModuleConfig = {
|
||||
},
|
||||
lifecycle: {
|
||||
onEnable: async () => {
|
||||
// 启用模块时拉起 Kernel 并开始 SSE 订阅
|
||||
// 若用户在监控设置中开启了"自动启动",则随模块启用而运行 Kernel
|
||||
try {
|
||||
const autoStart = await invoke<boolean>('monitor_get_auto_start')
|
||||
if (autoStart) {
|
||||
await invoke('monitor_start')
|
||||
}
|
||||
} catch {
|
||||
/* 忽略:可能 Kernel 未安装 */
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ const onConfirmOpenChange = (open: boolean) => {
|
||||
const activeTab = ref('overview')
|
||||
// 浮动标签切换器:注册到 TitleBar,滚动遮挡时自动显示
|
||||
const tabsStore = useModuleTabsStore()
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
const tabsListRef = useModuleTabs('proxy', activeTab, [
|
||||
{ value: 'overview', label: '概览' },
|
||||
{ value: 'proxies', label: '节点' },
|
||||
{ value: 'profiles', label: '订阅' },
|
||||
@@ -328,9 +328,9 @@ const init = async () => {
|
||||
await store.waitForApi()
|
||||
store.refreshVersion()
|
||||
loadProxiesWithError()
|
||||
// 若自动切换已开启,恢复定时器
|
||||
// 若自动切换已开启,恢复定时器(静默,不弹通知、不立即执行)
|
||||
if (autoSwitchEnabled.value) {
|
||||
startAutoSwitch()
|
||||
startAutoSwitch(false, false)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -345,23 +345,35 @@ onMounted(() => {
|
||||
// 窗口/标签页不可见时暂停状态轮询,恢复可见后下个 tick 自动继续
|
||||
if (document.hidden) return
|
||||
await store.refreshStatus()
|
||||
// 同步系统代理真实状态(注册表可能被外部改动,3s 周期足够感知)
|
||||
await store.refreshSystemProxy()
|
||||
}, 3000)
|
||||
// 页面重新可见时立即刷新一次系统代理状态(切回标签页/从托盘返回主窗口)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (statusTimer) clearInterval(statusTimer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
stopAutoSwitch()
|
||||
})
|
||||
|
||||
/** 页面可见性变化时刷新系统代理状态(低成本感知外部修改) */
|
||||
async function onVisibilityChange() {
|
||||
if (!document.hidden) {
|
||||
await store.refreshSystemProxy()
|
||||
}
|
||||
}
|
||||
|
||||
watch(running, async (val, old) => {
|
||||
if (val && !old) {
|
||||
await store.waitForApi()
|
||||
await store.refreshVersion()
|
||||
await loadProxiesWithError()
|
||||
// 自动切换若已开启,mihomo 启动/重启后恢复定时器
|
||||
// 自动切换若已开启,mihomo 启动/重启后恢复定时器(静默,不弹通知)
|
||||
// (handleStop 会停掉旧定时器,此处统一接管启动路径,避免开关显示开但功能静默失效)
|
||||
if (autoSwitchEnabled.value) {
|
||||
startAutoSwitch()
|
||||
startAutoSwitch(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -483,16 +495,21 @@ const quickSwitchNode = async (name: string) => {
|
||||
}
|
||||
|
||||
// ===== 自动切换节点 =====
|
||||
const startAutoSwitch = () => {
|
||||
const startAutoSwitch = (notify = true, immediate = true) => {
|
||||
stopAutoSwitch()
|
||||
if (!autoSwitchEnabled.value) return
|
||||
const ms = autoSwitchInterval.value * 60 * 1000
|
||||
autoSwitchTimer = setInterval(runAutoSwitch, ms)
|
||||
// 仅用户主动开启时提示;模块挂载/内核重启恢复定时器时静默,避免每次切换都弹通知
|
||||
if (notify) {
|
||||
toast.success('自动切换已开启', {
|
||||
description: `每 ${autoSwitchInterval.value} 分钟测试并切换至最优节点`
|
||||
})
|
||||
// 立即执行一次
|
||||
}
|
||||
// 立即执行一次(用户主动开启/调整时立即生效;进入模块恢复时跳过,避免每次进入都测速切换)
|
||||
if (immediate) {
|
||||
runAutoSwitch()
|
||||
}
|
||||
}
|
||||
|
||||
const stopAutoSwitch = () => {
|
||||
@@ -978,13 +995,9 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
<div class="flex items-center gap-1.5 min-w-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<span
|
||||
v-if="store.kernel?.exists"
|
||||
class="font-mono text-xs text-right truncate cursor-default"
|
||||
>{{ pathDisplay || pathShort }}</span>
|
||||
<span v-else class="font-mono text-xs text-right cursor-default">{{ pathShort }}</span>
|
||||
<span class="font-mono text-xs text-right truncate cursor-default">{{ pathDisplay || pathShort }}</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent class="max-w-[400px] break-all">{{ store.kernel?.path ?? '' }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">{{ store.kernel?.path ?? '' }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<template v-if="store.kernel?.exists">
|
||||
<Tooltip>
|
||||
|
||||
@@ -7,22 +7,110 @@ const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '代理设置',
|
||||
description: '配置网络代理、端口与控制接口',
|
||||
keywords: ['代理', 'proxy', '网络', 'network', '端口', 'port']
|
||||
keywords: ['代理', 'proxy', '网络', 'network', '端口', 'port'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '订阅管理',
|
||||
description: '导入与更新 Clash/mihomo 订阅',
|
||||
keywords: ['订阅', 'subscription', 'profile', '导入']
|
||||
keywords: ['订阅', 'subscription', 'profile', '导入'],
|
||||
tab: 'profiles'
|
||||
},
|
||||
{
|
||||
title: '节点选择',
|
||||
description: '切换代理节点并测试延迟',
|
||||
keywords: ['节点', 'node', '延迟', 'delay', '测速']
|
||||
keywords: ['节点', 'node', '延迟', 'delay', '测速'],
|
||||
tab: 'proxies'
|
||||
},
|
||||
{
|
||||
title: '系统代理',
|
||||
description: '开启或关闭 Windows 系统代理',
|
||||
keywords: ['系统代理', 'system proxy', '开关', 'toggle']
|
||||
keywords: ['系统代理', 'system proxy', '开关', 'toggle'],
|
||||
tab: 'overview'
|
||||
},
|
||||
{
|
||||
title: '导入订阅',
|
||||
description: '填入订阅地址导入新配置',
|
||||
keywords: ['导入', '订阅地址', 'import', 'url', '添加订阅'],
|
||||
tab: 'profiles'
|
||||
},
|
||||
{
|
||||
title: '更新订阅',
|
||||
description: '手动更新订阅配置',
|
||||
keywords: ['更新订阅', 'update', '刷新订阅'],
|
||||
tab: 'profiles'
|
||||
},
|
||||
{
|
||||
title: '自动切换节点',
|
||||
description: '定时测速并自动切换到最优节点',
|
||||
keywords: ['自动切换', 'auto switch', '智能', '最优节点', '测速'],
|
||||
tab: 'overview'
|
||||
},
|
||||
{
|
||||
title: '代理组测速',
|
||||
description: '测试代理组所有节点的延迟',
|
||||
keywords: ['测速', '延迟', 'delay', 'test', 'ping'],
|
||||
tab: 'proxies'
|
||||
},
|
||||
{
|
||||
title: '运行模式',
|
||||
description: '规则 / 全局 / 直连模式切换',
|
||||
keywords: ['模式', 'mode', 'rule', 'global', 'direct', '规则', '全局', '直连'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '混合代理端口',
|
||||
description: '配置 mihomo 混合代理端口',
|
||||
keywords: ['端口', 'port', 'mixed', '混合'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '控制接口地址',
|
||||
description: '配置外部控制接口地址',
|
||||
keywords: ['控制接口', 'external', 'controller', 'api', '地址'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: 'API 密钥',
|
||||
description: '设置 mihomo 外部 API 密钥',
|
||||
keywords: ['密钥', 'secret', 'token', '鉴权', 'api'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '允许局域网连接',
|
||||
description: '允许其他设备通过本机代理上网',
|
||||
keywords: ['局域网', 'lan', 'allowLan', '共享'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '日志级别',
|
||||
description: '配置 mihomo 日志输出级别',
|
||||
keywords: ['日志', 'log', 'level', 'debug', 'info'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '启动时自动启动 mihomo',
|
||||
description: '应用启动时自动运行代理内核',
|
||||
keywords: ['自动启动', 'autoStart', '开机', '启动内核'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '启动时自动开启系统代理',
|
||||
description: 'mihomo 启动后自动设置 Windows 系统代理',
|
||||
keywords: ['系统代理', '自动', 'autoSystemProxy'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '更新内核',
|
||||
description: '检查并更新 mihomo 内核版本',
|
||||
keywords: ['内核', '更新', 'kernel', 'update', '升级'],
|
||||
tab: 'overview'
|
||||
},
|
||||
{
|
||||
title: '安装内核',
|
||||
description: '首次安装 mihomo 内核',
|
||||
keywords: ['内核', '安装', 'kernel', 'install', '下载'],
|
||||
tab: 'overview'
|
||||
}
|
||||
]
|
||||
|
||||
@@ -51,6 +139,10 @@ export const moduleConfig: ModuleConfig = {
|
||||
const s = await commands.proxyGetSettings()
|
||||
if (s.autoStart) {
|
||||
await commands.proxyStart()
|
||||
// 若同时开启了"启动时自动开启系统代理",则一并开启系统代理
|
||||
if (s.autoSystemProxy) {
|
||||
await commands.proxySetSystemProxy()
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* 忽略:可能内核未安装 */
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
<script setup lang="ts">
|
||||
import { Pin } from '@lucide/vue'
|
||||
|
||||
defineProps<{
|
||||
items: string[]
|
||||
favs?: string[]
|
||||
open?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
pick: [value: string]
|
||||
fav: [value: string]
|
||||
}>()
|
||||
|
||||
function pick(value: string) {
|
||||
emit('pick', value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<!-- mousedown.prevent 阻止点击下拉项时输入框失焦,使 focus 触发的历史面板保持展开 -->
|
||||
<div
|
||||
v-if="open && ((favs && favs.length) || items.length)"
|
||||
class="qp-fa-dropdown"
|
||||
@mousedown.prevent
|
||||
>
|
||||
<!-- 钉住/常用(独立保存,显示在历史之上) -->
|
||||
<template v-if="favs && favs.length">
|
||||
<p class="qp-fa-dropdown-label">常用</p>
|
||||
<div
|
||||
v-for="f in favs"
|
||||
:key="'fav-' + f"
|
||||
class="qp-fa-dropdown-item"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-xs truncate"
|
||||
:title="f"
|
||||
@click="pick(f)"
|
||||
>
|
||||
{{ f || '(空)' }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="qp-fa-pin pinned"
|
||||
title="取消钉住"
|
||||
@click="emit('fav', f)"
|
||||
>
|
||||
<Pin class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<!-- 历史(最多 10 条,排除已钉住的) -->
|
||||
<p
|
||||
v-if="items.filter(x => !(favs ?? []).includes(x)).length"
|
||||
class="qp-fa-dropdown-label"
|
||||
>
|
||||
历史
|
||||
</p>
|
||||
<div
|
||||
v-for="it in items.filter(x => !(favs ?? []).includes(x))"
|
||||
:key="'his-' + it"
|
||||
class="qp-fa-dropdown-item"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 min-w-0 text-left text-xs truncate"
|
||||
:title="it"
|
||||
@click="pick(it)"
|
||||
>
|
||||
{{ it || '(空)' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="favs"
|
||||
type="button"
|
||||
class="qp-fa-pin"
|
||||
title="钉住为常用"
|
||||
@click="emit('fav', it)"
|
||||
>
|
||||
<Pin class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.qp-fa-dropdown {
|
||||
position: absolute;
|
||||
top: calc(100% + 2px);
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 50;
|
||||
max-height: 220px;
|
||||
overflow-y: auto;
|
||||
background: var(--popover, var(--card));
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown-label {
|
||||
padding: 3px 8px 1px;
|
||||
font-size: 10px;
|
||||
color: var(--muted-foreground);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px 6px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown-item:hover {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.qp-fa-pin {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-shrink: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 2px;
|
||||
color: var(--muted-foreground);
|
||||
cursor: pointer;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.1s, color 0.1s;
|
||||
}
|
||||
|
||||
.qp-fa-pin:hover {
|
||||
opacity: 1;
|
||||
color: var(--foreground);
|
||||
}
|
||||
|
||||
.qp-fa-pin.pinned {
|
||||
color: var(--primary);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown::-webkit-scrollbar-thumb {
|
||||
background: var(--muted-foreground);
|
||||
opacity: 0.3;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.qp-fa-dropdown::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
</style>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -276,11 +276,11 @@ async function changeEngine(v: string) {
|
||||
<!-- 标题与测试 -->
|
||||
<div class="flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold flex items-center gap-2">
|
||||
<Command class="h-5 w-5 text-primary" />
|
||||
<Command class="size-5 text-primary" />
|
||||
快速面板
|
||||
</h2>
|
||||
<Button size="sm" @click="testPopup">
|
||||
<Zap class="h-4 w-4 mr-1" />
|
||||
<Zap class="size-4 mr-1" />
|
||||
测试唤起
|
||||
</Button>
|
||||
</div>
|
||||
@@ -289,7 +289,7 @@ async function changeEngine(v: string) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<Keyboard class="h-4 w-4" />
|
||||
<Keyboard class="size-4" />
|
||||
唤起快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -350,7 +350,7 @@ async function changeEngine(v: string) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<Globe class="h-4 w-4" />
|
||||
<Globe class="size-4" />
|
||||
默认搜索引擎
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -376,7 +376,7 @@ async function changeEngine(v: string) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<FolderTree class="h-4 w-4" />
|
||||
<FolderTree class="size-4" />
|
||||
文件索引
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -406,14 +406,14 @@ async function changeEngine(v: string) {
|
||||
class="flex items-center gap-2 p-2 rounded-md bg-muted/40"
|
||||
>
|
||||
<FolderTree class="h-3.5 w-3.5 text-muted-foreground shrink-0" />
|
||||
<span class="text-xs font-mono truncate flex-1" :title="dir">{{ dir }}</span>
|
||||
<span class="text-xs font-mono truncate flex-1">{{ dir }}</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="h-6 w-6 shrink-0 hover:text-destructive"
|
||||
class="size-6 shrink-0 hover:text-destructive"
|
||||
@click="removeDir(idx)"
|
||||
>
|
||||
<X class="h-3 w-3" />
|
||||
<X class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div v-if="!form.indexDirs.length" class="text-xs text-muted-foreground py-2">
|
||||
@@ -435,7 +435,7 @@ async function changeEngine(v: string) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<Terminal class="h-4 w-4" />
|
||||
<Terminal class="size-4" />
|
||||
自定义命令
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -452,11 +452,11 @@ async function changeEngine(v: string) {
|
||||
<p class="text-xs font-medium truncate">{{ cmd.title }}</p>
|
||||
<p class="text-xs text-muted-foreground font-mono truncate">{{ cmd.command }} {{ cmd.args.join(' ') }}</p>
|
||||
</div>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6 shrink-0" @click="editCustomCommand(idx)">
|
||||
<Pencil class="h-3 w-3" />
|
||||
<Button variant="ghost" size="icon" class="size-6 shrink-0" @click="editCustomCommand(idx)">
|
||||
<Pencil class="size-3" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" class="h-6 w-6 shrink-0 hover:text-destructive" @click="removeCustomCommand(idx)">
|
||||
<X class="h-3 w-3" />
|
||||
<Button variant="ghost" size="icon" class="size-6 shrink-0 hover:text-destructive" @click="removeCustomCommand(idx)">
|
||||
<X class="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<div v-if="!form.customCommands.length" class="text-xs text-muted-foreground py-2">
|
||||
@@ -528,7 +528,15 @@ async function changeEngine(v: string) {
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">文件</Badge>
|
||||
<span class="text-muted-foreground">索引指定目录,快速定位文件</span>
|
||||
<span class="text-muted-foreground">索引指定目录,快速定位文件,支持打开/显示/复制路径/删除,.lnk 按应用处理</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">目录操作</Badge>
|
||||
<span class="text-muted-foreground">文件资源管理器批量处理:批量解压、正则批量重命名(实时预览)、筛选批量删除</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">历史</Badge>
|
||||
<span class="text-muted-foreground">记录最近交互,空查询优先展示</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">剪贴板</Badge>
|
||||
@@ -548,7 +556,7 @@ async function changeEngine(v: string) {
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">系统</Badge>
|
||||
<span class="text-muted-foreground">锁屏、退出应用</span>
|
||||
<span class="text-muted-foreground">系统命令(注册表、CMD/PowerShell、任务管理器、控制面板、关机/重启/休眠)及锁屏、退出应用</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">网页</Badge>
|
||||
|
||||
@@ -8,6 +8,31 @@ const searchItems: SearchIndexItem[] = [
|
||||
title: '快速面板',
|
||||
description: '全局快捷键唤起命令面板',
|
||||
keywords: ['快速面板', '快速启动', '搜索', '命令', 'quickpanel', 'launcher', 'spotlight']
|
||||
},
|
||||
{
|
||||
title: '唤起快捷键',
|
||||
description: '配置全局快捷键打开快速面板',
|
||||
keywords: ['快捷键', '热键', 'shortcut', 'hotkey', '唤起', '打开']
|
||||
},
|
||||
{
|
||||
title: '唤起位置',
|
||||
description: '设置面板弹出位置(屏幕中央 / 鼠标位置)',
|
||||
keywords: ['位置', '弹出', '光标', 'position', 'popup']
|
||||
},
|
||||
{
|
||||
title: '默认搜索引擎',
|
||||
description: '设置快速面板网页搜索的搜索引擎',
|
||||
keywords: ['搜索引擎', '搜索', '引擎', 'search', 'engine', 'bing', 'google']
|
||||
},
|
||||
{
|
||||
title: '文件索引',
|
||||
description: '构建与管理本地文件搜索索引',
|
||||
keywords: ['文件', '索引', '搜索', 'index', '目录', 'file']
|
||||
},
|
||||
{
|
||||
title: '自定义命令',
|
||||
description: '添加自定义启动命令',
|
||||
keywords: ['自定义', '命令', 'command', '启动']
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
Eraser, Undo2, Redo2, Trash2, Copy, Save, X, Image as ImageIcon,
|
||||
} from '@lucide/vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||
|
||||
// ===== 标注数据结构 =====
|
||||
type ToolType = 'rect' | 'arrow' | 'pen' | 'text' | 'mosaic' | 'highlight'
|
||||
@@ -451,41 +452,48 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<div class="h-screen w-screen flex flex-col bg-zinc-950 text-zinc-100 overflow-hidden">
|
||||
<TooltipProvider>
|
||||
<!-- 标题栏 -->
|
||||
<div
|
||||
class="h-9 flex items-center justify-between px-3 bg-zinc-900 border-b border-zinc-800 shrink-0 select-none"
|
||||
data-tauri-drag-region
|
||||
>
|
||||
<span class="text-sm font-medium">截图编辑器</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-zinc-400 hover:text-white hover:bg-zinc-800"
|
||||
title="关闭"
|
||||
@click="closeWindow"
|
||||
@mousedown.stop
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
<X class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>关闭</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<!-- 工具栏 -->
|
||||
<div class="flex items-center gap-3 px-3 py-2 bg-zinc-900 border-b border-zinc-800 shrink-0 flex-wrap">
|
||||
<!-- 工具组 -->
|
||||
<div class="flex items-center gap-1">
|
||||
<Tooltip v-for="tool in TOOLS" :key="tool.value">
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
v-for="tool in TOOLS"
|
||||
:key="tool.value"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:class="currentTool === tool.value
|
||||
? 'bg-zinc-700 text-white hover:bg-zinc-700 hover:text-white'
|
||||
: 'text-zinc-400 hover:bg-zinc-800 hover:text-white'"
|
||||
:title="tool.label"
|
||||
@click="currentTool = tool.value"
|
||||
>
|
||||
<component :is="tool.icon" class="h-4 w-4" />
|
||||
<component :is="tool.icon" class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ tool.label }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="h-6 w-px bg-zinc-700" />
|
||||
@@ -493,15 +501,17 @@ onUnmounted(() => {
|
||||
<!-- 颜色 -->
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-xs text-zinc-500">颜色</span>
|
||||
<Tooltip v-for="c in COLORS" :key="c">
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
v-for="c in COLORS"
|
||||
:key="c"
|
||||
class="size-6 rounded-full border border-zinc-500 transition-transform hover:scale-110"
|
||||
:class="currentColor === c ? 'ring-2 ring-blue-400 ring-offset-1 ring-offset-zinc-900 scale-110' : ''"
|
||||
:style="{ backgroundColor: c }"
|
||||
:title="c"
|
||||
@click="currentColor = c"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ c }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="h-6 w-px bg-zinc-700" />
|
||||
@@ -558,46 +568,62 @@ onUnmounted(() => {
|
||||
|
||||
<!-- 历史 / 清空 -->
|
||||
<div class="flex items-center gap-1">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-zinc-400 hover:bg-zinc-800 hover:text-white"
|
||||
:disabled="!canUndo"
|
||||
title="橡皮(撤销最近标注)"
|
||||
@click="undo"
|
||||
>
|
||||
<Eraser class="h-4 w-4" />
|
||||
<Eraser class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>橡皮(撤销最近标注)</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-zinc-400 hover:bg-zinc-800 hover:text-white"
|
||||
:disabled="!canUndo"
|
||||
title="撤销"
|
||||
@click="undo"
|
||||
>
|
||||
<Undo2 class="h-4 w-4" />
|
||||
<Undo2 class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>撤销</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-zinc-400 hover:bg-zinc-800 hover:text-white"
|
||||
:disabled="!canRedo"
|
||||
title="重做"
|
||||
@click="redo"
|
||||
>
|
||||
<Redo2 class="h-4 w-4" />
|
||||
<Redo2 class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>重做</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="text-zinc-400 hover:bg-red-900 hover:text-white"
|
||||
:disabled="!canUndo"
|
||||
title="清空"
|
||||
@click="clearAll"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
<Trash2 class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>清空</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -608,7 +634,7 @@ onUnmounted(() => {
|
||||
v-if="loadError"
|
||||
class="flex flex-col items-center justify-center h-full gap-3 text-zinc-400"
|
||||
>
|
||||
<ImageIcon class="h-12 w-12 opacity-40" />
|
||||
<ImageIcon class="size-12 opacity-40" />
|
||||
<p>未找到待编辑的截图</p>
|
||||
<Button variant="ghost" class="text-zinc-200 hover:bg-zinc-800 hover:text-white" @click="closeWindow">
|
||||
关闭
|
||||
@@ -655,13 +681,14 @@ onUnmounted(() => {
|
||||
取消
|
||||
</Button>
|
||||
<Button variant="ghost" class="text-zinc-200 hover:bg-zinc-800 hover:text-white" @click="saveToFile">
|
||||
<Save class="h-4 w-4" />
|
||||
<Save class="size-4" />
|
||||
保存到文件
|
||||
</Button>
|
||||
<Button variant="ghost" class="bg-blue-600 text-white hover:bg-blue-500" @click="copyToClipboard">
|
||||
<Copy class="h-4 w-4" />
|
||||
<Copy class="size-4" />
|
||||
复制到剪贴板
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onUnmounted, watch, nextTick } from 'vue'
|
||||
import {
|
||||
Keyboard, Settings, FolderOpen, Camera, Copy, Save, Trash2, Timer,
|
||||
Keyboard, Settings, FolderOpen, Camera, Copy, Save, Trash2, Timer, StickyNote,
|
||||
Image as ImageIcon, Loader2,
|
||||
} from '@lucide/vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
@@ -14,16 +14,17 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||
|
||||
const store = useScreenshotStore()
|
||||
|
||||
const activeTab = ref('settings')
|
||||
const tabsListRef = useModuleTabs(activeTab, [
|
||||
const tabsListRef = useModuleTabs('screenshot', activeTab, [
|
||||
{ value: 'settings', label: '设置' },
|
||||
{ value: 'history', label: '历史' },
|
||||
])
|
||||
|
||||
const HISTORY_LIMITS = [6, 12, 24, 48]
|
||||
const HISTORY_LIMITS = [24, 48, 96]
|
||||
const DELAY_OPTIONS = [0, 1, 2, 3, 5]
|
||||
|
||||
function formatTime(t: number): string {
|
||||
@@ -69,14 +70,45 @@ async function handleSave(item: RecentCapture) {
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePin(item: RecentCapture) {
|
||||
const idx = store.recent.findIndex((r) => r.id === item.id)
|
||||
await store.togglePin(idx >= 0 ? idx : 0)
|
||||
}
|
||||
|
||||
function handleDelete(item: RecentCapture) {
|
||||
void store.removeRecent(item)
|
||||
toast.success('已从历史移除')
|
||||
}
|
||||
|
||||
// ===== 快捷键录入器 =====
|
||||
const recording = ref(false)
|
||||
const recorderRef = ref<HTMLDivElement | null>(null)
|
||||
// ===== 历史保留数量:预设 + 自定义输入 =====
|
||||
const customLimit = ref('')
|
||||
|
||||
function onLimitPreset(n: number) {
|
||||
store.setSettings({ historyLimit: n })
|
||||
}
|
||||
|
||||
function onCustomLimit() {
|
||||
const v = parseInt(customLimit.value, 10)
|
||||
if (!Number.isFinite(v) || v < 1) {
|
||||
toast.warning('请输入大于 0 的数字')
|
||||
return
|
||||
}
|
||||
store.setSettings({ historyLimit: Math.min(999, Math.max(1, Math.floor(v))) })
|
||||
}
|
||||
|
||||
// 当前值不在预设中时,把自定义输入框预填为当前值
|
||||
watch(
|
||||
() => store.settings.historyLimit,
|
||||
(v) => {
|
||||
if (!HISTORY_LIMITS.includes(v)) customLimit.value = String(v)
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// ===== 快捷键录入器(截图 / 贴图共用) =====
|
||||
const recordingField = ref<'capture' | 'pin' | null>(null)
|
||||
const captureRecorderRef = ref<HTMLDivElement | null>(null)
|
||||
const pinRecorderRef = ref<HTMLDivElement | null>(null)
|
||||
|
||||
/** 把存储的快捷键字符串格式化为展示形式:ctrl+alt+a → Ctrl + Alt + A */
|
||||
function displayShortcut(s: string): string {
|
||||
@@ -119,11 +151,11 @@ function eventToShortcut(e: KeyboardEvent): string | null {
|
||||
}
|
||||
|
||||
function onRecordKey(e: KeyboardEvent) {
|
||||
if (!recording.value) return
|
||||
if (!recordingField.value) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.key === 'Escape') {
|
||||
recording.value = false
|
||||
recordingField.value = null
|
||||
return
|
||||
}
|
||||
// 仅修饰键按下时不结束(等待主键)
|
||||
@@ -133,24 +165,27 @@ function onRecordKey(e: KeyboardEvent) {
|
||||
toast.warning('不支持的按键组合,请使用字母/数字/功能键 + 修饰键')
|
||||
return
|
||||
}
|
||||
recording.value = false
|
||||
void commitShortcut(combo)
|
||||
const field = recordingField.value
|
||||
recordingField.value = null
|
||||
void commitShortcut(field, combo)
|
||||
}
|
||||
|
||||
async function commitShortcut(combo: string) {
|
||||
const ok = await store.setShortcut(combo)
|
||||
async function commitShortcut(field: 'capture' | 'pin', combo: string) {
|
||||
const ok = field === 'capture'
|
||||
? await store.setShortcut(combo)
|
||||
: await store.setPinShortcut(combo)
|
||||
if (ok) toast.success(`快捷键已更新为 ${displayShortcut(combo)}`)
|
||||
else toast.error('快捷键注册失败,可能被其他程序占用')
|
||||
}
|
||||
|
||||
async function startRecord() {
|
||||
recording.value = true
|
||||
async function startRecord(field: 'capture' | 'pin') {
|
||||
recordingField.value = field
|
||||
await nextTick()
|
||||
recorderRef.value?.focus()
|
||||
;(field === 'capture' ? captureRecorderRef : pinRecorderRef).value?.focus()
|
||||
}
|
||||
|
||||
watch(recording, (on) => {
|
||||
if (on) window.addEventListener('keydown', onRecordKey, true)
|
||||
watch(recordingField, (field) => {
|
||||
if (field) window.addEventListener('keydown', onRecordKey, true)
|
||||
else window.removeEventListener('keydown', onRecordKey, true)
|
||||
})
|
||||
|
||||
@@ -159,6 +194,11 @@ async function clearShortcut() {
|
||||
toast.success('已禁用截图快捷键')
|
||||
}
|
||||
|
||||
async function clearPinShortcut() {
|
||||
await store.setPinShortcut('')
|
||||
toast.success('已禁用贴图快捷键')
|
||||
}
|
||||
|
||||
// 导出监听(screenshot-exported)由应用级注册(main.ts/App.vue),随应用生命周期管理;
|
||||
// 模块卸载不得销毁该单例监听,否则离开截图模块后全局快捷键截图将不记录历史/不自动保存。
|
||||
|
||||
@@ -188,7 +228,7 @@ onUnmounted(() => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<Keyboard class="h-4 w-4 text-primary" />
|
||||
<Keyboard class="size-4 text-primary" />
|
||||
截图快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -198,13 +238,13 @@ onUnmounted(() => {
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<!-- 快捷键录入器 -->
|
||||
<div
|
||||
ref="recorderRef"
|
||||
ref="captureRecorderRef"
|
||||
class="hotkey-recorder"
|
||||
:class="{ recording }"
|
||||
:class="{ recording: recordingField === 'capture' }"
|
||||
tabindex="0"
|
||||
@click="startRecord"
|
||||
@click="startRecord('capture')"
|
||||
>
|
||||
<template v-if="recording">按下快捷键…(Esc 取消)</template>
|
||||
<template v-if="recordingField === 'capture'">按下快捷键…(Esc 取消)</template>
|
||||
<template v-else-if="store.settings.shortcut">
|
||||
{{ displayShortcut(store.settings.shortcut) }}
|
||||
</template>
|
||||
@@ -219,7 +259,7 @@ onUnmounted(() => {
|
||||
>清除</Button>
|
||||
</div>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
点击方框录入自定义快捷键,留空则禁用。默认 Ctrl + Alt + A
|
||||
点击方框录入自定义快捷键,留空则禁用。默认 Ctrl + 1
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
@@ -227,8 +267,8 @@ onUnmounted(() => {
|
||||
:disabled="store.capturing"
|
||||
@click="handleCapture"
|
||||
>
|
||||
<Loader2 v-if="store.capturing" class="h-4 w-4 animate-spin" />
|
||||
<Camera v-else class="h-4 w-4" />
|
||||
<Loader2 v-if="store.capturing" class="size-4 animate-spin" />
|
||||
<Camera v-else class="size-4" />
|
||||
立即截图
|
||||
</Button>
|
||||
</div>
|
||||
@@ -246,11 +286,52 @@ onUnmounted(() => {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 贴图快捷键 -->
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<StickyNote class="size-4 text-primary" />
|
||||
贴图快捷键
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div class="flex items-center justify-between gap-4 py-1">
|
||||
<div class="space-y-1 min-w-0">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<div
|
||||
ref="pinRecorderRef"
|
||||
class="hotkey-recorder"
|
||||
:class="{ recording: recordingField === 'pin' }"
|
||||
tabindex="0"
|
||||
@click="startRecord('pin')"
|
||||
>
|
||||
<template v-if="recordingField === 'pin'">按下快捷键…(Esc 取消)</template>
|
||||
<template v-else-if="store.settings.pinShortcut">
|
||||
{{ displayShortcut(store.settings.pinShortcut) }}
|
||||
</template>
|
||||
<template v-else>未设置(点击录入)</template>
|
||||
</div>
|
||||
<Button
|
||||
v-if="store.settings.pinShortcut"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-8 text-muted-foreground"
|
||||
@click="clearPinShortcut"
|
||||
>清除</Button>
|
||||
</div>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
把最近截图以原分辨率贴到屏幕(显示在原框选位置),再次按下可关闭贴图。默认 Alt + 1
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 截图选项 -->
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="text-sm flex items-center gap-2">
|
||||
<Settings class="h-4 w-4 text-primary" />
|
||||
<Settings class="size-4 text-primary" />
|
||||
截图选项
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -259,7 +340,7 @@ onUnmounted(() => {
|
||||
<div class="flex items-center justify-between gap-3 py-2">
|
||||
<div class="space-y-1">
|
||||
<Label class="flex items-center gap-2 text-base font-medium">
|
||||
<Timer class="h-4 w-4" />
|
||||
<Timer class="size-4" />
|
||||
延时截图
|
||||
</Label>
|
||||
<p class="text-sm text-muted-foreground">按下快捷键后倒计时再截图,便于切到目标画面</p>
|
||||
@@ -302,7 +383,7 @@ onUnmounted(() => {
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" class="shrink-0" @click="chooseSaveDir">
|
||||
<FolderOpen class="h-4 w-4" />
|
||||
<FolderOpen class="size-4" />
|
||||
选择目录
|
||||
</Button>
|
||||
</div>
|
||||
@@ -311,9 +392,9 @@ onUnmounted(() => {
|
||||
<div class="flex items-center justify-between gap-3 py-2 border-t">
|
||||
<div class="space-y-1">
|
||||
<Label class="text-base font-medium">历史保留数量</Label>
|
||||
<p class="text-sm text-muted-foreground">超过上限的旧截图将自动移除</p>
|
||||
<p class="text-sm text-muted-foreground">截图完成后自动持久化保存到应用目录,超过上限的旧截图将自动移除</p>
|
||||
</div>
|
||||
<div class="flex gap-1 shrink-0">
|
||||
<div class="flex items-center gap-1.5 shrink-0">
|
||||
<Button
|
||||
v-for="n in HISTORY_LIMITS"
|
||||
:key="n"
|
||||
@@ -323,8 +404,19 @@ onUnmounted(() => {
|
||||
:class="store.settings.historyLimit === n
|
||||
? 'bg-primary/10 text-primary hover:bg-primary/10'
|
||||
: 'text-muted-foreground'"
|
||||
@click="store.setSettings({ historyLimit: n })"
|
||||
@click="onLimitPreset(n)"
|
||||
>{{ n }}</Button>
|
||||
<input
|
||||
v-model="customLimit"
|
||||
type="number"
|
||||
min="1"
|
||||
max="999"
|
||||
class="h-8 w-16 rounded-md border border-input bg-transparent px-2 text-sm text-center outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
placeholder="自定义"
|
||||
title="输入自定义保留数量"
|
||||
@keydown.enter="onCustomLimit"
|
||||
@blur="onCustomLimit"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -342,9 +434,9 @@ onUnmounted(() => {
|
||||
v-if="store.recent.length === 0"
|
||||
class="flex flex-col items-center justify-center h-64 text-muted-foreground gap-3"
|
||||
>
|
||||
<ImageIcon class="h-12 w-12 opacity-40" />
|
||||
<ImageIcon class="size-12 opacity-40" />
|
||||
<p>暂无截图历史</p>
|
||||
<p class="text-xs">按 Ctrl + Alt + A 截图并导出后会显示在这里</p>
|
||||
<p class="text-xs">按 Ctrl + 1 截图并导出后会显示在这里</p>
|
||||
</div>
|
||||
|
||||
<!-- 历史网格 -->
|
||||
@@ -373,31 +465,55 @@ onUnmounted(() => {
|
||||
<div
|
||||
class="absolute inset-0 flex items-center justify-center gap-2 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity"
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon-sm"
|
||||
@click.stop="handlePin(item)"
|
||||
>
|
||||
<StickyNote class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>贴到屏幕</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon-sm"
|
||||
title="复制到剪贴板"
|
||||
@click.stop="handleCopy(item)"
|
||||
>
|
||||
<Copy class="h-4 w-4" />
|
||||
<Copy class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>复制到剪贴板</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon-sm"
|
||||
title="保存到文件"
|
||||
@click.stop="handleSave(item)"
|
||||
>
|
||||
<Save class="h-4 w-4" />
|
||||
<Save class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>保存到文件</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="icon-sm"
|
||||
class="text-destructive hover:text-destructive"
|
||||
title="从历史移除"
|
||||
@click.stop="handleDelete(item)"
|
||||
>
|
||||
<Trash2 class="h-4 w-4" />
|
||||
<Trash2 class="size-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>从历史移除</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '@lucide/vue'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||
import {
|
||||
TOOLS, COLORS, BLOCK_SIZES, ALPHAS, HANDLES, HANDLE_HIT, DRAG_THRESHOLD,
|
||||
type Phase, type ToolType, type Annotation, type DrawableAnnotation,
|
||||
@@ -1779,7 +1780,16 @@ async function finish() {
|
||||
}
|
||||
}
|
||||
if (!out) return
|
||||
await emit(EVENTS.screenshotExported, { pngBase64: out.b64, width: out.w, height: out.h })
|
||||
// 附带框选区域的屏幕逻辑坐标(DIP):窗口逻辑位置 + 选区图像坐标。
|
||||
// 截图图像按虚拟屏 DIP 捕获,坐标按 DIP 传递,贴图窗口按 DIP 布局即可 1:1 还原
|
||||
const spPos = selPhys.value
|
||||
await emit(EVENTS.screenshotExported, {
|
||||
pngBase64: out.b64,
|
||||
width: out.w,
|
||||
height: out.h,
|
||||
posX: Math.round(winOuterX / dpr + spPos.x),
|
||||
posY: Math.round(winOuterY / dpr + spPos.y),
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 完成失败', e)
|
||||
} finally {
|
||||
@@ -1801,7 +1811,14 @@ async function doSave() {
|
||||
})
|
||||
if (!path) return
|
||||
await commands.screenshotSavePng(out.b64, path)
|
||||
await emit(EVENTS.screenshotExported, { pngBase64: out.b64, width: out.w, height: out.h })
|
||||
const spPos = selPhys.value
|
||||
await emit(EVENTS.screenshotExported, {
|
||||
pngBase64: out.b64,
|
||||
width: out.w,
|
||||
height: out.h,
|
||||
posX: Math.round(winOuterX / dpr + spPos.x),
|
||||
posY: Math.round(winOuterY / dpr + spPos.y),
|
||||
})
|
||||
await win.hide().catch(() => {})
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 保存失败', e)
|
||||
@@ -1985,6 +2002,7 @@ onUnmounted(() => {
|
||||
@mousemove="onMouseMove"
|
||||
@mouseup="onMouseUp"
|
||||
>
|
||||
<TooltipProvider>
|
||||
<!-- 冻结的屏幕底图 -->
|
||||
<img
|
||||
v-if="imgSrc"
|
||||
@@ -2094,31 +2112,37 @@ onUnmounted(() => {
|
||||
<div v-if="showToolbar" ref="toolbarRef" class="toolbar" :style="toolbarPos" @mousedown.stop>
|
||||
<!-- 标注工具 -->
|
||||
<div class="tb-group">
|
||||
<Tooltip v-for="t in TOOLS" :key="t.value">
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
v-for="t in TOOLS"
|
||||
:key="t.value"
|
||||
class="tb-icon"
|
||||
:class="{ active: phase === 'editing' && currentTool === t.value }"
|
||||
:title="t.label"
|
||||
@click="onSelectTool(t.value)"
|
||||
>
|
||||
<component :is="t.icon" class="tb-svg" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ t.label }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="tb-sep" />
|
||||
|
||||
<!-- 颜色色卡:显示当前颜色,点击打开选色板 -->
|
||||
<Popover v-model:open="colorPickerOpen">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<PopoverTrigger as-child>
|
||||
<button
|
||||
class="color-badge"
|
||||
:class="{ disabled: !colorEnabled }"
|
||||
:style="{ '--swatch-color': effectiveColor }"
|
||||
:disabled="!colorEnabled"
|
||||
title="颜色"
|
||||
/>
|
||||
</PopoverTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>颜色</TooltipContent>
|
||||
</Tooltip>
|
||||
<PopoverContent class="w-auto p-3" align="start">
|
||||
<div class="color-popover">
|
||||
<input
|
||||
@@ -2128,15 +2152,17 @@ onUnmounted(() => {
|
||||
@input="onCustomColorPick(($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<div class="color-swatches">
|
||||
<Tooltip v-for="c in COLORS" :key="c">
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
v-for="c in COLORS"
|
||||
:key="c"
|
||||
class="color-swatch-mini"
|
||||
:class="{ active: effectiveColor === c }"
|
||||
:style="{ backgroundColor: c }"
|
||||
:title="c"
|
||||
@click="effectiveColor = c"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ c }}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
@@ -2144,14 +2170,18 @@ onUnmounted(() => {
|
||||
|
||||
<!-- 粗细 badge:点击打开 Slider -->
|
||||
<Popover v-model:open="lineWidthPickerOpen">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<PopoverTrigger as-child>
|
||||
<button
|
||||
class="width-badge"
|
||||
:class="{ disabled: !lineWidthEnabled }"
|
||||
:disabled="!lineWidthEnabled"
|
||||
title="粗细"
|
||||
>{{ effectiveLineWidth }}</button>
|
||||
</PopoverTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>粗细</TooltipContent>
|
||||
</Tooltip>
|
||||
<PopoverContent class="w-auto p-3" align="start">
|
||||
<div class="width-popover">
|
||||
<div class="width-popover-header">
|
||||
@@ -2174,43 +2204,62 @@ onUnmounted(() => {
|
||||
<template v-if="currentTool === 'mosaic'">
|
||||
<div class="tb-sep" />
|
||||
<div class="tb-group">
|
||||
<Tooltip v-for="b in BLOCK_SIZES" :key="b">
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
v-for="b in BLOCK_SIZES"
|
||||
:key="b"
|
||||
class="tb-num"
|
||||
:class="{ active: blockSize === b }"
|
||||
title="马赛克块大小"
|
||||
@click="blockSize = b"
|
||||
>{{ b }}</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>马赛克块大小</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-if="currentTool === 'highlight'">
|
||||
<div class="tb-sep" />
|
||||
<div class="tb-group">
|
||||
<Tooltip v-for="a in ALPHAS" :key="a">
|
||||
<TooltipTrigger as-child>
|
||||
<button
|
||||
v-for="a in ALPHAS"
|
||||
:key="a"
|
||||
class="tb-num"
|
||||
:class="{ active: highlightAlpha === a }"
|
||||
title="高亮透明度"
|
||||
@click="highlightAlpha = a"
|
||||
>{{ Math.round(a * 100) }}%</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>高亮透明度</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="tb-sep" />
|
||||
|
||||
<div class="tb-group">
|
||||
<button class="tb-icon" :disabled="!canUndo" title="撤销" @click="undo">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon" :disabled="!canUndo" @click="undo">
|
||||
<Undo2 class="tb-svg" />
|
||||
</button>
|
||||
<button class="tb-icon" :disabled="!canRedo" title="重做" @click="redo">
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>撤销</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon" :disabled="!canRedo" @click="redo">
|
||||
<Redo2 class="tb-svg" />
|
||||
</button>
|
||||
<button class="tb-icon" :disabled="!canUndo" title="清空标注" @click="clearAnnotations">
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>重做</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon" :disabled="!canUndo" @click="clearAnnotations">
|
||||
<Eraser class="tb-svg" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>清空标注</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="tb-sep" />
|
||||
@@ -2221,12 +2270,22 @@ onUnmounted(() => {
|
||||
|
||||
<!-- 复制 / 保存(置末) -->
|
||||
<div class="tb-group">
|
||||
<button class="tb-icon" title="保存到文件" @click="doSave">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon" @click="doSave">
|
||||
<Save class="tb-svg" />
|
||||
</button>
|
||||
<button class="tb-icon primary" title="复制到剪贴板 (Enter)" @click="finish">
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>保存到文件</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon primary" @click="finish">
|
||||
<Copy class="tb-svg" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>复制到剪贴板 (Enter)</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2245,6 +2304,7 @@ onUnmounted(() => {
|
||||
<div class="mag-hint">{{ hint.split(' · ').join('\n') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
<script setup lang="ts">
|
||||
// 贴图窗口:无边框、透明、置顶。
|
||||
// 图片以原分辨率显示,窗口定位到截图时的框选位置(原框选位置)。
|
||||
// 右下角展开图标,hover 展开 上一张 / 下一张 / 关闭。
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { getCurrentWindow, currentMonitor } from '@tauri-apps/api/window'
|
||||
import { LogicalPosition, LogicalSize } from '@tauri-apps/api/dpi'
|
||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { ChevronLeft, ChevronRight, X, Maximize2, Loader2 } from '@lucide/vue'
|
||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
|
||||
/** 图片四周留白(CSS 像素 = 逻辑像素 DIP,与截图图像分辨率单位一致),用于呈现蓝色光晕 */
|
||||
const GLOW_PAD = 18
|
||||
|
||||
const win = getCurrentWindow()
|
||||
const imgSrc = ref('')
|
||||
const imgCssW = ref(0)
|
||||
const imgCssH = ref(0)
|
||||
const loading = ref(false)
|
||||
const errorMsg = ref('')
|
||||
/** 历史列表(localStorage 与主窗口共享,最新在前) */
|
||||
const items = ref<{ filePath: string; width: number; height: number; posX?: number; posY?: number }[]>([])
|
||||
const cur = ref(0)
|
||||
|
||||
let showUnlisten: UnlistenFn | null = null
|
||||
|
||||
/** 同步主界面主题(独立窗口无 pinia,从 localStorage 读取应用设置) */
|
||||
function applyTheme() {
|
||||
const root = document.documentElement
|
||||
let theme = 'system'
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||
if (raw) {
|
||||
const s = JSON.parse(raw)
|
||||
theme = s.theme ?? 'system'
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
let isDark: boolean
|
||||
if (theme === 'system') {
|
||||
isDark = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
} else {
|
||||
isDark = theme === 'dark'
|
||||
}
|
||||
root.classList.toggle('dark', isDark)
|
||||
}
|
||||
|
||||
/** 从 localStorage 读取主窗口持久化的截图历史(图片文件在应用数据目录) */
|
||||
function readHistory() {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.screenshotHistory)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw) as {
|
||||
version?: number
|
||||
items?: { filePath: string; width: number; height: number; posX?: number; posY?: number }[]
|
||||
}
|
||||
if (!Array.isArray(parsed.items)) return []
|
||||
return parsed.items
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 窗口排版到目标位置(全部使用逻辑坐标/DIP):
|
||||
* 截图图像的分辨率是逻辑像素(BMP 按虚拟屏 DIP 捕获),CSS 像素与 DIP 一致,
|
||||
* 故图片以 item.width/height 的 CSS 尺寸显示即 1:1 还原;窗口尺寸 = 图片 + 2×留白,
|
||||
* 窗口位置 = 原框选位置 - 留白,使图片精确覆盖在截图时的区域上(跨 DPI 显示器也无需换算)。
|
||||
*/
|
||||
async function layoutTo(item: { width: number; height: number; posX?: number; posY?: number }) {
|
||||
const pad = GLOW_PAD
|
||||
let x = item.posX !== undefined ? item.posX - pad : 0
|
||||
let y = item.posY !== undefined ? item.posY - pad : 0
|
||||
// 无定位信息(如编辑器导出)时放到当前鼠标位置附近(鼠标坐标为物理像素,需换算为 DIP)
|
||||
if (item.posX === undefined || item.posY === undefined) {
|
||||
try {
|
||||
const [mx, my] = await commands.screenshotCursorPos()
|
||||
const mon = await currentMonitor()
|
||||
const s = mon?.scaleFactor || 1
|
||||
x = mx / s - pad
|
||||
y = my / s - pad
|
||||
} catch { /* 忽略,沿用 0,0 */ }
|
||||
}
|
||||
// 粗略限制在鼠标所在显示器内(避免贴图完全出现在屏幕外,至少保留 40px 可见)
|
||||
try {
|
||||
const mon = await currentMonitor()
|
||||
if (mon) {
|
||||
const s = mon.scaleFactor || 1
|
||||
const mlx = mon.position.x / s
|
||||
const mly = mon.position.y / s
|
||||
const mlw = mon.size.width / s
|
||||
const mlh = mon.size.height / s
|
||||
x = Math.min(Math.max(x, mlx), mlx + mlw - 40)
|
||||
y = Math.min(Math.max(y, mly), mly + mlh - 40)
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
// Windows 上非 resizable 窗口 setSize 会失效,须先临时开启再恢复:
|
||||
// 布局结束后恢复为不可缩放,禁用边缘拖动修改大小(仅保留左键自由拖动)
|
||||
await win.setPosition(new LogicalPosition(Math.round(x), Math.round(y)))
|
||||
await win.setResizable(true)
|
||||
await win.setSize(new LogicalSize(item.width + pad * 2, item.height + pad * 2))
|
||||
await win.setResizable(false)
|
||||
}
|
||||
|
||||
/** 加载并显示第 index 张截图(index 缺省/越界时按最近一张) */
|
||||
async function loadImage(index: number) {
|
||||
const list = items.value
|
||||
if (!list.length) {
|
||||
errorMsg.value = '暂无历史截图'
|
||||
loading.value = false
|
||||
await win.show().catch(() => {})
|
||||
return
|
||||
}
|
||||
const idx = Math.max(0, Math.min(index, list.length - 1))
|
||||
const item = list[idx]
|
||||
cur.value = idx
|
||||
loading.value = true
|
||||
errorMsg.value = ''
|
||||
try {
|
||||
const b64 = await commands.screenshotLoadCache(item.filePath)
|
||||
const dataUrl = `data:image/png;base64,${b64}`
|
||||
// 预解码:等待图片就绪后再排版显示,避免闪烁
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const img = new Image()
|
||||
img.onload = () => resolve()
|
||||
img.onerror = () => reject(new Error('图片解码失败'))
|
||||
img.src = dataUrl
|
||||
})
|
||||
// CSS 尺寸 = 原分辨率(逻辑像素/DIP),与 CSS 像素一致,1:1 还原截图时覆盖的区域
|
||||
await layoutTo(item)
|
||||
imgCssW.value = item.width
|
||||
imgCssH.value = item.height
|
||||
imgSrc.value = dataUrl
|
||||
await win.show().catch(() => {})
|
||||
loading.value = false
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 贴图加载失败', e)
|
||||
errorMsg.value = '加载图片失败:' + (e as Error).message
|
||||
loading.value = false
|
||||
await win.show().catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
function prev() {
|
||||
if (cur.value >= items.value.length - 1) return
|
||||
void loadImage(cur.value + 1)
|
||||
}
|
||||
|
||||
function next() {
|
||||
if (cur.value <= 0) return
|
||||
void loadImage(cur.value - 1)
|
||||
}
|
||||
|
||||
function closePin() {
|
||||
void win.hide().catch(() => {})
|
||||
}
|
||||
|
||||
/** 左键按下时启动原生窗口拖动(与 OSD 窗口同款方案:
|
||||
* 透明 + focus:false 窗口上 data-tauri-drag-region 不生效,需显式 startDragging) */
|
||||
function onImageMouseDown(e: MouseEvent) {
|
||||
if (e.button !== 0) return
|
||||
e.preventDefault()
|
||||
void win.startDragging().catch(() => {})
|
||||
}
|
||||
|
||||
/** 响应主窗口 'screenshot-pin-show':读取要贴的历史索引并加载显示 */
|
||||
function openPin() {
|
||||
items.value = readHistory()
|
||||
let index = 0
|
||||
try {
|
||||
index = Number(localStorage.getItem(STORAGE_KEYS.screenshotPinIndex) ?? 0) || 0
|
||||
} catch { /* 忽略 */ }
|
||||
void loadImage(index)
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
applyTheme()
|
||||
// 先注册 show 监听再通知 store 就绪,避免首轮事件丢失(与覆盖层同模式)
|
||||
showUnlisten = await listen(EVENTS.screenshotPinShow, () => {
|
||||
openPin()
|
||||
})
|
||||
await emit(EVENTS.screenshotPinReady)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
showUnlisten?.()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pin-root">
|
||||
<!-- 图片区:左键按住自由拖动(显式 startDragging),蓝色光晕阴影 -->
|
||||
<div
|
||||
class="pin-image"
|
||||
:style="{ width: imgCssW + 'px', height: imgCssH + 'px' }"
|
||||
@mousedown="onImageMouseDown"
|
||||
>
|
||||
<img
|
||||
v-if="imgSrc"
|
||||
:src="imgSrc"
|
||||
:style="{ width: imgCssW + 'px', height: imgCssH + 'px' }"
|
||||
draggable="false"
|
||||
alt="贴图"
|
||||
>
|
||||
<div v-else-if="errorMsg" class="pin-tip">{{ errorMsg }}</div>
|
||||
<div v-else-if="loading" class="pin-tip"><Loader2 class="size-5 animate-spin" /></div>
|
||||
</div>
|
||||
|
||||
<!-- 右下角控制:展开图标,hover 展开 上一张 / 下一张 / 关闭 -->
|
||||
<div class="pin-controls">
|
||||
<div class="pin-actions">
|
||||
<button
|
||||
class="pin-btn"
|
||||
title="上一张"
|
||||
:disabled="cur >= items.length - 1"
|
||||
@click="prev"
|
||||
>
|
||||
<ChevronLeft class="size-4" />
|
||||
</button>
|
||||
<button
|
||||
class="pin-btn"
|
||||
title="下一张"
|
||||
:disabled="cur <= 0"
|
||||
@click="next"
|
||||
>
|
||||
<ChevronRight class="size-4" />
|
||||
</button>
|
||||
<button class="pin-btn pin-btn-danger" title="关闭" @click="closePin">
|
||||
<X class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<button class="pin-expand" title="更多操作">
|
||||
<Maximize2 class="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.pin-root {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 18px; /* GLOW_PAD,与脚本常量一致;留白大于光晕扩散范围,避免光晕照出窗口外边框 */
|
||||
background: transparent;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pin-image {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 0; /* 直角 */
|
||||
cursor: grab;
|
||||
/* 散发蓝色光晕的阴影:无实线边框,且扩散范围控制在留白内(光晕小、柔和) */
|
||||
box-shadow:
|
||||
0 0 6px rgba(59, 130, 246, 0.55),
|
||||
0 0 14px rgba(59, 130, 246, 0.3);
|
||||
}
|
||||
|
||||
.pin-image:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
.pin-image img {
|
||||
display: block;
|
||||
user-select: none;
|
||||
-webkit-user-drag: none;
|
||||
}
|
||||
|
||||
.pin-tip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0 16px;
|
||||
box-sizing: border-box;
|
||||
color: rgba(255, 255, 255, 0.9);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
}
|
||||
|
||||
/* 右下角控制:独立于图片拖动区(兄弟节点),点击不触发拖动 */
|
||||
.pin-controls {
|
||||
position: absolute;
|
||||
right: 26px;
|
||||
bottom: 26px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.pin-expand,
|
||||
.pin-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
background: rgba(15, 23, 42, 0.65);
|
||||
backdrop-filter: blur(4px);
|
||||
transition: background-color 0.15s ease;
|
||||
}
|
||||
|
||||
.pin-btn:hover {
|
||||
background: rgba(30, 58, 138, 0.85);
|
||||
}
|
||||
|
||||
.pin-btn-danger:hover {
|
||||
background: rgba(185, 28, 28, 0.85);
|
||||
}
|
||||
|
||||
.pin-btn:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.pin-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
opacity: 0;
|
||||
visibility: hidden;
|
||||
transform: translateX(8px);
|
||||
transition:
|
||||
opacity 0.15s ease,
|
||||
transform 0.15s ease,
|
||||
visibility 0.15s;
|
||||
}
|
||||
|
||||
/* hover 展开三个图标按钮 */
|
||||
.pin-controls:hover .pin-actions,
|
||||
.pin-controls:focus-within .pin-actions {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateX(0);
|
||||
}
|
||||
</style>
|
||||
@@ -5,7 +5,44 @@ const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '截图工具',
|
||||
description: '捕获屏幕截图',
|
||||
keywords: ['截图', '屏幕', 'screenshot', 'capture']
|
||||
keywords: ['截图', '屏幕', 'screenshot', 'capture'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '截图历史',
|
||||
description: '查看和管理截图记录',
|
||||
keywords: ['历史', '记录', 'history', '截图'],
|
||||
tab: 'history'
|
||||
},
|
||||
{
|
||||
title: '截图快捷键',
|
||||
description: '配置全局截图快捷键',
|
||||
keywords: ['快捷键', '热键', 'shortcut', 'hotkey', '截图'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '贴图快捷键',
|
||||
description: '配置全局贴图快捷键',
|
||||
keywords: ['贴图', '快捷键', 'pin', 'shortcut'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '延时截图',
|
||||
description: '设置截图延时秒数',
|
||||
keywords: ['延时', '延迟', 'delay', '定时截图'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '自动保存到目录',
|
||||
description: '截图完成后自动保存到指定目录',
|
||||
keywords: ['自动保存', '目录', '路径', 'save', 'dir'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '历史保留数量',
|
||||
description: '设置截图历史记录保留上限',
|
||||
keywords: ['历史', '数量', '上限', 'history', 'limit'],
|
||||
tab: 'settings'
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -1,27 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
import { Monitor, Sun, Moon, Sparkles, Layers, LogOut, Package, GripVertical } from '@lucide/vue'
|
||||
import { Monitor, Sun, Moon, Sparkles, Layers, LogOut, Package, GripVertical, Info, RefreshCw, Download, Check, Loader2 } from '@lucide/vue'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
import { useAppStore, type Theme, type EffectType, type ModuleInfo } from '@/stores/appStore'
|
||||
import { useSearchStore } from '@/stores/searchStore'
|
||||
import { useProcessStore } from '@/stores/processStore'
|
||||
import { getModuleIcon } from '@/modules/icons'
|
||||
import { commands, type UpdateCheckResult } from '@/lib/bindings'
|
||||
import { EVENTS } from '@/lib/constants'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { VueDraggable } from 'vue-draggable-plus'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const searchStore = useSearchStore()
|
||||
const processStore = useProcessStore()
|
||||
|
||||
// ===== 关于 / 更新 =====
|
||||
|
||||
/** 更新进度事件载荷(与 Rust UpdateProgress 对应) */
|
||||
interface UpdateProgress {
|
||||
stage: string
|
||||
percent: number
|
||||
downloadedBytes: number
|
||||
totalBytes: number | null
|
||||
message: string
|
||||
}
|
||||
|
||||
/** 当前应用版本(启动时读取) */
|
||||
const currentVersion = ref('')
|
||||
/** 检查更新的结果 */
|
||||
const updateResult = ref<UpdateCheckResult | null>(null)
|
||||
const checking = ref(false)
|
||||
/** 应用本体更新中 */
|
||||
const appUpdating = ref(false)
|
||||
/** ThingHK 内核更新中 */
|
||||
const kernelUpdating = ref(false)
|
||||
const progress = ref<UpdateProgress | null>(null)
|
||||
const thinghkExists = ref(false)
|
||||
let progressUnlisten: UnlistenFn | null = null
|
||||
|
||||
const installTypeText = computed(() =>
|
||||
updateResult.value?.installType === 'installed' ? '安装版' : '便携版',
|
||||
)
|
||||
|
||||
const loadAppInfo = async () => {
|
||||
try {
|
||||
currentVersion.value = await commands.appVersion()
|
||||
} catch { /* 忽略:后端未就绪 */ }
|
||||
try {
|
||||
const info = await invoke('monitor_kernel_info') as { exists?: boolean }
|
||||
thinghkExists.value = info?.exists ?? false
|
||||
} catch { /* 忽略:内核未就绪 */ }
|
||||
}
|
||||
|
||||
/** 检查 Gitea 最新 release */
|
||||
const checkUpdate = async () => {
|
||||
if (checking.value || appUpdating.value) return
|
||||
checking.value = true
|
||||
try {
|
||||
updateResult.value = await commands.updateCheck()
|
||||
} catch (e) {
|
||||
console.error('[updater] 检查更新失败', e)
|
||||
} finally {
|
||||
checking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载并应用应用更新(便携版替换 exe / 安装版静默安装),触发应用退出重启 */
|
||||
const installUpdate = async () => {
|
||||
if (appUpdating.value) return
|
||||
appUpdating.value = true
|
||||
try {
|
||||
await commands.updateInstall()
|
||||
} catch (e) {
|
||||
console.error('[updater] 应用更新失败', e)
|
||||
appUpdating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 更新 ThingHK 内核:后端先停止监控内核再覆盖文件 */
|
||||
const updateThinghkKernel = async () => {
|
||||
if (kernelUpdating.value) return
|
||||
kernelUpdating.value = true
|
||||
try {
|
||||
await commands.updateThinghk()
|
||||
await loadAppInfo()
|
||||
} catch (e) {
|
||||
console.error('[updater] ThingHK 更新失败', e)
|
||||
} finally {
|
||||
kernelUpdating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 系统真实深浅色偏好,来自 appStore(应用启动时初始化,仅通过 onThemeChanged 更新,
|
||||
// 不受 setTheme 污染),用于"跟随系统"卡片色块。
|
||||
const systemDark = computed(() => appStore.systemDark)
|
||||
|
||||
onMounted(() => {
|
||||
loadAppInfo()
|
||||
// 监听更新进度事件(应用更新与 ThingHK 内核更新共用)
|
||||
listen<UpdateProgress>(EVENTS.updateProgress, (e) => {
|
||||
progress.value = e.payload
|
||||
if (e.payload.stage === 'done') {
|
||||
kernelUpdating.value = false
|
||||
progress.value = null
|
||||
}
|
||||
}).then((fn) => {
|
||||
progressUnlisten = fn
|
||||
})
|
||||
searchStore.registerAction('settings', 0, () => appStore.setTheme('light'))
|
||||
searchStore.registerAction('settings', 1, () => appStore.setTheme('dark'))
|
||||
searchStore.registerAction('settings', 2, () => appStore.setTheme('system'))
|
||||
@@ -29,6 +121,19 @@ onMounted(() => {
|
||||
searchStore.registerAction('settings', 4, () => appStore.setEffect('mica'))
|
||||
searchStore.registerAction('settings', 5, () => appStore.setEffect('acrylic'))
|
||||
searchStore.registerAction('settings', 6, () => appStore.toggleAutoStart())
|
||||
// 新增设置项(模块管理/关于/退出):仅定位滚动到对应卡片
|
||||
searchStore.registerAction('settings', 7, () => scrollToCard('settings-card-modules'))
|
||||
searchStore.registerAction('settings', 8, () => scrollToCard('settings-card-about'))
|
||||
searchStore.registerAction('settings', 9, () => scrollToCard('settings-card-about'))
|
||||
searchStore.registerAction('settings', 10, () => scrollToCard('settings-card-about'))
|
||||
searchStore.registerAction('settings', 11, () => scrollToCard('settings-card-quit'))
|
||||
// 主动刷新所有进程状态,确保内核 badge 显示当前真实状态(而非过期缓存)
|
||||
processStore.refreshAll().catch(() => { /* 忽略:后端可能未就绪 */ })
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
progressUnlisten?.()
|
||||
progressUnlisten = null
|
||||
})
|
||||
|
||||
const themes: Array<{ id: Theme; name: string; color: string; icon: typeof Sun }> = [
|
||||
@@ -80,6 +185,25 @@ const quitApp = async () => {
|
||||
await invoke('quit_app')
|
||||
}
|
||||
|
||||
/** 滚动到指定卡片(搜索导航定位用)。
|
||||
* 模块为异步加载,若卡片尚未渲染则短暂重试,直到模块挂载完成。 */
|
||||
const scrollToCard = (id: string) => {
|
||||
const tryScroll = (): boolean => {
|
||||
const el = document.getElementById(id)
|
||||
if (!el) return false
|
||||
el.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
return true
|
||||
}
|
||||
if (tryScroll()) return
|
||||
let attempts = 0
|
||||
const timer = window.setInterval(() => {
|
||||
attempts++
|
||||
if (tryScroll() || attempts >= 20) {
|
||||
window.clearInterval(timer)
|
||||
}
|
||||
}, 100)
|
||||
}
|
||||
|
||||
/** 判断模块开关是否处于处理中状态 */
|
||||
const isModuleToggling = (moduleId: string): boolean => {
|
||||
return appStore.togglingModules.has(moduleId)
|
||||
@@ -132,7 +256,7 @@ const onDragEnd = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<Sparkles class="h-5 w-5 text-primary" />
|
||||
<Sparkles class="size-5 text-primary" />
|
||||
常规设置
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -153,7 +277,7 @@ const onDragEnd = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<Layers class="h-5 w-5 text-primary" />
|
||||
<Layers class="size-5 text-primary" />
|
||||
主题切换
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -175,7 +299,7 @@ const onDragEnd = () => {
|
||||
>
|
||||
<component
|
||||
:is="theme.icon"
|
||||
class="h-8 w-8 transition-colors duration-300"
|
||||
class="size-8 transition-colors duration-300"
|
||||
:class="theme.id === 'dark' || (theme.id === 'system' && systemDark) ? 'text-white' : 'text-gray-800'"
|
||||
/>
|
||||
</div>
|
||||
@@ -198,7 +322,7 @@ const onDragEnd = () => {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<Sparkles class="h-5 w-5 text-primary" />
|
||||
<Sparkles class="size-5 text-primary" />
|
||||
效果切换
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -241,10 +365,10 @@ const onDragEnd = () => {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Card id="settings-card-modules">
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<Package class="h-5 w-5 text-primary" />
|
||||
<Package class="size-5 text-primary" />
|
||||
模块管理
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -271,7 +395,7 @@ const onDragEnd = () => {
|
||||
<div
|
||||
class="drag-handle cursor-grab active:cursor-grabbing text-muted-foreground/40 hover:text-muted-foreground transition-colors"
|
||||
>
|
||||
<GripVertical class="h-4 w-4 no-native-drag" />
|
||||
<GripVertical class="size-4 no-native-drag" />
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>拖拽排序</TooltipContent>
|
||||
@@ -280,7 +404,7 @@ const onDragEnd = () => {
|
||||
class="w-9 h-9 rounded-lg flex items-center justify-center"
|
||||
:class="module.enabled ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
|
||||
>
|
||||
<component :is="getModuleIcon(module.icon)" class="h-5 w-5" />
|
||||
<component :is="getModuleIcon(module.icon)" class="size-5" />
|
||||
</div>
|
||||
<div>
|
||||
<div class="font-medium text-sm flex items-center gap-2">
|
||||
@@ -311,10 +435,107 @@ const onDragEnd = () => {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<Card id="settings-card-about">
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<LogOut class="h-5 w-5 text-destructive" />
|
||||
<Info class="size-5 text-primary" />
|
||||
关于
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-1">
|
||||
<!-- 应用版本 + 检查更新 -->
|
||||
<div class="flex items-center justify-between py-2">
|
||||
<div class="space-y-1">
|
||||
<Label class="text-base font-medium">应用版本</Label>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Thing v{{ currentVersion || '…' }}
|
||||
<span v-if="updateResult" class="ml-1 text-xs px-1.5 py-0.5 rounded-full bg-muted">
|
||||
{{ installTypeText }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="checking || appUpdating"
|
||||
@click="checkUpdate"
|
||||
>
|
||||
<RefreshCw v-if="!checking" class="size-3.5 mr-1.5" />
|
||||
<Loader2 v-else class="size-3.5 mr-1.5 animate-spin" />
|
||||
{{ checking ? '检查中...' : '检查更新' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- 更新结果 -->
|
||||
<div v-if="updateResult" class="rounded-lg border border-border/50 p-3 space-y-2">
|
||||
<div v-if="updateResult.hasUpdate" class="space-y-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm font-medium">
|
||||
发现新版本 v{{ updateResult.latestVersion }}
|
||||
</span>
|
||||
<span class="text-xs text-muted-foreground">当前 v{{ updateResult.currentVersion }}</span>
|
||||
</div>
|
||||
<p
|
||||
v-if="updateResult.releaseBody"
|
||||
class="text-xs text-muted-foreground whitespace-pre-wrap max-h-20 overflow-y-auto"
|
||||
>
|
||||
{{ updateResult.releaseBody }}
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button size="sm" :disabled="appUpdating" @click="installUpdate">
|
||||
<Download class="size-3.5 mr-1.5" />
|
||||
{{ appUpdating ? '更新中...' : '下载并更新' }}
|
||||
</Button>
|
||||
<span class="text-xs text-muted-foreground">
|
||||
{{ installTypeText === '安装版' ? '将静默安装新版并重启' : '将替换程序文件并重启' }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="flex items-center gap-1.5 text-sm text-muted-foreground">
|
||||
<Check class="size-4 text-green-500" />
|
||||
已是最新版本
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 应用更新进度 -->
|
||||
<div v-if="appUpdating && progress" class="space-y-1.5 py-1">
|
||||
<div class="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{{ progress.message }}</span>
|
||||
<span class="font-mono">{{ progress.percent }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="progress.percent" />
|
||||
</div>
|
||||
|
||||
<!-- ThingHK 内核 -->
|
||||
<div class="flex items-center justify-between py-2 border-t border-border/50">
|
||||
<div class="space-y-1">
|
||||
<Label class="text-base font-medium">ThingHK 内核</Label>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
{{ thinghkExists ? '已安装' : '未安装' }} · 更新前请先停用监控模块
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" :disabled="kernelUpdating" @click="updateThinghkKernel">
|
||||
<Loader2 v-if="kernelUpdating && !progress" class="size-3.5 mr-1.5 animate-spin" />
|
||||
<Package v-else class="size-3.5 mr-1.5" />
|
||||
{{ kernelUpdating ? '更新中...' : '更新内核' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!-- ThingHK 更新进度 -->
|
||||
<div v-if="kernelUpdating && progress" class="space-y-1.5 py-1">
|
||||
<div class="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>{{ progress.message }}</span>
|
||||
<span class="font-mono">{{ progress.percent }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="progress.percent" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card id="settings-card-quit">
|
||||
<CardHeader>
|
||||
<CardTitle class="flex items-center gap-2">
|
||||
<LogOut class="size-5 text-destructive" />
|
||||
退出程序
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
@@ -324,7 +545,7 @@ const onDragEnd = () => {
|
||||
class="text-destructive border-destructive/20 hover:bg-destructive/10"
|
||||
@click="quitApp"
|
||||
>
|
||||
<LogOut class="h-4 w-4 mr-2" />
|
||||
<LogOut class="size-4 mr-2" />
|
||||
彻底退出
|
||||
</Button>
|
||||
</CardContent>
|
||||
|
||||
@@ -37,6 +37,31 @@ const searchItems: SearchIndexItem[] = [
|
||||
title: '开机自启',
|
||||
description: '启动 Windows 时自动运行应用',
|
||||
keywords: ['开机', '自启', '自动', 'auto', 'start']
|
||||
},
|
||||
{
|
||||
title: '模块管理',
|
||||
description: '启用/禁用模块与拖拽排序',
|
||||
keywords: ['模块', '管理', '排序', '禁用', '启用', 'module']
|
||||
},
|
||||
{
|
||||
title: '检查更新',
|
||||
description: '检查并下载应用新版本',
|
||||
keywords: ['更新', '版本', '升级', 'update', 'check', 'release']
|
||||
},
|
||||
{
|
||||
title: '应用版本',
|
||||
description: '查看当前应用版本与安装方式',
|
||||
keywords: ['版本', 'version', 'about', '关于']
|
||||
},
|
||||
{
|
||||
title: 'ThingHK 内核',
|
||||
description: '查看监控内核安装状态并更新',
|
||||
keywords: ['内核', 'thinghk', 'kernel', '监控', '更新']
|
||||
},
|
||||
{
|
||||
title: '退出程序',
|
||||
description: '彻底退出 Thing 应用',
|
||||
keywords: ['退出', '关闭', 'quit', 'exit', '结束']
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@@ -38,8 +38,17 @@ const state = reactive<TrayMenuState>({
|
||||
const loadingAction = ref<string | null>(null)
|
||||
const refreshing = ref(false)
|
||||
const osdVisible = ref(false)
|
||||
const nodeSelectOpen = ref(false)
|
||||
let unlistenFns: UnlistenFn[] = []
|
||||
|
||||
/** 菜单关闭/失焦前重置状态:关闭节点下拉框并取消所有焦点,避免下次打开时残留 */
|
||||
function resetMenuState() {
|
||||
nodeSelectOpen.value = false
|
||||
if (document.activeElement instanceof HTMLElement) {
|
||||
document.activeElement.blur()
|
||||
}
|
||||
}
|
||||
|
||||
function readOsdVisible(): boolean {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.monitorOsdConfig)
|
||||
@@ -260,6 +269,8 @@ const sortedNodes = computed(() => {
|
||||
})
|
||||
|
||||
async function handleAction(action: string, payload?: Record<string, unknown>) {
|
||||
// 点击菜单项即关闭下拉并取消焦点,避免下次打开残留
|
||||
resetMenuState()
|
||||
try { await invoke('tray_menu_hide') } catch { /* 忽略 */ }
|
||||
|
||||
if (action === 'proxy_refresh') refreshing.value = true
|
||||
@@ -305,6 +316,7 @@ function delayClass(delay: number | null): string {
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
resetMenuState()
|
||||
invoke('tray_menu_hide').catch(() => {})
|
||||
}
|
||||
}
|
||||
@@ -410,9 +422,16 @@ onMounted(async () => {
|
||||
await applyTheme()
|
||||
Object.assign(state, event.payload)
|
||||
osdVisible.value = readOsdVisible()
|
||||
// 显示前重置上次残留的下拉/焦点状态(双保险)
|
||||
resetMenuState()
|
||||
await measureAndShow()
|
||||
}))
|
||||
|
||||
// 菜单失焦(点击其他位置自动隐藏)时重置下拉框与焦点,避免下次打开时残留
|
||||
unlistenFns.push(await getCurrentWindow().onFocusChanged(({ payload: focused }) => {
|
||||
if (!focused) resetMenuState()
|
||||
}))
|
||||
|
||||
// 仅更新状态数据,不重新显示窗口。
|
||||
// 动作完成后的状态更新不应让已隐藏的菜单重新弹出(measureAndShow 会触发 win.show)。
|
||||
// 菜单显示统一由右键托盘触发的 tray-menu-show 事件负责。
|
||||
@@ -433,7 +452,7 @@ onUnmounted(() => {
|
||||
<div class="tray-menu-scroll flex-1 min-h-0 overflow-y-auto">
|
||||
<div class="tray-section">
|
||||
<div class="tray-section-header">
|
||||
<Globe class="h-4 w-4 text-primary" />
|
||||
<Globe class="size-4 text-primary" />
|
||||
<span class="tray-section-title">代理</span>
|
||||
<span v-if="state.proxyRunning" class="tray-status-dot running"></span>
|
||||
<span v-else class="tray-status-dot stopped"></span>
|
||||
@@ -441,12 +460,12 @@ onUnmounted(() => {
|
||||
|
||||
<div class="tray-section-body">
|
||||
<button class="tray-item" :disabled="proxyLoading" @click="handleProxyToggle">
|
||||
<component :is="proxyButtonIcon" class="h-4 w-4" />
|
||||
<component :is="proxyButtonIcon" class="size-4" />
|
||||
<span>{{ proxyButtonLabel }}</span>
|
||||
</button>
|
||||
|
||||
<button v-if="state.proxyRunning" class="tray-item" :disabled="proxyLoading" @click="handleSystemProxyToggle">
|
||||
<Power class="h-4 w-4" />
|
||||
<Power class="size-4" />
|
||||
<span>系统代理</span>
|
||||
<span class="tray-toggle-indicator" :class="{ active: state.systemProxy }"></span>
|
||||
</button>
|
||||
@@ -457,7 +476,7 @@ onUnmounted(() => {
|
||||
:disabled="proxyLoading"
|
||||
@click="handleAction('proxy_refresh')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" :class="{ 'animate-spin': refreshing }" />
|
||||
<RefreshCw class="size-4" :class="{ 'animate-spin': refreshing }" />
|
||||
<span>刷新节点列表</span>
|
||||
</button>
|
||||
|
||||
@@ -465,6 +484,7 @@ onUnmounted(() => {
|
||||
<label class="tray-node-label">节点</label>
|
||||
<Select
|
||||
:model-value="state.proxyCurrent ?? ''"
|
||||
v-model:open="nodeSelectOpen"
|
||||
:disabled="proxyLoading"
|
||||
@update:model-value="handleSelectNode"
|
||||
>
|
||||
@@ -482,7 +502,7 @@ onUnmounted(() => {
|
||||
:value="node.name"
|
||||
class="tray-select-option"
|
||||
>
|
||||
<Check v-if="node.isCurrent" class="h-3 w-3 text-primary flex-shrink-0" />
|
||||
<Check v-if="node.isCurrent" class="size-3 text-primary flex-shrink-0" />
|
||||
<span class="tray-select-badge-option">{{ abbreviateNodeName(node.name) }}</span>
|
||||
<span class="tray-select-delay" :class="delayClass(node.delay)">
|
||||
{{ delayText(node.delay) }}
|
||||
@@ -498,7 +518,7 @@ onUnmounted(() => {
|
||||
|
||||
<div class="tray-section">
|
||||
<div class="tray-section-header">
|
||||
<Monitor class="h-4 w-4 text-primary" />
|
||||
<Monitor class="size-4 text-primary" />
|
||||
<span class="tray-section-title">监控</span>
|
||||
<span v-if="state.monitorRunning" class="tray-status-dot running"></span>
|
||||
<span v-else class="tray-status-dot stopped"></span>
|
||||
@@ -506,7 +526,7 @@ onUnmounted(() => {
|
||||
|
||||
<div class="tray-section-body">
|
||||
<button class="tray-item" @click="handleAction('osd_toggle')">
|
||||
<Monitor class="h-4 w-4" />
|
||||
<Monitor class="size-4" />
|
||||
<span>OSD 显示</span>
|
||||
<span class="tray-toggle-indicator" :class="{ active: osdVisible }"></span>
|
||||
</button>
|
||||
@@ -515,7 +535,7 @@ onUnmounted(() => {
|
||||
:disabled="!state.monitorRunning"
|
||||
@click="handleAction('kernel_restart')"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
<RefreshCw class="size-4" />
|
||||
<span>重启 Kernel</span>
|
||||
</button>
|
||||
</div>
|
||||
@@ -524,18 +544,18 @@ onUnmounted(() => {
|
||||
<div class="tray-separator"></div>
|
||||
|
||||
<button class="tray-item" @click="handleAction('download_new')">
|
||||
<Download class="h-4 w-4" />
|
||||
<Download class="size-4" />
|
||||
<span>新建下载</span>
|
||||
</button>
|
||||
|
||||
<div class="tray-separator"></div>
|
||||
|
||||
<button class="tray-item" @click="handleAction('settings')">
|
||||
<Settings class="h-4 w-4" />
|
||||
<Settings class="size-4" />
|
||||
<span>常规设置</span>
|
||||
</button>
|
||||
<button class="tray-item tray-quit" @click="handleAction('quit')">
|
||||
<LogOut class="h-4 w-4" />
|
||||
<LogOut class="size-4" />
|
||||
<span>退出</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -247,7 +247,8 @@ export const useAppStore = defineStore('app', () => {
|
||||
moduleId,
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
keywords: item.keywords
|
||||
keywords: item.keywords,
|
||||
tab: item.tab
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -43,6 +43,8 @@ export const useClipboardStore = defineStore('clipboard', () => {
|
||||
const settings = ref<ClipboardSettings>({ ...DEFAULT_SETTINGS })
|
||||
const status = ref<ClipboardStatus>({ running: false, count: 0 })
|
||||
const loading = ref(false)
|
||||
/** 是否已完成首次加载:再次进入模块时 store 已有缓存,可即时渲染而非再弹骨架屏 */
|
||||
const initialized = ref(false)
|
||||
|
||||
// 事件监听(应用级单例,只注册一次)
|
||||
let changedUnlisten: UnlistenFn | null = null
|
||||
@@ -238,6 +240,7 @@ export const useClipboardStore = defineStore('clipboard', () => {
|
||||
settings,
|
||||
status,
|
||||
loading,
|
||||
initialized,
|
||||
init,
|
||||
dispose,
|
||||
fetchHistoryPage,
|
||||
|
||||
@@ -74,11 +74,21 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
try {
|
||||
// Rust 端序列化保证字段完整,断言为 Required 收窄后的类型
|
||||
const fresh = (await commands.downloaderGetTasks()) as DownloadTask[]
|
||||
// merge 化:保留本地仍在更新的任务对象(进度事件可能刚修改过它),
|
||||
// 避免整体替换导致进行中任务的实时进度/速度被快照回退
|
||||
// merge 化:进行中任务保留本地实时进度,避免快照回退;
|
||||
// 暂停/终态(paused/complete/error)时 Rust 端已同步完整进度(完成时
|
||||
// completed_size 已对齐 total_size),整体替换为服务端快照,
|
||||
// 避免本地旧进度覆盖导致"已完成但停在 99%"的状态不一致
|
||||
const merged = fresh.map(freshTask => {
|
||||
if (
|
||||
freshTask.status === 'paused' ||
|
||||
freshTask.status === 'complete' ||
|
||||
freshTask.status === 'error'
|
||||
) {
|
||||
return freshTask
|
||||
}
|
||||
const local = tasks.value.find(t => t.id === freshTask.id)
|
||||
return local ?? freshTask
|
||||
if (!local) return freshTask
|
||||
return { ...local, status: freshTask.status, error: freshTask.error }
|
||||
})
|
||||
tasks.value = merged
|
||||
} catch (e) {
|
||||
@@ -91,6 +101,10 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
const updateTaskProgress = (payload: ProgressPayload) => {
|
||||
const task = tasks.value.find((t) => t.id === payload.id)
|
||||
if (task) {
|
||||
// 终态任务忽略迟到的进度事件(下载完成后 in-flight 事件可能把状态/进度回退)
|
||||
if (task.status === 'complete' || task.status === 'error') return
|
||||
// 已暂停任务忽略仍携带 active 的迟到事件(暂停瞬间发出的旧事件)
|
||||
if (task.status === 'paused' && payload.status === 'active') return
|
||||
task.completedSize = payload.completedSize
|
||||
task.totalSize = payload.totalSize
|
||||
task.speed = payload.speed
|
||||
|
||||
@@ -28,6 +28,27 @@ export const useModuleTabsStore = defineStore('moduleTabs', () => {
|
||||
/** 是否显示浮动切换器(TabsList 滚出可视区时为 true) */
|
||||
const floatingVisible = ref<boolean>(false)
|
||||
|
||||
/** 待跳转 tab(搜索导航设置):{ moduleId, tab },模块挂载/已挂载时消费 */
|
||||
const pendingTab = ref<{ moduleId: string; tab: string } | null>(null)
|
||||
|
||||
/** 设置待跳转 tab(搜索结果点击时调用) */
|
||||
const setPendingTab = (moduleId: string, tab: string) => {
|
||||
pendingTab.value = { moduleId, tab }
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费指定模块的待跳转 tab(返回 tab 值并清除)。
|
||||
* 仅在 moduleId 匹配时消费,避免误切当前已挂载模块的 tab。
|
||||
*/
|
||||
const consumePendingTab = (moduleId: string): string | null => {
|
||||
if (pendingTab.value && pendingTab.value.moduleId === moduleId) {
|
||||
const tab = pendingTab.value.tab
|
||||
pendingTab.value = null
|
||||
return tab
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 当前模块注册的保存处理函数(null 表示无保存按钮,如自动保存模块) */
|
||||
const saveHandler = ref<(() => unknown) | null>(null)
|
||||
/** 保存中状态(驱动按钮 disabled + loading 图标) */
|
||||
@@ -93,6 +114,7 @@ export const useModuleTabsStore = defineStore('moduleTabs', () => {
|
||||
tabs,
|
||||
activeTab,
|
||||
floatingVisible,
|
||||
pendingTab,
|
||||
saveHandler,
|
||||
saving,
|
||||
saveVisible,
|
||||
@@ -100,6 +122,8 @@ export const useModuleTabsStore = defineStore('moduleTabs', () => {
|
||||
unregisterTabs,
|
||||
setFloatingVisible,
|
||||
setActiveTab,
|
||||
setPendingTab,
|
||||
consumePendingTab,
|
||||
registerSave,
|
||||
runSave
|
||||
}
|
||||
|
||||
@@ -325,6 +325,9 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
/** 提权标志是否已启用(后续启动自动触发 UAC) */
|
||||
const elevateOnLaunch = ref(false)
|
||||
|
||||
/** "应用启动时自动启动监控内核"开关(持久化于后端 settings.json) */
|
||||
const autoStart = ref(false)
|
||||
|
||||
/** 硬件监控配置(可用硬件 + 传感器类型清单 + 当前启用状态) */
|
||||
const hardwareConfig = ref<HardwareConfigResponse | null>(null)
|
||||
|
||||
@@ -540,6 +543,27 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 刷新"自动启动监控内核"开关状态 */
|
||||
async function refreshAutoStart() {
|
||||
try {
|
||||
autoStart.value = await invoke<boolean>('monitor_get_auto_start')
|
||||
} catch (e) {
|
||||
logger.error('获取自动启动开关失败: ' + e)
|
||||
}
|
||||
return autoStart.value
|
||||
}
|
||||
|
||||
/** 设置"自动启动监控内核"开关 */
|
||||
async function setAutoStart(enabled: boolean) {
|
||||
try {
|
||||
await invoke('monitor_set_auto_start', { enabled })
|
||||
autoStart.value = enabled
|
||||
} catch (e) {
|
||||
errorMsg.value = String(e)
|
||||
logger.error('设置自动启动开关失败: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 拉取硬件监控配置(可用硬件 + 传感器类型清单 + 当前启用状态) */
|
||||
async function fetchHardwareConfig() {
|
||||
try {
|
||||
@@ -641,7 +665,7 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
try {
|
||||
// 启动心跳,驱动 connState 的断线判定(SSE 断开后依赖不再变化,须有心跳触发重算)
|
||||
startHeartbeat()
|
||||
await Promise.all([refreshStatus(), refreshKernelInfo(), refreshElevateOnLaunch()])
|
||||
await Promise.all([refreshStatus(), refreshKernelInfo(), refreshElevateOnLaunch(), refreshAutoStart()])
|
||||
await subscribe()
|
||||
// 若 Kernel 已就绪,立即拉一次快照避免 UI 空白
|
||||
if (status.value?.ready) {
|
||||
@@ -956,18 +980,14 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
// 注册 OSD 窗口事件监听
|
||||
setupOsdEventListeners().catch(e => logger.error('[OSD] 事件监听注册失败: ' + e))
|
||||
|
||||
// 监听托盘菜单"切换 OSD"事件(应用级常驻,不随模块挂载/卸载变化)
|
||||
// 监听托盘菜单"切换 OSD"事件(应用级常驻,不随模块挂载/卸载变化)。
|
||||
// 只修改 overlayEnabled,窗口显示/隐藏统一由下方 store watch 处理,
|
||||
// 与主界面 OSD 开关(updateOsdConfig)走完全相同的路径,避免双 hide 竞态。
|
||||
listen(EVENTS.trayToggleOsd, () => {
|
||||
osdConfig.value.overlayEnabled = !osdConfig.value.overlayEnabled
|
||||
saveOsdConfig(osdConfig.value)
|
||||
if (osdConfig.value.overlayEnabled) {
|
||||
if (osdConfig.value.overlayItems.length === 0) {
|
||||
if (osdConfig.value.overlayEnabled && osdConfig.value.overlayItems.length === 0) {
|
||||
toast.warning('OSD 显示项为空,已开启但未创建窗口')
|
||||
} else {
|
||||
ensureOverlayWindow().catch(e => logger.error('[OSD] 托盘开启悬浮窗失败: ' + e))
|
||||
}
|
||||
} else {
|
||||
hideOverlayWindow().catch(e => logger.error('[OSD] 托盘关闭悬浮窗失败: ' + e))
|
||||
}
|
||||
}).then(unlisten => { osdEventUnlisteners.push(unlisten) })
|
||||
.catch(e => logger.error('[OSD] 注册 tray:toggle-osd 监听失败: ' + e))
|
||||
@@ -978,6 +998,11 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
// OSD 开关变化时创建/隐藏悬浮窗
|
||||
osdWatchStops.push(watch(() => osdConfig.value.overlayEnabled, (enabled) => {
|
||||
if (enabled) {
|
||||
// OSD 显示开启时自动开启"应用启动时自动启动监控内核",
|
||||
// 使 OSD 持续显示不因重启而中断
|
||||
if (!autoStart.value) {
|
||||
setAutoStart(true).catch(e => logger.error('[OSD] 自动开启 autoStart 失败: ' + e))
|
||||
}
|
||||
// 开启时若显示项为空则不创建窗口
|
||||
if (osdConfig.value.overlayItems.length === 0) return
|
||||
ensureOverlayWindow().catch(e => logger.error('[OSD] 创建悬浮窗失败: ' + e))
|
||||
@@ -1061,6 +1086,7 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
initialized,
|
||||
networkSpeed,
|
||||
elevateOnLaunch,
|
||||
autoStart,
|
||||
hardwareConfig,
|
||||
// getters
|
||||
connState,
|
||||
@@ -1071,6 +1097,8 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
refreshStatus,
|
||||
refreshKernelInfo,
|
||||
refreshElevateOnLaunch,
|
||||
refreshAutoStart,
|
||||
setAutoStart,
|
||||
start,
|
||||
elevateSelf,
|
||||
cancelElevation,
|
||||
|
||||
@@ -41,6 +41,14 @@ export const useProcessStore = defineStore('process', () => {
|
||||
})
|
||||
}
|
||||
|
||||
/** 释放进程状态事件监听(应用退出或热重载时调用) */
|
||||
const destroyListener = () => {
|
||||
if (unlistenFn) {
|
||||
unlistenFn()
|
||||
unlistenFn = null
|
||||
}
|
||||
}
|
||||
|
||||
/** 通过模块 ID 启动进程(自动从注册表读取进程配置) */
|
||||
const startByModule = async (moduleId: string): Promise<ProcessInfo> => {
|
||||
const config = moduleRegistry.getConfig(moduleId)
|
||||
@@ -104,6 +112,7 @@ export const useProcessStore = defineStore('process', () => {
|
||||
return {
|
||||
processes,
|
||||
initListener,
|
||||
destroyListener,
|
||||
startByModule,
|
||||
stopByModule,
|
||||
refreshStatus,
|
||||
|
||||
@@ -191,6 +191,15 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
return settings.value
|
||||
}
|
||||
|
||||
/** 刷新系统代理真实状态(读取 Windows 注册表,不依赖 settings.json 缓存) */
|
||||
const refreshSystemProxy = async () => {
|
||||
try {
|
||||
systemProxy.value = await commands.proxyGetSystemProxy()
|
||||
} catch {
|
||||
/* 忽略:后端可能未就绪 */
|
||||
}
|
||||
}
|
||||
|
||||
const saveSettings = async (s: FullProxySettings) => {
|
||||
await commands.proxySaveSettings(s)
|
||||
settings.value = s
|
||||
@@ -342,6 +351,7 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
// kernel & process
|
||||
refreshKernel,
|
||||
refreshStatus,
|
||||
refreshSystemProxy,
|
||||
start,
|
||||
stop,
|
||||
restart,
|
||||
|
||||
+254
-13
@@ -5,7 +5,7 @@ import { PhysicalPosition, PhysicalSize } from '@tauri-apps/api/dpi'
|
||||
import { availableMonitors } from '@tauri-apps/api/window'
|
||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { EVENTS, WINDOWS } from '@/lib/constants'
|
||||
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
|
||||
@@ -19,6 +19,9 @@ export interface RecentCapture {
|
||||
height: number
|
||||
time: number
|
||||
mode: string
|
||||
/** 截图时框选区域的物理屏幕坐标(贴图窗口按原位置显示;编辑器导出可能缺失) */
|
||||
posX?: number
|
||||
posY?: number
|
||||
}
|
||||
|
||||
/** 截图设置(localStorage 持久化) */
|
||||
@@ -31,16 +34,21 @@ export interface ScreenshotSettings {
|
||||
historyLimit: number
|
||||
/** 全局截图快捷键(空字符串表示禁用) */
|
||||
shortcut: string
|
||||
/** 贴图全局快捷键(空字符串表示禁用),再次按下关闭贴图 */
|
||||
pinShortcut: string
|
||||
/** 截图延时(秒),0 表示立即截图 */
|
||||
delay: number
|
||||
}
|
||||
|
||||
const SETTINGS_KEY = 'screenshot-settings'
|
||||
/** 设置版本:结构变更(默认值/字段增删)时递增,清除旧数据以应用新默认值 */
|
||||
const SETTINGS_VERSION = 2
|
||||
const DEFAULT_SETTINGS: ScreenshotSettings = {
|
||||
autoSave: false,
|
||||
saveDir: '',
|
||||
historyLimit: 12,
|
||||
shortcut: 'ctrl+alt+a',
|
||||
historyLimit: 48,
|
||||
shortcut: 'ctrl+1',
|
||||
pinShortcut: 'alt+1',
|
||||
delay: 0,
|
||||
}
|
||||
|
||||
@@ -51,6 +59,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
|
||||
let exportUnlisten: UnlistenFn | null = null
|
||||
let shortcutUnlisten: UnlistenFn | null = null
|
||||
/** 覆盖层就绪事件监听(initOverlay 注册,destroyExportListener 一并释放) */
|
||||
let overlayReadyUnlisten: UnlistenFn | null = null
|
||||
/** 常驻截图覆盖层窗口(启动时创建,之后每次截图复用,避免重复 WebView 初始化) */
|
||||
const OVERLAY_LABEL = WINDOWS.screenshotOverlay
|
||||
let overlayWin: WebviewWindow | null = null
|
||||
@@ -58,14 +68,36 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
let overlayReadyPromise: Promise<void> | null = null
|
||||
let readyListenerInit = false
|
||||
|
||||
// ===== 贴图窗口 =====
|
||||
const PIN_LABEL = WINDOWS.screenshotPin
|
||||
const PIN_INDEX_KEY = STORAGE_KEYS.screenshotPinIndex
|
||||
/** 常驻贴图窗口(首次贴图时创建,之后复用;无边框透明置顶) */
|
||||
let pinWin: WebviewWindow | null = null
|
||||
let pinReadyUnlisten: UnlistenFn | null = null
|
||||
let pinReadyListenerInit = false
|
||||
let pinReadyResolve: (() => void) | null = null
|
||||
let pinReadyPromise: Promise<void> | null = null
|
||||
/** 贴图全局快捷键事件监听 */
|
||||
let pinShortcutUnlisten: UnlistenFn | null = null
|
||||
|
||||
// ===== 历史持久化 =====
|
||||
const HISTORY_KEY = STORAGE_KEYS.screenshotHistory
|
||||
const HISTORY_VERSION = 1
|
||||
|
||||
// ===== 设置持久化 =====
|
||||
function loadSettings() {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_KEY)
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw) as Partial<ScreenshotSettings>
|
||||
const parsed = JSON.parse(raw) as Partial<ScreenshotSettings> & { version?: number }
|
||||
if (parsed.version !== SETTINGS_VERSION) {
|
||||
// 结构变更:重置为新默认值(应用新的默认快捷键 / 贴图快捷键 / 保留数量)
|
||||
settings.value = { ...DEFAULT_SETTINGS }
|
||||
saveSettings()
|
||||
} else {
|
||||
settings.value = { ...DEFAULT_SETTINGS, ...parsed }
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 加载设置失败', e)
|
||||
localStorage.removeItem(SETTINGS_KEY)
|
||||
@@ -74,7 +106,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
|
||||
function saveSettings() {
|
||||
try {
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings.value))
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify({ version: SETTINGS_VERSION, ...settings.value }))
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 保存设置失败', e)
|
||||
}
|
||||
@@ -83,6 +115,11 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
function setSettings(patch: Partial<ScreenshotSettings>) {
|
||||
settings.value = { ...settings.value, ...patch }
|
||||
saveSettings()
|
||||
// 保留数量变更:立即裁剪历史(含删除超限缓存文件)
|
||||
if (patch.historyLimit !== undefined) {
|
||||
enforceHistoryLimit()
|
||||
persistHistory()
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 窗口定位 =====
|
||||
@@ -193,7 +230,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
if (readyListenerInit) return
|
||||
readyListenerInit = true
|
||||
resetOverlayReady()
|
||||
await listen(EVENTS.screenshotOverlayReady, () => {
|
||||
overlayReadyUnlisten = await listen(EVENTS.screenshotOverlayReady, () => {
|
||||
overlayReadyResolve?.()
|
||||
})
|
||||
await ensureOverlay()
|
||||
@@ -247,9 +284,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
})
|
||||
}
|
||||
|
||||
/** 追加历史项:删除超出上限的最旧缓存文件 */
|
||||
function addRecent(thumb: string, filePath: string, width: number, height: number, mode: string) {
|
||||
recent.value.unshift({ id: crypto.randomUUID(), thumb, filePath, width, height, time: Date.now(), mode })
|
||||
/** 按保留数量裁剪历史(超出部分删除缓存文件) */
|
||||
function enforceHistoryLimit() {
|
||||
const limit = Math.max(1, settings.value.historyLimit)
|
||||
if (recent.value.length > limit) {
|
||||
const removed = recent.value.splice(limit)
|
||||
@@ -259,10 +295,68 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 持久化历史元数据(含缩略图与定位坐标)到 localStorage,供重启恢复 */
|
||||
function persistHistory() {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
HISTORY_KEY,
|
||||
JSON.stringify({ version: HISTORY_VERSION, items: recent.value }),
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 持久化历史失败(可能超出存储限额)', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 应用启动时恢复历史:版本不匹配/损坏则丢弃;并按当前保留数量清理超限文件 */
|
||||
function loadHistory() {
|
||||
try {
|
||||
const raw = localStorage.getItem(HISTORY_KEY)
|
||||
if (!raw) return
|
||||
const parsed = JSON.parse(raw) as { version?: number; items?: RecentCapture[] }
|
||||
if (parsed.version !== HISTORY_VERSION || !Array.isArray(parsed.items)) {
|
||||
localStorage.removeItem(HISTORY_KEY)
|
||||
return
|
||||
}
|
||||
const limit = Math.max(1, settings.value.historyLimit)
|
||||
const items = parsed.items.slice(0, limit)
|
||||
for (const extra of parsed.items.slice(limit)) {
|
||||
void commands.screenshotDeleteCache(extra.filePath)
|
||||
}
|
||||
recent.value = items
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 恢复历史失败', e)
|
||||
recent.value = []
|
||||
}
|
||||
}
|
||||
|
||||
/** 追加历史项:持久化 + 删除超出上限的最旧缓存文件 */
|
||||
function addRecent(
|
||||
thumb: string,
|
||||
filePath: string,
|
||||
width: number,
|
||||
height: number,
|
||||
mode: string,
|
||||
pos?: { x: number; y: number },
|
||||
) {
|
||||
recent.value.unshift({
|
||||
id: crypto.randomUUID(),
|
||||
thumb,
|
||||
filePath,
|
||||
width,
|
||||
height,
|
||||
time: Date.now(),
|
||||
mode,
|
||||
...(pos ? { posX: pos.x, posY: pos.y } : {}),
|
||||
})
|
||||
enforceHistoryLimit()
|
||||
persistHistory()
|
||||
}
|
||||
|
||||
/** 移除单个历史项(同时删除缓存文件) */
|
||||
async function removeRecent(item: RecentCapture) {
|
||||
const idx = recent.value.findIndex((r) => r.id === item.id)
|
||||
if (idx >= 0) recent.value.splice(idx, 1)
|
||||
persistHistory()
|
||||
try {
|
||||
await commands.screenshotDeleteCache(item.filePath)
|
||||
} catch (e) {
|
||||
@@ -275,6 +369,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
void commands.screenshotDeleteCache(item.filePath)
|
||||
}
|
||||
recent.value = []
|
||||
persistHistory()
|
||||
}
|
||||
|
||||
/** 从历史缓存加载完整 PNG base64(一次性,不常驻) */
|
||||
@@ -303,13 +398,27 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
}
|
||||
|
||||
/** 覆盖层/编辑器导出处理:记录历史(缩略图 + 缓存落盘)+ 按设置自动保存 */
|
||||
async function handleExport(payload: { pngBase64: string; width: number; height: number }) {
|
||||
const { pngBase64, width, height } = payload
|
||||
async function handleExport(payload: {
|
||||
pngBase64: string
|
||||
width: number
|
||||
height: number
|
||||
/** 截图时框选区域的物理屏幕坐标(贴图窗口按原位置显示;编辑器导出缺失) */
|
||||
posX?: number
|
||||
posY?: number
|
||||
}) {
|
||||
const { pngBase64, width, height, posX, posY } = payload
|
||||
try {
|
||||
// 完整图落盘缓存目录,历史只保留缩略图,避免完整 base64 常驻内存
|
||||
const filePath = await commands.screenshotSaveCache(pngBase64)
|
||||
const thumb = await makeThumb(pngBase64, width, height)
|
||||
addRecent(thumb, filePath, width, height, 'capture')
|
||||
addRecent(
|
||||
thumb,
|
||||
filePath,
|
||||
width,
|
||||
height,
|
||||
'capture',
|
||||
posX !== undefined && posY !== undefined ? { x: posX, y: posY } : undefined,
|
||||
)
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 历史缓存失败', e)
|
||||
}
|
||||
@@ -335,7 +444,9 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
pngBase64: string
|
||||
width: number
|
||||
height: number
|
||||
}>('screenshot-exported', (e) => {
|
||||
posX?: number
|
||||
posY?: number
|
||||
}>(EVENTS.screenshotExported, (e) => {
|
||||
void handleExport(e.payload)
|
||||
})
|
||||
}
|
||||
@@ -371,11 +482,132 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 贴图窗口 =====
|
||||
function resetPinReady() {
|
||||
pinReadyPromise = new Promise<void>((resolve) => {
|
||||
pinReadyResolve = resolve
|
||||
})
|
||||
}
|
||||
|
||||
/** 等待贴图窗口就绪(首次创建时等 onMounted 完成,之后立即返回) */
|
||||
async function waitPinReady() {
|
||||
await Promise.race([
|
||||
pinReadyPromise,
|
||||
new Promise<void>((r) => setTimeout(r, 3000)),
|
||||
])
|
||||
}
|
||||
|
||||
/** 注册贴图窗口就绪监听(首次贴图前调用) */
|
||||
async function ensurePinReadyListener() {
|
||||
if (pinReadyListenerInit) return
|
||||
pinReadyListenerInit = true
|
||||
resetPinReady()
|
||||
pinReadyUnlisten = await listen(EVENTS.screenshotPinReady, () => {
|
||||
pinReadyResolve?.()
|
||||
})
|
||||
}
|
||||
|
||||
/** 创建常驻贴图窗口(无边框、透明、置顶、无任务栏;首次贴图时创建,之后复用) */
|
||||
async function ensurePinWindow() {
|
||||
if (pinWin) {
|
||||
const existing = await WebviewWindow.getByLabel(PIN_LABEL).catch(() => null)
|
||||
if (existing) {
|
||||
pinWin = existing
|
||||
return
|
||||
}
|
||||
pinWin = null
|
||||
}
|
||||
resetPinReady()
|
||||
pinWin = new WebviewWindow(PIN_LABEL, {
|
||||
url: 'index.html#screenshot-pin',
|
||||
title: '贴图',
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 120,
|
||||
height: 120,
|
||||
// 创建时必须 resizable:true(Windows 上非 resizable 窗口 setSize 会失效);
|
||||
// 每次布局结束后在贴图窗口内恢复 setResizable(false),禁用边缘拖动缩放,仅保留左键自由拖动
|
||||
resizable: true,
|
||||
decorations: false,
|
||||
alwaysOnTop: true,
|
||||
skipTaskbar: true,
|
||||
transparent: true,
|
||||
shadow: false,
|
||||
focus: false,
|
||||
visible: false,
|
||||
})
|
||||
await waitPinReady()
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换贴图:已打开则关闭;否则把第 index 张截图贴到屏幕(原框选位置)。
|
||||
* index 省略时为最近一张截图。
|
||||
*/
|
||||
async function togglePin(index?: number) {
|
||||
if (!recent.value.length) {
|
||||
toast('暂无截图可贴图')
|
||||
return
|
||||
}
|
||||
await ensurePinReadyListener()
|
||||
if (pinWin) {
|
||||
try {
|
||||
if (await pinWin.isVisible()) {
|
||||
await pinWin.hide()
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
/* 窗口可能尚未就绪,忽略 */
|
||||
}
|
||||
}
|
||||
const i = Math.max(0, Math.min(index ?? 0, recent.value.length - 1))
|
||||
localStorage.setItem(PIN_INDEX_KEY, String(i))
|
||||
await ensurePinWindow()
|
||||
await emit(EVENTS.screenshotPinShow)
|
||||
}
|
||||
|
||||
/** 监听 Rust 侧 emit 的 'screenshot-pin-shortcut' 事件(贴图快捷键按下时切换) */
|
||||
async function initPinShortcutListener() {
|
||||
if (pinShortcutUnlisten) return
|
||||
pinShortcutUnlisten = await listen(EVENTS.screenshotPinShortcut, () => {
|
||||
void togglePin()
|
||||
})
|
||||
}
|
||||
|
||||
/** 应用启动时按已保存的设置注册贴图全局快捷键(默认 Alt+1) */
|
||||
async function initPinShortcutRegistration() {
|
||||
try {
|
||||
await commands.screenshotRegisterPinShortcut(settings.value.pinShortcut)
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 贴图快捷键注册失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 修改贴图快捷键:持久化 + 重新注册(传空字符串禁用) */
|
||||
async function setPinShortcut(shortcut: string) {
|
||||
const next = shortcut.trim()
|
||||
setSettings({ pinShortcut: next })
|
||||
try {
|
||||
await commands.screenshotRegisterPinShortcut(next)
|
||||
return true
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 贴图快捷键注册失败', e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function destroyExportListener() {
|
||||
if (exportUnlisten) {
|
||||
exportUnlisten()
|
||||
exportUnlisten = null
|
||||
}
|
||||
if (overlayReadyUnlisten) {
|
||||
overlayReadyUnlisten()
|
||||
overlayReadyUnlisten = null
|
||||
}
|
||||
if (pinReadyUnlisten) {
|
||||
pinReadyUnlisten()
|
||||
pinReadyUnlisten = null
|
||||
}
|
||||
}
|
||||
|
||||
function destroyShortcutListener() {
|
||||
@@ -383,6 +615,10 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
shortcutUnlisten()
|
||||
shortcutUnlisten = null
|
||||
}
|
||||
if (pinShortcutUnlisten) {
|
||||
pinShortcutUnlisten()
|
||||
pinShortcutUnlisten = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -400,12 +636,17 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
removeRecent,
|
||||
loadFullImage,
|
||||
loadSettings,
|
||||
loadHistory,
|
||||
setSettings,
|
||||
setShortcut,
|
||||
togglePin,
|
||||
setPinShortcut,
|
||||
initExportListener,
|
||||
destroyExportListener,
|
||||
initShortcutListener,
|
||||
initShortcutRegistration,
|
||||
destroyShortcutListener,
|
||||
initPinShortcutListener,
|
||||
initPinShortcutRegistration,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -2,6 +2,8 @@ export interface SearchIndexItem {
|
||||
title: string
|
||||
description?: string
|
||||
keywords: string[]
|
||||
/** 跳转目标:模块内部 tab(如 proxy 的 'settings'),无 tab 则只切换模块 */
|
||||
tab?: string
|
||||
}
|
||||
|
||||
export interface SearchIndexConfig {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { moduleRegistry } from '@/modules/registry'
|
||||
import { getTextForms, bestScore } from '@/modules/quickpanel/engine'
|
||||
|
||||
export interface SearchItem {
|
||||
id: string
|
||||
@@ -8,6 +9,8 @@ export interface SearchItem {
|
||||
title: string
|
||||
description?: string
|
||||
keywords: string[]
|
||||
/** 跳转目标:模块内部 tab(无则只切换模块) */
|
||||
tab?: string
|
||||
action?: () => void
|
||||
}
|
||||
|
||||
@@ -29,7 +32,8 @@ export const useSearchStore = defineStore('search', () => {
|
||||
moduleId,
|
||||
title: item.title,
|
||||
description: item.description,
|
||||
keywords: item.keywords
|
||||
keywords: item.keywords,
|
||||
tab: item.tab
|
||||
}
|
||||
if (!items.value.find(i => i.id === searchItem.id)) {
|
||||
items.value.push(searchItem)
|
||||
@@ -76,14 +80,21 @@ export const useSearchStore = defineStore('search', () => {
|
||||
|
||||
const search = (query: string) => {
|
||||
if (!query.trim()) return []
|
||||
const lowerQuery = query.toLowerCase()
|
||||
return items.value.filter(item => {
|
||||
const titleMatch = item.title.toLowerCase().includes(lowerQuery)
|
||||
const descMatch = item.description ? item.description.toLowerCase().includes(lowerQuery) : false
|
||||
const keywordMatch = item.keywords.some(k => k.toLowerCase().includes(lowerQuery))
|
||||
const moduleIdMatch = item.moduleId.toLowerCase().includes(lowerQuery)
|
||||
return titleMatch || descMatch || keywordMatch || moduleIdMatch
|
||||
// 复用快速面板匹配引擎:标题/描述/关键词/模块名 多形态模糊匹配(支持拼音、子序列)
|
||||
const scored = items.value
|
||||
.map(item => {
|
||||
let score = Math.max(
|
||||
bestScore(query, getTextForms(item.title)),
|
||||
bestScore(query, getTextForms(item.description ?? '')),
|
||||
bestScore(query, getTextForms(item.keywords.join(' ')))
|
||||
)
|
||||
const moduleName = moduleRegistry.getConfig(item.moduleId)?.name ?? item.moduleId
|
||||
score = Math.max(score, bestScore(query, getTextForms(moduleName)) * 0.9)
|
||||
return { item, score }
|
||||
})
|
||||
.filter(e => e.score > 0)
|
||||
.sort((a, b) => b.score - a.score)
|
||||
return scored.map(e => e.item)
|
||||
}
|
||||
|
||||
const getItemsByModule = (moduleId: string) => {
|
||||
|
||||
@@ -161,6 +161,17 @@
|
||||
}
|
||||
}
|
||||
|
||||
/* 桌面应用体验:默认禁止文本选中(按钮/下拉框/标题等控件文字不可拖动选择),
|
||||
输入框、文本域、可编辑区域仍允许选择/复制 */
|
||||
html, body, #app {
|
||||
user-select: none;
|
||||
-webkit-user-select: none;
|
||||
}
|
||||
input, textarea, [contenteditable='true'] {
|
||||
user-select: text;
|
||||
-webkit-user-select: text;
|
||||
}
|
||||
|
||||
#app {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
|
||||
@@ -23,6 +23,23 @@ export default defineConfig(async () => ({
|
||||
input: {
|
||||
main: fileURLToPath(new URL("./index.html", import.meta.url)),
|
||||
},
|
||||
// 分包策略:vendor 独立 chunk,业务迭代时不强制重下载依赖
|
||||
// - vue/pinia/@vueuse: Vue 生态核心,变更频率低
|
||||
// - reka-ui/@lucide: UI 组件库,体积较大且稳定
|
||||
// - tauri: Tauri 前端 API,仅在 Tauri 升级时变化
|
||||
output: {
|
||||
manualChunks: {
|
||||
'vue-vendor': ['vue', 'pinia', '@vueuse/core'],
|
||||
'ui-vendor': ['reka-ui', '@lucide/vue'],
|
||||
'tauri-vendor': [
|
||||
'@tauri-apps/api',
|
||||
'@tauri-apps/plugin-autostart',
|
||||
'@tauri-apps/plugin-dialog',
|
||||
'@tauri-apps/plugin-global-shortcut',
|
||||
'@tauri-apps/plugin-opener',
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user