细节调整及优化(26.8.3)
This commit is contained in:
+8
-6
@@ -87,6 +87,9 @@ const loadModule = async (moduleId: string) => {
|
||||
}
|
||||
|
||||
const handleModuleChange = (moduleId: string) => {
|
||||
// 同模块不重新加载(保留组件状态);搜索/托盘跳转到当前模块时仅触发 tab 导航
|
||||
if (activeModule.value === moduleId) return
|
||||
|
||||
// 调用上一个模块的 onDeactivate 钩子
|
||||
const prevConfig = moduleRegistry.getConfig(activeModule.value)
|
||||
prevConfig?.lifecycle?.onDeactivate?.()
|
||||
@@ -96,10 +99,9 @@ const handleModuleChange = (moduleId: string) => {
|
||||
loadModule(moduleId)
|
||||
}
|
||||
|
||||
// 搜索跳转与普通切换同路径:补齐 onDeactivate 钩子,避免旧模块资源泄漏
|
||||
const handleSearch = (moduleId: string) => {
|
||||
activeModule.value = moduleId
|
||||
localStorage.setItem(LAST_MODULE_KEY, moduleId)
|
||||
loadModule(moduleId)
|
||||
handleModuleChange(moduleId)
|
||||
}
|
||||
|
||||
const getFallbackModule = () => {
|
||||
@@ -110,14 +112,14 @@ const getFallbackModule = () => {
|
||||
return fallback?.id || 'settings'
|
||||
}
|
||||
|
||||
watch(() => appStore.enabledModules.length, () => {
|
||||
// 按 id 列表监听(而非 length):同时禁用一个 + 启用另一个时 length 不变,会漏检回退
|
||||
watch(() => appStore.enabledModules.map(m => m.id).join(','), () => {
|
||||
// 启动期间 activeModule 尚未确定,跳过
|
||||
if (!activeModule.value) return
|
||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||
if (activeModule.value !== 'settings' && !enabledIds.includes(activeModule.value)) {
|
||||
const fallback = getFallbackModule()
|
||||
activeModule.value = fallback
|
||||
loadModule(fallback)
|
||||
handleModuleChange(fallback)
|
||||
}
|
||||
// 模块启用/禁用变化时重新同步快速面板命令缓存
|
||||
quickpanelStore.syncCommands()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
|
||||
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'
|
||||
import { Search, Settings, ChevronRight, ArrowUp, Check, Loader2 } from '@lucide/vue'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
@@ -66,6 +66,65 @@ const handleSettingSelect = (item: SearchItem) => {
|
||||
isSearchFocused.value = false
|
||||
}
|
||||
|
||||
// ===== 搜索下拉键盘导航(↑↓ 移动 / Enter 选择 / ESC 清空) =====
|
||||
|
||||
/** 下拉扁平结果(模块在前、设置项在后),用于统一索引 */
|
||||
const flatResults = computed(() => [
|
||||
...filteredModules.value.map(m => ({ kind: 'module' as const, id: m.id })),
|
||||
...searchResults.value.map(s => ({ kind: 'setting' as const, id: s.id }))
|
||||
])
|
||||
|
||||
/** 当前高亮索引(-1 无高亮) */
|
||||
const highlightIndex = ref(-1)
|
||||
|
||||
const isDropdownOpen = computed(() => isSearchFocused.value && hasSearchContent.value)
|
||||
|
||||
// 查询变化时重置高亮到第一项
|
||||
watch(searchQuery, () => {
|
||||
highlightIndex.value = flatResults.value.length > 0 ? 0 : -1
|
||||
})
|
||||
|
||||
const selectIndex = (index: number) => {
|
||||
const entry = flatResults.value[index]
|
||||
if (!entry) return
|
||||
if (entry.kind === 'module') {
|
||||
handleSearchSelect(entry.id)
|
||||
} else {
|
||||
const item = searchResults.value.find(s => s.id === entry.id)
|
||||
if (item) handleSettingSelect(item)
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearchKeydown = (e: KeyboardEvent) => {
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
||||
if (!isDropdownOpen.value || flatResults.value.length === 0) return
|
||||
e.preventDefault()
|
||||
const delta = e.key === 'ArrowDown' ? 1 : -1
|
||||
const len = flatResults.value.length
|
||||
highlightIndex.value = (highlightIndex.value + delta + len) % len
|
||||
// 高亮项滚动到下拉可视区(容器 overflow-y-auto)
|
||||
nextTick(() => {
|
||||
document
|
||||
.querySelector(`[data-search-idx="${highlightIndex.value}"]`)
|
||||
?.scrollIntoView({ block: 'nearest' })
|
||||
})
|
||||
} else if (e.key === 'Enter') {
|
||||
if (isDropdownOpen.value && highlightIndex.value >= 0) {
|
||||
e.preventDefault()
|
||||
selectIndex(highlightIndex.value)
|
||||
}
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
if (searchQuery.value) {
|
||||
// 第一阶段:清空查询(下拉随内容消失)
|
||||
searchQuery.value = ''
|
||||
} else {
|
||||
// 第二阶段:失焦收起
|
||||
;(e.target as HTMLElement).blur()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let tauriWindow: ReturnType<typeof getCurrentWindow> | null = null
|
||||
try {
|
||||
tauriWindow = getCurrentWindow()
|
||||
@@ -196,12 +255,23 @@ const initScrollListener = () => {
|
||||
}
|
||||
}
|
||||
|
||||
// resize 节流定时器:拖拽调整大小时 onResized 高频触发,避免每次都发 isMaximized IPC
|
||||
let resizeDebounce: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
onMounted(async () => {
|
||||
if (tauriWindow) {
|
||||
try {
|
||||
isMaximized.value = await tauriWindow.isMaximized()
|
||||
unlistenMaximize = await tauriWindow.onResized(async () => {
|
||||
isMaximized.value = await tauriWindow!.isMaximized()
|
||||
unlistenMaximize = await tauriWindow.onResized(() => {
|
||||
if (resizeDebounce) return
|
||||
resizeDebounce = setTimeout(async () => {
|
||||
resizeDebounce = null
|
||||
try {
|
||||
isMaximized.value = await tauriWindow!.isMaximized()
|
||||
} catch {
|
||||
/* 窗口已销毁等异常忽略 */
|
||||
}
|
||||
}, 150)
|
||||
})
|
||||
} catch {
|
||||
// 非 Tauri 环境忽略
|
||||
@@ -218,6 +288,7 @@ onMounted(async () => {
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('mousemove', handleFirstMouseMove)
|
||||
if (restoreHoverTimer) clearTimeout(restoreHoverTimer)
|
||||
if (resizeDebounce) clearTimeout(resizeDebounce)
|
||||
if (unlistenMaximize) unlistenMaximize()
|
||||
if (unlistenFocus) unlistenFocus()
|
||||
if (scrollViewport) scrollViewport.removeEventListener('scroll', handleMainScroll)
|
||||
@@ -302,9 +373,10 @@ const handleBlur = () => {
|
||||
class="h-7 pl-8 text-sm bg-secondary/50 border-0 focus-visible:ring-1"
|
||||
@focus="isSearchFocused = true"
|
||||
@blur="handleBlur"
|
||||
@keydown="handleSearchKeydown"
|
||||
/>
|
||||
<div
|
||||
v-if="isSearchFocused && hasSearchContent"
|
||||
<div
|
||||
v-if="isDropdownOpen"
|
||||
class="absolute top-full left-0 right-0 mt-1 bg-popover border border-border rounded-md shadow-lg z-50 overflow-hidden max-h-64 overflow-y-auto"
|
||||
>
|
||||
<template v-if="filteredModules.length > 0">
|
||||
@@ -312,25 +384,31 @@ const handleBlur = () => {
|
||||
模块
|
||||
</div>
|
||||
<button
|
||||
v-for="module in filteredModules"
|
||||
v-for="(module, mi) in filteredModules"
|
||||
:key="module.id"
|
||||
class="w-full px-3 py-2 text-left text-sm hover:bg-accent transition-colors flex items-center gap-2"
|
||||
:class="highlightIndex === mi ? 'bg-accent' : ''"
|
||||
:data-search-idx="mi"
|
||||
@click="handleSearchSelect(module.id)"
|
||||
@mouseenter="highlightIndex = mi"
|
||||
>
|
||||
<span>{{ module.name }}</span>
|
||||
</button>
|
||||
</template>
|
||||
|
||||
|
||||
<template v-if="searchResults.length > 0">
|
||||
<div v-if="filteredModules.length > 0" class="border-t border-border"></div>
|
||||
<div class="px-2 py-1 text-xs font-semibold text-muted-foreground uppercase tracking-wider">
|
||||
设置项
|
||||
</div>
|
||||
<button
|
||||
v-for="item in searchResults"
|
||||
v-for="(item, si) in searchResults"
|
||||
:key="item.id"
|
||||
class="w-full px-3 py-2 text-left text-sm hover:bg-accent transition-colors flex items-center gap-2"
|
||||
:class="highlightIndex === filteredModules.length + si ? 'bg-accent' : ''"
|
||||
:data-search-idx="filteredModules.length + si"
|
||||
@click="handleSettingSelect(item)"
|
||||
@mouseenter="highlightIndex = filteredModules.length + si"
|
||||
>
|
||||
<Settings class="size-4 text-muted-foreground shrink-0" />
|
||||
<div class="flex-1 min-w-0">
|
||||
|
||||
+63
-20
@@ -9,24 +9,32 @@ export const commands = {
|
||||
/** 检查 Gitea 最新 release,返回版本对比与可用资产 */
|
||||
updateCheck: () => __TAURI_INVOKE<UpdateCheckResult>("update_check"),
|
||||
/**
|
||||
* 更新应用本体。
|
||||
* 便携版:下载 thing_{v}_x64.exe → update.bat 覆盖重启;
|
||||
* 安装版:下载 thing_{v}_x64-setup.exe → 提权静默安装 /S。
|
||||
* 下载进度通过 UPDATE_PROGRESS 事件上报,调用方返回前会触发应用退出。
|
||||
* 更新应用本体(安装阶段)。下载由前端下载模块完成,本命令接收已下载的
|
||||
* 安装包路径(便携版 thing_{v}_x64.exe / 安装版 thing_{v}_x64-setup.exe)。
|
||||
* 便携版:copy 到临时目录 → update.bat 覆盖重启;
|
||||
* 安装版:copy 到临时目录 → 提权静默安装 /S。
|
||||
* 调用返回前会触发应用退出。
|
||||
*/
|
||||
updateInstall: () => __TAURI_INVOKE<null>("update_install"),
|
||||
updateInstall: (downloadedPath: string) => __TAURI_INVOKE<null>("update_install", { downloadedPath }),
|
||||
/** 更新 ThingHK 内核:下载 thing-hk_{v}.zip → 停止监控内核 → 覆盖内核文件 */
|
||||
updateThinghk: () => __TAURI_INVOKE<null>("update_thinghk"),
|
||||
proxyActivateProfile: (id: string) => __TAURI_INVOKE<null>("proxy_activate_profile", { id }),
|
||||
/** 应用内核更新:下载阶段已由下载模块完成,本方法仅做 need_stop → 解压 → 替换。 */
|
||||
proxyApplyKernelUpdate: (zipPath: string) => __TAURI_INVOKE<KernelInfo>("proxy_apply_kernel_update", { zipPath }),
|
||||
/** 取消内核下载/安装(设置取消标志,下载循环轮询后中止) */
|
||||
proxyCancelKernelInstall: () => __TAURI_INVOKE<null>("proxy_cancel_kernel_install"),
|
||||
proxyCheckKernelUpdate: () => __TAURI_INVOKE<KernelUpdateInfo>("proxy_check_kernel_update"),
|
||||
proxyClearSystemProxy: () => __TAURI_INVOKE<null>("proxy_clear_system_proxy"),
|
||||
proxyCloseConnection: (id: string) => __TAURI_INVOKE<null>("proxy_close_connection", { id }),
|
||||
/**
|
||||
* 前端确认 mihomo 已停止,唤醒等待中的安装流程继续解压替换。
|
||||
* (下载阶段允许 mihomo 运行以便走系统代理,解压替换前必须停止 mihomo,否则 exe 被占用)
|
||||
*/
|
||||
proxyConfirmInstall: () => __TAURI_INVOKE<null>("proxy_confirm_install"),
|
||||
proxyDeleteProfile: (id: string) => __TAURI_INVOKE<null>("proxy_delete_profile", { id }),
|
||||
proxyGetSettings: () => __TAURI_INVOKE<ProxySettings>("proxy_get_settings"),
|
||||
proxyGetSystemProxy: () => __TAURI_INVOKE<boolean>("proxy_get_system_proxy"),
|
||||
proxyImportProfile: (url: string, name: string) => __TAURI_INVOKE<ProfileMeta>("proxy_import_profile", { url, name }),
|
||||
/** 首次安装内核(与 update_kernel 共用 install_kernel 实现,语义独立便于前端区分场景) */
|
||||
proxyInstallKernel: (mirrorPrefix: string | null) => __TAURI_INVOKE<KernelInfo>("proxy_install_kernel", { mirrorPrefix }),
|
||||
proxyKernelInfo: () => __TAURI_INVOKE<KernelInfo>("proxy_kernel_info"),
|
||||
proxyRestart: () => __TAURI_INVOKE<ProcessInfo>("proxy_restart"),
|
||||
proxySaveSettings: (settings: ProxySettings) => __TAURI_INVOKE<null>("proxy_save_settings", { settings }),
|
||||
@@ -36,11 +44,13 @@ export const commands = {
|
||||
proxyStatus: () => __TAURI_INVOKE<ProxyStatus>("proxy_status"),
|
||||
proxyStop: () => __TAURI_INVOKE<null>("proxy_stop"),
|
||||
proxyTestDelay: (name: string, url: string | null, timeout: number | null) => __TAURI_INVOKE<number>("proxy_test_delay", { name, url, timeout }),
|
||||
proxyUpdateKernel: (mirrorPrefix: string | null) => __TAURI_INVOKE<KernelInfo>("proxy_update_kernel", { mirrorPrefix }),
|
||||
proxyUpdateProfile: (id: string) => __TAURI_INVOKE<ProfileMeta>("proxy_update_profile", { id }),
|
||||
/** 读取快速面板设置(快捷键等) */
|
||||
quickpanelGetSettings: () => __TAURI_INVOKE<QuickPanelSettings>("quickpanel_get_settings"),
|
||||
/** 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口 */
|
||||
/**
|
||||
* 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口,
|
||||
* 索引目录变化时闲时自动重建索引。
|
||||
*/
|
||||
quickpanelSaveSettings: (settings: QuickPanelSettings) => __TAURI_INVOKE<null>("quickpanel_save_settings", { settings }),
|
||||
/** 注册(或切换)快速面板全局快捷键 */
|
||||
quickpanelRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("quickpanel_register_shortcut", { shortcut }),
|
||||
@@ -58,6 +68,7 @@ export const commands = {
|
||||
* 初始化文件索引数据库(应用启动时调用)。
|
||||
* 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
|
||||
* 无需重建即可继续自动同步文件变更。
|
||||
* 若从未构建过(首次运行),闲时自动建立索引,无需用户手动点"构建索引"。
|
||||
*/
|
||||
quickpanelInitFileIndex: () => __TAURI_INVOKE<null>("quickpanel_init_file_index"),
|
||||
/** 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用) */
|
||||
@@ -138,6 +149,8 @@ export const commands = {
|
||||
/** 图片 PNG base64(仅 image 类型) */
|
||||
imageBase64: string | null,
|
||||
}) & (ClipboardItem) | null>("clipboard_get_item", { id }),
|
||||
/** 获取图片缩略图 PNG base64(弹窗悬停预览用,避免加载全尺寸图片) */
|
||||
clipboardGetThumb: (id: number) => __TAURI_INVOKE<string | null>("clipboard_get_thumb", { id }),
|
||||
clipboardSetPinned: (id: number, pinned: boolean) => __TAURI_INVOKE<boolean>("clipboard_set_pinned", { id, pinned }),
|
||||
clipboardDelete: (id: number) => __TAURI_INVOKE<boolean>("clipboard_delete", { id }),
|
||||
clipboardClear: () => __TAURI_INVOKE<boolean>("clipboard_clear"),
|
||||
@@ -160,6 +173,26 @@ export const commands = {
|
||||
clipboardShowWindow: () => __TAURI_INVOKE<null>("clipboard_show_window"),
|
||||
/** 隐藏弹窗并模拟 Ctrl+V 粘贴到原窗口 */
|
||||
clipboardPasteToTarget: () => __TAURI_INVOKE<null>("clipboard_paste_to_target"),
|
||||
/** 在弹窗旁显示独立预览窗口(悬停/键盘选中时调用) */
|
||||
clipboardShowPreview: (id: number) => __TAURI_INVOKE<null>("clipboard_show_preview", { id }),
|
||||
/** 隐藏独立预览窗口 */
|
||||
clipboardHidePreview: () => __TAURI_INVOKE<null>("clipboard_hide_preview"),
|
||||
/**
|
||||
* 按内容自适应调整预览窗大小(逻辑像素)。前端加载内容(文本测高、图片按宽高比)后调用,
|
||||
* 窗口贴合内容消除留白;后端按弹窗所在屏工作区钳制并重新对齐弹窗。
|
||||
* allow_flip:初始落位为 true(优先侧放不下可换侧);放大/还原为 false(保持原侧)。
|
||||
*/
|
||||
clipboardResizePreview: (width: number | null, height: number | null, allowFlip: boolean) => __TAURI_INVOKE<null>("clipboard_resize_preview", { width, height, allowFlip }),
|
||||
/**
|
||||
* 显示已就绪的预览窗口。前端完成内容加载与 resize 后调用,窗口以最终尺寸出现,
|
||||
* 消除"先以上次尺寸(可能是放大态大窗)显示再缩回"的闪烁。
|
||||
*/
|
||||
clipboardRevealPreview: () => __TAURI_INVOKE<null>("clipboard_reveal_preview"),
|
||||
/**
|
||||
* 预览窗交互锁定:前端预览窗收到 mousedown(放大/缩小、复制、选择文本)时调用。
|
||||
* 此后弹窗+预览不因失焦/鼠标离开而关闭,仅当点击外部或弹窗重新聚焦时退出锁定。
|
||||
*/
|
||||
clipboardPreviewInteracted: () => __TAURI_INVOKE<null>("clipboard_preview_interacted"),
|
||||
/** 获取所有任务 */
|
||||
downloaderGetTasks: () => __TAURI_INVOKE<DownloadTask[]>("downloader_get_tasks"),
|
||||
/** 检查 URL 重复性并探测文件信息(添加下载前调用) */
|
||||
@@ -182,6 +215,8 @@ export const commands = {
|
||||
downloaderOpenUrl: (url: string) => __TAURI_INVOKE<null>("downloader_open_url", { url }),
|
||||
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
|
||||
screenshotDisableTransitions: (label: string) => __TAURI_INVOKE<null>("screenshot_disable_transitions", { label }),
|
||||
/** 一次 IPC 完成指定窗口的显示与聚焦(截图覆盖层显示关键路径,减少串行往返) */
|
||||
screenshotShowOverlay: (label: string) => __TAURI_INVOKE<null>("screenshot_show_overlay", { label }),
|
||||
/** 注册(或切换)截图全局快捷键。传入空字符串则禁用快捷键。 */
|
||||
screenshotRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("screenshot_register_shortcut", { shortcut }),
|
||||
/** 注销截图全局快捷键 */
|
||||
@@ -193,8 +228,11 @@ export const commands = {
|
||||
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 编码。
|
||||
* 同时返回捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返)。
|
||||
*/
|
||||
screenshotCaptureFullscreen: () => __TAURI_INVOKE<CaptureStart>("screenshot_capture_fullscreen"),
|
||||
/** 全屏捕获编码为 PNG base64 并清除(全屏截图直接进编辑器) */
|
||||
screenshotFullscreenPng: () => __TAURI_INVOKE<CaptureData>("screenshot_fullscreen_png"),
|
||||
/** 清除静态全屏捕获(覆盖层关闭/取消时释放内存) */
|
||||
@@ -203,15 +241,12 @@ export const commands = {
|
||||
screenshotCropStored: (x: number, y: number, w: number, h: number) => __TAURI_INVOKE<CaptureData>("screenshot_crop_stored", { x, y, w, h }),
|
||||
/** 裁剪已存储的全屏捕获并直接写入剪贴板(一次 IPC 完成"裁剪+复制") */
|
||||
screenshotCropCopyStored: (x: number, y: number, w: number, h: number) => __TAURI_INVOKE<CaptureData>("screenshot_crop_copy_stored", { x, y, w, h }),
|
||||
/** 拾取指定物理屏幕坐标下的顶层窗口 */
|
||||
screenshotWindowFromPoint: (x: number, y: number) => __TAURI_INVOKE<{
|
||||
hwnd: number,
|
||||
title: string,
|
||||
rect: ScreenRect,
|
||||
/** DWM 扩展边框矩形(视觉边界,去掉最大化窗口的隐形缩放边框),命中测试用 rect,高亮用 visual_rect */
|
||||
visualRect: ScreenRect | null,
|
||||
} | null>("screenshot_window_from_point", { x, y }),
|
||||
/** 获取当前鼠标物理屏幕坐标(覆盖层打开时定位初始悬停窗口) */
|
||||
/**
|
||||
* 枚举可拾取的顶层窗口(Z 序顶→底,排除本进程/不可见/工具窗口)。
|
||||
* 前端在截图开始时缓存列表,鼠标移动时在 JS 侧本地命中测试,消除逐帧 IPC 往返。
|
||||
*/
|
||||
screenshotPickList: () => __TAURI_INVOKE<WindowInfo[]>("screenshot_pick_list"),
|
||||
/** 获取当前鼠标物理屏幕坐标(贴图窗口拖动跟随等场景使用) */
|
||||
screenshotCursorPos: () => __TAURI_INVOKE<[number, number]>("screenshot_cursor_pos"),
|
||||
/** 枚举所有可见顶层窗口 */
|
||||
screenshotEnumWindows: () => __TAURI_INVOKE<WindowInfo[]>("screenshot_enum_windows"),
|
||||
@@ -252,6 +287,12 @@ export type CaptureData = {
|
||||
height: number,
|
||||
};
|
||||
|
||||
/** 截图启动信息:捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返) */
|
||||
export type CaptureStart = {
|
||||
cursorX: number,
|
||||
cursorY: number,
|
||||
};
|
||||
|
||||
/** check_url 命令返回的结果 */
|
||||
export type CheckUrlResult = {
|
||||
/** 探测是否成功 */
|
||||
@@ -377,6 +418,8 @@ export type DownloaderSettings = {
|
||||
deleteFilesOnRemove?: boolean,
|
||||
/** 添加下载前检查重复(URL 或文件名重复时询问) */
|
||||
checkDuplicate?: boolean,
|
||||
/** 下载是否使用代理:true=尊重系统代理(mihomo 开启系统代理时经其转发),false=强制直连 */
|
||||
useProxy?: boolean,
|
||||
};
|
||||
|
||||
/** 重复类型 */
|
||||
|
||||
@@ -24,11 +24,18 @@ export const EVENTS = {
|
||||
clipboardChanged: 'clipboard-changed',
|
||||
clipboardPopupShow: 'clipboard-popup-show',
|
||||
clipboardPopupHide: 'clipboard-popup-hide',
|
||||
clipboardPreviewShow: 'clipboard-preview-show',
|
||||
clipboardPreviewHide: 'clipboard-preview-hide',
|
||||
// 鼠标进入/离开独立预览窗(弹窗据此决定是否延迟隐藏预览,便于点击复制/放大)
|
||||
clipboardPreviewEnter: 'clipboard-preview-enter',
|
||||
clipboardPreviewLeave: 'clipboard-preview-leave',
|
||||
// 快速面板
|
||||
quickpanelShow: 'quickpanel-show',
|
||||
quickpanelHide: 'quickpanel-hide',
|
||||
quickpanelExecuteCommand: 'quickpanel-execute-command',
|
||||
quickpanelExtractProgress: 'quickpanel-extract-progress',
|
||||
// 文件索引构建完成(闲时自动建立/重建、手动构建)
|
||||
quickpanelIndexUpdated: 'quickpanel-index-updated',
|
||||
// 截图
|
||||
screenshotBegin: 'screenshot-begin',
|
||||
screenshotOverlayReady: 'screenshot-overlay-ready',
|
||||
@@ -39,10 +46,16 @@ export const EVENTS = {
|
||||
screenshotExported: 'screenshot-exported',
|
||||
// 内核安装进度
|
||||
kernelInstallProgress: 'kernel-install-progress',
|
||||
// 后端自动切换节点完成(后台执行,刷新节点列表并提示)
|
||||
proxyAutoSwitch: 'proxy-auto-switch',
|
||||
// 应用更新进度
|
||||
updateProgress: 'update-progress',
|
||||
// 监控 OSD
|
||||
osdStateUpdate: 'osd-state-update',
|
||||
/** OSD 数据通道:仅推送显示项 key→value 映射 + 网速(高频,每秒) */
|
||||
osdDataUpdate: 'osd-data-update',
|
||||
/** OSD 窗口挂载后请求主窗口补发配置+数据(防止错过创建时的首推) */
|
||||
osdConfigRequest: 'osd-config-request',
|
||||
osdContentSize: 'osd-content-size',
|
||||
osdSystemUiActive: 'osd-system-ui-active',
|
||||
osdSystemUiInactive: 'osd-system-ui-inactive',
|
||||
@@ -57,6 +70,8 @@ export const EVENTS = {
|
||||
// 其他
|
||||
processStatusChanged: 'process-status-changed',
|
||||
downloadAdded: 'download-added',
|
||||
/** 任务被删除(浏览器扩展通过 HTTP API 删除任务时发出,前端据此刷新任务列表) */
|
||||
downloadRemoved: 'download-removed',
|
||||
/** 浏览器扩展通过 HTTP API 新增下载(置前主窗口并跳到下载画面) */
|
||||
downloadExtensionAdded: 'download-extension-added',
|
||||
} as const
|
||||
@@ -79,6 +94,7 @@ export const STORAGE_KEYS = {
|
||||
quickpanelDeleteFilterFavs: 'thing_quickpanel_delete_filter_favs',
|
||||
currencyRates: 'thing_quickpanel_currency_rates',
|
||||
monitorOsdConfig: 'thing_monitor_osd_config',
|
||||
monitorOverviewCards: 'thing_monitor_overview_cards',
|
||||
screenshotHistory: 'thing_screenshot_history',
|
||||
screenshotPinIndex: 'thing_screenshot_pin_index',
|
||||
} as const
|
||||
|
||||
@@ -25,6 +25,7 @@ window.addEventListener('unhandledrejection', (event) => {
|
||||
const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Promise<{ default: Component }>]> = [
|
||||
['#osd-overlay', 'OSD', () => import('./modules/monitor/OsdWindow.vue')],
|
||||
['#clipboard-popup', '剪贴板弹窗', () => import('./modules/clipboard/ClipboardPopup.vue')],
|
||||
['#clipboard-preview', '剪贴板预览', () => import('./modules/clipboard/ClipboardPreview.vue')],
|
||||
['#quick-panel', '快速面板弹窗', () => import('./modules/quickpanel/QuickPanel.vue')],
|
||||
['#tray-menu', '托盘菜单', () => import('./modules/tray/TrayMenu.vue')],
|
||||
['#screenshot-overlay', '截图覆盖层', () => import('./modules/screenshot/ScreenshotOverlay.vue')],
|
||||
|
||||
@@ -76,6 +76,8 @@ const gotoPage = async (p: number) => {
|
||||
const detailOpen = ref(false)
|
||||
const detailLoading = ref(false)
|
||||
const detail = ref<ClipboardItemDetail | null>(null)
|
||||
/** 详情加载序号:快速点击多个条目时丢弃过期请求结果,避免旧请求覆盖新详情 */
|
||||
let detailSeq = 0
|
||||
const openDetail = async (item: ClipboardItem) => {
|
||||
// reka-ui Dialog 打开时会把当前活动元素记为 triggerElement,关闭时对其无 preventScroll 地 focus,
|
||||
// 导致历史列表的 ScrollAreaViewport(tabindex=0) 被聚焦并滚回顶部。打开前 blur,避免记录滚动容器。
|
||||
@@ -86,7 +88,9 @@ const openDetail = async (item: ClipboardItem) => {
|
||||
detailOpen.value = true
|
||||
detailLoading.value = true
|
||||
detail.value = null
|
||||
const seq = ++detailSeq
|
||||
const d = await store.getItem(item.id)
|
||||
if (seq !== detailSeq) return // 过期请求丢弃
|
||||
detail.value = d
|
||||
detailLoading.value = false
|
||||
}
|
||||
@@ -616,7 +620,7 @@ onUnmounted(() => {
|
||||
<p v-else-if="detail.kind === 'image'" class="text-sm text-muted-foreground text-center py-8">
|
||||
图片预览不可用
|
||||
</p>
|
||||
<pre v-else-if="detail.kind === 'text'" class="text-sm whitespace-pre-wrap break-all font-mono bg-muted/50 p-3 rounded">{{ detail.content }}</pre>
|
||||
<pre v-else-if="detail.kind === 'text'" class="text-sm whitespace-pre-wrap break-all font-mono bg-muted/50 p-3 rounded select-text cursor-text">{{ detail.content }}</pre>
|
||||
<ul v-else-if="detail.kind === 'files'" class="space-y-1 text-sm">
|
||||
<li
|
||||
v-for="(p, i) in (parseFiles(detail.content))"
|
||||
|
||||
@@ -12,6 +12,10 @@ import {
|
||||
} from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
||||
} from '@/components/ui/pagination'
|
||||
@@ -27,6 +31,8 @@ const total = ref(0)
|
||||
const currentPage = ref(1)
|
||||
const PAGE_SIZE = 50
|
||||
const searchQuery = ref('')
|
||||
/** 类型筛选:全部/文本/图片/文件 */
|
||||
const kindFilter = ref<'all' | 'text' | 'image' | 'files'>('all')
|
||||
const selectedIndex = ref(0)
|
||||
const loading = ref(false)
|
||||
const searchInputRef = ref<HTMLInputElement | null>(null)
|
||||
@@ -38,21 +44,37 @@ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)
|
||||
// ===== 数据加载 =====
|
||||
/** 加载请求序号:翻页/搜索快速操作时丢弃过期请求结果,避免旧请求覆盖新结果 */
|
||||
let loadSeq = 0
|
||||
/** 列表视图:history = 全部历史(后端分页);pinned = 仅钉住条目(前端筛选+分页) */
|
||||
const viewMode = ref<'history' | 'pinned'>('history')
|
||||
async function loadData() {
|
||||
const seq = ++loadSeq
|
||||
loading.value = true
|
||||
try {
|
||||
const q = searchQuery.value.trim()
|
||||
const offset = (currentPage.value - 1) * PAGE_SIZE
|
||||
let res: HistoryPage
|
||||
if (q) {
|
||||
res = await commands.clipboardSearch(q, PAGE_SIZE, offset)
|
||||
if (viewMode.value === 'pinned') {
|
||||
// 钉住视图:一次性取回,前端按类型/搜索筛选并分页
|
||||
const all = await commands.clipboardGetPinned()
|
||||
if (seq !== loadSeq) return
|
||||
const q = searchQuery.value.trim().toLowerCase()
|
||||
const kind = kindFilter.value
|
||||
let filtered = all
|
||||
if (kind !== 'all') filtered = filtered.filter(i => i.kind === kind)
|
||||
if (q) filtered = filtered.filter(i => i.preview.toLowerCase().includes(q))
|
||||
total.value = filtered.length
|
||||
const start = (currentPage.value - 1) * PAGE_SIZE
|
||||
items.value = filtered.slice(start, start + PAGE_SIZE)
|
||||
} else {
|
||||
res = await commands.clipboardGetHistory(PAGE_SIZE, offset, 'all')
|
||||
const q = searchQuery.value.trim()
|
||||
const offset = (currentPage.value - 1) * PAGE_SIZE
|
||||
let res: HistoryPage
|
||||
if (q) {
|
||||
res = await commands.clipboardSearch(q, PAGE_SIZE, offset)
|
||||
} else {
|
||||
res = await commands.clipboardGetHistory(PAGE_SIZE, offset, kindFilter.value)
|
||||
}
|
||||
if (seq !== loadSeq) return // 过期请求丢弃
|
||||
items.value = res.items
|
||||
total.value = res.total
|
||||
}
|
||||
if (seq !== loadSeq) return // 过期请求丢弃
|
||||
items.value = res.items
|
||||
total.value = res.total
|
||||
selectedIndex.value = 0
|
||||
} catch (e) {
|
||||
if (seq !== loadSeq) return
|
||||
@@ -67,13 +89,20 @@ async function loadData() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 切换历史/钉住视图 */
|
||||
async function toggleViewMode() {
|
||||
viewMode.value = viewMode.value === 'history' ? 'pinned' : 'history'
|
||||
currentPage.value = 1
|
||||
await loadData()
|
||||
}
|
||||
|
||||
async function gotoPage(p: number) {
|
||||
currentPage.value = Math.min(Math.max(1, p), totalPages.value)
|
||||
await loadData()
|
||||
}
|
||||
|
||||
// 防抖搜索
|
||||
watch(searchQuery, () => {
|
||||
// 防抖搜索/筛选
|
||||
watch([searchQuery, kindFilter], () => {
|
||||
currentPage.value = 1
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(loadData, 200)
|
||||
@@ -107,7 +136,14 @@ async function deleteItem(item: ClipboardItem, ev: Event) {
|
||||
ev.stopPropagation()
|
||||
try {
|
||||
await commands.clipboardDelete(item.id)
|
||||
// 本地先移除保持即时反馈,再整页刷新(total/分页数与后端保持一致;
|
||||
// 钉住视图下数据源也需重建)
|
||||
items.value = items.value.filter((i) => i.id !== item.id)
|
||||
// 当前页删空且不在第一页:回退一页,避免停留在空页
|
||||
if (items.value.length === 0 && currentPage.value > 1) {
|
||||
currentPage.value -= 1
|
||||
}
|
||||
await loadData()
|
||||
} catch (e) {
|
||||
console.error('[clipboard-popup] 删除失败:', e)
|
||||
}
|
||||
@@ -121,19 +157,109 @@ async function hideWindow() {
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 独立预览窗口 =====
|
||||
async function showPreview(item: ClipboardItem) {
|
||||
try {
|
||||
await commands.clipboardShowPreview(item.id)
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
async function hidePreview() {
|
||||
try {
|
||||
await commands.clipboardHidePreview()
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 存储条目预览文本元素,用于检测是否被截断(仅截断的文本才显示预览) */
|
||||
const previewEls = new Map<number, HTMLElement>()
|
||||
function setPreviewEl(id: number, el: unknown) {
|
||||
if (el instanceof HTMLElement) previewEls.set(id, el)
|
||||
else previewEls.delete(id)
|
||||
}
|
||||
|
||||
/** line-clamp-1 截断检测:内容高度超过单行即视为截断 */
|
||||
function isTextTruncated(id: number): boolean {
|
||||
const el = previewEls.get(id)
|
||||
if (!el) return true // 无法测量时保守显示
|
||||
return el.scrollHeight > el.clientHeight
|
||||
}
|
||||
|
||||
/** 当前条目是否需要预览:图片始终预览;文本仅被截断时预览 */
|
||||
function needsPreview(item: ClipboardItem): boolean {
|
||||
if (item.kind === 'image') return true
|
||||
if (item.kind === 'text') return isTextTruncated(item.id)
|
||||
return false
|
||||
}
|
||||
|
||||
let hoverTimer: ReturnType<typeof setTimeout> | null = null
|
||||
/** 鼠标是否位于独立预览窗内:为 true 时离开条目不隐藏预览,便于点击复制/放大 */
|
||||
const mouseInPreview = ref(false)
|
||||
|
||||
/** 键盘选中:立即显示/隐藏预览(不等待悬停延迟) */
|
||||
function showSelectedPreview() {
|
||||
cancelHoverTimer()
|
||||
mouseInPreview.value = false
|
||||
const item = items.value[selectedIndex.value]
|
||||
if (item && needsPreview(item)) {
|
||||
void showPreview(item)
|
||||
} else {
|
||||
void hidePreview()
|
||||
}
|
||||
}
|
||||
|
||||
function onItemHover(idx: number, item: ClipboardItem) {
|
||||
selectedIndex.value = idx
|
||||
// 先取消之前的定时器
|
||||
cancelHoverTimer()
|
||||
mouseInPreview.value = false
|
||||
// 不需要预览的条目:立即隐藏预览(避免前一条目的预览残留)
|
||||
if (!needsPreview(item)) {
|
||||
void hidePreview()
|
||||
return
|
||||
}
|
||||
// 100ms 后显示(快速响应悬停意图,同时避免鼠标快速划过时频繁开关)
|
||||
hoverTimer = setTimeout(() => {
|
||||
void showPreview(item)
|
||||
}, 100)
|
||||
}
|
||||
|
||||
function onItemLeave() {
|
||||
// 延迟隐藏:避免鼠标在条目间快速移动时预览闪烁。
|
||||
// 若鼠标已移入预览窗(点击复制/放大),由 preview-enter 事件取消该定时器。
|
||||
cancelHoverTimer()
|
||||
if (mouseInPreview.value) return
|
||||
hoverTimer = setTimeout(() => {
|
||||
void hidePreview()
|
||||
}, 250)
|
||||
}
|
||||
|
||||
function cancelHoverTimer() {
|
||||
if (hoverTimer) {
|
||||
clearTimeout(hoverTimer)
|
||||
hoverTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 键盘导航 =====
|
||||
// 类型筛选 Select 的展开状态:展开时 ↑↓/Enter/Esc 由 Select 自行处理,
|
||||
// 不触发列表导航/粘贴/关闭弹窗
|
||||
const selectOpen = ref(false)
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (selectOpen.value) return
|
||||
if (e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
selectedIndex.value = Math.min(selectedIndex.value + 1, items.value.length - 1)
|
||||
cancelHoverTimer()
|
||||
previewVisible.value = false
|
||||
showSelectedPreview()
|
||||
scrollSelectedIntoView()
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
|
||||
cancelHoverTimer()
|
||||
previewVisible.value = false
|
||||
showSelectedPreview()
|
||||
scrollSelectedIntoView()
|
||||
} else if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
@@ -141,6 +267,8 @@ function onKeydown(e: KeyboardEvent) {
|
||||
if (item) selectAndPaste(item)
|
||||
} else if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
cancelHoverTimer()
|
||||
void hidePreview()
|
||||
hideWindow()
|
||||
}
|
||||
}
|
||||
@@ -176,62 +304,6 @@ const formatTime = (ms: number) => {
|
||||
|
||||
const hasItems = computed(() => items.value.length > 0)
|
||||
|
||||
// ===== 图片悬停预览(悬停 100ms 后显示缩略图) =====
|
||||
const previewSrc = ref('')
|
||||
const previewVisible = ref(false)
|
||||
let hoverTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// 缓存已加载的图片 id → dataUrl,避免重复请求
|
||||
const imageCache = new Map<number, string>()
|
||||
|
||||
/** 根据 base64 前缀判断 MIME 类型 */
|
||||
function buildImageDataUrl(b64: string): string {
|
||||
const mime = b64.startsWith('/9j/') ? 'image/jpeg' : 'image/png'
|
||||
return `data:${mime};base64,${b64}`
|
||||
}
|
||||
|
||||
async function onItemHover(idx: number, item: ClipboardItem) {
|
||||
selectedIndex.value = idx
|
||||
// 仅图片类型触发预览
|
||||
if (item.kind !== 'image') {
|
||||
cancelHoverTimer()
|
||||
previewVisible.value = false
|
||||
return
|
||||
}
|
||||
// 先取消之前的定时器和预览
|
||||
cancelHoverTimer()
|
||||
// 100ms 后加载并显示(快速响应悬停意图)
|
||||
hoverTimer = setTimeout(async () => {
|
||||
try {
|
||||
let src = imageCache.get(item.id)
|
||||
if (!src) {
|
||||
const detail = await commands.clipboardGetItem(item.id)
|
||||
if (detail?.imageBase64) {
|
||||
src = buildImageDataUrl(detail.imageBase64)
|
||||
imageCache.set(item.id, src)
|
||||
}
|
||||
}
|
||||
if (src) {
|
||||
previewSrc.value = src
|
||||
previewVisible.value = true
|
||||
}
|
||||
} catch {
|
||||
/* 忽略加载失败 */
|
||||
}
|
||||
}, 100)
|
||||
}
|
||||
|
||||
function cancelHoverTimer() {
|
||||
if (hoverTimer) {
|
||||
clearTimeout(hoverTimer)
|
||||
hoverTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function onItemLeave() {
|
||||
cancelHoverTimer()
|
||||
previewVisible.value = false
|
||||
}
|
||||
|
||||
// ===== 主题应用(与主应用同步) =====
|
||||
/** 从 localStorage 读取主应用的主题设置 */
|
||||
function readMainTheme(): { theme: string; effect: string } {
|
||||
@@ -334,15 +406,37 @@ onMounted(async () => {
|
||||
await applyTheme()
|
||||
searchQuery.value = ''
|
||||
currentPage.value = 1
|
||||
// 重置预览状态,清空缓存避免历史图片占用内存
|
||||
// 隐藏独立预览窗口(弹窗重新显示时清除上次预览)
|
||||
cancelHoverTimer()
|
||||
previewVisible.value = false
|
||||
imageCache.clear()
|
||||
mouseInPreview.value = false
|
||||
void hidePreview()
|
||||
await loadData()
|
||||
await nextTick()
|
||||
searchInputRef.value?.focus()
|
||||
}))
|
||||
|
||||
// 监听弹窗隐藏事件:取消悬停定时器并隐藏预览,避免弹窗隐藏后残留定时器重新弹出预览窗
|
||||
unlistenFns.push(await listen(EVENTS.clipboardPopupHide, () => {
|
||||
cancelHoverTimer()
|
||||
mouseInPreview.value = false
|
||||
void hidePreview()
|
||||
}))
|
||||
|
||||
// 鼠标进入预览窗:取消条目离开触发的隐藏定时器,允许在预览窗内停留并点击复制/放大
|
||||
unlistenFns.push(await listen(EVENTS.clipboardPreviewEnter, () => {
|
||||
mouseInPreview.value = true
|
||||
cancelHoverTimer()
|
||||
}))
|
||||
|
||||
// 鼠标离开预览窗:恢复可隐藏状态并延迟隐藏;鼠标移回条目时由 onItemHover 重新显示
|
||||
unlistenFns.push(await listen(EVENTS.clipboardPreviewLeave, () => {
|
||||
mouseInPreview.value = false
|
||||
cancelHoverTimer()
|
||||
hoverTimer = setTimeout(() => {
|
||||
void hidePreview()
|
||||
}, 250)
|
||||
}))
|
||||
|
||||
// 加载初始数据
|
||||
await loadData()
|
||||
await nextTick()
|
||||
@@ -364,9 +458,9 @@ onUnmounted(() => {
|
||||
|
||||
<template>
|
||||
<div class="popup-root flex flex-col h-screen w-screen" @keydown="onKeydown">
|
||||
<!-- 搜索栏(与剪切板主页统一样式) -->
|
||||
<!-- 搜索栏(与剪切板主页统一样式)+ 类型筛选 -->
|
||||
<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">
|
||||
<div class="relative flex-1 min-w-0">
|
||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
ref="searchInputRef"
|
||||
@@ -376,16 +470,20 @@ onUnmounted(() => {
|
||||
spellcheck="false"
|
||||
/>
|
||||
</div>
|
||||
<span class="text-xs text-muted-foreground whitespace-nowrap">{{ total }} 条</span>
|
||||
<Select v-model="kindFilter" :open="selectOpen" @update:open="selectOpen = $event">
|
||||
<SelectTrigger size="sm" class="w-[76px] shrink-0 text-xs" title="按类型筛选">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<!-- 内容宽度与 trigger 等宽:覆盖默认 min-w-[8rem](128px),紧凑弹窗内不显过宽 -->
|
||||
<SelectContent class="w-(--reka-select-trigger-width) min-w-0">
|
||||
<SelectItem value="all">全部</SelectItem>
|
||||
<SelectItem value="text">文本</SelectItem>
|
||||
<SelectItem value="image">图片</SelectItem>
|
||||
<SelectItem value="files">文件</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<!-- 图片悬停预览浮层 -->
|
||||
<Transition name="popup-preview">
|
||||
<div v-if="previewVisible && previewSrc" class="popup-preview">
|
||||
<img :src="previewSrc" alt="预览" />
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<!-- 列表 -->
|
||||
<ScrollArea class="popup-list flex-1 min-h-0">
|
||||
<div class="space-y-1.5 p-2">
|
||||
@@ -419,7 +517,10 @@ onUnmounted(() => {
|
||||
>
|
||||
<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">{{ item.preview }}</p>
|
||||
<p
|
||||
class="text-sm break-all line-clamp-1"
|
||||
:ref="el => setPreviewEl(item.id, el)"
|
||||
>{{ 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>
|
||||
@@ -437,38 +538,56 @@ onUnmounted(() => {
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<!-- 分页(与剪切板历史统一样式) -->
|
||||
<div v-if="totalPages > 1" class="flex items-center justify-center gap-1 px-2 py-1 border-t border-border">
|
||||
<Pagination
|
||||
v-slot="{ page }"
|
||||
:page="currentPage"
|
||||
:total="total"
|
||||
:items-per-page="PAGE_SIZE"
|
||||
:sibling-count="1"
|
||||
show-edges
|
||||
@update:page="gotoPage"
|
||||
>
|
||||
<PaginationContent v-slot="{ items: pageItems }" class="gap-1">
|
||||
<template v-for="(item, index) in pageItems" :key="index">
|
||||
<PaginationItem
|
||||
v-if="item.type === 'page'"
|
||||
:value="item.value"
|
||||
:is-active="item.value === page"
|
||||
size="icon"
|
||||
class="size-7 text-xs"
|
||||
>
|
||||
{{ item.value }}
|
||||
</PaginationItem>
|
||||
<PaginationEllipsis v-else class="size-7" />
|
||||
</template>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
<!-- 底部:总数 + 分页 + 视图切换(grid 两侧 1fr 等宽,分页严格居中) -->
|
||||
<div class="grid grid-cols-[1fr_auto_1fr] items-center gap-2 px-3 py-1 border-t border-border shrink-0">
|
||||
<span class="text-xs text-muted-foreground whitespace-nowrap justify-self-start">{{ total }} 条</span>
|
||||
<div v-if="totalPages > 1" class="justify-self-center">
|
||||
<Pagination
|
||||
v-slot="{ page }"
|
||||
:page="currentPage"
|
||||
:total="total"
|
||||
:items-per-page="PAGE_SIZE"
|
||||
:sibling-count="1"
|
||||
show-edges
|
||||
@update:page="gotoPage"
|
||||
>
|
||||
<PaginationContent v-slot="{ items: pageItems }" class="gap-1">
|
||||
<template v-for="(item, index) in pageItems" :key="index">
|
||||
<PaginationItem
|
||||
v-if="item.type === 'page'"
|
||||
:value="item.value"
|
||||
:is-active="item.value === page"
|
||||
size="icon"
|
||||
class="size-7 text-xs"
|
||||
>
|
||||
{{ item.value }}
|
||||
</PaginationItem>
|
||||
<PaginationEllipsis v-else class="size-7" />
|
||||
</template>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
<!-- col-start-3:无分页时中间轨道宽为 0,若不固定列位置按钮会被自动放置
|
||||
到第 2 轨道(视觉居中),显式固定第 3 轨道保证始终贴右 -->
|
||||
<div class="justify-self-end col-start-3">
|
||||
<Button
|
||||
:variant="viewMode === 'pinned' ? 'default' : 'outline'"
|
||||
size="sm"
|
||||
class="h-7 px-2 text-xs gap-1"
|
||||
:title="viewMode === 'pinned' ? '当前:仅钉住条目,点击查看全部历史' : '当前:全部历史,点击仅查看钉住条目'"
|
||||
@click="toggleViewMode"
|
||||
>
|
||||
<!-- 图标与文字同义(Pin=钉住视图 / ClipboardList=历史视图),高亮表示当前视图 -->
|
||||
<component :is="viewMode === 'pinned' ? Pin : ClipboardList" class="size-3.5" />
|
||||
{{ viewMode === 'pinned' ? '钉住' : '历史' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 底部提示 -->
|
||||
<div class="popup-footer shrink-0">
|
||||
<span><kbd>↑</kbd><kbd>↓</kbd> 导航</span>
|
||||
<span><kbd>Enter</kbd> 粘贴</span>
|
||||
<span><kbd>Enter</kbd>/<kbd>左键</kbd> 粘贴</span>
|
||||
<span><kbd>Esc</kbd> 关闭</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -588,39 +707,6 @@ onUnmounted(() => {
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
|
||||
/* 图片悬停预览浮层:固定在弹窗右上角,不遮挡列表操作 */
|
||||
.popup-preview {
|
||||
position: absolute;
|
||||
top: 50px;
|
||||
right: 10px;
|
||||
z-index: 100;
|
||||
max-width: 180px;
|
||||
max-height: 180px;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.25);
|
||||
background: var(--popover, var(--background));
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.popup-preview img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 180px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
/* 预览浮层淡入淡出 */
|
||||
.popup-preview-enter-active,
|
||||
.popup-preview-leave-active {
|
||||
transition: opacity 0.15s ease;
|
||||
}
|
||||
.popup-preview-enter-from,
|
||||
.popup-preview-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.popup-footer kbd {
|
||||
background: var(--muted);
|
||||
color: var(--foreground);
|
||||
|
||||
@@ -0,0 +1,369 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { listen, emit, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { getCurrentWindow, Effect, EffectState } from '@tauri-apps/api/window'
|
||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
||||
import { commands } from '@/lib/bindings'
|
||||
import { ZoomIn, ZoomOut, FileText, Image as ImageIcon } from '@lucide/vue'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
|
||||
// ===== 状态 =====
|
||||
const kind = ref<'text' | 'image' | ''>('')
|
||||
const textContent = ref('')
|
||||
const thumbSrc = ref('')
|
||||
const fullSrc = ref('')
|
||||
const enlarged = ref(false)
|
||||
const loading = ref(false)
|
||||
let unlistenFns: UnlistenFn[] = []
|
||||
// 加载序号:连续悬停快速切换时丢弃过期请求结果
|
||||
let loadSeq = 0
|
||||
|
||||
/** 根据 base64 前缀判断 MIME 类型 */
|
||||
function buildImageDataUrl(b64: string): string {
|
||||
const mime = b64.startsWith('/9j/') ? 'image/jpeg' : 'image/png'
|
||||
return `data:${mime};base64,${b64}`
|
||||
}
|
||||
|
||||
// ===== 窗口尺寸自适应(贴合内容消除留白) =====
|
||||
// 布局常量(逻辑像素,与模板样式对应)
|
||||
const PAD = 12 // 内容区 p-3
|
||||
const HEADER_H = 30 // 头部栏高度(py-1.5*2 + 行高 + 边框)
|
||||
const TEXT_W = 360 // 文本预览窗口宽
|
||||
const THUMB_MAX_W = 440 // 缩略态图片最大显示宽
|
||||
const THUMB_MAX_H = 340 // 缩略态图片最大显示高
|
||||
const DEF_W = 340 // 默认/兜底窗口宽(非文本图片、加载失败)
|
||||
const DEF_H = 300 // 默认/兜底窗口高
|
||||
|
||||
/** 离屏测量文本在指定内容宽下的自然高度(样式与模板 pre 一致,保证测量准确) */
|
||||
function measureTextHeight(text: string, width: number): number {
|
||||
const el = document.createElement('pre')
|
||||
el.className = 'text-xs whitespace-pre-wrap break-all font-mono leading-relaxed'
|
||||
el.style.cssText = `position:fixed;left:-9999px;top:0;width:${width}px;margin:0;visibility:hidden`
|
||||
el.textContent = text
|
||||
document.body.appendChild(el)
|
||||
const h = el.getBoundingClientRect().height
|
||||
el.remove()
|
||||
return h
|
||||
}
|
||||
|
||||
/** 读取图片原始尺寸 */
|
||||
function loadImageSize(src: string): Promise<{ w: number; h: number }> {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image()
|
||||
img.onload = () => resolve({ w: img.naturalWidth || 0, h: img.naturalHeight || 0 })
|
||||
img.onerror = () => resolve({ w: 0, h: 0 })
|
||||
img.src = src
|
||||
})
|
||||
}
|
||||
|
||||
/** 按当前内容自适应窗口尺寸:文本测高、图片按宽高比(放大态用原图尺寸),
|
||||
* 后端按工作区钳制并重新对齐弹窗;完成后 reveal 显示(窗口出现即最终尺寸,
|
||||
* 无"先大后小"闪烁)。seq 用于丢弃快速切换时的过期请求。
|
||||
* allowFlip:初始落位为 true(放不下可换侧);放大/还原为 false(保持原侧)。 */
|
||||
async function fitWindow(seq: number, allowFlip: boolean) {
|
||||
let w = DEF_W
|
||||
let h = DEF_H
|
||||
if (kind.value === 'text') {
|
||||
const th = measureTextHeight(textContent.value, TEXT_W - PAD * 2)
|
||||
w = TEXT_W
|
||||
h = HEADER_H + PAD * 2 + th
|
||||
} else if (kind.value === 'image') {
|
||||
const src = enlarged.value ? fullSrc.value : thumbSrc.value
|
||||
if (src) {
|
||||
const { w: iw, h: ih } = await loadImageSize(src)
|
||||
if (seq !== loadSeq) return
|
||||
if (iw && ih) {
|
||||
let dw = iw
|
||||
let dh = ih
|
||||
if (!enlarged.value) {
|
||||
// 缩略态:等比缩放进显示区(不放大超过图片自身尺寸)
|
||||
const scale = Math.min(THUMB_MAX_W / iw, THUMB_MAX_H / ih, 1)
|
||||
dw = Math.round(iw * scale)
|
||||
dh = Math.round(ih * scale)
|
||||
}
|
||||
w = dw + PAD * 2
|
||||
h = dh + HEADER_H + PAD * 2
|
||||
}
|
||||
}
|
||||
}
|
||||
if (seq !== loadSeq) return
|
||||
try {
|
||||
// 先 resize(窗口仍隐藏)完成定位,再 reveal 以最终尺寸显示
|
||||
await commands.clipboardResizePreview(w, h, allowFlip)
|
||||
await commands.clipboardRevealPreview()
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 根据条目 id 加载预览内容(文本取全文,图片先取缩略图) */
|
||||
async function loadItem(id: number) {
|
||||
const seq = ++loadSeq
|
||||
loading.value = true
|
||||
enlarged.value = false
|
||||
kind.value = ''
|
||||
textContent.value = ''
|
||||
thumbSrc.value = ''
|
||||
fullSrc.value = ''
|
||||
try {
|
||||
const detail = await commands.clipboardGetItem(id)
|
||||
if (seq !== loadSeq) return
|
||||
if (detail?.kind === 'text') {
|
||||
kind.value = 'text'
|
||||
textContent.value = detail.content ?? ''
|
||||
} else if (detail?.kind === 'image') {
|
||||
kind.value = 'image'
|
||||
if (detail.imageBase64) fullSrc.value = buildImageDataUrl(detail.imageBase64)
|
||||
const thumb = await commands.clipboardGetThumb(id).catch(() => null)
|
||||
if (seq !== loadSeq) return
|
||||
thumbSrc.value = thumb ? buildImageDataUrl(thumb) : fullSrc.value
|
||||
}
|
||||
} catch {
|
||||
/* 加载失败保持空态 */
|
||||
} finally {
|
||||
if (seq === loadSeq) {
|
||||
loading.value = false
|
||||
// 初始落位:允许换侧(优先侧放不下时切到另一侧)
|
||||
void fitWindow(seq, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 图片点击:缩略图 ↔ 原图放大切换(窗口随内容自适应:放大态按原图尺寸) */
|
||||
function toggleEnlarge() {
|
||||
if (kind.value !== 'image' || !fullSrc.value) return
|
||||
enlarged.value = !enlarged.value
|
||||
// 尺寸变化不换侧:窗口跳侧会使鼠标落在窗外误触发隐藏;保持原侧靠工作区 clamp
|
||||
void fitWindow(loadSeq, false)
|
||||
}
|
||||
|
||||
// ===== 鼠标进入/离开联动 =====
|
||||
// 弹窗的 onItemLeave 会在鼠标离开条目后延迟隐藏预览;鼠标移入预览窗时通知弹窗
|
||||
// 取消隐藏定时器,保证停留在预览窗内可点击"复制/放大",移出后再隐藏。
|
||||
// mousedown 也重新上报进入状态:兜底防止 WebView2 偶发的 mouseleave 触发隐藏定时器,
|
||||
// 保证"点击预览文本/放大按钮"不会因此关闭预览。
|
||||
// 交互锁定:一旦点击过预览窗(放大/缩小、复制、选择文本),通知后端进入锁定模式
|
||||
// ——弹窗+预览不再因失焦/鼠标离开而关闭,仅点击外部或弹窗重新聚焦时退出;
|
||||
// 此时鼠标离开预览窗也不上报 leave(预览保持显示,由看护线程管理生命周期)。
|
||||
const interacted = ref(false)
|
||||
|
||||
function onRootEnter() {
|
||||
void emit(EVENTS.clipboardPreviewEnter)
|
||||
}
|
||||
|
||||
function onRootMouseDown() {
|
||||
onRootEnter()
|
||||
interacted.value = true
|
||||
void commands.clipboardPreviewInteracted().catch(() => {})
|
||||
}
|
||||
|
||||
function onRootLeave() {
|
||||
// 交互锁定模式:不上报离开,预览保持显示(点击外部才随弹窗一起关闭)
|
||||
if (interacted.value) return
|
||||
void emit(EVENTS.clipboardPreviewLeave)
|
||||
}
|
||||
|
||||
/** Ctrl+C:有选区交给浏览器默认复制;无选区则复制整段文本,支持预览窗内自由复制 */
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'c') {
|
||||
if (window.getSelection()?.toString().trim()) return
|
||||
if (textContent.value) {
|
||||
e.preventDefault()
|
||||
navigator.clipboard?.writeText(textContent.value).catch(() => {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 主题应用(与弹窗保持一致) =====
|
||||
function readMainTheme(): { theme: string; effect: string } {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEYS.appSettings)
|
||||
if (raw) {
|
||||
const s = JSON.parse(raw)
|
||||
return { theme: s.theme ?? 'system', effect: s.effect ?? 'mica' }
|
||||
}
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
return { theme: 'system', effect: 'mica' }
|
||||
}
|
||||
|
||||
function resolveIsDark(theme: string): boolean {
|
||||
if (theme === 'dark') return true
|
||||
if (theme === 'light') return false
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
async function applyTheme() {
|
||||
const root = document.documentElement
|
||||
const { theme, effect } = readMainTheme()
|
||||
try {
|
||||
const tauriWin = getCurrentWindow()
|
||||
if (theme === 'system') await tauriWin.setTheme(null)
|
||||
else await tauriWin.setTheme(theme as 'dark' | 'light')
|
||||
} catch {
|
||||
/* 非 Tauri 环境忽略 */
|
||||
}
|
||||
const isDark = resolveIsDark(theme)
|
||||
root.classList.remove('dark', 'effect-mica', 'effect-acrylic', 'effect-normal')
|
||||
root.classList.add(`effect-${effect}`)
|
||||
if (isDark) root.classList.add('dark')
|
||||
try {
|
||||
const tauriWin = getCurrentWindow()
|
||||
await tauriWin.clearEffects()
|
||||
if (effect === 'mica') {
|
||||
await tauriWin.setEffects({
|
||||
effects: [Effect.Mica],
|
||||
// 预览窗为 NoActivate 悬浮窗,永远不会进入激活态;
|
||||
// FollowsWindowActiveState 会渲染成非激活的淡化效果,与弹窗不一致。
|
||||
// 强制 Active 态渲染,保证与弹窗视觉统一。
|
||||
state: EffectState.Active,
|
||||
color: isDark ? [30, 41, 59, 0] : [248, 250, 252, 0],
|
||||
})
|
||||
await tauriWin.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else if (effect === 'acrylic') {
|
||||
await tauriWin.setEffects({
|
||||
effects: [Effect.Acrylic],
|
||||
state: EffectState.Active,
|
||||
color: isDark ? [30, 41, 59, 0] : [248, 250, 252, 0],
|
||||
})
|
||||
await tauriWin.setBackgroundColor('#00000000')
|
||||
root.style.setProperty('--popup-bg', 'transparent')
|
||||
} else {
|
||||
await tauriWin.setBackgroundColor(isDark ? '#0f172a' : '#ffffff')
|
||||
root.style.setProperty('--popup-bg', isDark ? '#0f172a' : '#ffffff')
|
||||
}
|
||||
} catch {
|
||||
/* 非 Tauri 环境忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await applyTheme()
|
||||
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const onThemeChange = () => applyTheme()
|
||||
mq.addEventListener('change', onThemeChange)
|
||||
unlistenFns.push(() => mq.removeEventListener('change', onThemeChange))
|
||||
|
||||
// 弹窗悬停/选中条目 → 先同步主题(主应用可能切换了主题),再加载内容
|
||||
unlistenFns.push(await listen<number>(EVENTS.clipboardPreviewShow, async (e) => {
|
||||
await applyTheme()
|
||||
void loadItem(e.payload)
|
||||
}))
|
||||
|
||||
// 隐藏/离开 → 清空内容;预览实际隐藏时复位交互锁定(下次悬停恢复常规模式)
|
||||
unlistenFns.push(await listen(EVENTS.clipboardPreviewHide, () => {
|
||||
loadSeq++ // 丢弃在途请求
|
||||
kind.value = ''
|
||||
textContent.value = ''
|
||||
thumbSrc.value = ''
|
||||
fullSrc.value = ''
|
||||
enlarged.value = false
|
||||
loading.value = false
|
||||
interacted.value = false
|
||||
}))
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
unlistenFns.forEach((fn) => fn())
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="preview-root h-screen w-screen outline-none"
|
||||
tabindex="0"
|
||||
@mouseenter="onRootEnter"
|
||||
@mousedown="onRootMouseDown"
|
||||
@mouseleave="onRootLeave"
|
||||
@keydown="onKeydown"
|
||||
>
|
||||
<!-- 加载中 -->
|
||||
<div v-if="loading" class="h-full flex items-center justify-center text-xs text-muted-foreground">
|
||||
加载中…
|
||||
</div>
|
||||
|
||||
<!-- 文本预览 -->
|
||||
<div v-else-if="kind === 'text'" class="h-full flex flex-col">
|
||||
<div class="flex items-center px-3 py-1.5 border-b border-border shrink-0">
|
||||
<span class="text-xs text-muted-foreground flex items-center gap-1.5">
|
||||
<FileText class="size-3.5" />文本预览/自由复制
|
||||
</span>
|
||||
</div>
|
||||
<ScrollArea class="flex-1 min-h-0">
|
||||
<pre class="text-xs whitespace-pre-wrap break-all font-mono select-text cursor-text leading-relaxed p-3">{{ textContent }}</pre>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<!-- 图片预览 -->
|
||||
<div v-else-if="kind === 'image'" class="h-full flex flex-col">
|
||||
<div class="flex items-center justify-between px-3 py-1.5 border-b border-border shrink-0">
|
||||
<span class="text-xs text-muted-foreground flex items-center gap-1.5">
|
||||
<ImageIcon class="size-3.5" />图片预览
|
||||
</span>
|
||||
<button v-if="fullSrc" class="preview-btn" :title="enlarged ? '还原' : '点击查看原图'" @click="toggleEnlarge">
|
||||
<component :is="enlarged ? ZoomOut : ZoomIn" class="h-3.5 w-3.5" />{{ enlarged ? '还原' : '放大' }}
|
||||
</button>
|
||||
</div>
|
||||
<!-- 放大态:ScrollArea 滚动查看原图;缩略态:内容居中不滚动 -->
|
||||
<ScrollArea v-if="enlarged" class="flex-1 min-h-0">
|
||||
<div class="p-3">
|
||||
<img
|
||||
:src="fullSrc"
|
||||
alt="剪贴板图片预览"
|
||||
class="rounded block cursor-default"
|
||||
@click="toggleEnlarge"
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div v-else class="flex-1 min-h-0 p-3 preview-img-thumb">
|
||||
<img
|
||||
:src="thumbSrc"
|
||||
alt="剪贴板图片预览"
|
||||
class="rounded block max-w-full max-h-full mx-auto cursor-zoom-in"
|
||||
@click="toggleEnlarge"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 空态 -->
|
||||
<div v-else class="h-full flex items-center justify-center text-xs text-muted-foreground">
|
||||
将鼠标悬停条目查看预览
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.preview-root {
|
||||
font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', 'PingFang SC', sans-serif;
|
||||
background: var(--popup-bg, transparent);
|
||||
color: var(--foreground);
|
||||
border-radius: 8px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.preview-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
padding: 2px 8px;
|
||||
border-radius: 5px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--muted);
|
||||
color: var(--foreground);
|
||||
cursor: pointer;
|
||||
transition: background-color 0.1s;
|
||||
}
|
||||
.preview-btn:hover {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
/* 缩略图态:内容居中,图片不放大 */
|
||||
.preview-img-thumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
</style>
|
||||
@@ -12,7 +12,7 @@ import { toast } from 'vue-sonner'
|
||||
import { open as openDialog } from '@tauri-apps/plugin-dialog'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
import { useDownloaderStore, type DownloadTask, type TaskStatus, type CheckUrlResult } from '@/stores/downloaderStore'
|
||||
import { useDownloaderStore, type DownloadTask, type DownloaderSettings, type TaskStatus, type CheckUrlResult } from '@/stores/downloaderStore'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
@@ -63,6 +63,18 @@ const showSecret = ref(false)
|
||||
// 下载设置快捷弹窗(任务页工具栏入口)
|
||||
const downloadSettingsOpen = ref(false)
|
||||
|
||||
// ===== 设置草案 =====
|
||||
// 设置页/快捷弹窗编辑的是本地草案,点击"保存"才写入 store.settings(生效值)并持久化;
|
||||
// 避免未保存的编辑污染全应用读取的生效值(主页代理开关、添加任务默认值等)
|
||||
const settingsDraft = ref<DownloaderSettings | null>(null)
|
||||
watch(
|
||||
() => store.settings,
|
||||
(s) => {
|
||||
settingsDraft.value = s ? { ...s } : null
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
)
|
||||
|
||||
// ===== 任务列表:筛选 / 排序 / 搜索 / 分页 =====
|
||||
type StatusFilter = 'all' | TaskStatus
|
||||
type SortField = 'id' | 'name' | 'size'
|
||||
@@ -108,6 +120,12 @@ const formatSpeed = (bytesPerSec: number): string => {
|
||||
return `${formatSize(bytesPerSec)}/s`
|
||||
}
|
||||
|
||||
/** 总大小显示:0 表示未知大小(未探测到或服务器未返回),显示"未知"避免误导 */
|
||||
const formatTotalSize = (bytes: number): string => {
|
||||
if (!bytes || bytes === 0) return '未知'
|
||||
return formatSize(bytes)
|
||||
}
|
||||
|
||||
/** 格式化剩余时间(秒)为易读形式 */
|
||||
const formatEta = (seconds: number): string => {
|
||||
if (!isFinite(seconds) || seconds <= 0) return ''
|
||||
@@ -253,6 +271,8 @@ const formatTime = (ts: number): string => {
|
||||
|
||||
// 分段详情
|
||||
const segmentProgress = (seg: { completed: number; start: number; end: number }): number => {
|
||||
// 未知大小段(start=0, end=0)无长度可计算进度,返回 0 避免误显示 100%
|
||||
if (seg.start === 0 && seg.end === 0) return 0
|
||||
const len = seg.end - seg.start + 1
|
||||
if (len <= 0) return 0
|
||||
return Math.min(100, Math.round((seg.completed / len) * 100))
|
||||
@@ -297,6 +317,7 @@ const handleAddDownload = async () => {
|
||||
const checkEnabled = store.settings?.checkDuplicate ?? true
|
||||
if (checkEnabled) {
|
||||
// 逐个检查重复
|
||||
duplicateSuccessCount.value = 0
|
||||
await processUrlsWithCheck(uris, dir)
|
||||
} else {
|
||||
// 直接添加
|
||||
@@ -319,8 +340,8 @@ const handleAddDownload = async () => {
|
||||
}
|
||||
|
||||
/** 逐个检查 URL 重复性,发现重复时弹出确认对话框 */
|
||||
async function processUrlsWithCheck(urls: string[], dir: string | undefined) {
|
||||
let successCount = 0
|
||||
async function processUrlsWithCheck(urls: string[], dir: string | undefined, initialCount = 0) {
|
||||
let successCount = initialCount
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const uri = urls[i]
|
||||
try {
|
||||
@@ -345,7 +366,8 @@ async function processUrlsWithCheck(urls: string[], dir: string | undefined) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
// 发现重复:弹出确认对话框,暂停处理
|
||||
// 发现重复:先保存已成功数量,再弹出确认对话框,暂停处理
|
||||
duplicateSuccessCount.value = successCount
|
||||
duplicateDialogState.value = {
|
||||
open: true,
|
||||
url: uri,
|
||||
@@ -366,6 +388,7 @@ async function processUrlsWithCheck(urls: string[], dir: string | undefined) {
|
||||
}
|
||||
}
|
||||
finishAdd(successCount)
|
||||
duplicateSuccessCount.value = 0
|
||||
}
|
||||
|
||||
/** 完成添加:显示提示并关闭对话框 */
|
||||
@@ -387,7 +410,8 @@ const onDuplicateConfirm = async () => {
|
||||
const dir = addDir.value.trim() || undefined
|
||||
duplicateDialogState.value.open = false
|
||||
|
||||
let successCount = 0
|
||||
// 从累积计数开始(包含弹出本对话框之前已成功添加的数量)
|
||||
let successCount = duplicateSuccessCount.value
|
||||
try {
|
||||
await store.addTask(url, undefined, dir, undefined, true) // autoRename=true
|
||||
successCount++
|
||||
@@ -396,24 +420,28 @@ const onDuplicateConfirm = async () => {
|
||||
}
|
||||
|
||||
// 继续处理剩余 URL
|
||||
const remaining = pendingUrls.slice(currentIndex + 1)
|
||||
for (const uri of remaining) {
|
||||
for (let i = currentIndex + 1; i < pendingUrls.length; i++) {
|
||||
const uri = pendingUrls[i]
|
||||
let result: CheckUrlResult | null = null
|
||||
try {
|
||||
const result = await store.checkUrl(uri, dir)
|
||||
if (result.ok && result.duplicate !== 'none') {
|
||||
// 又发现重复,再次弹出确认
|
||||
duplicateDialogState.value = {
|
||||
open: true,
|
||||
url: uri,
|
||||
result,
|
||||
pendingUrls,
|
||||
currentIndex: pendingUrls.indexOf(uri),
|
||||
}
|
||||
// 已添加的成功数通过闭包传递不太方便,直接在这里 finish 后再继续
|
||||
// 简化处理:保存 successCount 到 state,下一次确认时累加
|
||||
duplicateSuccessCount.value = successCount
|
||||
return
|
||||
result = await store.checkUrl(uri, dir)
|
||||
} catch (e) {
|
||||
logger.error(`检查 ${uri} 失败: ` + e)
|
||||
}
|
||||
if (result && result.ok && result.duplicate !== 'none') {
|
||||
// 又发现重复:保存已成功数量,再次弹出确认
|
||||
duplicateSuccessCount.value = successCount
|
||||
duplicateDialogState.value = {
|
||||
open: true,
|
||||
url: uri,
|
||||
result,
|
||||
pendingUrls,
|
||||
currentIndex: i,
|
||||
}
|
||||
return
|
||||
}
|
||||
// 检查失败(result 为 null)或无重复:直接添加(自动重命名以防磁盘文件冲突)
|
||||
try {
|
||||
await store.addTask(uri, undefined, dir, undefined, true)
|
||||
successCount++
|
||||
} catch (e) {
|
||||
@@ -421,6 +449,7 @@ const onDuplicateConfirm = async () => {
|
||||
}
|
||||
}
|
||||
finishAdd(successCount)
|
||||
duplicateSuccessCount.value = 0
|
||||
}
|
||||
|
||||
/** 累积的成功计数(跨多次重复确认) */
|
||||
@@ -432,9 +461,9 @@ const onDuplicateSkip = () => {
|
||||
duplicateDialogState.value.open = false
|
||||
const remaining = pendingUrls.slice(currentIndex + 1)
|
||||
if (remaining.length > 0) {
|
||||
// 继续处理剩余 URL(不添加当前这个)
|
||||
// 继续处理剩余 URL(不添加当前这个),并带上此前已累积的成功数量
|
||||
const dir = addDir.value.trim() || undefined
|
||||
processUrlsWithCheck(remaining, dir).then(() => {})
|
||||
processUrlsWithCheck(remaining, dir, duplicateSuccessCount.value)
|
||||
} else {
|
||||
finishAdd(duplicateSuccessCount.value)
|
||||
duplicateSuccessCount.value = 0
|
||||
@@ -472,8 +501,8 @@ const handleSelectDir = async () => {
|
||||
const handleSelectSettingsDir = async () => {
|
||||
try {
|
||||
const selected = await openDialog({ directory: true, multiple: false })
|
||||
if (typeof selected === 'string' && store.settings) {
|
||||
await store.saveSettings({ ...store.settings, downloadDir: selected })
|
||||
if (typeof selected === 'string' && settingsDraft.value) {
|
||||
await store.saveSettings({ ...settingsDraft.value, downloadDir: selected })
|
||||
toast.success('下载目录已更新')
|
||||
}
|
||||
} catch (e) {
|
||||
@@ -483,9 +512,9 @@ const handleSelectSettingsDir = async () => {
|
||||
|
||||
// ===== 设置保存 =====
|
||||
const handleSaveSettings = async (): Promise<boolean> => {
|
||||
if (!store.settings) return false
|
||||
if (!settingsDraft.value) return false
|
||||
try {
|
||||
await store.saveSettings(store.settings)
|
||||
await store.saveSettings({ ...settingsDraft.value })
|
||||
toast.success('设置已保存')
|
||||
return true
|
||||
} catch (e) {
|
||||
@@ -494,6 +523,18 @@ const handleSaveSettings = async (): Promise<boolean> => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 切换代理开关并立即保存(新任务/探测立即生效,正在下载的任务不受影响) */
|
||||
const toggleProxy = async () => {
|
||||
if (!store.settings) return
|
||||
const next = !store.settings.useProxy
|
||||
try {
|
||||
await store.saveSettings({ ...store.settings, useProxy: next })
|
||||
toast.success(next ? '已启用系统代理下载' : '已切换为直连下载')
|
||||
} catch (e) {
|
||||
toast.error('切换失败: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
// 注册保存处理函数到标签栏 store(TitleBar 保存按钮调用)
|
||||
tabsStore.registerSave(handleSaveSettings)
|
||||
|
||||
@@ -504,7 +545,8 @@ const handleDialogSave = async () => {
|
||||
}
|
||||
|
||||
// ===== 扩展 =====
|
||||
const EXTENSION_STORE_URL = 'https://chromewebstore.google.com/'
|
||||
// Thing Extension 已发布到 Microsoft Edge 加载项商店,暂定优先 Edge;后续如需支持 Chrome 商店再补充入口
|
||||
const EXTENSION_STORE_URL = 'https://microsoftedge.microsoft.com/addons/detail/thing-extension/fpcffdkeemoibkhldghjbkgbgbdpofbo'
|
||||
const handleInstallExtensionOnline = async () => {
|
||||
try {
|
||||
await commands.downloaderOpenUrl(EXTENSION_STORE_URL)
|
||||
@@ -529,9 +571,24 @@ const handleCopy = async (text: string, label: string) => {
|
||||
|
||||
// ===== 生命周期 =====
|
||||
|
||||
// 托盘/扩展触发的标志位:模块已挂载时由 watcher 即时消费
|
||||
// (App.vue 同模块切换不再重新挂载组件,onMounted 不会重新执行)
|
||||
watch(pendingNewDownload, (v) => {
|
||||
if (v) {
|
||||
pendingNewDownload.value = false
|
||||
addDialogOpen.value = true
|
||||
}
|
||||
})
|
||||
watch(pendingShowDownloadTasks, (v) => {
|
||||
if (v) {
|
||||
pendingShowDownloadTasks.value = false
|
||||
activeTab.value = 'tasks'
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await store.init()
|
||||
// 消费托盘菜单"新建下载"标志位
|
||||
// 消费托盘菜单"新建下载"标志位(挂载前设置的场景,watcher 尚未生效)
|
||||
if (pendingNewDownload.value) {
|
||||
pendingNewDownload.value = false
|
||||
addDialogOpen.value = true
|
||||
@@ -747,7 +804,7 @@ const toggleSortOrder = () => {
|
||||
</Tooltip>
|
||||
|
||||
<!-- 搜索框 -->
|
||||
<div class="relative flex-1 min-w-[180px] max-w-xs">
|
||||
<div class="relative flex-1 min-w-[150px] max-w-[220px]">
|
||||
<Search class="absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="searchText"
|
||||
@@ -756,6 +813,26 @@ const toggleSortOrder = () => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 代理开关 -->
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
class="size-8 p-0 bg-transparent"
|
||||
@click="toggleProxy"
|
||||
>
|
||||
<Globe
|
||||
class="size-4"
|
||||
:class="store.settings?.useProxy ? 'text-primary' : 'text-muted-foreground'"
|
||||
/>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
{{ store.settings?.useProxy ? '使用系统代理(mihomo 开启系统代理时经其转发)' : '直连模式' }}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
@@ -800,7 +877,7 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-3 flex-wrap">
|
||||
<span>
|
||||
{{ formatSize(task.completedSize) }} / {{ formatSize(task.totalSize) }}
|
||||
{{ formatSize(task.completedSize) }} / {{ formatTotalSize(task.totalSize) }}
|
||||
</span>
|
||||
<span v-if="task.status === 'active'" class="flex items-center gap-1 text-green-600 dark:text-green-400">
|
||||
<Download class="size-3" />
|
||||
@@ -987,9 +1064,9 @@ const toggleSortOrder = () => {
|
||||
<Label class="text-xs">下载目录</Label>
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
:model-value="store.settings?.downloadDir ?? ''"
|
||||
:model-value="settingsDraft?.downloadDir ?? ''"
|
||||
class="font-mono text-sm"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.downloadDir = String(v))"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.downloadDir = String(v))"
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
@@ -1005,39 +1082,39 @@ const toggleSortOrder = () => {
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">最大同时下载数</Label>
|
||||
<Input
|
||||
:model-value="store.settings?.maxConcurrent ?? 5"
|
||||
:model-value="settingsDraft?.maxConcurrent ?? 5"
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.maxConcurrent = parseInt(String(v)) || 5)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.maxConcurrent = parseInt(String(v)) || 5)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">单任务最大连接数</Label>
|
||||
<Input
|
||||
:model-value="store.settings?.maxConnections ?? 8"
|
||||
:model-value="settingsDraft?.maxConnections ?? 8"
|
||||
type="number"
|
||||
min="1"
|
||||
max="64"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.maxConnections = parseInt(String(v)) || 8)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.maxConnections = parseInt(String(v)) || 8)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">全局速度限制 KB/s(0=不限)</Label>
|
||||
<Input
|
||||
:model-value="store.settings?.globalSpeedLimit ?? 0"
|
||||
:model-value="settingsDraft?.globalSpeedLimit ?? 0"
|
||||
type="number"
|
||||
min="0"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.globalSpeedLimit = parseInt(String(v)) || 0)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.globalSpeedLimit = parseInt(String(v)) || 0)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<Label for="continue-dl" class="cursor-pointer">断点续传</Label>
|
||||
<Switch
|
||||
id="continue-dl"
|
||||
:model-value="store.settings?.continueDownload ?? true"
|
||||
@update:model-value="(v: boolean) => store.settings && (store.settings.continueDownload = v)"
|
||||
:model-value="settingsDraft?.continueDownload ?? true"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.continueDownload = v)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
@@ -1047,8 +1124,8 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<Switch
|
||||
id="delete-files-on-remove"
|
||||
:model-value="store.settings?.deleteFilesOnRemove ?? false"
|
||||
@update:model-value="(v: boolean) => store.settings && (store.settings.deleteFilesOnRemove = v)"
|
||||
:model-value="settingsDraft?.deleteFilesOnRemove ?? false"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.deleteFilesOnRemove = v)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
@@ -1058,8 +1135,19 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<Switch
|
||||
id="check-duplicate"
|
||||
:model-value="store.settings?.checkDuplicate ?? true"
|
||||
@update:model-value="(v: boolean) => store.settings && (store.settings.checkDuplicate = v)"
|
||||
:model-value="settingsDraft?.checkDuplicate ?? true"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.checkDuplicate = v)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<Label for="dl-use-proxy" class="cursor-pointer">使用系统代理</Label>
|
||||
<span class="text-xs text-muted-foreground">下载时尊重系统代理设置(mihomo 开启系统代理时经其转发),关闭则强制直连</span>
|
||||
</div>
|
||||
<Switch
|
||||
id="dl-use-proxy"
|
||||
:model-value="settingsDraft?.useProxy ?? true"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.useProxy = v)"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
@@ -1078,20 +1166,20 @@ const toggleSortOrder = () => {
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">API 端口</Label>
|
||||
<Input
|
||||
:model-value="store.settings?.extensionPort ?? 16800"
|
||||
:model-value="settingsDraft?.extensionPort ?? 16800"
|
||||
type="number"
|
||||
min="1024"
|
||||
max="65535"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.extensionPort = parseInt(String(v)) || 16800)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.extensionPort = parseInt(String(v)) || 16800)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">认证密钥(可空)</Label>
|
||||
<Input
|
||||
:model-value="store.settings?.extensionSecret ?? ''"
|
||||
:model-value="settingsDraft?.extensionSecret ?? ''"
|
||||
type="password"
|
||||
placeholder="留空不启用鉴权"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.extensionSecret = String(v))"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.extensionSecret = String(v))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1118,7 +1206,7 @@ const toggleSortOrder = () => {
|
||||
<CardContent class="flex flex-col gap-4">
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Thing Extension 是一个浏览器扩展,可接管浏览器下载,将下载任务发送到内置下载引擎。
|
||||
支持 Chrome、Edge 等基于 Chromium 的浏览器。
|
||||
已上架 Microsoft Edge 加载项商店,暂定优先使用 Edge;同时支持其他基于 Chromium 的浏览器(需手动加载)。
|
||||
</p>
|
||||
|
||||
<div v-if="store.extensionInfo" class="flex flex-col gap-3">
|
||||
@@ -1202,16 +1290,42 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
|
||||
<div class="rounded-md bg-muted p-3 text-xs text-muted-foreground">
|
||||
<p class="font-medium text-foreground mb-1.5 flex items-center gap-1.5">
|
||||
<p class="font-medium text-foreground mb-2 flex items-center gap-1.5">
|
||||
<Globe class="h-3.5 w-3.5" />
|
||||
配置说明
|
||||
安装与认证说明
|
||||
</p>
|
||||
<ol class="list-decimal list-inside space-y-0.5">
|
||||
<li>在扩展设置中填入 API 地址:<code class="font-mono">{{ store.extensionInfo?.url || 'http://127.0.0.1:16800/' }}</code></li>
|
||||
<li>若设置了认证密钥,请在扩展中填入相同的密钥</li>
|
||||
<li>浏览器访问 <code class="font-mono">chrome://extensions</code>(Edge 为 <code class="font-mono">edge://extensions</code>)</li>
|
||||
<li>开启"开发者模式",加载已解压的扩展程序</li>
|
||||
</ol>
|
||||
<div class="space-y-2.5">
|
||||
<div>
|
||||
<p class="font-medium text-foreground mb-1">一、安装扩展</p>
|
||||
<ol class="list-decimal list-inside space-y-0.5">
|
||||
<li>点击上方"在线安装",跳转至 Microsoft Edge 加载项商店安装 Thing Extension</li>
|
||||
<li>安装后点击浏览器工具栏右侧的拼图图标,将扩展固定到工具栏以便操作</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-foreground mb-1">二、配置连接与认证</p>
|
||||
<ol class="list-decimal list-inside space-y-0.5">
|
||||
<li>打开扩展弹窗,在"服务器地址"中填入上方 API 地址:<code class="font-mono">{{ store.extensionInfo?.url || 'http://127.0.0.1:16800/' }}</code></li>
|
||||
<li>若本页设置了认证密钥,请在扩展"认证密钥"中填入相同的密钥;未设置则留空</li>
|
||||
<li>点击"测试连接",提示"已连接 · Thing 下载引擎"即表示认证成功</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-foreground mb-1">三、安全提示</p>
|
||||
<ul class="list-disc list-inside space-y-0.5">
|
||||
<li>密钥为空时仅允许本机访问,局域网内其他设备无法调用下载引擎</li>
|
||||
<li>设置密钥可防止未授权设备向下载引擎提交任务,请妥善保管</li>
|
||||
<li>修改端口或密钥后需在"设置"中保存并重启应用,再同步更新扩展</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<p class="font-medium text-foreground mb-1">四、其他 Chromium 浏览器(手动加载)</p>
|
||||
<ol class="list-decimal list-inside space-y-0.5">
|
||||
<li>浏览器访问 <code class="font-mono">edge://extensions</code>(Chrome 为 <code class="font-mono">chrome://extensions</code>),开启"开发者模式"</li>
|
||||
<li>点击"加载已解压的扩展程序",选择扩展所在目录</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -1233,15 +1347,15 @@ const toggleSortOrder = () => {
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div v-if="store.settings" class="flex flex-col gap-3 py-2">
|
||||
<div v-if="settingsDraft" class="flex flex-col gap-3 py-2">
|
||||
<!-- 下载目录 -->
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">下载目录</Label>
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
:model-value="store.settings.downloadDir"
|
||||
:model-value="settingsDraft.downloadDir"
|
||||
class="font-mono text-sm"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.downloadDir = String(v))"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.downloadDir = String(v))"
|
||||
/>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
@@ -1259,21 +1373,21 @@ const toggleSortOrder = () => {
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">最大同时下载数</Label>
|
||||
<Input
|
||||
:model-value="store.settings.maxConcurrent"
|
||||
:model-value="settingsDraft.maxConcurrent"
|
||||
type="number"
|
||||
min="1"
|
||||
max="20"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.maxConcurrent = parseInt(String(v)) || 5)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.maxConcurrent = parseInt(String(v)) || 5)"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">单任务最大连接数</Label>
|
||||
<Input
|
||||
:model-value="store.settings.maxConnections"
|
||||
:model-value="settingsDraft.maxConnections"
|
||||
type="number"
|
||||
min="1"
|
||||
max="64"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.maxConnections = parseInt(String(v)) || 8)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.maxConnections = parseInt(String(v)) || 8)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1282,10 +1396,10 @@ const toggleSortOrder = () => {
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<Label class="text-xs">全局速度限制 KB/s(0=不限)</Label>
|
||||
<Input
|
||||
:model-value="store.settings.globalSpeedLimit"
|
||||
:model-value="settingsDraft.globalSpeedLimit"
|
||||
type="number"
|
||||
min="0"
|
||||
@update:model-value="(v: string | number) => store.settings && (store.settings.globalSpeedLimit = parseInt(String(v)) || 0)"
|
||||
@update:model-value="(v: string | number) => settingsDraft && (settingsDraft.globalSpeedLimit = parseInt(String(v)) || 0)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1294,8 +1408,21 @@ const toggleSortOrder = () => {
|
||||
<Label for="dl-continue" class="cursor-pointer">断点续传</Label>
|
||||
<Switch
|
||||
id="dl-continue"
|
||||
:model-value="store.settings.continueDownload"
|
||||
@update:model-value="(v: boolean) => store.settings && (store.settings.continueDownload = v)"
|
||||
:model-value="settingsDraft.continueDownload"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.continueDownload = v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 使用系统代理 -->
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<Label for="dl-dialog-use-proxy" class="cursor-pointer">使用系统代理</Label>
|
||||
<span class="text-xs text-muted-foreground">关闭则强制直连</span>
|
||||
</div>
|
||||
<Switch
|
||||
id="dl-dialog-use-proxy"
|
||||
:model-value="settingsDraft.useProxy"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.useProxy = v)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1307,8 +1434,8 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<Switch
|
||||
id="dl-delete-files"
|
||||
:model-value="store.settings.deleteFilesOnRemove"
|
||||
@update:model-value="(v: boolean) => store.settings && (store.settings.deleteFilesOnRemove = v)"
|
||||
:model-value="settingsDraft.deleteFilesOnRemove"
|
||||
@update:model-value="(v: boolean) => settingsDraft && (settingsDraft.deleteFilesOnRemove = v)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1542,7 +1669,7 @@ const toggleSortOrder = () => {
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-xs text-muted-foreground">文件总大小</span>
|
||||
<span>{{ formatSize(detailTask.totalSize) }}</span>
|
||||
<span>{{ formatTotalSize(detailTask.totalSize) }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-xs text-muted-foreground">已下载</span>
|
||||
@@ -1550,7 +1677,7 @@ const toggleSortOrder = () => {
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-xs text-muted-foreground">下载进度</span>
|
||||
<span>{{ getProgress(detailTask) }}%</span>
|
||||
<span>{{ detailTask.totalSize ? getProgress(detailTask) + '%' : '未知' }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col gap-0.5">
|
||||
<span class="text-xs text-muted-foreground">当前速度</span>
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
ShieldCheck, ShieldOff, Zap, Thermometer, Clock, ChevronDown,
|
||||
ArrowDown, ArrowUp, Wifi, FolderOpen, Copy, ListChecks,
|
||||
Monitor as MonitorIcon, GripVertical, SlidersHorizontal,
|
||||
Eye, EyeOff, MousePointerClick,
|
||||
Eye, EyeOff, MousePointerClick, Plus, PencilLine,
|
||||
CircuitBoard, BatteryFull,
|
||||
} from '@lucide/vue'
|
||||
import type { LucideIcon } from '@lucide/vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { VueDraggable } from 'vue-draggable-plus'
|
||||
@@ -23,8 +25,10 @@ import {
|
||||
type AlertConfig,
|
||||
DEFAULT_COLOR_THEME,
|
||||
} from '@/stores/monitorStore'
|
||||
import { STORAGE_KEYS } from '@/lib/constants'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { fmt, tempColor, loadColor, fmtSpeed, typeLabel, groupDisplayName, groupIcon } from './format'
|
||||
import { fmt, tempColor, fmtSpeed, typeLabel, groupDisplayName, groupIcon } from './format'
|
||||
import OverviewCard, { type OverviewCardView } from './OverviewCard.vue'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -193,6 +197,183 @@ const storageDrives = computed<StorageDrive[]>(() => {
|
||||
const downSpeed = computed(() => fmtSpeed(store.networkSpeed?.downloadBps ?? null))
|
||||
const upSpeed = computed(() => fmtSpeed(store.networkSpeed?.uploadBps ?? null))
|
||||
|
||||
// ===== 概览页卡片化布局(模板化卡片 + 自由添加/排序) =====
|
||||
|
||||
/** 概览卡片类型 id */
|
||||
type OverviewCardId = 'cpu' | 'gpu' | 'memory' | 'network' | 'storage' | 'motherboard' | 'battery' | 'psu'
|
||||
|
||||
/** 卡片目录:可添加的全部硬件卡片 */
|
||||
const OVERVIEW_CARD_CATALOG: { id: OverviewCardId; name: string; desc: string; icon: LucideIcon }[] = [
|
||||
{ id: 'cpu', name: 'CPU', desc: '温度 / 功耗 / 负载', icon: Cpu },
|
||||
{ id: 'gpu', name: 'GPU', desc: '温度 / 功耗 / 负载', icon: Gauge },
|
||||
{ id: 'memory', name: '内存', desc: '用量 / 负载', icon: MemoryStick },
|
||||
{ id: 'network', name: '网络', desc: '下载 / 上传速率', icon: Wifi },
|
||||
{ id: 'storage', name: '存储', desc: '各硬盘温度 / 容量 / 使用率', icon: HardDrive },
|
||||
{ id: 'motherboard', name: '主板', desc: '温度 / 风扇', icon: CircuitBoard },
|
||||
{ id: 'battery', name: '电池', desc: '电量 / 充放电功率', icon: BatteryFull },
|
||||
{ id: 'psu', name: '电源', desc: '输出功率', icon: Zap },
|
||||
]
|
||||
|
||||
const OVERVIEW_CARDS_VERSION = 1
|
||||
/** 默认显示的卡片(用户需求:cpu/gpu/内存/网络) */
|
||||
const DEFAULT_OVERVIEW_CARDS: OverviewCardId[] = ['cpu', 'gpu', 'memory', 'network']
|
||||
|
||||
/** 加载持久化的卡片列表(过滤未知 id,空则回退默认) */
|
||||
function loadOverviewCards(): OverviewCardId[] {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEYS.monitorOverviewCards)
|
||||
if (!saved) return [...DEFAULT_OVERVIEW_CARDS]
|
||||
const parsed = JSON.parse(saved)
|
||||
if (parsed?.version !== OVERVIEW_CARDS_VERSION) return [...DEFAULT_OVERVIEW_CARDS]
|
||||
const ids: string[] = Array.isArray(parsed.cards) ? parsed.cards : []
|
||||
const valid = ids.filter(id => OVERVIEW_CARD_CATALOG.some(c => c.id === id)) as OverviewCardId[]
|
||||
return valid.length ? valid : [...DEFAULT_OVERVIEW_CARDS]
|
||||
} catch {
|
||||
return [...DEFAULT_OVERVIEW_CARDS]
|
||||
}
|
||||
}
|
||||
|
||||
/** 当前显示的卡片列表(顺序即显示顺序) */
|
||||
const overviewCards = ref<OverviewCardId[]>(loadOverviewCards())
|
||||
|
||||
function saveOverviewCards() {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEYS.monitorOverviewCards, JSON.stringify({
|
||||
version: OVERVIEW_CARDS_VERSION,
|
||||
cards: overviewCards.value,
|
||||
}))
|
||||
} catch { /* 忽略 localStorage 写入失败 */ }
|
||||
}
|
||||
|
||||
/** 编辑模式:显示拖拽把手/移除按钮,启用拖拽排序 */
|
||||
const overviewEditing = ref(false)
|
||||
/** 添加卡片 Popover 开关 */
|
||||
const overviewAddOpen = ref(false)
|
||||
|
||||
/** 尚未添加的卡片(添加菜单内容) */
|
||||
const addableOverviewCards = computed(() =>
|
||||
OVERVIEW_CARD_CATALOG.filter(c => !overviewCards.value.includes(c.id))
|
||||
)
|
||||
|
||||
function addOverviewCard(id: OverviewCardId) {
|
||||
if (overviewCards.value.includes(id)) return
|
||||
overviewCards.value.push(id)
|
||||
saveOverviewCards()
|
||||
overviewAddOpen.value = false
|
||||
}
|
||||
|
||||
function removeOverviewCard(id: string) {
|
||||
overviewCards.value = overviewCards.value.filter(c => c !== id)
|
||||
saveOverviewCards()
|
||||
}
|
||||
|
||||
/** 拖拽排序结束:持久化新顺序 */
|
||||
function onOverviewDragEnd() {
|
||||
saveOverviewCards()
|
||||
}
|
||||
|
||||
// --- 主板/电池/电源数据提取(卡片用) ---
|
||||
|
||||
/** 主板分组(motherboard 为空时回退 superio / embeddedcontroller) */
|
||||
const boardGroup = computed(() =>
|
||||
store.groupById['motherboard'] ?? store.groupById['superio'] ?? store.groupById['embeddedcontroller'] ?? null
|
||||
)
|
||||
const boardName = computed(() => boardGroup.value?.sensors[0]?.hardwareName ?? null)
|
||||
const boardTemp = computed(() =>
|
||||
boardGroup.value?.sensors.find(s => s.type === 'temperature' && s.value != null)?.value ?? null
|
||||
)
|
||||
const boardFan = computed(() =>
|
||||
boardGroup.value?.sensors.find(s => s.type === 'fan' && s.value != null)?.value ?? null
|
||||
)
|
||||
|
||||
const batteryLevel = computed(() => {
|
||||
const g = store.groupById['battery']
|
||||
if (!g) return null
|
||||
return g.sensors.find(s => s.name === 'Battery Level' && s.type === 'level')?.value
|
||||
?? g.sensors.find(s => s.type === 'level')?.value
|
||||
?? null
|
||||
})
|
||||
const batteryCharge = computed(() => store.findSensorValue('battery', { name: 'Battery Charge', type: 'power' }))
|
||||
const batteryDischarge = computed(() => store.findSensorValue('battery', { name: 'Battery Discharge', type: 'power' }))
|
||||
const batteryName = computed(() => store.groupById['battery']?.sensors[0]?.hardwareName ?? null)
|
||||
|
||||
const psuPower = computed(() => store.findSensorValue('psu', { type: 'power' }))
|
||||
const psuName = computed(() => store.groupById['psu']?.sensors[0]?.hardwareName ?? null)
|
||||
|
||||
/** 构建各卡片视图数据(从上面的 computed 提取值并格式化) */
|
||||
function buildOverviewCardView(id: OverviewCardId): OverviewCardView {
|
||||
switch (id) {
|
||||
case 'cpu':
|
||||
return {
|
||||
id, title: 'CPU', icon: Cpu, subtitle: cpuModel.value,
|
||||
main: { label: '封装温度', labelIcon: Thermometer, text: fmt(cpuTemp.value, 0), unit: '°C', colorClass: tempColor(cpuTemp.value) },
|
||||
subs: [{ label: '功耗', labelIcon: Zap, text: fmt(cpuPower.value, 1), unit: 'W' }],
|
||||
load: { label: '总负载', value: cpuLoad.value },
|
||||
}
|
||||
case 'gpu':
|
||||
return {
|
||||
id, title: 'GPU', icon: Gauge, subtitle: gpuModel.value,
|
||||
main: { label: '核心温度', labelIcon: Thermometer, text: fmt(gpuTemp.value, 0), unit: '°C', colorClass: tempColor(gpuTemp.value) },
|
||||
subs: [{ label: '功耗', labelIcon: Zap, text: fmt(gpuPower.value, 1), unit: 'W' }],
|
||||
load: { label: '3D 负载', value: gpuLoad.value },
|
||||
}
|
||||
case 'memory':
|
||||
return {
|
||||
id, title: '内存', icon: MemoryStick,
|
||||
subtitle: memTotalGB.value != null ? `${fmt(memTotalGB.value, 0)} GB` : null,
|
||||
subtitleFull: memModuleModels.value.join(', ') || null,
|
||||
main: { label: '已使用', labelIcon: MemoryStick, text: fmt(memUsedGB.value, 1), unit: ` / ${fmt(memTotalGB.value, 1)} GB` },
|
||||
subs: [],
|
||||
load: { label: '负载', value: memLoad.value },
|
||||
}
|
||||
case 'network':
|
||||
return {
|
||||
id, title: '网络', icon: Wifi,
|
||||
main: { label: '下载', labelIcon: ArrowDown, text: downSpeed.value.value, unit: downSpeed.value.unit, colorClass: 'text-sky-500' },
|
||||
subs: [{ label: '上传', labelIcon: ArrowUp, text: upSpeed.value.value, unit: upSpeed.value.unit, colorClass: 'text-violet-500' }],
|
||||
load: null,
|
||||
}
|
||||
case 'storage':
|
||||
return {
|
||||
id, title: '存储', icon: HardDrive,
|
||||
subtitle: storageDrives.value.length ? `${storageDrives.value.length} 个设备` : null,
|
||||
main: { label: '', text: '' },
|
||||
subs: [],
|
||||
load: null,
|
||||
wide: true,
|
||||
}
|
||||
case 'motherboard':
|
||||
return {
|
||||
id, title: '主板', icon: CircuitBoard, subtitle: boardName.value,
|
||||
main: { label: '温度', labelIcon: Thermometer, text: fmt(boardTemp.value, 0), unit: '°C', colorClass: tempColor(boardTemp.value) },
|
||||
subs: [{ label: '风扇', text: fmt(boardFan.value, 0), unit: 'RPM' }],
|
||||
load: null,
|
||||
}
|
||||
case 'battery':
|
||||
return {
|
||||
id, title: '电池', icon: BatteryFull, subtitle: batteryName.value,
|
||||
main: { label: '电量', labelIcon: BatteryFull, text: fmt(batteryLevel.value, 0), unit: '%' },
|
||||
subs: [
|
||||
{ label: '充电', labelIcon: Zap, text: fmt(batteryCharge.value, 1), unit: 'W' },
|
||||
{ label: '放电', labelIcon: Zap, text: fmt(batteryDischarge.value, 1), unit: 'W' },
|
||||
],
|
||||
load: null,
|
||||
}
|
||||
case 'psu':
|
||||
return {
|
||||
id, title: '电源', icon: Zap, subtitle: psuName.value,
|
||||
main: { label: '输出功率', labelIcon: Zap, text: fmt(psuPower.value, 1), unit: 'W' },
|
||||
subs: [],
|
||||
load: null,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 当前卡片视图列表(与 overviewCards 顺序一一对应) */
|
||||
const overviewCardViews = computed<OverviewCardView[]>(() =>
|
||||
overviewCards.value.map(buildOverviewCardView)
|
||||
)
|
||||
|
||||
// ===== 连接状态徽章 =====
|
||||
const stateMeta: Record<ConnectionState, { text: string; class: string }> = {
|
||||
idle: { text: '未启动', class: 'bg-muted text-muted-foreground' },
|
||||
@@ -1139,249 +1320,155 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
<p class="text-sm">正在加载...</p>
|
||||
</div>
|
||||
|
||||
<!-- 始终显示卡片网格,未启动时数据以占位符显示,保持画面完整 -->
|
||||
<div v-else key="content" class="grid grid-cols-1 md:grid-cols-3 gap-2.5">
|
||||
<!-- CPU(温度 + 功耗 + 频率,未读数据以 -- 占位) -->
|
||||
<Card class="py-0 gap-0">
|
||||
<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>
|
||||
<Tooltip>
|
||||
<template v-else>
|
||||
<!-- ===== Kernel 状态栏(置顶紧凑横条) ===== -->
|
||||
<Card class="py-0 gap-0 mb-2.5">
|
||||
<CardContent class="px-3.5 py-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">
|
||||
<span class="flex items-center gap-1.5 font-medium text-sm">
|
||||
<Activity class="size-4 text-primary" />Kernel
|
||||
</span>
|
||||
<span :class="['px-2 py-0.5 rounded-full', stateMeta[store.connState].class]">
|
||||
{{ stateMeta[store.connState].text }}
|
||||
</span>
|
||||
<Badge :variant="store.snapshot?.isAdmin ? 'default' : 'outline'" :class="store.snapshot?.isAdmin ? 'bg-emerald-500 hover:bg-emerald-500' : ''">
|
||||
{{ store.snapshot?.isAdmin ? '管理员' : '普通' }}
|
||||
</Badge>
|
||||
<Badge v-if="store.status?.thingElevated" variant="outline" class="border-emerald-500/50 text-emerald-600 dark:text-emerald-400">
|
||||
<ShieldCheck class="size-2.5 mr-0.5" />提权
|
||||
</Badge>
|
||||
<span class="text-muted-foreground">PID: <span class="font-mono text-foreground">{{ store.status?.pid ?? '--' }}</span></span>
|
||||
<span class="text-muted-foreground">传感器: <span class="font-mono text-foreground">{{ store.status?.sensorCount ?? '--' }}</span></span>
|
||||
<span class="text-muted-foreground">重启: <span class="font-mono text-foreground">{{ store.status?.restartCount ?? 0 }}</span></span>
|
||||
<span class="text-muted-foreground">事件: <span class="font-mono text-foreground">{{ store.eventCount }}</span></span>
|
||||
<div class="flex items-center gap-1.5 ml-auto">
|
||||
<!-- 启动中 loading(starting=true 但状态还没变为 loading 时显示) -->
|
||||
<Button v-if="store.starting && store.connState === 'idle'" size="xs" variant="outline" disabled>
|
||||
<Loader2 class="size-3 animate-spin" />启动中
|
||||
</Button>
|
||||
<!-- 启动按钮(未运行且非启动中时显示) -->
|
||||
<Button v-if="store.connState === 'idle' && !store.starting" size="xs" :disabled="store.starting" @click="handleStart">
|
||||
<Play class="size-3" />启动
|
||||
</Button>
|
||||
<!-- 提权按钮(标志未启用时显示:设置标志 + 以管理员权限重启 Thing) -->
|
||||
<Tooltip v-if="!store.elevateOnLaunch">
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2">{{ cpuModel ?? '--' }}</span>
|
||||
<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>{{ cpuModel ?? '' }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">以管理员权限重启 Thing(弹 UAC,ThingHK 子进程继承权限,后续启动自动提权,崩溃自动重启)</TooltipContent>
|
||||
</Tooltip>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
<!-- 温度 + 功耗 -->
|
||||
<div class="flex items-end justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1"><Thermometer class="size-3" />封装温度</div>
|
||||
<div :class="['text-2xl font-bold tabular-nums leading-tight', tempColor(cpuTemp)]">
|
||||
{{ fmt(cpuTemp, 0) }}<span class="text-sm font-normal">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1 justify-end"><Zap class="size-3" />功耗</div>
|
||||
<div class="text-base font-medium tabular-nums">{{ fmt(cpuPower, 1) }}<span class="text-xs text-muted-foreground ml-0.5">W</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 负载 -->
|
||||
<div>
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground flex items-center gap-1"><Gauge class="size-3" />总负载</span>
|
||||
<span :class="['font-medium tabular-nums', loadColor(cpuLoad)]">{{ fmt(cpuLoad, 0) }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="cpuLoad ?? 0" class="h-1.5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- GPU(结构与 CPU 一致:温度 + 功耗,未读数据以 -- 占位) -->
|
||||
<Card class="py-0 gap-0">
|
||||
<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>
|
||||
<Tooltip>
|
||||
<!-- 取消提权按钮(标志已启用时显示:清除标志,下次启动不触发 UAC) -->
|
||||
<Tooltip v-else>
|
||||
<TooltipTrigger as-child>
|
||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2">{{ gpuModel ?? '--' }}</span>
|
||||
<Button size="xs" variant="outline" class="gap-1 text-muted-foreground hover:text-foreground" @click="handleCancelElevation">
|
||||
<ShieldOff class="size-3" />取消提权
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ gpuModel ?? '' }}</TooltipContent>
|
||||
<TooltipContent class="max-w-[480px] break-words">取消提权,下次启动将以普通权限运行(不影响当前会话)</TooltipContent>
|
||||
</Tooltip>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
<!-- 温度 + 功耗(与 CPU 卡片结构一致) -->
|
||||
<div class="flex items-end justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1"><Thermometer class="size-3" />核心温度</div>
|
||||
<div :class="['text-2xl font-bold tabular-nums leading-tight', tempColor(gpuTemp)]">
|
||||
{{ fmt(gpuTemp, 0) }}<span class="text-sm font-normal">°C</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-right">
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1 justify-end"><Zap class="size-3" />功耗</div>
|
||||
<div class="text-base font-medium tabular-nums">{{ fmt(gpuPower, 1) }}<span class="text-xs text-muted-foreground ml-0.5">W</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 负载 -->
|
||||
<div>
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground flex items-center gap-1"><Gauge class="size-3" />3D 负载</span>
|
||||
<span :class="['font-medium tabular-nums', loadColor(gpuLoad)]">{{ fmt(gpuLoad, 0) }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="gpuLoad ?? 0" class="h-1.5" />
|
||||
<Button size="xs" variant="outline" :disabled="store.starting || store.stopping || store.connState === 'idle'" @click="handleRefresh">
|
||||
<RefreshCw class="size-3" />刷新
|
||||
</Button>
|
||||
<Button size="xs" variant="outline" :disabled="store.starting || store.stopping || store.connState === 'idle'" @click="handleStop">
|
||||
<Square class="size-3" />停止
|
||||
</Button>
|
||||
<Separator orientation="vertical" class="h-4 mx-0.5" />
|
||||
<!-- 编辑布局开关:拖拽排序 / 删除卡片 -->
|
||||
<Button
|
||||
size="xs"
|
||||
:variant="overviewEditing ? 'default' : 'outline'"
|
||||
:title="overviewEditing ? '完成编辑' : '编辑卡片布局(拖拽排序 / 删除)'"
|
||||
@click="overviewEditing = !overviewEditing"
|
||||
>
|
||||
<PencilLine class="size-3" />{{ overviewEditing ? '完成' : '编辑布局' }}
|
||||
</Button>
|
||||
<!-- 添加卡片 -->
|
||||
<Popover v-model:open="overviewAddOpen">
|
||||
<PopoverTrigger as-child>
|
||||
<Button size="xs" variant="outline" :disabled="!addableOverviewCards.length" title="添加硬件卡片">
|
||||
<Plus class="size-3" />添加卡片
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent class="w-64 p-1.5" align="end">
|
||||
<button
|
||||
v-for="c in addableOverviewCards"
|
||||
:key="c.id"
|
||||
class="w-full flex items-center gap-2.5 rounded-md px-2.5 py-2 text-sm hover:bg-accent transition-colors text-left"
|
||||
@click="addOverviewCard(c.id)"
|
||||
>
|
||||
<component :is="c.icon" class="size-4 text-primary shrink-0" />
|
||||
<span class="min-w-0">
|
||||
<span class="block truncate">{{ c.name }}</span>
|
||||
<span class="block text-xs text-muted-foreground truncate">{{ c.desc }}</span>
|
||||
</span>
|
||||
</button>
|
||||
<div v-if="!addableOverviewCards.length" class="px-2.5 py-2 text-xs text-muted-foreground text-center">所有卡片均已添加</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 内存(主指标大字 + 进度条,未读数据以 -- 占位) -->
|
||||
<Card class="py-0 gap-0">
|
||||
<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>
|
||||
<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">
|
||||
<!-- 已使用 / 总容量(主指标,与 CPU 温度对齐) -->
|
||||
<div class="flex items-end justify-between gap-2">
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1"><MemoryStick class="size-3" />已使用</div>
|
||||
<div class="text-2xl font-bold tabular-nums leading-tight">
|
||||
{{ fmt(memUsedGB, 1) }}<span class="text-sm font-normal text-muted-foreground"> / {{ fmt(memTotalGB, 1) }} GB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 负载进度条(与 CPU 负载对齐) -->
|
||||
<div>
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground flex items-center gap-1"><Gauge class="size-3" />负载</span>
|
||||
<span :class="['font-medium tabular-nums', loadColor(memLoad)]">{{ fmt(memLoad, 0) }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="memLoad ?? 0" class="h-1.5" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 网络(跨3列,下载/上传速率,独立于 Kernel 由 Tauri 后台推送) -->
|
||||
<Card class="md:col-span-3 py-0 gap-0">
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center gap-1.5 text-sm">
|
||||
<Wifi class="size-4 text-primary" />网络
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5">
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<!-- 下载 -->
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1 mb-0.5"><ArrowDown class="size-3 text-sky-500" />下载</div>
|
||||
<div class="text-2xl font-bold tabular-nums leading-tight text-sky-500">
|
||||
{{ downSpeed.value }}<span class="text-sm font-normal text-muted-foreground ml-0.5">{{ downSpeed.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 上传 -->
|
||||
<div>
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1 mb-0.5"><ArrowUp class="size-3 text-violet-500" />上传</div>
|
||||
<div class="text-2xl font-bold tabular-nums leading-tight text-violet-500">
|
||||
{{ upSpeed.value }}<span class="text-sm font-normal text-muted-foreground ml-0.5">{{ upSpeed.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- 存储(跨3列):列出各硬盘温度/容量/使用率,未读到以占位符显示 -->
|
||||
<Card class="md:col-span-3 py-0 gap-0">
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center gap-1.5 text-sm">
|
||||
<HardDrive class="size-4 text-primary" />存储
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5">
|
||||
<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">
|
||||
<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>
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground">使用率</span>
|
||||
<span class="font-mono tabular-nums">{{ fmt(drive.usedPct, 0) }}%</span>
|
||||
<!-- ===== 硬件信息卡片网格(模板化,可编辑:拖拽排序 / 删除 / 添加) ===== -->
|
||||
<VueDraggable
|
||||
v-model="overviewCards"
|
||||
:animation="200"
|
||||
:force-fallback="true"
|
||||
handle=".overview-drag-handle"
|
||||
ghost-class="opacity-40"
|
||||
chosen-class="drag-chosen"
|
||||
:disabled="!overviewEditing"
|
||||
class="grid grid-cols-1 md:grid-cols-4 gap-2.5"
|
||||
@end="onOverviewDragEnd()"
|
||||
>
|
||||
<OverviewCard
|
||||
v-for="view in overviewCardViews"
|
||||
:key="view.id"
|
||||
:view="view"
|
||||
:editing="overviewEditing"
|
||||
@remove="removeOverviewCard(view.id)"
|
||||
>
|
||||
<!-- 存储卡:多盘列表 -->
|
||||
<template v-if="view.id === 'storage'" #body>
|
||||
<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">
|
||||
<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>
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground">使用率</span>
|
||||
<span class="font-mono tabular-nums">{{ fmt(drive.usedPct, 0) }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="drive.usedPct ?? 0" class="h-1" />
|
||||
</div>
|
||||
<div class="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>容量</span>
|
||||
<span class="font-mono tabular-nums">{{ fmt(drive.usedGB, 1) }} / {{ fmt(drive.totalGB, 1) }} GB</span>
|
||||
</div>
|
||||
<Progress :model-value="drive.usedPct ?? 0" class="h-1" />
|
||||
</div>
|
||||
<div class="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<span>容量</span>
|
||||
<span class="font-mono tabular-nums">{{ fmt(drive.usedGB, 1) }} / {{ fmt(drive.totalGB, 1) }} GB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 无数据占位(保持卡片结构完整) -->
|
||||
<div v-else class="text-xs text-muted-foreground py-2 text-center">暂无存储数据</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- Kernel 状态卡片(跨3列,含启动/停止/刷新/提权按钮) -->
|
||||
<Card class="md:col-span-3 py-0 gap-0">
|
||||
<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"><Activity class="size-4 text-primary" />Kernel 状态</span>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span :class="['text-xs px-2 py-0.5 rounded-full', stateMeta[store.connState].class]">
|
||||
{{ stateMeta[store.connState].text }}
|
||||
</span>
|
||||
<Badge :variant="store.snapshot?.isAdmin ? 'default' : 'outline'" :class="store.snapshot?.isAdmin ? 'bg-emerald-500 hover:bg-emerald-500' : ''">
|
||||
{{ store.snapshot?.isAdmin ? '管理员' : '普通' }}
|
||||
</Badge>
|
||||
<Badge v-if="store.status?.thingElevated" variant="outline" class="text-xs border-emerald-500/50 text-emerald-600 dark:text-emerald-400">
|
||||
<ShieldCheck class="size-2.5 mr-0.5" />提权
|
||||
</Badge>
|
||||
</div>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5">
|
||||
<div class="flex flex-wrap items-center gap-x-4 gap-y-1.5 text-xs">
|
||||
<span class="text-muted-foreground">PID: <span class="font-mono text-foreground">{{ store.status?.pid ?? '--' }}</span></span>
|
||||
<span class="text-muted-foreground">传感器: <span class="font-mono text-foreground">{{ store.status?.sensorCount ?? '--' }}</span></span>
|
||||
<span class="text-muted-foreground">重启: <span class="font-mono text-foreground">{{ store.status?.restartCount ?? 0 }}</span></span>
|
||||
<span class="text-muted-foreground">事件: <span class="font-mono text-foreground">{{ store.eventCount }}</span></span>
|
||||
<div class="flex items-center gap-1.5 ml-auto">
|
||||
<!-- 启动中 loading(starting=true 但状态还没变为 loading 时显示) -->
|
||||
<Button v-if="store.starting && store.connState === 'idle'" size="xs" variant="outline" disabled>
|
||||
<Loader2 class="size-3 animate-spin" />启动中
|
||||
</Button>
|
||||
<!-- 启动按钮(未运行且非启动中时显示) -->
|
||||
<Button v-if="store.connState === 'idle' && !store.starting" size="xs" :disabled="store.starting" @click="handleStart">
|
||||
<Play class="size-3" />启动
|
||||
</Button>
|
||||
<!-- 提权按钮(标志未启用时显示:设置标志 + 以管理员权限重启 Thing) -->
|
||||
<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) -->
|
||||
<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>
|
||||
<Button size="xs" variant="outline" :disabled="store.starting || store.stopping || store.connState === 'idle'" @click="handleStop">
|
||||
<Square class="size-3" />停止
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div v-else class="text-xs text-muted-foreground py-2 text-center">暂无存储数据</div>
|
||||
</template>
|
||||
</OverviewCard>
|
||||
<!-- 空占位(全部卡片移除后显示) -->
|
||||
<Card v-if="!overviewCards.length" class="col-span-full py-0 gap-0 no-drag">
|
||||
<CardContent class="py-8 text-center text-sm text-muted-foreground">
|
||||
暂无卡片,点击上方"添加卡片"添加硬件
|
||||
</CardContent>
|
||||
</Card>
|
||||
</VueDraggable>
|
||||
|
||||
<!-- 断线提示 -->
|
||||
<Card v-if="store.connState === 'disconnected'" class="md:col-span-3 border-orange-500/40 py-0 gap-0">
|
||||
<Card v-if="store.connState === 'disconnected'" class="mt-2.5 border-orange-500/40 py-0 gap-0">
|
||||
<CardContent class="pt-3 flex items-start gap-2 text-sm">
|
||||
<AlertTriangle class="size-4 text-orange-500 mt-0.5 shrink-0" />
|
||||
<div>
|
||||
@@ -1392,7 +1479,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
</Card>
|
||||
|
||||
<!-- 错误提示 -->
|
||||
<Card v-if="store.errorMsg" class="md:col-span-3 border-red-500/40 py-0 gap-0">
|
||||
<Card v-if="store.errorMsg" class="mt-2.5 border-red-500/40 py-0 gap-0">
|
||||
<CardContent class="pt-3 flex items-start gap-2 text-sm">
|
||||
<AlertTriangle class="size-4 text-red-500 mt-0.5 shrink-0" />
|
||||
<div>
|
||||
@@ -1401,7 +1488,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</template>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
|
||||
@@ -77,31 +77,19 @@ interface OsdConfig {
|
||||
overlayY?: number | null
|
||||
}
|
||||
|
||||
interface SensorEntry {
|
||||
name: string
|
||||
type: string
|
||||
hardwareName: string
|
||||
value: number | null
|
||||
unit: string
|
||||
}
|
||||
|
||||
interface SensorGroup {
|
||||
id: string
|
||||
sensors: SensorEntry[]
|
||||
}
|
||||
|
||||
interface SensorSnapshot {
|
||||
groups: SensorGroup[]
|
||||
}
|
||||
|
||||
interface NetworkSpeed {
|
||||
downloadBps: number
|
||||
uploadBps: number
|
||||
}
|
||||
|
||||
/** 配置通道载荷(低频:配置变化时推送) */
|
||||
interface OsdStatePayload {
|
||||
config: OsdConfig
|
||||
snapshot: SensorSnapshot | null
|
||||
}
|
||||
|
||||
/** 数据通道载荷(高频:仅显示项 key→value 映射 + 网速) */
|
||||
interface OsdDataPayload {
|
||||
data: Record<string, number | null>
|
||||
networkSpeed: NetworkSpeed | null
|
||||
}
|
||||
|
||||
@@ -333,7 +321,8 @@ function fmtFixedUnit(item: OsdItem): string {
|
||||
|
||||
// ===== 状态 =====
|
||||
const config = ref<OsdConfig | null>(null)
|
||||
const snapshot = ref<SensorSnapshot | null>(null)
|
||||
/** 数据通道:显示项 key→value 映射(由主窗口每秒推送,替代全量快照) */
|
||||
const dataMap = ref<Record<string, number | null>>({})
|
||||
const networkSpeed = ref<NetworkSpeed | null>(null)
|
||||
let unlistenFns: UnlistenFn[] = []
|
||||
|
||||
@@ -341,15 +330,7 @@ let unlistenFns: UnlistenFn[] = []
|
||||
function getOsdItemValue(item: OsdItem): number | null {
|
||||
if (item.special === 'net-up') return networkSpeed.value?.uploadBps ?? null
|
||||
if (item.special === 'net-down') return networkSpeed.value?.downloadBps ?? null
|
||||
if (!snapshot.value) return null
|
||||
for (const g of snapshot.value.groups) {
|
||||
if (g.id !== item.groupId) continue
|
||||
const s = g.sensors.find(s =>
|
||||
s.hardwareName === item.hardwareName && s.name === item.sensorName && s.type === item.type
|
||||
)
|
||||
if (s) return s.value ?? null
|
||||
}
|
||||
return null
|
||||
return dataMap.value[item.key] ?? null
|
||||
}
|
||||
|
||||
// ===== 颜色主题 =====
|
||||
@@ -514,15 +495,19 @@ onMounted(async () => {
|
||||
console.error('[OSD] 启动置顶监视失败:', e)
|
||||
}
|
||||
|
||||
// 监听主窗口推送的 OSD 状态
|
||||
unlistenFns.push(await listen<OsdStatePayload>('osd-state-update', (e) => {
|
||||
// 监听主窗口推送的 OSD 配置(低频通道)
|
||||
unlistenFns.push(await listen<OsdStatePayload>(EVENTS.osdStateUpdate, (e) => {
|
||||
config.value = e.payload.config
|
||||
snapshot.value = e.payload.snapshot
|
||||
networkSpeed.value = e.payload.networkSpeed
|
||||
// 数据/配置变化后重新测量尺寸
|
||||
// 配置变化(字号/布局/显示项)后重新测量尺寸
|
||||
scheduleMeasure()
|
||||
}))
|
||||
|
||||
// 监听主窗口推送的 OSD 数据(高频通道:key→value 映射 + 网速)
|
||||
unlistenFns.push(await listen<OsdDataPayload>(EVENTS.osdDataUpdate, (e) => {
|
||||
dataMap.value = e.payload.data
|
||||
networkSpeed.value = e.payload.networkSpeed
|
||||
}))
|
||||
|
||||
// 监听系统 UI 覆盖事件
|
||||
unlistenFns.push(await listen(EVENTS.osdSystemUiActive, async () => {
|
||||
await applyTopmost(false)
|
||||
@@ -531,6 +516,10 @@ onMounted(async () => {
|
||||
unlistenFns.push(await listen(EVENTS.osdSystemUiInactive, async () => {
|
||||
await applyTopmost(true)
|
||||
}))
|
||||
|
||||
// 监听注册完成后,主动请求主窗口补发配置+数据
|
||||
// (数据通道不含配置;若窗口加载慢错过创建时的首推,需主动请求,否则会一直空白)
|
||||
await emit(EVENTS.osdConfigRequest)
|
||||
})
|
||||
|
||||
/** 鼠标按下:仅在关闭穿透时响应左键拖动 */
|
||||
@@ -652,6 +641,13 @@ onUnmounted(() => {
|
||||
display: inline-flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: stretch;
|
||||
/* 文本永不换行:配置变更(如中英文切换)到窗口 resize 之间存在异步窗口期,
|
||||
若允许换行,中文标签(内存/网络)会在旧窗口宽度内竖排;禁止后仅临时溢出,
|
||||
随内容测量上报触发 setSize 立即恢复 */
|
||||
white-space: nowrap;
|
||||
/* 不被 osd-root(100vw 旧窗口宽度)压缩:否则 getBoundingClientRect 测到的是
|
||||
被旧窗口钳制的宽度而非真实内容宽度,上报后 setSize 不变,窗口永远无法变宽 */
|
||||
flex-shrink: 0;
|
||||
backdrop-filter: blur(8px);
|
||||
padding: 3px 4px;
|
||||
gap: 0;
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 概览页信息卡片模板:统一 CPU/GPU/内存/网络/主板/电池/电源等硬件卡片的结构。
|
||||
* - 标题行:图标 + 标题 + 右侧次要信息(截断 + tooltip)
|
||||
* - 主体:主指标(大字)+ 次指标(右侧小字)+ 负载进度条
|
||||
* - #body 插槽可整体替换主体(如存储卡的多盘列表)
|
||||
* - 编辑模式:显示拖拽把手(.overview-drag-handle)与移除按钮
|
||||
*/
|
||||
import type { LucideIcon } from '@lucide/vue'
|
||||
import { GripVertical } from '@lucide/vue'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { fmt, loadColor } from './format'
|
||||
|
||||
export interface CardMetric {
|
||||
/** 指标名(如 封装温度/功耗) */
|
||||
label: string
|
||||
/** 已格式化的值文本(null 数据传 '--',由 fmt 处理) */
|
||||
text: string
|
||||
/** 值后缀单位(小号弱化显示,可为 ' / 32.0 GB' 这类复合后缀) */
|
||||
unit?: string
|
||||
/** 值颜色 class(温度/负载等着色) */
|
||||
colorClass?: string
|
||||
/** 标签前小图标 */
|
||||
labelIcon?: LucideIcon
|
||||
}
|
||||
|
||||
export interface CardLoad {
|
||||
label: string
|
||||
value: number | null
|
||||
}
|
||||
|
||||
export interface OverviewCardView {
|
||||
/** 卡片类型 id(同目录卡片持久化标识) */
|
||||
id: string
|
||||
title: string
|
||||
icon: LucideIcon
|
||||
/** 右上角次要信息(型号等,截断 + tooltip 完整内容) */
|
||||
subtitle?: string | null
|
||||
/** tooltip 完整内容(默认同 subtitle) */
|
||||
subtitleFull?: string | null
|
||||
/** 主指标(大字) */
|
||||
main: CardMetric
|
||||
/** 次指标(右侧小字) */
|
||||
subs: CardMetric[]
|
||||
/** 负载进度条(null 不显示) */
|
||||
load?: CardLoad | null
|
||||
/** 是否占满整行(如存储多盘列表) */
|
||||
wide?: boolean
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
view: OverviewCardView
|
||||
/** 编辑模式:显示拖拽把手与移除按钮 */
|
||||
editing?: boolean
|
||||
}>(), { editing: false })
|
||||
|
||||
defineEmits<{ remove: [] }>()
|
||||
|
||||
/**
|
||||
* 型号显示文本:超长时截断头部、保留尾部(如 …(TM) i5-10400)。
|
||||
* 后缀(型号核心部分)通常最具辨识度;完整内容见 tooltip。
|
||||
* 型号 span 自身为 flex-1(宽度由布局决定、不随内容变化),直接测量它;
|
||||
* canvas 按该元素实际计算字体测量 + 二分查找保留最长尾部。
|
||||
* 编辑模式把手/删除按钮占位时 span 自动变窄,截断随之收紧。
|
||||
*/
|
||||
const subtitleRef = ref<HTMLElement | null>(null)
|
||||
const { width: subtitleAvailWidth } = useElementSize(subtitleRef)
|
||||
|
||||
let measureCtx: CanvasRenderingContext2D | null = null
|
||||
/** 按型号 span 的实际计算字体测量文本宽度;canvas 不可用时按字符数估算 */
|
||||
function textWidth(text: string): number {
|
||||
const el = subtitleRef.value
|
||||
if (!measureCtx) measureCtx = document.createElement('canvas').getContext('2d')
|
||||
if (!measureCtx || !el) return text.length * 7
|
||||
const cs = getComputedStyle(el)
|
||||
measureCtx.font = `${cs.fontWeight} ${cs.fontSize} ${cs.fontFamily}`
|
||||
return measureCtx.measureText(text).width
|
||||
}
|
||||
|
||||
const displaySubtitle = computed(() => {
|
||||
const s = props.view.subtitle
|
||||
if (!s) return s
|
||||
const avail = subtitleAvailWidth.value - 2 // 预留亚像素/取整余量
|
||||
if (avail <= 0) return s // 容器未就绪:先完整渲染,由 CSS truncate 兜底一帧
|
||||
if (textWidth(s) <= avail) return s
|
||||
// 二分找最大 n:'…' + 末尾 n 字符能放进可用宽度
|
||||
let lo = 1
|
||||
let hi = s.length
|
||||
while (lo < hi) {
|
||||
const mid = Math.ceil((lo + hi) / 2)
|
||||
if (textWidth(`…${s.slice(-mid)}`) <= avail) lo = mid
|
||||
else hi = mid - 1
|
||||
}
|
||||
return `…${s.slice(-lo)}`
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card
|
||||
:class="[
|
||||
'py-0 gap-0 overflow-hidden',
|
||||
view.wide ? 'col-span-full' : '',
|
||||
]"
|
||||
>
|
||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
||||
<CardTitle class="flex items-center gap-1.5 text-sm">
|
||||
<!-- 扁平单行 flex:把手/图标/标题 + 型号(flex-1 占满剩余)+ 删除按钮 -->
|
||||
<span
|
||||
v-if="editing"
|
||||
class="overview-drag-handle cursor-grab active:cursor-grabbing text-muted-foreground/40 hover:text-muted-foreground transition-colors no-native-drag shrink-0"
|
||||
title="拖动排序"
|
||||
>
|
||||
<GripVertical class="size-3.5" />
|
||||
</span>
|
||||
<component :is="view.icon" class="size-4 text-primary shrink-0" />
|
||||
<span class="truncate">{{ view.title }}</span>
|
||||
<!-- 型号:直接 flex 子项(自动块化,truncate 生效),flex-1 宽度由布局决定 -->
|
||||
<Tooltip v-if="view.subtitle">
|
||||
<TooltipTrigger as-child>
|
||||
<span ref="subtitleRef" class="min-w-0 flex-1 truncate text-right text-xs text-muted-foreground font-normal">{{ displaySubtitle }}</span>
|
||||
</TooltipTrigger>
|
||||
<!-- align=end:触发 span 为 flex-1 撑满标题行,默认居中对齐会让 tooltip 落在卡片中央;
|
||||
对齐右缘使其出现在右对齐的型号文字正上方 -->
|
||||
<TooltipContent align="end">{{ view.subtitleFull ?? view.subtitle }}</TooltipContent>
|
||||
</Tooltip>
|
||||
<span v-else class="flex-1" aria-hidden="true" />
|
||||
<Button
|
||||
v-if="editing"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
class="text-muted-foreground hover:text-destructive shrink-0"
|
||||
title="移除卡片"
|
||||
@click="$emit('remove')"
|
||||
>
|
||||
<span class="text-lg leading-none">×</span>
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
||||
<!-- 自定义主体(如存储多盘列表) -->
|
||||
<slot name="body">
|
||||
<!-- 主指标 + 次指标 -->
|
||||
<div class="flex items-end justify-between gap-2">
|
||||
<div class="min-w-0">
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<component :is="view.main.labelIcon" v-if="view.main.labelIcon" class="size-3 shrink-0" />
|
||||
<span class="truncate">{{ view.main.label }}</span>
|
||||
</div>
|
||||
<div :class="['text-2xl font-bold tabular-nums leading-tight', view.main.colorClass]">
|
||||
{{ view.main.text }}<span v-if="view.main.unit" class="text-sm font-normal text-muted-foreground">{{ view.main.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-for="sub in view.subs" :key="sub.label" class="text-right shrink-0">
|
||||
<div class="text-xs text-muted-foreground flex items-center gap-1 justify-end">
|
||||
<component :is="sub.labelIcon" v-if="sub.labelIcon" class="size-3 shrink-0" />
|
||||
<span>{{ sub.label }}</span>
|
||||
</div>
|
||||
<div :class="['text-base font-medium tabular-nums', sub.colorClass]">
|
||||
{{ sub.text }}<span v-if="sub.unit" class="text-xs text-muted-foreground ml-0.5 font-normal">{{ sub.unit }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- 负载进度条 -->
|
||||
<div v-if="view.load">
|
||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
||||
<span class="text-muted-foreground">{{ view.load.label }}</span>
|
||||
<span :class="['font-medium tabular-nums', loadColor(view.load.value)]">{{ fmt(view.load.value, 0) }}%</span>
|
||||
</div>
|
||||
<Progress :model-value="view.load.value ?? 0" class="h-1.5" />
|
||||
</div>
|
||||
</slot>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
+169
-113
@@ -7,12 +7,14 @@ import {
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { appDataDir } from '@tauri-apps/api/path'
|
||||
import { revealItemInDir } from '@tauri-apps/plugin-opener'
|
||||
import { useProxyStore, type ProxyNode } from '@/stores/proxyStore'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { EVENTS } from '@/lib/constants'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
@@ -66,7 +68,14 @@ const onConfirmCancel = () => {
|
||||
confirmState.value.resolve?.(false)
|
||||
}
|
||||
const onConfirmOpenChange = (open: boolean) => {
|
||||
if (!open) onConfirmCancel()
|
||||
// reka-ui 的 AlertDialogAction/Cancel 点击时会先触发 update:open(false)(自动关闭),
|
||||
// 再触发各自的 @click。若关闭事件立即按「取消」处理,会把确认误判为取消(确认按钮点了没反应)。
|
||||
// 因此关闭时的取消判定推迟到当前事件循环的 click 处理器执行完毕后再进行。
|
||||
if (!open && !confirmState.value.resolved) {
|
||||
setTimeout(() => {
|
||||
if (!confirmState.value.resolved) onConfirmCancel()
|
||||
}, 0)
|
||||
}
|
||||
confirmState.value.open = open
|
||||
}
|
||||
|
||||
@@ -90,16 +99,13 @@ const testingGroups = ref<Set<string>>(new Set())
|
||||
const loadingProxies = ref(false)
|
||||
const checkingUpdate = ref(false)
|
||||
const updatingKernel = ref(false)
|
||||
const kernelUpdateInfo = ref<{ latestVersion: string; hasUpdate: boolean } | null>(null)
|
||||
const kernelUpdateInfo = ref<{ latestVersion: string; hasUpdate: boolean; downloadUrl: string } | null>(null)
|
||||
|
||||
// 自动切换节点(从 settings 持久化)
|
||||
// 自动切换节点(从 settings 持久化;执行由后端调度)
|
||||
const autoSwitchEnabled = ref(false)
|
||||
const autoSwitchInterval = ref(5) // 分钟
|
||||
const autoSwitchTargetGroup = ref('') // 目标代理组
|
||||
const autoSwitchRegion = ref('') // 空=全部,否则按地区过滤
|
||||
let autoSwitchTimer: ReturnType<typeof setInterval> | null = null
|
||||
/** 自动切换执行中标志(防重入:测速超时时上一轮未结束,间隔触发会重叠) */
|
||||
let autoSwitchRunning = false
|
||||
|
||||
// 从 store.settings 同步自动切换设置
|
||||
const syncAutoSwitchSettings = () => {
|
||||
@@ -127,6 +133,9 @@ const saveAutoSwitchSettings = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
// 后端自动切换事件监听句柄(模块卸载时关闭)
|
||||
let autoSwitchUnlisten: UnlistenFn[] = []
|
||||
|
||||
// 手风琴展开项
|
||||
const accordionValue = ref<string>('')
|
||||
|
||||
@@ -328,10 +337,6 @@ const init = async () => {
|
||||
await store.waitForApi()
|
||||
store.refreshVersion()
|
||||
loadProxiesWithError()
|
||||
// 若自动切换已开启,恢复定时器(静默,不弹通知、不立即执行)
|
||||
if (autoSwitchEnabled.value) {
|
||||
startAutoSwitch(false, false)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// 无论初始化链路是否出错,都结束"加载中"占位,避免模块永久卡死
|
||||
@@ -350,12 +355,17 @@ onMounted(() => {
|
||||
}, 3000)
|
||||
// 页面重新可见时立即刷新一次系统代理状态(切回标签页/从托盘返回主窗口)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
// 监听后端自动切换节点完成事件(后台执行,不依赖模块激活)
|
||||
listen<{ switched?: boolean; group?: string; name?: string; delay?: number }>(EVENTS.proxyAutoSwitch, onProxyAutoSwitch)
|
||||
.then(fn => autoSwitchUnlisten.push(fn))
|
||||
.catch(err => logger.error('注册自动切换事件监听失败: ' + err))
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (statusTimer) clearInterval(statusTimer)
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
stopAutoSwitch()
|
||||
autoSwitchUnlisten.forEach(fn => fn())
|
||||
autoSwitchUnlisten = []
|
||||
})
|
||||
|
||||
/** 页面可见性变化时刷新系统代理状态(低成本感知外部修改) */
|
||||
@@ -370,11 +380,6 @@ watch(running, async (val, old) => {
|
||||
await store.waitForApi()
|
||||
await store.refreshVersion()
|
||||
await loadProxiesWithError()
|
||||
// 自动切换若已开启,mihomo 启动/重启后恢复定时器(静默,不弹通知)
|
||||
// (handleStop 会停掉旧定时器,此处统一接管启动路径,避免开关显示开但功能静默失效)
|
||||
if (autoSwitchEnabled.value) {
|
||||
startAutoSwitch(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -417,7 +422,6 @@ const handleStart = async () => {
|
||||
const handleStop = async () => {
|
||||
stopping.value = true
|
||||
try {
|
||||
stopAutoSwitch()
|
||||
await store.stop()
|
||||
toast.success('mihomo 已停止')
|
||||
} catch (e) {
|
||||
@@ -448,6 +452,12 @@ const handleRestart = async () => {
|
||||
|
||||
// ===== 系统代理 =====
|
||||
const onToggleSystemProxy = async (on: boolean) => {
|
||||
// 停机时禁止开启(正常情况下开关已禁用,此处兜底防止外部调用)
|
||||
if (on && !running.value) {
|
||||
toast.warning('请先启动 mihomo 再开启系统代理')
|
||||
store.refreshSystemProxy()
|
||||
return
|
||||
}
|
||||
sysProxyLoading.value = true
|
||||
try {
|
||||
await store.toggleSystemProxy(on)
|
||||
@@ -485,46 +495,26 @@ const quickSwitchNode = async (name: string) => {
|
||||
try {
|
||||
await store.selectProxy(mainGroupName.value, name)
|
||||
toast.success('节点已切换', { description: name })
|
||||
// 测速新节点
|
||||
store.testDelay(name).then(delay => {
|
||||
toast.success(`${name}`, { description: `延迟 ${delay}ms` })
|
||||
// 测速新节点:用 testDelayBatch 以更新 history,保证节点 Badge 显示与结果一致
|
||||
store.testDelayBatch([name]).then(() => {
|
||||
const delay = store.proxies[name]?.history?.[0]?.delay
|
||||
if (delay && delay > 0) {
|
||||
toast.success(`${name}`, { description: `延迟 ${delay}ms` })
|
||||
}
|
||||
}).catch(() => {})
|
||||
} catch (e) {
|
||||
toast.error('切换节点失败', { description: String(e) })
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 自动切换节点 =====
|
||||
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 = () => {
|
||||
if (autoSwitchTimer) {
|
||||
clearInterval(autoSwitchTimer)
|
||||
autoSwitchTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 自动切换节点(执行由后端调度,前端仅负责维护设置并刷新/提示) =====
|
||||
const onToggleAutoSwitch = (on: boolean) => {
|
||||
autoSwitchEnabled.value = on
|
||||
if (on) {
|
||||
startAutoSwitch()
|
||||
toast.success('自动切换已开启', {
|
||||
description: `每 ${autoSwitchInterval.value} 分钟测试并切换至最优节点`
|
||||
})
|
||||
} else {
|
||||
stopAutoSwitch()
|
||||
toast.info('自动切换已关闭')
|
||||
}
|
||||
saveAutoSwitchSettings()
|
||||
@@ -532,52 +522,21 @@ const onToggleAutoSwitch = (on: boolean) => {
|
||||
|
||||
const onAutoSwitchIntervalChange = (val: unknown) => {
|
||||
autoSwitchInterval.value = Number(val) || 5
|
||||
if (autoSwitchEnabled.value) {
|
||||
startAutoSwitch()
|
||||
}
|
||||
saveAutoSwitchSettings()
|
||||
}
|
||||
|
||||
const runAutoSwitch = async () => {
|
||||
if (autoSwitchRunning) return
|
||||
autoSwitchRunning = true
|
||||
/** 后端自动切换完成后刷新节点列表并提示(后台亦可运行,不依赖模块激活) */
|
||||
const onProxyAutoSwitch = async (e: { payload: { switched?: boolean; group?: string; name?: string; delay?: number } }) => {
|
||||
const p = e.payload
|
||||
try {
|
||||
const groupName = autoSwitchTargetGroup.value || mainGroupName.value
|
||||
if (!groupName || !running.value) return
|
||||
const nodes = filteredNodes.value
|
||||
if (!nodes.length) return
|
||||
|
||||
// 使用 testDelayBatch 测速,它会更新 store.proxies[name].history,
|
||||
// 确保 UI 显示的延迟与选优结果一致
|
||||
await store.testDelayBatch(nodes)
|
||||
|
||||
// 从更新后的 history 读取最新延迟
|
||||
const results = nodes.map(name => ({
|
||||
name,
|
||||
delay: store.proxies[name]?.history?.[0]?.delay ?? 0
|
||||
}))
|
||||
|
||||
// 找到有效延迟中最低的
|
||||
const valid = results.filter(r => r.delay > 0)
|
||||
if (!valid.length) {
|
||||
toast.warning('所有节点均超时,未切换')
|
||||
return
|
||||
}
|
||||
valid.sort((a, b) => a.delay - b.delay)
|
||||
const best = valid[0]
|
||||
|
||||
// 如果当前节点不是最优,则切换
|
||||
const currentNow = store.proxies[groupName]?.now ?? ''
|
||||
if (currentNow !== best.name) {
|
||||
await store.selectProxy(groupName, best.name)
|
||||
toast.success('已自动切换到最优节点', {
|
||||
description: `${best.name} (${best.delay}ms)`
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('自动切换失败: ' + e)
|
||||
} finally {
|
||||
autoSwitchRunning = false
|
||||
await store.loadProxies()
|
||||
} catch (err) {
|
||||
logger.error('自动切换后刷新节点失败: ' + err)
|
||||
}
|
||||
if (p?.switched && p.name && p.delay) {
|
||||
toast.success('已自动切换到最优节点', {
|
||||
description: `${p.name} (${p.delay}ms)`
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -586,7 +545,7 @@ const handleCheckUpdate = async () => {
|
||||
checkingUpdate.value = true
|
||||
try {
|
||||
const info = await store.checkKernelUpdate()
|
||||
kernelUpdateInfo.value = { latestVersion: info.latestVersion, hasUpdate: info.hasUpdate }
|
||||
kernelUpdateInfo.value = { latestVersion: info.latestVersion, hasUpdate: info.hasUpdate, downloadUrl: info.downloadUrl }
|
||||
if (info.hasUpdate) {
|
||||
toast.info('发现新版本', { description: `最新: ${info.latestVersion}` })
|
||||
} else {
|
||||
@@ -607,31 +566,26 @@ const handleUpdateKernel = async () => {
|
||||
/** 是否展开"更新内核"区块(下载源 + 进度) */
|
||||
const updateExpanded = ref(false)
|
||||
|
||||
/** 开始更新:停止 mihomo → 调用 updateKernel(复用 installProgress 进度机制) */
|
||||
/** 开始更新:确保有下载 URL → 调用 updateKernel(复用 installProgress 进度机制)。
|
||||
* 下载阶段允许 mihomo 运行(可通过当前系统代理下载),
|
||||
* 解压替换前由 need_stop 阶段弹窗要求停止 mihomo */
|
||||
const handleStartUpdate = async () => {
|
||||
if (store.installing) return
|
||||
// 确认停止 mihomo
|
||||
if (running.value) {
|
||||
const ok = await showConfirm({
|
||||
title: '更新内核',
|
||||
description: '更新内核需要先停止 mihomo,确认继续?',
|
||||
confirmText: '继续更新'
|
||||
})
|
||||
if (!ok) return
|
||||
updatingKernel.value = true
|
||||
// 使用检查更新时获取的下载 URL(缺失时先补查一次,避免后端二次请求 GitHub)
|
||||
let url = kernelUpdateInfo.value?.downloadUrl ?? ''
|
||||
if (!url) {
|
||||
try {
|
||||
await store.stop()
|
||||
const info = await store.checkKernelUpdate()
|
||||
url = info.downloadUrl
|
||||
kernelUpdateInfo.value = { latestVersion: info.latestVersion, hasUpdate: info.hasUpdate, downloadUrl: info.downloadUrl }
|
||||
} catch (e) {
|
||||
toast.error('停止 mihomo 失败', { description: String(e) })
|
||||
updatingKernel.value = false
|
||||
toast.error('获取更新信息失败', { description: String(e) })
|
||||
return
|
||||
} finally {
|
||||
updatingKernel.value = false
|
||||
}
|
||||
}
|
||||
toast.info('开始下载更新...')
|
||||
try {
|
||||
await store.updateKernel(selectedMirrorPrefix.value)
|
||||
await store.updateKernel(selectedMirrorPrefix.value, url)
|
||||
} catch (e) {
|
||||
toast.error('内核更新失败', { description: String(e) })
|
||||
}
|
||||
@@ -641,7 +595,9 @@ const handleStartUpdate = async () => {
|
||||
const installStageText = computed(() => {
|
||||
const stage = store.installProgress?.stage
|
||||
switch (stage) {
|
||||
case 'checking': return '正在检查'
|
||||
case 'downloading': return '正在下载'
|
||||
case 'need_stop': return '等待停止 mihomo'
|
||||
case 'extracting': return '正在解压'
|
||||
case 'replacing': return '正在安装'
|
||||
case 'done': return '安装完成'
|
||||
@@ -654,6 +610,7 @@ const installStageColor = computed(() => {
|
||||
const stage = store.installProgress?.stage
|
||||
if (stage === 'done') return 'text-emerald-500'
|
||||
if (stage === 'error') return 'text-destructive'
|
||||
if (stage === 'need_stop') return 'text-amber-500'
|
||||
return 'text-primary'
|
||||
})
|
||||
|
||||
@@ -672,6 +629,25 @@ const installPercentDisplay = computed(() => {
|
||||
|
||||
const installHasTotal = computed(() => store.installProgress?.totalBytes != null)
|
||||
|
||||
/** 停止下载进行中标记(防止重复点击) */
|
||||
const stoppingDownload = ref(false)
|
||||
|
||||
/** 停止下载:通知后端中止,并立即回退到下载方式卡片(保留 updateExpanded 供重新选择) */
|
||||
const handleStopDownload = async () => {
|
||||
if (stoppingDownload.value || !store.installing) return
|
||||
stoppingDownload.value = true
|
||||
try {
|
||||
await store.cancelKernelInstall()
|
||||
// 立即复位 UI 状态回退到下载方式卡片;后端下载循环稍后中止,updateKernel 会静默结束
|
||||
store.installing = false
|
||||
store.clearInstallProgress()
|
||||
} catch (e) {
|
||||
toast.error('停止下载失败', { description: String(e) })
|
||||
} finally {
|
||||
stoppingDownload.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const formatMB = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)} MB`
|
||||
|
||||
// ===== 首次安装内核 =====
|
||||
@@ -709,12 +685,55 @@ const handleInstallKernel = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** need_stop 弹窗处理中标记(防止重复触发) */
|
||||
let handlingNeedStop = false
|
||||
|
||||
/**
|
||||
* 下载完成、解压替换前:弹窗提示用户停止 mihomo,确认后停止 mihomo 并唤醒后端继续安装。
|
||||
* 取消则中止整个安装流程(后端正在等待确认,通过取消唤醒)。
|
||||
*/
|
||||
const handleNeedStop = async () => {
|
||||
if (handlingNeedStop) return
|
||||
handlingNeedStop = true
|
||||
try {
|
||||
const wasRunning = running.value
|
||||
const ok = await showConfirm({
|
||||
title: '停止 mihomo 后继续',
|
||||
description: wasRunning
|
||||
? '下载已完成。安装新内核前需要停止 mihomo,点击「停止并继续」将自动停止 mihomo 并完成安装。'
|
||||
: '下载已完成。即将安装新内核,点击「继续」完成安装。',
|
||||
confirmText: wasRunning ? '停止并继续' : '继续'
|
||||
})
|
||||
if (!ok) {
|
||||
// 用户取消:中止安装(后端在等待确认,置取消标志唤醒其返回)
|
||||
await store.cancelKernelInstall()
|
||||
return
|
||||
}
|
||||
if (wasRunning) {
|
||||
await store.stop()
|
||||
}
|
||||
await store.confirmInstall()
|
||||
} catch (e) {
|
||||
toast.error('停止 mihomo 失败', { description: String(e) })
|
||||
// 停止失败则中止安装,避免替换阶段因 exe 占用而报错
|
||||
try {
|
||||
await store.cancelKernelInstall()
|
||||
} catch {
|
||||
// 忽略:cancelKernelInstall 内部已记录日志
|
||||
}
|
||||
} finally {
|
||||
handlingNeedStop = false
|
||||
}
|
||||
}
|
||||
|
||||
// 监听安装/更新进度终态,弹 toast 并延时清空进度
|
||||
// 同时处理更新场景下的 updateExpanded 清理(与 installProgress 同步清除,避免更新区块闪烁)
|
||||
watch(
|
||||
() => store.installProgress?.stage,
|
||||
(stage) => {
|
||||
if (stage === 'done') {
|
||||
if (stage === 'need_stop') {
|
||||
handleNeedStop()
|
||||
} else if (stage === 'done') {
|
||||
toast.success('内核安装完成', {
|
||||
description: store.installProgress?.message
|
||||
})
|
||||
@@ -899,12 +918,35 @@ watch(() => store.settings, syncLocalSettings, { immediate: true })
|
||||
|
||||
const saveSettingsForm = async () => {
|
||||
if (!store.settings) return
|
||||
const prev = store.settings
|
||||
try {
|
||||
await store.saveSettings({
|
||||
...store.settings,
|
||||
...localSettings.value
|
||||
})
|
||||
toast.success('设置已保存')
|
||||
|
||||
// 网络相关字段(端口/接口/密钥)变更需重启 mihomo 才生效,运行实例仍在旧值上;
|
||||
// 提示用户重启,避免后续代理 API 调用打到新地址而失败
|
||||
const networkChanged =
|
||||
localSettings.value.mixedPort !== prev.mixedPort ||
|
||||
localSettings.value.externalController !== prev.externalController ||
|
||||
localSettings.value.secret !== prev.secret
|
||||
if (networkChanged && running.value) {
|
||||
toast.warning('端口/接口/密钥已保存,重启 mihomo 后生效(期间代理 API 使用新地址可能暂时不可用)')
|
||||
} else {
|
||||
toast.success('设置已保存')
|
||||
}
|
||||
|
||||
// 纯模式变更(网络字段未变)在运行中即时生效,与概览页行为一致,
|
||||
// 避免「UI 显示新模式、运行实例仍是旧模式」的不一致
|
||||
if (!networkChanged && localSettings.value.mode !== prev.mode && running.value) {
|
||||
try {
|
||||
await invokePatchConfigs({ mode: localSettings.value.mode })
|
||||
await store.loadProxies()
|
||||
} catch (modeErr) {
|
||||
logger.error('运行中应用模式失败,重启后生效: ' + modeErr)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error('保存失败', { description: String(e) })
|
||||
}
|
||||
@@ -1128,12 +1170,12 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
<div class="flex items-center justify-between text-xs">
|
||||
<span :class="installStageColor" class="flex items-center gap-1.5 font-medium">
|
||||
<Loader2
|
||||
v-if="['downloading', 'extracting', 'replacing'].includes(store.installProgress.stage)"
|
||||
v-if="['checking', 'downloading', 'extracting', 'replacing'].includes(store.installProgress.stage)"
|
||||
key="stage-loading"
|
||||
class="size-3 animate-spin"
|
||||
/>
|
||||
<Check v-else-if="store.installProgress.stage === 'done'" key="stage-done" class="size-3" />
|
||||
<AlertCircle v-else-if="store.installProgress.stage === 'error'" key="stage-error" class="size-3" />
|
||||
<AlertCircle v-else-if="['need_stop', 'error'].includes(store.installProgress.stage)" key="stage-warn" class="size-3" />
|
||||
{{ installStageText }}
|
||||
</span>
|
||||
<span v-if="installHasTotal && store.installProgress.stage === 'downloading'" class="font-mono text-muted-foreground">
|
||||
@@ -1141,7 +1183,7 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
</span>
|
||||
</div>
|
||||
<Progress
|
||||
v-if="installHasTotal || store.installProgress.stage !== 'downloading'"
|
||||
v-if="installHasTotal || (store.installProgress.stage !== 'downloading' && store.installProgress.stage !== 'checking')"
|
||||
key="progress-bar"
|
||||
:model-value="installPercentDisplay"
|
||||
class="h-2"
|
||||
@@ -1163,6 +1205,20 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
</template>
|
||||
<template v-else>{{ store.installProgress.message }}</template>
|
||||
</p>
|
||||
<!-- 停止下载:仅在进行中的检查/下载阶段显示,点击后回退到下载方式卡片 -->
|
||||
<div
|
||||
v-if="['checking', 'downloading'].includes(store.installProgress.stage)"
|
||||
class="flex justify-end"
|
||||
>
|
||||
<Button
|
||||
size="sm" variant="outline" class="h-7 text-xs"
|
||||
:disabled="stoppingDownload"
|
||||
@click="handleStopDownload"
|
||||
>
|
||||
<Loader2 v-if="stoppingDownload" class="size-3 animate-spin" />
|
||||
<Square v-else class="size-3" />停止下载
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -1371,7 +1427,7 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="store.systemProxy"
|
||||
:disabled="sysProxyLoading"
|
||||
:disabled="sysProxyLoading || !running"
|
||||
@update:model-value="onToggleSystemProxy"
|
||||
/>
|
||||
</CardContent>
|
||||
@@ -1627,7 +1683,7 @@ tabsStore.registerSave(saveSettingsForm)
|
||||
</Tabs>
|
||||
|
||||
<!-- 通用确认对话框 -->
|
||||
<AlertDialog :model-value="confirmState.open" @update:model-value="onConfirmOpenChange">
|
||||
<AlertDialog :open="confirmState.open" @update:open="onConfirmOpenChange">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{{ confirmState.opts.title }}</AlertDialogTitle>
|
||||
|
||||
@@ -34,6 +34,8 @@ const explorerDir = ref('')
|
||||
const actionMode = ref<'none' | 'extract' | 'rename' | 'delete'>('none')
|
||||
// 面板模式下的窗口高度(比搜索态更高,容纳列表+输入)
|
||||
const ACTION_HEIGHT = 620
|
||||
// 跳过下一次 query 变更触发的防抖搜索(面板 show/hide 重置输入时使用,避免重复搜索)
|
||||
let skipNextSearch = false
|
||||
|
||||
// 批量解压进度事件负载:specta 不导出事件类型,需在此与 Rust 端 actions.rs 同名结构体保持同步
|
||||
interface ExtractProgress {
|
||||
@@ -190,7 +192,8 @@ async function doSearch() {
|
||||
const seq = ++searchSeq
|
||||
const q = query.value.trim()
|
||||
if (!q) {
|
||||
// 空查询:当前目录文件操作(若检测到 Explorer 目录)+ 命令快捷入口 + 历史
|
||||
// 空查询:当前目录文件操作(若检测到 Explorer 目录)+ 历史置顶 + 系统相关条目
|
||||
// (程序相关设置不参与默认展示;所有 Provider 空查询零 IPC,首屏即时)
|
||||
const items = await aggregateSearch('')
|
||||
if (seq !== searchSeq) return // 过期请求丢弃
|
||||
const dirItems = getExplorerActions()
|
||||
@@ -227,9 +230,14 @@ async function doSearch() {
|
||||
|
||||
// 防抖搜索
|
||||
watch(query, () => {
|
||||
// 面板模式下输入搜索词:先退出面板,恢复窗口高度
|
||||
// show/hide 重置输入时跳过(由事件处理器显式搜索/清空)
|
||||
if (skipNextSearch) {
|
||||
skipNextSearch = false
|
||||
return
|
||||
}
|
||||
// 面板模式下输入搜索词:先退出面板,恢复窗口高度(不立即搜索,由下方防抖统一触发)
|
||||
if (actionMode.value !== 'none') {
|
||||
exitMode()
|
||||
exitMode(true)
|
||||
}
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
collapseSubActions()
|
||||
@@ -309,14 +317,15 @@ async function enterDeleteMode() {
|
||||
document.querySelector<HTMLInputElement>('.qp-fa-delete-filter')?.focus()
|
||||
}
|
||||
|
||||
async function exitMode() {
|
||||
async function exitMode(skipSearch = false) {
|
||||
if (actionMode.value === 'none') return
|
||||
actionMode.value = 'none'
|
||||
extractReset()
|
||||
renameReset()
|
||||
deleteReset()
|
||||
await setWindowHeight(420)
|
||||
await doSearch()
|
||||
// watch(query) 路径跳过:稍后防抖会用新 query 搜索,避免双重搜索
|
||||
if (!skipSearch) await doSearch()
|
||||
}
|
||||
|
||||
function extractReset() {
|
||||
@@ -804,7 +813,7 @@ function onSubActionHover(idx: number) {
|
||||
/** 应用类条目(含历史中的应用)不显示 subtitle(路径),让布局更紧凑 */
|
||||
const isAppLike = (item: QPItem) => !!item.iconPath
|
||||
const groupIcon = (group: string) => {
|
||||
if (group === '命令') return Command
|
||||
if (group === '设置') return Settings
|
||||
if (group === '计算') return Calculator
|
||||
if (group === '网页') return Globe
|
||||
if (group === '系统') return Lock
|
||||
@@ -818,7 +827,7 @@ const groupIcon = (group: string) => {
|
||||
|
||||
/** 类型 badge 颜色映射(柔和色块风格,跟随亮/暗主题) */
|
||||
const GROUP_COLORS: Record<string, string> = {
|
||||
命令: 'bg-indigo-500/15 text-indigo-600 dark:text-indigo-400',
|
||||
设置: 'bg-indigo-500/15 text-indigo-600 dark:text-indigo-400',
|
||||
计算: 'bg-amber-500/15 text-amber-600 dark:text-amber-400',
|
||||
网页: 'bg-rose-500/15 text-rose-600 dark:text-rose-400',
|
||||
系统: 'bg-slate-500/15 text-slate-600 dark:text-slate-400',
|
||||
@@ -910,6 +919,16 @@ async function applyTheme() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 检查文件索引状态(后台自动构建完成后启用文件搜索)。首次调用需打开 SQLite,宜后台执行 */
|
||||
async function refreshIndexReady() {
|
||||
try {
|
||||
const stats = await commands.quickpanelFileIndexStats()
|
||||
setFileIndexReady((stats?.total ?? 0) > 0)
|
||||
} catch {
|
||||
/* 索引未初始化,忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await applyTheme()
|
||||
|
||||
@@ -929,10 +948,12 @@ onMounted(async () => {
|
||||
window.addEventListener('storage', onStorage)
|
||||
unlistenFns.push(() => window.removeEventListener('storage', onStorage))
|
||||
|
||||
// 监听弹窗显示事件:同步主题 + 更新 Explorer 当前目录 + 清空输入 + 加载初始结果
|
||||
// 监听弹窗显示事件:更新 Explorer 当前目录 + 清空输入 + 加载初始结果。
|
||||
// 主题同步与索引状态检查均不阻塞首屏结果(索引首次查询需打开 SQLite)
|
||||
unlistenFns.push(await listen<{ dir: string | null }>(EVENTS.quickpanelShow, async (e) => {
|
||||
await applyTheme()
|
||||
explorerDir.value = e.payload?.dir ?? ''
|
||||
void applyTheme()
|
||||
void refreshIndexReady()
|
||||
// 若上次关闭时停留在面板模式,恢复搜索态和窗口高度
|
||||
if (actionMode.value !== 'none') {
|
||||
actionMode.value = 'none'
|
||||
@@ -941,7 +962,15 @@ onMounted(async () => {
|
||||
deleteReset()
|
||||
await setWindowHeight(420)
|
||||
}
|
||||
query.value = ''
|
||||
// 丢弃残留的防抖搜索;重置输入不触发新搜索(下方显式搜索)
|
||||
if (searchTimer) {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
if (query.value !== '') {
|
||||
skipNextSearch = true
|
||||
query.value = ''
|
||||
}
|
||||
await doSearch()
|
||||
await nextTick()
|
||||
inputRef.value?.focus()
|
||||
@@ -953,27 +982,32 @@ onMounted(async () => {
|
||||
}))
|
||||
|
||||
unlistenFns.push(await listen(EVENTS.quickpanelHide, () => {
|
||||
query.value = ''
|
||||
// 取消未触发的防抖搜索;重置输入时跳过搜索(面板已隐藏,避免无效搜索)
|
||||
if (searchTimer) {
|
||||
clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
if (query.value !== '') {
|
||||
skipNextSearch = true
|
||||
query.value = ''
|
||||
}
|
||||
results.value = []
|
||||
}))
|
||||
|
||||
// 初始加载(空查询显示快捷入口)
|
||||
// 独立窗口需自行检查文件索引状态(主窗口的 setFileIndexReady 不共享到此上下文)
|
||||
try {
|
||||
const stats = await commands.quickpanelFileIndexStats()
|
||||
setFileIndexReady((stats?.total ?? 0) > 0)
|
||||
} catch {
|
||||
/* 索引未初始化,忽略 */
|
||||
}
|
||||
await doSearch()
|
||||
await nextTick()
|
||||
inputRef.value?.focus()
|
||||
|
||||
// 先显示窗口(兜底重建路径依赖此调用才真正显示):让面板尽快出现,
|
||||
// 后续数据加载(索引统计/初始搜索)不阻塞显示,避免 dev 下首屏渲染慢导致"唤不出"。
|
||||
try {
|
||||
await commands.quickpanelShowWindow()
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
|
||||
// 初始加载(空查询显示历史置顶 + 系统条目;Provider 空查询零 IPC,即时渲染)
|
||||
// 独立窗口需自行检查文件索引状态(主窗口的 setFileIndexReady 不共享到此上下文)
|
||||
void refreshIndexReady()
|
||||
await doSearch()
|
||||
await nextTick()
|
||||
inputRef.value?.focus()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
@@ -992,7 +1026,7 @@ onUnmounted(() => {
|
||||
ref="inputRef"
|
||||
v-model="query"
|
||||
class="qp-input"
|
||||
placeholder="搜索命令、应用、文件…"
|
||||
placeholder="搜索应用、文件、系统命令…"
|
||||
spellcheck="false"
|
||||
autocomplete="off"
|
||||
/>
|
||||
@@ -1007,7 +1041,7 @@ onUnmounted(() => {
|
||||
<!-- 批量解压面板 -->
|
||||
<template v-if="actionMode === 'extract'">
|
||||
<div class="qp-action-head">
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode"><ChevronLeft class="size-4" /></button>
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode()"><ChevronLeft class="size-4" /></button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="qp-action-title">批量解压</p>
|
||||
<p class="qp-action-dir truncate" :title="explorerDir">{{ explorerDir }}</p>
|
||||
@@ -1108,7 +1142,7 @@ onUnmounted(() => {
|
||||
<!-- 批量重命名面板 -->
|
||||
<template v-else-if="actionMode === 'rename'">
|
||||
<div class="qp-action-head">
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode"><ChevronLeft class="size-4" /></button>
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode()"><ChevronLeft class="size-4" /></button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="qp-action-title">批量重命名</p>
|
||||
<p class="qp-action-dir truncate" :title="explorerDir">{{ explorerDir }}</p>
|
||||
@@ -1215,7 +1249,7 @@ onUnmounted(() => {
|
||||
<!-- 批量删除面板 -->
|
||||
<template v-else-if="actionMode === 'delete'">
|
||||
<div class="qp-action-head">
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode"><ChevronLeft class="size-4" /></button>
|
||||
<button class="qp-back-btn" title="返回搜索" @click="exitMode()"><ChevronLeft class="size-4" /></button>
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="qp-action-title">批量删除</p>
|
||||
<p class="qp-action-dir truncate" :title="explorerDir">{{ explorerDir }}</p>
|
||||
@@ -1324,7 +1358,7 @@ onUnmounted(() => {
|
||||
<div v-else-if="!hasResults()" class="qp-empty">
|
||||
<Command class="size-10 mb-3 opacity-40" />
|
||||
<p class="text-sm">输入关键词开始搜索</p>
|
||||
<p class="text-xs mt-1 opacity-60">命令 · 计算 · 系统 · 网页</p>
|
||||
<p class="text-xs mt-1 opacity-60">设置 · 应用 · 文件 · 系统 · 网页</p>
|
||||
</div>
|
||||
<template v-else>
|
||||
<!-- 目录操作(批量解压/重命名/删除,置顶,可键盘导航) -->
|
||||
@@ -1434,7 +1468,7 @@ onUnmounted(() => {
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
|
||||
<!-- 其他结果(命令/应用/系统等,可键盘导航,索引偏移 dirActionItems.length + historyItems.length) -->
|
||||
<!-- 其他结果(设置/应用/系统等,可键盘导航,索引偏移 dirActionItems.length + historyItems.length) -->
|
||||
<template v-for="(item, idx) in otherItems" :key="item.id">
|
||||
<div
|
||||
class="qp-item"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, onMounted, onUnmounted, watch, nextTick } from 'vue'
|
||||
import { open } from '@tauri-apps/plugin-dialog'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { toast } from 'vue-sonner'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
@@ -10,7 +11,7 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
||||
import { setFileIndexReady, invalidateCustomCommandsCache } from './providers'
|
||||
import { STORAGE_KEYS } from '@/lib/constants'
|
||||
import { STORAGE_KEYS, EVENTS } from '@/lib/constants'
|
||||
|
||||
interface CustomCommand {
|
||||
id: string
|
||||
@@ -43,6 +44,8 @@ interface IndexStats {
|
||||
}
|
||||
const indexStats = ref<IndexStats | null>(null)
|
||||
const building = ref(false)
|
||||
// 索引构建完成事件监听器(onUnmounted 时注销)
|
||||
let indexUpdatedUnlisten: UnlistenFn | null = null
|
||||
|
||||
async function refreshStats() {
|
||||
try {
|
||||
@@ -96,6 +99,10 @@ onMounted(async () => {
|
||||
console.error('[quickpanel] 读取设置失败:', e)
|
||||
}
|
||||
await refreshStats()
|
||||
// 监听索引构建完成事件(闲时自动建立/重建):刷新统计,无需手动刷新
|
||||
indexUpdatedUnlisten = await listen<number>(EVENTS.quickpanelIndexUpdated, () => {
|
||||
void refreshStats()
|
||||
})
|
||||
})
|
||||
|
||||
// ===== 保存 =====
|
||||
@@ -233,6 +240,7 @@ async function clearShortcut() {
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('keydown', onRecordKey, true)
|
||||
indexUpdatedUnlisten?.()
|
||||
// 注销保存处理函数与标签状态,防止其他模块 activeTab=settings 时误执行本模块 saveSettings
|
||||
tabsStore.unregisterTabs()
|
||||
})
|
||||
@@ -515,8 +523,8 @@ async function changeEngine(v: string) {
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-2">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">命令</Badge>
|
||||
<span class="text-muted-foreground">跳转到已启用模块</span>
|
||||
<Badge variant="secondary">设置</Badge>
|
||||
<span class="text-muted-foreground">本程序模块导航与退出应用(搜索时显示,不占用默认视图)</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">自定义</Badge>
|
||||
@@ -556,7 +564,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">系统命令(注册表、CMD/PowerShell、任务管理器、控制面板、关机/重启/休眠)及锁屏、退出应用</span>
|
||||
<span class="text-muted-foreground">系统命令(注册表、CMD/PowerShell、任务管理器、控制面板、关机/重启/休眠)及锁屏,打开面板默认显示</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<Badge variant="secondary">网页</Badge>
|
||||
|
||||
@@ -40,7 +40,7 @@ export const moduleConfig: ModuleConfig = {
|
||||
id: 'quickpanel',
|
||||
name: '快速面板',
|
||||
icon: 'quickpanel',
|
||||
description: '全局快捷键唤起的多源命令面板(命令/应用/文件/计算)',
|
||||
description: '全局快捷键唤起的多源快速启动面板(设置/应用/文件/系统/计算)',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./QuickPanelModule.vue'),
|
||||
|
||||
@@ -39,7 +39,8 @@ export function getProviders(): QPProvider[] {
|
||||
|
||||
/**
|
||||
* 聚合搜索:并行调用各 Provider,合并结果,按 score 降序排序。
|
||||
* 空查询时返回 command Provider 的快捷入口 + system Provider 的固定项。
|
||||
* 空查询时返回历史置顶 + system Provider 的系统条目
|
||||
* (程序相关设置归入「设置」分类,不参与默认展示)。
|
||||
*/
|
||||
export async function aggregateSearch(query: string): Promise<QPItem[]> {
|
||||
const all = getProviders()
|
||||
|
||||
@@ -37,20 +37,20 @@ export class AppProvider implements QPProvider {
|
||||
priority = 95
|
||||
|
||||
async search(query: string): Promise<QPItem[]> {
|
||||
const apps = await loadApps()
|
||||
if (!query.trim()) {
|
||||
// 空查询:不显示应用(避免列表过长),由命令入口承担
|
||||
// 空查询:不显示应用(避免列表过长),也跳过应用扫描 IPC(不阻塞默认视图首屏)
|
||||
return []
|
||||
}
|
||||
const apps = await loadApps()
|
||||
const results: Array<{ item: QPItem; score: number }> = []
|
||||
let idx = 0
|
||||
for (const app of apps) {
|
||||
const forms = buildItemForms(app.name)
|
||||
const score = bestScore(query, forms)
|
||||
if (score >= 0) {
|
||||
results.push({
|
||||
item: {
|
||||
id: `app-${idx}`,
|
||||
// 稳定 id(基于路径):扫描结果顺序变化时历史记录仍能恢复原应用
|
||||
id: `app-${app.path}`,
|
||||
title: app.name,
|
||||
subtitle: app.path,
|
||||
group: '应用',
|
||||
@@ -62,7 +62,6 @@ export class AppProvider implements QPProvider {
|
||||
score,
|
||||
})
|
||||
}
|
||||
idx++
|
||||
}
|
||||
results.sort((a, b) => b.score - a.score)
|
||||
return results.slice(0, 15).map(r => ({ ...r.item, score: r.score }))
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* command Provider:复用主应用模块搜索项。
|
||||
* command Provider:复用主应用模块搜索项(程序内导航入口)。
|
||||
* 独立窗口约束:不加载主应用 store,从 localStorage 读取主应用写入的命令缓存,
|
||||
* 执行时 emit `quickpanel-execute-command` 事件通知主窗口切换模块。
|
||||
* 分类为「设置」:本程序相关条目;空查询不返回(默认视图只显示系统相关条目)。
|
||||
*/
|
||||
import { emit } from '@tauri-apps/api/event'
|
||||
import { bestScore } from '../engine'
|
||||
@@ -19,37 +20,43 @@ interface CachedCommand {
|
||||
keywords: string[]
|
||||
}
|
||||
|
||||
// 解析结果缓存:避免每次按键重复 JSON.parse;
|
||||
// 主窗口写入命令缓存时通过跨窗口 storage 事件失效
|
||||
let commandCache: CachedCommand[] | null = null
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (e.key === COMMANDS_KEY) commandCache = null
|
||||
})
|
||||
}
|
||||
|
||||
function loadCommands(): CachedCommand[] {
|
||||
if (commandCache) return commandCache
|
||||
try {
|
||||
const raw = localStorage.getItem(COMMANDS_KEY)
|
||||
if (!raw) return []
|
||||
return JSON.parse(raw) as CachedCommand[]
|
||||
commandCache = raw ? (JSON.parse(raw) as CachedCommand[]) : []
|
||||
} catch {
|
||||
return []
|
||||
commandCache = []
|
||||
}
|
||||
return commandCache
|
||||
}
|
||||
|
||||
export class CommandProvider implements QPProvider {
|
||||
id = 'command'
|
||||
label = '命令'
|
||||
label = '设置'
|
||||
priority = 100
|
||||
|
||||
search(query: string): QPItem[] {
|
||||
// 空查询不返回程序相关设置:默认视图只显示系统相关条目
|
||||
if (!query.trim()) return []
|
||||
const commands = loadCommands()
|
||||
if (!query.trim() || !commands.length) {
|
||||
// 无输入时返回前几条命令作为快捷入口
|
||||
if (!query.trim()) {
|
||||
return commands.slice(0, 6).map((c, i) => this.toItem(c, i))
|
||||
}
|
||||
return []
|
||||
}
|
||||
if (!commands.length) return []
|
||||
|
||||
const results: Array<{ item: QPItem; score: number }> = []
|
||||
commands.forEach((c, idx) => {
|
||||
commands.forEach((c) => {
|
||||
const forms = buildItemForms(c.title, c.keywords)
|
||||
const score = bestScore(query, forms)
|
||||
if (score >= 0) {
|
||||
const item = this.toItem(c, idx)
|
||||
const item = this.toItem(c)
|
||||
results.push({ item, score })
|
||||
}
|
||||
})
|
||||
@@ -57,12 +64,13 @@ export class CommandProvider implements QPProvider {
|
||||
return results.map(r => ({ ...r.item, score: r.score }))
|
||||
}
|
||||
|
||||
private toItem(c: CachedCommand, idx: number): QPItem {
|
||||
private toItem(c: CachedCommand): QPItem {
|
||||
return {
|
||||
id: `cmd-${c.moduleId}-${idx}`,
|
||||
// 稳定 id(moduleId + title):模块启停导致列表重排时,历史记录仍能恢复原条目
|
||||
id: `cmd-${c.moduleId}-${c.title}`,
|
||||
title: c.title,
|
||||
subtitle: c.description || c.moduleName,
|
||||
group: '命令',
|
||||
group: '设置',
|
||||
action: async () => {
|
||||
// 通知主窗口切换到对应模块
|
||||
await emit(EVENTS.quickpanelExecuteCommand, { moduleId: c.moduleId })
|
||||
|
||||
@@ -40,8 +40,8 @@ export class CustomCommandProvider implements QPProvider {
|
||||
priority = 92
|
||||
|
||||
async search(query: string): Promise<QPItem[]> {
|
||||
if (!query.trim()) return [] // 空查询跳过设置读取 IPC
|
||||
const cmds = await loadCustomCommands()
|
||||
if (!query.trim()) return []
|
||||
const results: Array<{ item: QPItem; score: number }> = []
|
||||
for (const cmd of cmds) {
|
||||
const forms = buildItemForms(cmd.title)
|
||||
|
||||
@@ -19,13 +19,14 @@ export class FileProvider implements QPProvider {
|
||||
if (!fileIndexReady) return []
|
||||
try {
|
||||
const files = await commands.quickpanelSearchFiles(query.trim(), 20)
|
||||
return files.map((f, idx) => {
|
||||
return files.map((f) => {
|
||||
// .lnk 快捷方式按应用处理:带图标、用启动命令,并与开始菜单应用统一去重
|
||||
// 注意:Rust 返回的 ext 不带点(如 "lnk"),这里直接按文件名判断最稳妥
|
||||
const isLnk = !f.isDir && f.name.toLowerCase().endsWith('.lnk')
|
||||
if (isLnk) {
|
||||
return {
|
||||
id: `file-app-${idx}`,
|
||||
// 稳定 id(基于路径):搜索结果顺序变化时历史记录仍能恢复原条目
|
||||
id: `file-app-${f.path}`,
|
||||
title: f.name,
|
||||
subtitle: f.path,
|
||||
group: '应用',
|
||||
@@ -46,7 +47,8 @@ export class FileProvider implements QPProvider {
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: `file-${idx}`,
|
||||
// 稳定 id(基于路径):搜索结果顺序变化时历史记录仍能恢复原条目
|
||||
id: `file-${f.path}`,
|
||||
title: f.name,
|
||||
subtitle: f.path,
|
||||
group: '文件',
|
||||
|
||||
@@ -33,9 +33,9 @@ export class SpecialProvider implements QPProvider {
|
||||
priority = 60
|
||||
|
||||
async search(query: string): Promise<QPItem[]> {
|
||||
if (!query.trim()) return [] // 空查询不占用列表(也跳过 IPC),由用户主动搜索
|
||||
const list = await loadSpecials()
|
||||
if (!list.length) return []
|
||||
if (!query.trim()) return [] // 空查询不占用列表,由用户主动搜索
|
||||
|
||||
const open = async (s: SpecialLocation) => {
|
||||
try {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* system Provider:系统操作。
|
||||
* 内置常用系统命令(regedit / cmd / powershell 等),title 为中文主名,
|
||||
* keywords 补充英文/别名;拼音全拼与首字母由引擎从 title 的 CJK 部分自动推导。
|
||||
* 「退出 Thing」为本程序相关条目,归入设置分类(空查询不显示)。
|
||||
*/
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { bestScore, type TextForms } from '../engine'
|
||||
@@ -122,7 +123,7 @@ export class SystemProvider implements QPProvider {
|
||||
}
|
||||
},
|
||||
}))
|
||||
// 锁屏 + 退出 应用本身
|
||||
// 锁屏(系统操作)+ 退出应用(本程序相关 → 设置分类,默认视图不显示)
|
||||
items.push(
|
||||
{
|
||||
id: 'sys-lock',
|
||||
@@ -141,7 +142,7 @@ export class SystemProvider implements QPProvider {
|
||||
id: 'sys-quit',
|
||||
title: '退出 Thing',
|
||||
subtitle: '关闭应用程序',
|
||||
group: '系统',
|
||||
group: '设置',
|
||||
action: async () => {
|
||||
try {
|
||||
await invoke('quit_app')
|
||||
@@ -163,7 +164,8 @@ export class SystemProvider implements QPProvider {
|
||||
search(query: string): QPItem[] {
|
||||
const items = this.buildItems()
|
||||
|
||||
if (!query.trim()) return items
|
||||
// 空查询:只返回系统相关条目(「退出 Thing」等程序相关项归入设置分类,不默认显示)
|
||||
if (!query.trim()) return items.filter(i => i.group === '系统')
|
||||
const scored: Array<{ item: QPItem; score: number }> = []
|
||||
for (const item of items) {
|
||||
const forms = this.itemForms(item)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onUnmounted, watch, nextTick } from 'vue'
|
||||
import { ref, computed, onUnmounted, watch, nextTick } from 'vue'
|
||||
import {
|
||||
Keyboard, Settings, FolderOpen, Camera, Copy, Save, Trash2, Timer, StickyNote,
|
||||
Image as ImageIcon, Loader2,
|
||||
@@ -29,10 +29,8 @@ const DELAY_OPTIONS = [0, 1, 2, 3, 5]
|
||||
|
||||
function formatTime(t: number): string {
|
||||
const d = new Date(t)
|
||||
const hh = String(d.getHours()).padStart(2, '0')
|
||||
const mm = String(d.getMinutes()).padStart(2, '0')
|
||||
const ss = String(d.getSeconds()).padStart(2, '0')
|
||||
return `${hh}:${mm}:${ss}`
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
|
||||
}
|
||||
|
||||
function thumbSrc(item: RecentCapture): string {
|
||||
@@ -82,6 +80,8 @@ function handleDelete(item: RecentCapture) {
|
||||
|
||||
// ===== 历史保留数量:预设 + 自定义输入 =====
|
||||
const customLimit = ref('')
|
||||
/** 当前值不在预设中 → 自定义模式(输入框高亮表示选中) */
|
||||
const isCustomLimit = computed(() => !HISTORY_LIMITS.includes(store.settings.historyLimit))
|
||||
|
||||
function onLimitPreset(n: number) {
|
||||
store.setSettings({ historyLimit: n })
|
||||
@@ -411,7 +411,8 @@ onUnmounted(() => {
|
||||
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"
|
||||
class="h-8 w-24 rounded-md border bg-transparent px-2 text-sm text-center outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50"
|
||||
:class="isCustomLimit ? 'border-primary bg-primary/10 text-primary' : 'border-input'"
|
||||
placeholder="自定义"
|
||||
title="输入自定义保留数量"
|
||||
@keydown.enter="onCustomLimit"
|
||||
@@ -426,7 +427,7 @@ onUnmounted(() => {
|
||||
</TabsContent>
|
||||
|
||||
<!-- 历史记录 -->
|
||||
<TabsContent value="history" class="flex-1 min-h-0 mt-0">
|
||||
<TabsContent value="history" class="flex-1 min-h-0 mt-4">
|
||||
<ScrollArea class="h-full">
|
||||
<div>
|
||||
<!-- 空状态 -->
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type Point, type Sel, type CaptureData, type WindowInfo, type HandleDir,
|
||||
type RectAnno, type EllipseAnno, type ArrowAnno, type PenAnno, type TextAnno,
|
||||
type MosaicAnno, type HighlightAnno, type NumberAnno,
|
||||
type ScreenshotBeginPayload,
|
||||
} from './types'
|
||||
|
||||
// ===== 窗口 / 底图 =====
|
||||
@@ -65,6 +66,21 @@ const currentHwnd = ref(0)
|
||||
let pickRaf = 0
|
||||
let lastPickX = -1
|
||||
let lastPickY = -1
|
||||
/** 拾取窗口列表(Z 序顶→底,begin 事件携带,与冻结底图同一时刻),JS 本地命中测试零 IPC */
|
||||
let pickWindows: WindowInfo[] = []
|
||||
/** 最近一次鼠标物理坐标(ESC 等回到 pick 阶段时按当前位置恢复高亮,无需移动鼠标) */
|
||||
const lastMousePhys = { x: 0, y: 0 }
|
||||
|
||||
// 入场淡入(快门定格感):idle=整体透明(窗口 show 前的起点)→ fade=淡入中 → done=常态
|
||||
const enterState = ref<'idle' | 'fade' | 'done'>('done')
|
||||
let enterTimer: number | null = null
|
||||
function resetEnterAnim() {
|
||||
if (enterTimer !== null) {
|
||||
clearTimeout(enterTimer)
|
||||
enterTimer = null
|
||||
}
|
||||
enterState.value = 'idle'
|
||||
}
|
||||
|
||||
// 移动 / 缩放
|
||||
const moving = ref(false)
|
||||
@@ -655,51 +671,22 @@ function canvasPoint(e: MouseEvent): Point {
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 窗口识别 =====
|
||||
function scheduleWindowPick(cssX: number, cssY: number) {
|
||||
const physX = Math.round(winOuterX + cssX * dpr)
|
||||
const physY = Math.round(winOuterY + cssY * dpr)
|
||||
if (physX === lastPickX && physY === lastPickY) return
|
||||
lastPickX = physX
|
||||
lastPickY = physY
|
||||
if (pickRaf) return
|
||||
pickRaf = requestAnimationFrame(async () => {
|
||||
pickRaf = 0
|
||||
try {
|
||||
const info = await invoke<WindowInfo | null>('screenshot_window_from_point', {
|
||||
x: physX,
|
||||
y: physY,
|
||||
})
|
||||
if (phase.value !== 'pick') return
|
||||
if (info) {
|
||||
// 高亮框用 DWM 视觉边界,避免 GetWindowRect 包含隐形缩放边框导致大一圈
|
||||
const r = info.visualRect ?? info.rect
|
||||
winHighlight.value = {
|
||||
x: (r.x - winOuterX) / dpr,
|
||||
y: (r.y - winOuterY) / dpr,
|
||||
w: r.width / dpr,
|
||||
h: r.height / dpr,
|
||||
title: info.title,
|
||||
}
|
||||
currentHwnd.value = info.hwnd
|
||||
} else {
|
||||
winHighlight.value = null
|
||||
currentHwnd.value = 0
|
||||
}
|
||||
} catch {
|
||||
// 忽略拾取错误
|
||||
// ===== 窗口识别(本地命中测试,零 IPC) =====
|
||||
/** 在缓存列表中命中测试(与 Rust 拾取同语义:rect 包含点,取 Z 序最顶的第一个命中) */
|
||||
function hitTestWindow(physX: number, physY: number): WindowInfo | null {
|
||||
for (const info of pickWindows) {
|
||||
const r = info.rect
|
||||
if (physX >= r.x && physX < r.x + r.width && physY >= r.y && physY < r.y + r.height) {
|
||||
return info
|
||||
}
|
||||
})
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 按物理坐标拾取窗口(覆盖层打开时定位鼠标所在窗口) */
|
||||
async function pickAt(physX: number, physY: number) {
|
||||
try {
|
||||
const info = await invoke<WindowInfo | null>('screenshot_window_from_point', {
|
||||
x: physX,
|
||||
y: physY,
|
||||
})
|
||||
if (phase.value !== 'pick' || !info) return
|
||||
/** 应用窗口命中结果到高亮状态 */
|
||||
function applyWindowInfo(info: WindowInfo | null) {
|
||||
if (info) {
|
||||
// 高亮框用 DWM 视觉边界,避免 GetWindowRect 包含隐形缩放边框导致大一圈
|
||||
const r = info.visualRect ?? info.rect
|
||||
winHighlight.value = {
|
||||
x: (r.x - winOuterX) / dpr,
|
||||
@@ -709,11 +696,34 @@ async function pickAt(physX: number, physY: number) {
|
||||
title: info.title,
|
||||
}
|
||||
currentHwnd.value = info.hwnd
|
||||
} catch {
|
||||
// 忽略拾取错误
|
||||
} else {
|
||||
winHighlight.value = null
|
||||
currentHwnd.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleWindowPick(cssX: number, cssY: number) {
|
||||
const physX = Math.round(winOuterX + cssX * dpr)
|
||||
const physY = Math.round(winOuterY + cssY * dpr)
|
||||
if (physX === lastPickX && physY === lastPickY) return
|
||||
lastPickX = physX
|
||||
lastPickY = physY
|
||||
if (pickRaf) return
|
||||
pickRaf = requestAnimationFrame(() => {
|
||||
pickRaf = 0
|
||||
if (phase.value !== 'pick') return
|
||||
// 用最新位置命中(一帧内多次移动时取最后一次,不丢帧)
|
||||
applyWindowInfo(hitTestWindow(lastPickX, lastPickY))
|
||||
})
|
||||
}
|
||||
|
||||
/** 按物理坐标拾取窗口并立即应用高亮(同步,无 IPC) */
|
||||
function pickWindowAt(physX: number, physY: number) {
|
||||
lastPickX = physX
|
||||
lastPickY = physY
|
||||
applyWindowInfo(hitTestWindow(physX, physY))
|
||||
}
|
||||
|
||||
// ===== 选区流转 =====
|
||||
function resetAnnotations() {
|
||||
annotations.value = []
|
||||
@@ -739,6 +749,13 @@ function enterSelected() {
|
||||
phase.value = 'selected'
|
||||
}
|
||||
|
||||
/** 回到窗口拾取阶段,并按当前鼠标位置立即恢复高亮(ESC/点击选区外时无需移动鼠标) */
|
||||
function backToPick() {
|
||||
dragTracking.value = false
|
||||
phase.value = 'pick'
|
||||
pickWindowAt(lastMousePhys.x, lastMousePhys.y)
|
||||
}
|
||||
|
||||
/** 点击窗口 → 以窗口矩形为选区 */
|
||||
function selectWindow(w: { x: number; y: number; w: number; h: number }) {
|
||||
sel.value = { x: w.x, y: w.y, w: w.w, h: w.h }
|
||||
@@ -752,9 +769,9 @@ function onMouseDown(e: MouseEvent) {
|
||||
dragTracking.value = true
|
||||
dragStart.value = { x: e.clientX, y: e.clientY }
|
||||
} else if (phase.value === 'selected') {
|
||||
// 点击选区外 → 取消选中,回到窗口识别
|
||||
// 点击选区外 → 取消选中,回到窗口识别(按点击位置恢复高亮)
|
||||
resetAnnotations()
|
||||
phase.value = 'pick'
|
||||
backToPick()
|
||||
} else if (phase.value === 'editing') {
|
||||
// 点击选区外 → 提交未完成的文字、取消选中并退出标注,回到选区调整
|
||||
commitText()
|
||||
@@ -816,6 +833,9 @@ function onHandleMouseDown(dir: HandleDir, e: MouseEvent) {
|
||||
}
|
||||
|
||||
function onMouseMove(e: MouseEvent) {
|
||||
// 追踪鼠标物理坐标(ESC 等回到 pick 阶段时按当前位置恢复窗口高亮)
|
||||
lastMousePhys.x = Math.round(winOuterX + e.clientX * dpr)
|
||||
lastMousePhys.y = Math.round(winOuterY + e.clientY * dpr)
|
||||
// 取色器放大镜更新(rAF 节流)
|
||||
scheduleMagnifier(e)
|
||||
|
||||
@@ -975,10 +995,9 @@ function onKeyDown(e: KeyboardEvent) {
|
||||
}
|
||||
} else if (phase.value === 'selected') {
|
||||
resetAnnotations()
|
||||
phase.value = 'pick'
|
||||
backToPick()
|
||||
} else if (phase.value === 'drawing') {
|
||||
dragTracking.value = false
|
||||
phase.value = 'pick'
|
||||
backToPick()
|
||||
} else {
|
||||
cancel()
|
||||
}
|
||||
@@ -1901,15 +1920,17 @@ onMounted(async () => {
|
||||
// 禁用窗口显示/隐藏过渡动画(消除进入/关闭时的缩放动画),失败静默
|
||||
commands.screenshotDisableTransitions(WINDOWS.screenshotOverlay).catch(() => {})
|
||||
// 先注册 begin 监听再通知 store 就绪,避免首轮事件丢失
|
||||
beginUnlisten = await listen(EVENTS.screenshotBegin, () => {
|
||||
void beginCapture()
|
||||
beginUnlisten = await listen<ScreenshotBeginPayload>(EVENTS.screenshotBegin, (e) => {
|
||||
void beginCapture(e.payload)
|
||||
})
|
||||
await emit(EVENTS.screenshotOverlayReady)
|
||||
})
|
||||
|
||||
/** 响应 store 的 'screenshot-begin':先装载底图(隐藏中),解码完成后再一次性显示窗口 */
|
||||
async function beginCapture() {
|
||||
async function beginCapture(payload?: ScreenshotBeginPayload) {
|
||||
try {
|
||||
// 入场动画准备:整体置为透明起点(窗口 show 后从透明淡入,底图/遮罩/高亮同步出现)
|
||||
resetEnterAnim()
|
||||
// 每次截图开始时同步主界面主题(覆盖层是常驻窗口,主界面可能已切换主题)
|
||||
applyTheme()
|
||||
// 重置到"拾取"初始状态
|
||||
@@ -1927,13 +1948,23 @@ async function beginCapture() {
|
||||
pixelCanvas = null
|
||||
pixelCtx = null
|
||||
|
||||
// 缓存窗口拾取列表与捕获时刻光标(pick 阶段鼠标移动零 IPC 命中测试)
|
||||
pickWindows = payload?.windows ?? []
|
||||
lastMousePhys.x = payload?.cursorX ?? 0
|
||||
lastMousePhys.y = payload?.cursorY ?? 0
|
||||
lastPickX = -1
|
||||
lastPickY = -1
|
||||
|
||||
// 先清除上一轮底图,避免"旧图一闪";窗口隐藏期间完成新底图的传输与解码
|
||||
imgSrc.value = ''
|
||||
resetImgReady()
|
||||
loading.value = true
|
||||
|
||||
// 取全屏捕获的 BMP 原始字节(raw IPC → ArrayBuffer),Blob URL 免编码直接显示
|
||||
const buf = await invoke<ArrayBuffer>('screenshot_get_fullscreen_bmp')
|
||||
// 并行:BMP 传输(raw IPC → ArrayBuffer,Blob URL 免编码直接显示)+ 窗口外框位置
|
||||
const [buf, pos] = await Promise.all([
|
||||
invoke<ArrayBuffer>('screenshot_get_fullscreen_bmp'),
|
||||
win.outerPosition(),
|
||||
])
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl)
|
||||
const blob = new Blob([buf], { type: 'image/bmp' })
|
||||
objectUrl = URL.createObjectURL(blob)
|
||||
@@ -1946,31 +1977,36 @@ async function beginCapture() {
|
||||
])
|
||||
loading.value = false
|
||||
|
||||
const pos = await win.outerPosition()
|
||||
winOuterX = pos.x
|
||||
winOuterY = pos.y
|
||||
dpr = window.devicePixelRatio || 1
|
||||
// 窗口显示前同步尺寸:store 的 setSize 可能在 webview ready 前就已调用,
|
||||
// onResized 回调可能错过,此处主动刷新确保 winW/winH 正确
|
||||
await refreshWinSize()
|
||||
await win.show()
|
||||
await win.setFocus()
|
||||
// 显示前完成初始窗口命中(捕获时刻光标处):首帧即"窗口高亮",无"全屏遮罩→高亮"闪烁
|
||||
pickWindowAt(lastMousePhys.x, lastMousePhys.y)
|
||||
// 一次 IPC 完成 show + setFocus(比两次 JS 调用少一次往返)
|
||||
await commands.screenshotShowOverlay(WINDOWS.screenshotOverlay)
|
||||
// 窗口已显示(首帧即透明起点):整体从透明淡入,定格画面+遮罩+高亮同步浮现,不突兀
|
||||
enterState.value = 'fade'
|
||||
enterTimer = window.setTimeout(() => {
|
||||
enterState.value = 'done'
|
||||
enterTimer = null
|
||||
}, 220)
|
||||
// 窗口显示后再次刷新尺寸:隐藏窗口的 innerWidth/innerHeight 可能仍是初始 800×600,
|
||||
// show() 后 WebView2 才更新 DOM 尺寸,需重新读取确保工具栏定位正确
|
||||
await refreshWinSize()
|
||||
// 再延迟一帧重读(WebView2 尺寸更新可能滞后一帧)
|
||||
requestAnimationFrame(() => void refreshWinSize())
|
||||
|
||||
// 默认识别鼠标所在窗口(按下快捷键时鼠标仍在原位)
|
||||
try {
|
||||
const [cx, cy] = await invoke<[number, number]>('screenshot_cursor_pos')
|
||||
await pickAt(cx, cy)
|
||||
} catch {
|
||||
// 忽略初始定位失败,移动鼠标后自动识别
|
||||
}
|
||||
} catch (e) {
|
||||
errorMsg.value = (e as Error).message
|
||||
loading.value = false
|
||||
// 错误提示需立即可见:跳过淡入(idle 全透明会看不到错误信息)
|
||||
if (enterTimer !== null) {
|
||||
clearTimeout(enterTimer)
|
||||
enterTimer = null
|
||||
}
|
||||
enterState.value = 'done'
|
||||
// 出错时也显示窗口,展示错误信息(带关闭按钮)
|
||||
await win.show().catch(() => {})
|
||||
}
|
||||
@@ -1986,6 +2022,7 @@ onUnmounted(() => {
|
||||
if (pickRaf) cancelAnimationFrame(pickRaf)
|
||||
if (magRaf) cancelAnimationFrame(magRaf)
|
||||
if (redrawRaf) cancelAnimationFrame(redrawRaf)
|
||||
if (enterTimer !== null) clearTimeout(enterTimer)
|
||||
staticCanvas = null
|
||||
magGridCanvas = null
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl)
|
||||
@@ -1997,7 +2034,7 @@ onUnmounted(() => {
|
||||
<template>
|
||||
<div
|
||||
class="overlay-root"
|
||||
:class="cursorClass"
|
||||
:class="[cursorClass, enterState !== 'done' ? `overlay-enter-${enterState}` : '']"
|
||||
@mousedown="onMouseDown"
|
||||
@mousemove="onMouseMove"
|
||||
@mouseup="onMouseUp"
|
||||
@@ -2317,6 +2354,14 @@ onUnmounted(() => {
|
||||
-webkit-user-select: none;
|
||||
touch-action: none;
|
||||
}
|
||||
/* 入场淡入:idle=透明起点(窗口 show 前已就位),fade=180ms ease-out 浮现定格画面+遮罩 */
|
||||
.overlay-enter-idle {
|
||||
opacity: 0;
|
||||
}
|
||||
.overlay-enter-fade {
|
||||
opacity: 1;
|
||||
transition: opacity 180ms ease-out;
|
||||
}
|
||||
.bg-img {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
// 贴图窗口:无边框、透明、置顶。
|
||||
// 图片以原分辨率显示,窗口定位到截图时的框选位置(原框选位置)。
|
||||
// 右下角展开图标,hover 展开 上一张 / 下一张 / 关闭。
|
||||
// 左键按住拖动;右键图片弹出菜单(上一张 / 下一张 / 关闭);窗口聚焦后 ESC 弹确认框关闭。
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
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 { ChevronLeft, ChevronRight, X, Loader2 } from '@lucide/vue'
|
||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
@@ -26,6 +27,181 @@ const cur = ref(0)
|
||||
|
||||
let showUnlisten: UnlistenFn | null = null
|
||||
|
||||
// ===== 贴图数据缓存(LRU,值为 Blob URL):命中时上一张/下一张切换零 IPC、零等待 =====
|
||||
const imgCache = new Map<string, string>()
|
||||
const IMG_CACHE_MAX = 4
|
||||
|
||||
function cacheGet(key: string): string | undefined {
|
||||
const v = imgCache.get(key)
|
||||
if (v !== undefined) {
|
||||
imgCache.delete(key)
|
||||
imgCache.set(key, v) // LRU 触碰:移到最新
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
function cachePut(key: string, val: string) {
|
||||
if (imgCache.has(key)) imgCache.delete(key)
|
||||
imgCache.set(key, val)
|
||||
if (imgCache.size > IMG_CACHE_MAX) {
|
||||
const oldest = imgCache.keys().next().value
|
||||
if (oldest !== undefined) {
|
||||
// 逐出最旧条目并释放 Blob 底层字节(显示中的图片恒为最新条目,不会被逐出)
|
||||
const url = imgCache.get(oldest)
|
||||
if (url) URL.revokeObjectURL(url)
|
||||
imgCache.delete(oldest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取历史缓存 PNG 原始字节并包装为 Blob URL(raw IPC,省 base64 编码与 ~33% 传输开销) */
|
||||
async function loadCacheBlobUrl(path: string): Promise<string> {
|
||||
const buf = await invoke<ArrayBuffer>('screenshot_load_cache_raw', { path })
|
||||
return URL.createObjectURL(new Blob([buf], { type: 'image/png' }))
|
||||
}
|
||||
|
||||
/** 后台预取相邻贴图:切换上一张/下一张时命中缓存,瞬间完成 */
|
||||
function preloadAdjacent() {
|
||||
const list = items.value
|
||||
for (const i of [cur.value + 1, cur.value - 1]) {
|
||||
if (i < 0 || i >= list.length) continue
|
||||
const it = list[i]
|
||||
if (imgCache.has(it.filePath)) continue
|
||||
void loadCacheBlobUrl(it.filePath)
|
||||
.then(url => cachePut(it.filePath, url))
|
||||
.catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 右键菜单 / ESC 关闭确认 =====
|
||||
const menuOpen = ref(false)
|
||||
const menuX = ref(0)
|
||||
const menuY = ref(0)
|
||||
const confirmOpen = ref(false)
|
||||
/** 菜单/确认框估算尺寸(定位钳制 + 小贴图扩窗依据) */
|
||||
const MENU_W = 156
|
||||
const MENU_H = 132
|
||||
const DIALOG_W = 250
|
||||
const DIALOG_H = 118
|
||||
/** 扩窗前的原始窗口尺寸(菜单/确认框关闭后还原) */
|
||||
let baseSize: { w: number; h: number } | null = null
|
||||
|
||||
// 窗口创建时 focus:false 带 WS_EX_NOACTIVATE(点击不激活、无键盘焦点)。
|
||||
// 交互(拖动/右键)时临时置为可聚焦并抢占焦点,ESC 可用;
|
||||
// 隐藏前还原为不可聚焦,避免下次 show()(SW_SHOW)激活窗口抢走当前应用焦点。
|
||||
let focusable = false
|
||||
|
||||
async function ensureFocused() {
|
||||
try {
|
||||
if (!focusable) {
|
||||
focusable = true
|
||||
await win.setFocusable(true)
|
||||
}
|
||||
if (!document.hasFocus()) await win.setFocus()
|
||||
} catch { /* 忽略 */ }
|
||||
}
|
||||
|
||||
async function resetFocusable() {
|
||||
focusable = false
|
||||
await win.setFocusable(false).catch(() => {})
|
||||
}
|
||||
|
||||
/** Windows 上非 resizable 窗口 setSize 失效,须先开后还原 */
|
||||
async function resizeWindow(w: number, h: number) {
|
||||
await win.setResizable(true)
|
||||
await win.setSize(new LogicalSize(w, h))
|
||||
await win.setResizable(false)
|
||||
}
|
||||
|
||||
/** 小贴图(窗口小于菜单/确认框)时临时扩窗容纳,关闭后还原原尺寸 */
|
||||
async function syncViewport(needW: number, needH: number) {
|
||||
try {
|
||||
if (needW > 0) {
|
||||
const w = window.innerWidth
|
||||
const h = window.innerHeight
|
||||
if (w >= needW && h >= needH) return
|
||||
if (!baseSize) baseSize = { w, h }
|
||||
await resizeWindow(Math.max(w, needW), Math.max(h, needH))
|
||||
} else if (baseSize) {
|
||||
const s = baseSize
|
||||
baseSize = null
|
||||
await resizeWindow(s.w, s.h)
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
}
|
||||
|
||||
/** 收起菜单并还原视口(后续无重排时使用;切换图片等随后 layoutTo 的路径不要调) */
|
||||
function closeMenu() {
|
||||
menuOpen.value = false
|
||||
void syncViewport(0, 0)
|
||||
}
|
||||
|
||||
function cancelConfirm() {
|
||||
confirmOpen.value = false
|
||||
void syncViewport(0, 0)
|
||||
}
|
||||
|
||||
async function openConfirm() {
|
||||
confirmOpen.value = true
|
||||
await syncViewport(DIALOG_W, DIALOG_H)
|
||||
}
|
||||
|
||||
/** 键盘:ESC 收起菜单 / 取消确认 / 唤起关闭确认;Enter 确认关闭 */
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
e.preventDefault()
|
||||
if (menuOpen.value) {
|
||||
// 菜单直接转入关闭确认(baseSize 保留,扩窗尺寸兼容复用)
|
||||
menuOpen.value = false
|
||||
void openConfirm()
|
||||
} else if (confirmOpen.value) {
|
||||
cancelConfirm()
|
||||
} else {
|
||||
void openConfirm()
|
||||
}
|
||||
} else if (e.key === 'Enter' && confirmOpen.value) {
|
||||
e.preventDefault()
|
||||
void closePin()
|
||||
}
|
||||
}
|
||||
|
||||
/** 失焦时收起右键菜单(确认框保留,属模态意图) */
|
||||
function onBlur() {
|
||||
if (menuOpen.value) closeMenu()
|
||||
}
|
||||
|
||||
/** 右键图片弹出操作菜单;同时抢占键盘焦点使 ESC 可用 */
|
||||
function onContextMenu(e: MouseEvent) {
|
||||
e.preventDefault()
|
||||
void ensureFocused()
|
||||
// 以右键点为基准,钳制在窗口内(小贴图按扩窗后的保证视口计算)
|
||||
const vw = Math.max(window.innerWidth, MENU_W + 8)
|
||||
const vh = Math.max(window.innerHeight, MENU_H + 8)
|
||||
menuX.value = Math.max(4, Math.min(e.clientX + 2, vw - MENU_W - 4))
|
||||
menuY.value = Math.max(4, Math.min(e.clientY + 2, vh - MENU_H - 4))
|
||||
confirmOpen.value = false
|
||||
menuOpen.value = true
|
||||
void syncViewport(MENU_W + 8, MENU_H + 8)
|
||||
}
|
||||
|
||||
/** 菜单项:切换图片(跳过视口还原,layoutTo 会重排窗口) */
|
||||
function onMenuPrev() {
|
||||
menuOpen.value = false
|
||||
baseSize = null
|
||||
prev()
|
||||
}
|
||||
|
||||
function onMenuNext() {
|
||||
menuOpen.value = false
|
||||
baseSize = null
|
||||
next()
|
||||
}
|
||||
|
||||
function onMenuClose() {
|
||||
menuOpen.value = false
|
||||
void closePin()
|
||||
}
|
||||
|
||||
/** 同步主界面主题(独立窗口无 pinia,从 localStorage 读取应用设置) */
|
||||
function applyTheme() {
|
||||
const root = document.documentElement
|
||||
@@ -118,8 +294,12 @@ async function loadImage(index: number) {
|
||||
loading.value = true
|
||||
errorMsg.value = ''
|
||||
try {
|
||||
const b64 = await commands.screenshotLoadCache(item.filePath)
|
||||
const dataUrl = `data:image/png;base64,${b64}`
|
||||
// 缓存命中时跳过读盘 + IPC 传输(切换瞬间完成)
|
||||
let dataUrl = cacheGet(item.filePath)
|
||||
if (!dataUrl) {
|
||||
dataUrl = await loadCacheBlobUrl(item.filePath)
|
||||
cachePut(item.filePath, dataUrl)
|
||||
}
|
||||
// 预解码:等待图片就绪后再排版显示,避免闪烁
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const img = new Image()
|
||||
@@ -134,6 +314,8 @@ async function loadImage(index: number) {
|
||||
imgSrc.value = dataUrl
|
||||
await win.show().catch(() => {})
|
||||
loading.value = false
|
||||
// 后台预取相邻贴图,下一次切换命中缓存
|
||||
preloadAdjacent()
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 贴图加载失败', e)
|
||||
errorMsg.value = '加载图片失败:' + (e as Error).message
|
||||
@@ -152,8 +334,13 @@ function next() {
|
||||
void loadImage(cur.value - 1)
|
||||
}
|
||||
|
||||
function closePin() {
|
||||
void win.hide().catch(() => {})
|
||||
async function closePin() {
|
||||
menuOpen.value = false
|
||||
confirmOpen.value = false
|
||||
baseSize = null
|
||||
// 还原不可聚焦:下次 show() 不会激活窗口抢走当前应用焦点
|
||||
await resetFocusable()
|
||||
await win.hide().catch(() => {})
|
||||
}
|
||||
|
||||
/** 左键按下时启动原生窗口拖动(与 OSD 窗口同款方案:
|
||||
@@ -161,12 +348,24 @@ function closePin() {
|
||||
function onImageMouseDown(e: MouseEvent) {
|
||||
if (e.button !== 0) return
|
||||
e.preventDefault()
|
||||
// 菜单打开时点击图片:仅收起菜单,不启动拖动
|
||||
if (menuOpen.value) {
|
||||
closeMenu()
|
||||
return
|
||||
}
|
||||
// 拖动同时确保键盘焦点(首次交互置为可聚焦,后续点击由系统自然激活)
|
||||
void ensureFocused()
|
||||
void win.startDragging().catch(() => {})
|
||||
}
|
||||
|
||||
/** 响应主窗口 'screenshot-pin-show':读取要贴的历史索引并加载显示 */
|
||||
function openPin() {
|
||||
items.value = readHistory()
|
||||
// 复位交互状态(窗口隐藏期间 store 可能已还原可聚焦标记,此处同步)
|
||||
menuOpen.value = false
|
||||
confirmOpen.value = false
|
||||
baseSize = null
|
||||
focusable = false
|
||||
let index = 0
|
||||
try {
|
||||
index = Number(localStorage.getItem(STORAGE_KEYS.screenshotPinIndex) ?? 0) || 0
|
||||
@@ -176,6 +375,8 @@ function openPin() {
|
||||
|
||||
onMounted(async () => {
|
||||
applyTheme()
|
||||
window.addEventListener('keydown', onKeyDown)
|
||||
window.addEventListener('blur', onBlur)
|
||||
// 先注册 show 监听再通知 store 就绪,避免首轮事件丢失(与覆盖层同模式)
|
||||
showUnlisten = await listen(EVENTS.screenshotPinShow, () => {
|
||||
openPin()
|
||||
@@ -184,17 +385,20 @@ onMounted(async () => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('keydown', onKeyDown)
|
||||
window.removeEventListener('blur', onBlur)
|
||||
showUnlisten?.()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pin-root">
|
||||
<!-- 图片区:左键按住自由拖动(显式 startDragging),蓝色光晕阴影 -->
|
||||
<!-- 图片区:左键按住自由拖动(显式 startDragging),右键弹出操作菜单,蓝色光晕阴影 -->
|
||||
<div
|
||||
class="pin-image"
|
||||
:style="{ width: imgCssW + 'px', height: imgCssH + 'px' }"
|
||||
@mousedown="onImageMouseDown"
|
||||
@contextmenu="onContextMenu"
|
||||
>
|
||||
<img
|
||||
v-if="imgSrc"
|
||||
@@ -207,32 +411,40 @@ onUnmounted(() => {
|
||||
<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" />
|
||||
<!-- 右键操作菜单:上一张 / 下一张 / 关闭贴图 -->
|
||||
<div
|
||||
v-if="menuOpen"
|
||||
class="pin-menu"
|
||||
:style="{ left: menuX + 'px', top: menuY + 'px' }"
|
||||
@mousedown.stop
|
||||
@contextmenu.prevent
|
||||
>
|
||||
<button class="pin-menu-item" :disabled="cur >= items.length - 1" @click="onMenuPrev">
|
||||
<ChevronLeft class="size-4" /><span>上一张</span>
|
||||
</button>
|
||||
<button class="pin-menu-item" :disabled="cur <= 0" @click="onMenuNext">
|
||||
<ChevronRight class="size-4" /><span>下一张</span>
|
||||
</button>
|
||||
<div class="pin-menu-sep" />
|
||||
<button class="pin-menu-item pin-menu-danger" @click="onMenuClose">
|
||||
<X class="size-4" /><span>关闭贴图</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- ESC 关闭确认:Enter / 按钮确认,ESC / 点击遮罩取消 -->
|
||||
<div
|
||||
v-if="confirmOpen"
|
||||
class="pin-confirm-mask"
|
||||
@mousedown.self="cancelConfirm"
|
||||
@contextmenu.prevent.stop
|
||||
>
|
||||
<div class="pin-confirm">
|
||||
<div class="pin-confirm-text">关闭这张贴图?</div>
|
||||
<div class="pin-confirm-btns">
|
||||
<button class="pin-confirm-btn" @click="cancelConfirm">取消</button>
|
||||
<button class="pin-confirm-btn pin-confirm-danger" @click="closePin">关闭</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -284,64 +496,106 @@ onUnmounted(() => {
|
||||
background: rgba(15, 23, 42, 0.85);
|
||||
}
|
||||
|
||||
/* 右下角控制:独立于图片拖动区(兄弟节点),点击不触发拖动 */
|
||||
.pin-controls {
|
||||
/* 右键操作菜单:毛玻璃暗色卡片,定位在右键点附近(脚本钳制在窗口内) */
|
||||
.pin-menu {
|
||||
position: absolute;
|
||||
right: 26px;
|
||||
bottom: 26px;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
z-index: 30;
|
||||
min-width: 148px;
|
||||
padding: 4px;
|
||||
border-radius: 10px;
|
||||
background: rgba(15, 23, 42, 0.92);
|
||||
backdrop-filter: blur(8px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.pin-expand,
|
||||
.pin-btn {
|
||||
.pin-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: rgba(255, 255, 255, 0.92);
|
||||
background: rgba(15, 23, 42, 0.65);
|
||||
backdrop-filter: blur(4px);
|
||||
transition: background-color 0.15s ease;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.12s ease;
|
||||
}
|
||||
|
||||
.pin-btn:hover {
|
||||
background: rgba(30, 58, 138, 0.85);
|
||||
.pin-menu-item:hover:not(:disabled) {
|
||||
background: rgba(59, 130, 246, 0.9);
|
||||
}
|
||||
|
||||
.pin-btn-danger:hover {
|
||||
background: rgba(185, 28, 28, 0.85);
|
||||
}
|
||||
|
||||
.pin-btn:disabled {
|
||||
.pin-menu-item: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;
|
||||
.pin-menu-danger:hover:not(:disabled) {
|
||||
background: rgba(185, 28, 28, 0.9);
|
||||
}
|
||||
|
||||
/* hover 展开三个图标按钮 */
|
||||
.pin-controls:hover .pin-actions,
|
||||
.pin-controls:focus-within .pin-actions {
|
||||
opacity: 1;
|
||||
visibility: visible;
|
||||
transform: translateX(0);
|
||||
.pin-menu-sep {
|
||||
height: 1px;
|
||||
margin: 4px 6px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
/* ESC 关闭确认:全窗遮罩 + 居中卡片 */
|
||||
.pin-confirm-mask {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 40;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
.pin-confirm {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: rgba(15, 23, 42, 0.95);
|
||||
backdrop-filter: blur(8px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.pin-confirm-text {
|
||||
font-size: 13px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pin-confirm-btns {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.pin-confirm-btn {
|
||||
padding: 5px 14px;
|
||||
border: none;
|
||||
border-radius: 7px;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
color: #fff;
|
||||
transition: background-color 0.12s ease;
|
||||
}
|
||||
|
||||
.pin-confirm-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.22);
|
||||
}
|
||||
|
||||
.pin-confirm-danger {
|
||||
background: rgba(185, 28, 28, 0.85);
|
||||
}
|
||||
|
||||
.pin-confirm-danger:hover {
|
||||
background: rgba(220, 38, 38, 0.95);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -39,6 +39,13 @@ export interface WindowInfo {
|
||||
visualRect: { x: number; y: number; width: number; height: number } | null
|
||||
}
|
||||
|
||||
/** screenshot-begin 事件 payload:捕获时刻光标物理坐标 + 拾取窗口列表(Z 序顶→底) */
|
||||
export interface ScreenshotBeginPayload {
|
||||
cursorX: number
|
||||
cursorY: number
|
||||
windows: WindowInfo[]
|
||||
}
|
||||
|
||||
// ===== 工具与选项 =====
|
||||
export const TOOLS: { value: ToolType; icon: Component; label: string }[] = [
|
||||
{ value: 'rect', icon: Square, label: '矩形' },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { Monitor, Sun, Moon, Sparkles, Layers, LogOut, Package, GripVertical, Info, RefreshCw, Download, Check, Loader2 } from '@lucide/vue'
|
||||
import { Monitor, Sun, Moon, Sparkles, Layers, LogOut, Package, GripVertical, Info, RefreshCw, Download, Check, Loader2, X } from '@lucide/vue'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Label } from '@/components/ui/label'
|
||||
@@ -9,6 +9,7 @@ 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 { useDownloaderStore } from '@/stores/downloaderStore'
|
||||
import { getModuleIcon } from '@/modules/icons'
|
||||
import { commands, type UpdateCheckResult } from '@/lib/bindings'
|
||||
import { EVENTS } from '@/lib/constants'
|
||||
@@ -16,6 +17,7 @@ import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { VueDraggable } from 'vue-draggable-plus'
|
||||
import { toast } from 'vue-sonner'
|
||||
|
||||
const appStore = useAppStore()
|
||||
const searchStore = useSearchStore()
|
||||
@@ -67,23 +69,152 @@ const checkUpdate = async () => {
|
||||
updateResult.value = await commands.updateCheck()
|
||||
} catch (e) {
|
||||
console.error('[updater] 检查更新失败', e)
|
||||
toast.error('检查更新失败', { description: String(e) })
|
||||
} finally {
|
||||
checking.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 下载并应用应用更新(便携版替换 exe / 安装版静默安装),触发应用退出重启 */
|
||||
// ===== 应用更新:复用下载模块下载安装包(重试/限速/进度事件成熟可靠),
|
||||
// 下载完成后调用 update_install 执行安装并退出。与代理模块 mihomo 内核更新同模式。 =====
|
||||
|
||||
const downloaderStore = useDownloaderStore()
|
||||
|
||||
/** 下载中显示取消按钮(下载完成进入 applying 阶段后不可取消) */
|
||||
const downloadCancellable = ref(false)
|
||||
/** 取消下载的唤醒回调(由等待 Promise 设置) */
|
||||
let cancelAppDownload: (() => void) | null = null
|
||||
|
||||
/** 格式化速度 MB/s */
|
||||
const fmtSpeed = (bytesPerSec: number) => `${(bytesPerSec / 1024 / 1024).toFixed(2)} MB/s`
|
||||
|
||||
/** 下载并应用应用更新:下载模块下载 → update_install 安装(触发应用退出重启) */
|
||||
const installUpdate = async () => {
|
||||
if (appUpdating.value) return
|
||||
const result = updateResult.value
|
||||
if (!result) return
|
||||
// 与后端选择逻辑一致:安装版找 -setup.exe,便携版找非 setup 的 .exe
|
||||
const asset = result.installType === 'installed'
|
||||
? result.assets.find(a => a.name.endsWith('-setup.exe'))
|
||||
: result.assets.find(a => a.name.endsWith('.exe') && !a.name.includes('setup'))
|
||||
if (!asset) {
|
||||
toast.error('未找到可用的更新安装包', { description: `安装类型: ${installTypeText.value},请在 release 页手动下载` })
|
||||
return
|
||||
}
|
||||
|
||||
appUpdating.value = true
|
||||
progress.value = {
|
||||
stage: 'downloading',
|
||||
percent: 0,
|
||||
downloadedBytes: 0,
|
||||
totalBytes: asset.size || null,
|
||||
message: '准备开始下载...'
|
||||
}
|
||||
|
||||
let taskId: string | null = null
|
||||
let downloadProgressFn: UnlistenFn | null = null
|
||||
// 用对象持有完成事件解绑函数,避免闭包内赋值导致的 TS 类型收窄问题(同 proxyStore)
|
||||
const completeHolder: { fn: UnlistenFn | null } = { fn: null }
|
||||
let downloadOk = false
|
||||
try {
|
||||
await commands.updateInstall()
|
||||
// 确保下载模块事件监听已注册(下载器 UI 与这里共用事件流)
|
||||
try { await downloaderStore.startEventListeners() } catch { /* 忽略 */ }
|
||||
taskId = await downloaderStore.addTask(asset.browserDownloadUrl, asset.name, undefined, {}, false)
|
||||
|
||||
// 下载进度 → 更新进度条
|
||||
downloadProgressFn = await listen<{
|
||||
id: string; completedSize: number; totalSize: number; speed: number; status: string
|
||||
}>('download-progress', (e) => {
|
||||
if (e.payload.id !== taskId || !appUpdating.value) return
|
||||
const pct = e.payload.totalSize > 0
|
||||
? Math.round((e.payload.completedSize / e.payload.totalSize) * 100)
|
||||
: 0
|
||||
progress.value = {
|
||||
stage: 'downloading',
|
||||
percent: pct,
|
||||
downloadedBytes: e.payload.completedSize,
|
||||
totalBytes: e.payload.totalSize,
|
||||
message: e.payload.speed > 0
|
||||
? `正在下载... ${fmtSpeed(e.payload.speed)}`
|
||||
: '正在下载...'
|
||||
}
|
||||
})
|
||||
|
||||
// 等待下载完成 / 失败 / 取消
|
||||
downloadCancellable.value = true
|
||||
const dlResult = await new Promise<{ ok: boolean; error?: string }>((resolve) => {
|
||||
let settled = false
|
||||
const finish = (r: { ok: boolean; error?: string }) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
cancelAppDownload = null
|
||||
resolve(r)
|
||||
}
|
||||
// 任务添加后瞬间进入终态(如探测即失败)
|
||||
const initial = downloaderStore.tasks.find(t => t.id === taskId)
|
||||
if (initial) {
|
||||
if (initial.status === 'complete') { finish({ ok: true }); return }
|
||||
if (initial.status === 'error') { finish({ ok: false, error: initial.error || '下载失败' }); return }
|
||||
}
|
||||
cancelAppDownload = () => finish({ ok: false, error: '已取消下载' })
|
||||
listen<{ id: string; status: string; error: string | null }>('download-complete', (e) => {
|
||||
if (e.payload.id === taskId) {
|
||||
if (e.payload.status === 'complete') finish({ ok: true })
|
||||
else finish({ ok: false, error: e.payload.error || '下载失败' })
|
||||
}
|
||||
}).then(fn => { completeHolder.fn = fn })
|
||||
})
|
||||
downloadCancellable.value = false
|
||||
if (!dlResult.ok) throw new Error(dlResult.error || '下载失败')
|
||||
downloadOk = true
|
||||
|
||||
// 取下载文件路径 → 移除任务记录(保留文件,安装命令内部会 copy 到临时目录并清理)
|
||||
const dlTask = downloaderStore.tasks.find(t => t.id === taskId)
|
||||
if (!dlTask) throw new Error('下载任务未找到')
|
||||
const exePath = dlTask.dir + '/' + dlTask.filename
|
||||
try {
|
||||
await downloaderStore.removeTask(taskId, false)
|
||||
taskId = null
|
||||
} catch { /* 任务清理失败不阻断安装 */ }
|
||||
|
||||
// 安装阶段(后端 emit applying 进度 → 执行安装 → app.exit(0))
|
||||
progress.value = {
|
||||
stage: 'applying',
|
||||
percent: 100,
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
message: installTypeText.value === '安装版' ? '正在启动安装程序...' : '正在替换程序文件...'
|
||||
}
|
||||
await commands.updateInstall(exePath)
|
||||
// 成功路径后端已退出应用,不会执行到这里
|
||||
} catch (e) {
|
||||
console.error('[updater] 应用更新失败', e)
|
||||
const msg = String(e)
|
||||
if (msg.includes('已取消下载')) {
|
||||
toast.info('已取消更新下载')
|
||||
} else {
|
||||
toast.error('应用更新失败', { description: msg })
|
||||
}
|
||||
// 清理下载任务:下载失败/取消时删除半成品文件
|
||||
if (taskId) {
|
||||
try { await downloaderStore.removeTask(taskId, !downloadOk) } catch { /* 忽略 */ }
|
||||
}
|
||||
appUpdating.value = false
|
||||
progress.value = null
|
||||
} finally {
|
||||
downloadCancellable.value = false
|
||||
cancelAppDownload = null
|
||||
if (downloadProgressFn) downloadProgressFn()
|
||||
if (completeHolder.fn) completeHolder.fn()
|
||||
}
|
||||
}
|
||||
|
||||
/** 取消应用更新下载(仅下载阶段可取消) */
|
||||
const cancelUpdateDownload = async () => {
|
||||
if (!downloadCancellable.value) return
|
||||
cancelAppDownload?.()
|
||||
}
|
||||
|
||||
/** 更新 ThingHK 内核:后端先停止监控内核再覆盖文件 */
|
||||
const updateThinghkKernel = async () => {
|
||||
if (kernelUpdating.value) return
|
||||
@@ -91,8 +222,10 @@ const updateThinghkKernel = async () => {
|
||||
try {
|
||||
await commands.updateThinghk()
|
||||
await loadAppInfo()
|
||||
toast.success('ThingHK 内核更新完成')
|
||||
} catch (e) {
|
||||
console.error('[updater] ThingHK 更新失败', e)
|
||||
toast.error('ThingHK 内核更新失败', { description: String(e) })
|
||||
} finally {
|
||||
kernelUpdating.value = false
|
||||
}
|
||||
@@ -110,6 +243,9 @@ onMounted(() => {
|
||||
if (e.payload.stage === 'done') {
|
||||
kernelUpdating.value = false
|
||||
progress.value = null
|
||||
} else if (e.payload.stage === 'error') {
|
||||
// ThingHK 内核更新失败(后端 emit);应用更新失败走命令 reject 路径
|
||||
kernelUpdating.value = false
|
||||
}
|
||||
}).then((fn) => {
|
||||
progressUnlisten = fn
|
||||
@@ -501,7 +637,19 @@ const onDragEnd = () => {
|
||||
<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 class="flex items-center gap-2">
|
||||
<span class="font-mono">{{ progress.percent }}%</span>
|
||||
<Button
|
||||
v-if="downloadCancellable"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="h-5 px-1.5 text-xs"
|
||||
@click="cancelUpdateDownload"
|
||||
>
|
||||
<X class="size-3 mr-0.5" />
|
||||
取消
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Progress :model-value="progress.percent" />
|
||||
</div>
|
||||
|
||||
@@ -315,6 +315,8 @@ function delayClass(delay: number | null): string {
|
||||
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key === 'Escape') {
|
||||
// Select 下拉打开时优先由其自行关闭(ESC 只关下拉),不关闭整个菜单
|
||||
if (nodeSelectOpen.value) return
|
||||
e.preventDefault()
|
||||
resetMenuState()
|
||||
invoke('tray_menu_hide').catch(() => {})
|
||||
@@ -365,9 +367,17 @@ function resolveIsDark(theme: string): boolean {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
|
||||
/** 上次已应用的主题组合缓存:未变化时跳过(省 4-6 次 IPC,降低菜单显示延迟) */
|
||||
let lastAppliedThemeKey = ''
|
||||
|
||||
async function applyTheme() {
|
||||
const root = document.documentElement
|
||||
const { theme, effect } = readMainTheme()
|
||||
const isDark = resolveIsDark(theme)
|
||||
|
||||
const key = `${theme}|${effect}|${isDark}`
|
||||
if (key === lastAppliedThemeKey) return
|
||||
lastAppliedThemeKey = key
|
||||
|
||||
try {
|
||||
const tauriWin = getCurrentWindow()
|
||||
@@ -378,8 +388,6 @@ async function applyTheme() {
|
||||
}
|
||||
} catch { /* 非 Tauri 环境忽略 */ }
|
||||
|
||||
const isDark = resolveIsDark(theme)
|
||||
|
||||
root.classList.remove('dark', 'effect-mica', 'effect-acrylic', 'effect-normal')
|
||||
root.classList.add(`effect-${effect}`)
|
||||
if (isDark) root.classList.add('dark')
|
||||
@@ -433,10 +441,15 @@ onMounted(async () => {
|
||||
}))
|
||||
|
||||
// 仅更新状态数据,不重新显示窗口。
|
||||
// 动作完成后的状态更新不应让已隐藏的菜单重新弹出(measureAndShow 会触发 win.show)。
|
||||
// 菜单显示统一由右键托盘触发的 tray-menu-show 事件负责。
|
||||
unlistenFns.push(await listen<TrayMenuState>('tray-menu-state-updated', (event) => {
|
||||
// - 动作完成后的状态更新:菜单已隐藏,只更新数据(不重新弹出)
|
||||
// - 右键后完整状态补充到达(基础状态先行显示,节点数据异步跟上):
|
||||
// 菜单可见时重新测量调整窗口尺寸(tray_menu_ready 幂等,重新定位+resize,不会重复显示动画)
|
||||
unlistenFns.push(await listen<TrayMenuState>('tray-menu-state-updated', async (event) => {
|
||||
Object.assign(state, event.payload)
|
||||
try {
|
||||
const visible = await getCurrentWindow().isVisible()
|
||||
if (visible) await measureAndShow()
|
||||
} catch { /* 非 Tauri 环境忽略 */ }
|
||||
}))
|
||||
|
||||
// 预创建模式下不再调用 tray_menu_show_window,窗口显示统一由 tray_menu_ready 触发
|
||||
|
||||
@@ -86,6 +86,9 @@ export const useClipboardStore = defineStore('clipboard', () => {
|
||||
}
|
||||
|
||||
// ===== 查询 =====
|
||||
/** 列表请求序号:翻页/搜索/过滤快速操作时丢弃过期请求结果,避免旧请求覆盖新结果 */
|
||||
let listSeq = 0
|
||||
|
||||
/** 拉取指定页的历史数据。pageSize 默认 50。 */
|
||||
const fetchHistoryPage = async (opts: {
|
||||
kind?: string
|
||||
@@ -96,10 +99,13 @@ export const useClipboardStore = defineStore('clipboard', () => {
|
||||
const pageSize = opts.pageSize ?? 50
|
||||
const page = Math.max(1, opts.page ?? 1)
|
||||
const offset = (page - 1) * pageSize
|
||||
const seq = ++listSeq
|
||||
try {
|
||||
const res = await commands.clipboardGetHistory(pageSize, offset, kind)
|
||||
history.value = res.items
|
||||
historyTotal.value = res.total
|
||||
if (seq === listSeq) {
|
||||
history.value = res.items
|
||||
historyTotal.value = res.total
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('获取历史失败: ' + e)
|
||||
}
|
||||
@@ -123,10 +129,13 @@ export const useClipboardStore = defineStore('clipboard', () => {
|
||||
if (!query.trim()) {
|
||||
return fetchHistoryPage({ page, pageSize })
|
||||
}
|
||||
const seq = ++listSeq
|
||||
try {
|
||||
const res = await commands.clipboardSearch(query, pageSize, (page - 1) * pageSize)
|
||||
history.value = res.items
|
||||
historyTotal.value = res.total
|
||||
if (seq === listSeq) {
|
||||
history.value = res.items
|
||||
historyTotal.value = res.total
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error('搜索失败: ' + e)
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ interface ProgressPayload {
|
||||
totalSize: number
|
||||
speed: number
|
||||
status: TaskStatus
|
||||
/** 每个分段的已下载字节(与任务 segments 一一对应,供详情弹窗实时展示) */
|
||||
segments: number[]
|
||||
}
|
||||
|
||||
/** 下载完成事件载荷 */
|
||||
@@ -68,6 +70,7 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
let progressUnlisten: UnlistenFn | null = null
|
||||
let completeUnlisten: UnlistenFn | null = null
|
||||
let addedUnlisten: UnlistenFn | null = null
|
||||
let removedUnlisten: UnlistenFn | null = null
|
||||
|
||||
// ===== 任务列表 =====
|
||||
const refreshTasks = async () => {
|
||||
@@ -109,6 +112,13 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
task.totalSize = payload.totalSize
|
||||
task.speed = payload.speed
|
||||
task.status = payload.status
|
||||
// 分段实时进度(详情弹窗分段条随下载动态更新)
|
||||
if (Array.isArray(payload.segments)) {
|
||||
task.segments.forEach((seg, i) => {
|
||||
const v = payload.segments?.[i]
|
||||
if (v !== undefined) seg.completed = v
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,7 +225,7 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
}
|
||||
|
||||
const startEventListeners = async () => {
|
||||
if (progressUnlisten && completeUnlisten && addedUnlisten) return
|
||||
if (progressUnlisten && completeUnlisten && addedUnlisten && removedUnlisten) return
|
||||
if (!progressUnlisten) {
|
||||
progressUnlisten = await listen<ProgressPayload>('download-progress', (e) => {
|
||||
// 同名任务只保留最新进度,合并后由 rAF 统一应用
|
||||
@@ -234,6 +244,12 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
refreshTasks()
|
||||
})
|
||||
}
|
||||
if (!removedUnlisten) {
|
||||
removedUnlisten = await listen<{ id: string }>('download-removed', () => {
|
||||
// 任务被删除(浏览器扩展通过 HTTP API 删除时前端无从感知),刷新任务列表
|
||||
refreshTasks()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const stopEventListeners = () => {
|
||||
@@ -249,6 +265,10 @@ export const useDownloaderStore = defineStore('downloader', () => {
|
||||
addedUnlisten()
|
||||
addedUnlisten = null
|
||||
}
|
||||
if (removedUnlisten) {
|
||||
removedUnlisten()
|
||||
removedUnlisten = null
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 初始化 =====
|
||||
|
||||
+108
-63
@@ -3,7 +3,7 @@ import { computed, ref, watch } from 'vue'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { currentMonitor, LogicalPosition, LogicalSize } from '@tauri-apps/api/window'
|
||||
import { currentMonitor, LogicalPosition } from '@tauri-apps/api/window'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||
@@ -335,7 +335,7 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
|
||||
/**
|
||||
* OSD 配置(store 级统一管理,App 启动时 initOsd 显式初始化)。
|
||||
* 快照/网速事件到达时若 OSD 开启则 store 统一推送 osd-state-update,
|
||||
* 快照/网速事件到达时若 OSD 开启则 store 统一推送 osd-data-update(仅显示项 key→value),
|
||||
* 使 OSD 数据流不依赖组件生命周期(模块卸载后 OSD 窗口仍能持续刷新)。
|
||||
*/
|
||||
const osdConfig = ref<OsdConfig>(loadOsdConfig())
|
||||
@@ -352,17 +352,47 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
}, 200)
|
||||
}
|
||||
|
||||
/** 推送 OSD 状态到所有 OSD 窗口(仅 OSD 开启时生效) */
|
||||
/** 传感器 key→value 映射(key 格式与 OSD 显示项一致:{groupId}/{hwName}/{sensorName}/{type} 小写化)
|
||||
* 快照到达时重算一次,供 OSD 数据推送 O(1) 查值,替代向 OSD 窗口推送全量快照 */
|
||||
const sensorKeyMap = computed<Record<string, number | null>>(() => {
|
||||
const map: Record<string, number | null> = {}
|
||||
for (const g of snapshot.value?.groups ?? []) {
|
||||
for (const s of g.sensors) {
|
||||
map[`${g.id}/${s.hardwareName}/${s.name}/${s.type}`.replace(/\s+/g, '_').toLowerCase()] = s.value ?? null
|
||||
}
|
||||
}
|
||||
return map
|
||||
})
|
||||
|
||||
/** 推送 OSD 数据到所有 OSD 窗口(高频通道:仅显示项 key→value 映射 + 网速,每秒一次) */
|
||||
async function pushOsdState() {
|
||||
if (!osdConfig.value.overlayEnabled) return
|
||||
try {
|
||||
const map = sensorKeyMap.value
|
||||
const data: Record<string, number | null> = {}
|
||||
for (const item of osdConfig.value.overlayItems) {
|
||||
// 网速特殊项不查快照,通过 networkSpeed 字段携带
|
||||
if (item.special) continue
|
||||
data[item.key] = map[item.key] ?? null
|
||||
}
|
||||
await emit(EVENTS.osdDataUpdate, {
|
||||
data,
|
||||
networkSpeed: networkSpeed.value,
|
||||
})
|
||||
} catch (e) {
|
||||
logger.error('[OSD] 推送数据失败: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 推送 OSD 配置到所有 OSD 窗口(低频通道:配置变化时调用,防抖合并) */
|
||||
async function pushOsdConfig() {
|
||||
if (!osdConfig.value.overlayEnabled) return
|
||||
try {
|
||||
await emit(EVENTS.osdStateUpdate, {
|
||||
config: osdConfig.value,
|
||||
snapshot: snapshot.value,
|
||||
networkSpeed: networkSpeed.value,
|
||||
})
|
||||
} catch (e) {
|
||||
logger.error('[OSD] 推送状态失败: ' + e)
|
||||
logger.error('[OSD] 推送配置失败: ' + e)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -705,6 +735,8 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
|
||||
/** 抑制百分比 watch 的程序定位标志:拖动 onMoved 更新百分比时置 true,避免触发 resetOverlayPosition 循环 */
|
||||
let suppressPercentWatch = false
|
||||
/** 抑制 onMoved 处理的程序定位标志:osd_set_bounds 原子调整触发 moved 事件时跳过反算(百分比已是驱动值,无需回写) */
|
||||
let suppressMovedHandling = false
|
||||
|
||||
/** 构建用于 OSD 窗口的 URL(基于当前页面 URL 替换 hash) */
|
||||
function osdUrl(hash: string): string {
|
||||
@@ -793,9 +825,11 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
async function ensureOverlayWindow() {
|
||||
const existing = await WebviewWindow.getByLabel(OSD_OVERLAY_LABEL)
|
||||
if (existing) {
|
||||
// 窗口已存在,仅显示并推送最新状态
|
||||
// 窗口已存在,仅显示并推送最新配置 + 数据
|
||||
// 不做估算 resize:内容测量上报(osd-content-size)是唯一尺寸/位置更新源,
|
||||
// 推送配置后 OSD 重新渲染并上报实际尺寸,由监听端原子 setBounds
|
||||
await existing.show()
|
||||
await updateOsdWindowSize()
|
||||
await pushOsdConfig()
|
||||
await pushOsdState()
|
||||
return
|
||||
}
|
||||
@@ -816,16 +850,11 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
osdConfig.value.overlayItems,
|
||||
)
|
||||
|
||||
// 优先使用保存的像素位置;否则根据百分比计算默认位置
|
||||
let x: number, y: number
|
||||
if (osdConfig.value.overlayX != null && osdConfig.value.overlayY != null) {
|
||||
x = osdConfig.value.overlayX
|
||||
y = osdConfig.value.overlayY
|
||||
} else {
|
||||
const pos = computePositionFromPct(logicalW, logicalH, w, h, osdConfig.value.positionXPct, osdConfig.value.positionYPct)
|
||||
x = pos.x
|
||||
y = pos.y
|
||||
}
|
||||
// 位置统一由百分比计算(百分比是唯一位置真相源:拖动后反算更新百分比,
|
||||
// 尺寸变化时按百分比重锚;不再使用保存的像素位置,避免旧尺寸像素与新尺寸不匹配)
|
||||
const pos = computePositionFromPct(logicalW, logicalH, w, h, osdConfig.value.positionXPct, osdConfig.value.positionYPct)
|
||||
const x = pos.x
|
||||
const y = pos.y
|
||||
|
||||
const win = new WebviewWindow(OSD_OVERLAY_LABEL, {
|
||||
url: osdUrl('osd-overlay'),
|
||||
@@ -848,29 +877,29 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
})
|
||||
|
||||
win.once('tauri://created', async () => {
|
||||
// 等待 webview 加载后推送初始状态
|
||||
setTimeout(() => pushOsdState(), 300)
|
||||
// 监听窗口移动,保存像素位置并同步更新百分比(拖动结束后触发)
|
||||
// 等待 webview 加载后推送初始配置 + 数据
|
||||
setTimeout(() => { void pushOsdConfig(); void pushOsdState() }, 300)
|
||||
// 监听窗口移动(用户拖动结束后触发),反算更新百分比
|
||||
try {
|
||||
const winInstance = await win
|
||||
const unlisten = await winInstance.onMoved(async ({ payload }) => {
|
||||
osdConfig.value.overlayX = payload.x
|
||||
osdConfig.value.overlayY = payload.y
|
||||
// 反算百分比:xPct = x / availW * 100,availW = screenW - windowW
|
||||
// 程序性 setBounds/setPosition 触发的移动:位置由百分比驱动,无需反算
|
||||
if (suppressMovedHandling) return
|
||||
// payload 为物理像素(PhysicalPosition),需转逻辑像素后再反算百分比
|
||||
// 置 suppressPercentWatch=true 避免百分比变化触发 resetOverlayPosition 循环
|
||||
suppressPercentWatch = true
|
||||
try {
|
||||
const monitor = await currentMonitor()
|
||||
const screenW = (monitor?.size.width ?? 1920) / (monitor?.scaleFactor ?? 1)
|
||||
const screenH = (monitor?.size.height ?? 1080) / (monitor?.scaleFactor ?? 1)
|
||||
const size = await winInstance.outerSize()
|
||||
const scale = monitor?.scaleFactor ?? 1
|
||||
const screenW = (monitor?.size.width ?? 1920) / scale
|
||||
const screenH = (monitor?.size.height ?? 1080) / scale
|
||||
const size = await winInstance.outerSize()
|
||||
const winW = size.width / scale
|
||||
const winH = size.height / scale
|
||||
const availW = Math.max(1, screenW - winW)
|
||||
const availH = Math.max(1, screenH - winH)
|
||||
osdConfig.value.positionXPct = Math.round((payload.x / availW) * 100)
|
||||
osdConfig.value.positionYPct = Math.round((payload.y / availH) * 100)
|
||||
osdConfig.value.positionXPct = Math.round(((payload.x / scale) / availW) * 100)
|
||||
osdConfig.value.positionYPct = Math.round(((payload.y / scale) / availH) * 100)
|
||||
} catch { /* 忽略百分比反算失败 */ }
|
||||
saveOsdConfig(osdConfig.value)
|
||||
// 下一个微任务后解除抑制(让本次 watch 回调跳过即可)
|
||||
@@ -893,21 +922,38 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/** 根据当前配置更新悬浮窗窗口尺寸(显示项数量/布局/字号变化时调用) */
|
||||
async function updateOsdWindowSize() {
|
||||
/** 调整悬浮窗尺寸并按百分比重锚位置(原子操作)
|
||||
* 尺寸变化(增删显示项/切换语言/改字号)时统一按百分比重新计算坐标,
|
||||
* 使右对齐/居中等相对位置在新宽度下保持(xPct=100 右对齐 → 右边缘始终贴屏)。
|
||||
* 通过 Rust osd_set_bounds 一次 SetWindowPos 同时更新位置+尺寸,
|
||||
* 避免 setSize 与 setPosition 两次调用之间的中间帧(宽度已变、位置未动 → 闪烁)。 */
|
||||
async function resizeOsdWindowWithAnchor(width: number, height: number) {
|
||||
const w = await WebviewWindow.getByLabel(OSD_OVERLAY_LABEL)
|
||||
if (!w) return
|
||||
try {
|
||||
const existing = await WebviewWindow.getByLabel(OSD_OVERLAY_LABEL)
|
||||
if (!existing) return
|
||||
const hasNetItem = osdConfig.value.overlayItems.some(i => i.special === 'net-up' || i.special === 'net-down')
|
||||
const { w, h } = computeOsdWindowSize(
|
||||
osdConfig.value.overlayItems.length,
|
||||
osdConfig.value.layout,
|
||||
osdConfig.value.fontSize,
|
||||
hasNetItem,
|
||||
osdConfig.value.overlayItems,
|
||||
)
|
||||
await existing.setSize(new LogicalSize(w, h))
|
||||
} catch { /* 忽略 */ }
|
||||
const monitor = await currentMonitor()
|
||||
const scale = monitor?.scaleFactor ?? 1
|
||||
const screenW = (monitor?.size.width ?? 1920) / scale
|
||||
const screenH = (monitor?.size.height ?? 1080) / scale
|
||||
const pos = computePositionFromPct(screenW, screenH, width, height, osdConfig.value.positionXPct, osdConfig.value.positionYPct)
|
||||
// 抑制本次程序性移动触发的 onMoved 反算(百分比已是驱动值,回写可能因 round 产生扰动)
|
||||
suppressMovedHandling = true
|
||||
suppressPercentWatch = true
|
||||
// 逻辑坐标 → 物理像素(osd_set_bounds 接收物理像素)
|
||||
await invoke('osd_set_bounds', {
|
||||
label: OSD_OVERLAY_LABEL,
|
||||
x: Math.round(pos.x * scale),
|
||||
y: Math.round(pos.y * scale),
|
||||
w: Math.round(width * scale),
|
||||
h: Math.round(height * scale),
|
||||
})
|
||||
} catch { /* 忽略 */ } finally {
|
||||
// moved 事件异步到达,延迟解除抑制
|
||||
setTimeout(() => {
|
||||
suppressMovedHandling = false
|
||||
suppressPercentWatch = false
|
||||
}, 150)
|
||||
}
|
||||
}
|
||||
|
||||
/** 重置悬浮窗位置到默认(百分比位置),清除保存的像素位置
|
||||
@@ -929,7 +975,10 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
const w = size.width / scale
|
||||
const h = size.height / scale
|
||||
const pos = computePositionFromPct(screenW, screenH, w, h, osdConfig.value.positionXPct, osdConfig.value.positionYPct)
|
||||
// 抑制程序性移动触发的 onMoved 反算
|
||||
suppressMovedHandling = true
|
||||
await existing.setPosition(new LogicalPosition(pos.x, pos.y))
|
||||
setTimeout(() => { suppressMovedHandling = false }, 150)
|
||||
}
|
||||
} catch { /* 忽略 */ }
|
||||
}
|
||||
@@ -946,17 +995,21 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
// 仅当尺寸变化超过 1px 时才 setSize,避免无意义的频繁调用
|
||||
let lastW = 0
|
||||
let lastH = 0
|
||||
const unlisten = await listen<{ width: number; height: number }>('osd-content-size', async (e) => {
|
||||
const unlisten = await listen<{ width: number; height: number }>(EVENTS.osdContentSize, async (e) => {
|
||||
const { width, height } = e.payload
|
||||
if (Math.abs(width - lastW) < 1 && Math.abs(height - lastH) < 1) return
|
||||
lastW = width
|
||||
lastH = height
|
||||
try {
|
||||
const w = await WebviewWindow.getByLabel(OSD_OVERLAY_LABEL)
|
||||
if (w) await w.setSize(new LogicalSize(width, height))
|
||||
} catch { /* 忽略 */ }
|
||||
await resizeOsdWindowWithAnchor(width, height)
|
||||
})
|
||||
osdEventUnlisteners.push(unlisten)
|
||||
// OSD 窗口挂载完成后请求补发配置+数据:
|
||||
// 数据通道不含配置,若窗口加载慢错过创建时的首推(300ms),需由窗口主动请求
|
||||
const unlistenReq = await listen(EVENTS.osdConfigRequest, () => {
|
||||
void pushOsdConfig()
|
||||
void pushOsdState()
|
||||
})
|
||||
osdEventUnlisteners.push(unlistenReq)
|
||||
}
|
||||
|
||||
/** initOsd 幂等守卫:监听/配置 watcher 只注册一次(App 启动 + 模块挂载均会调用) */
|
||||
@@ -1033,29 +1086,21 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
resetOverlayPosition().catch(() => {})
|
||||
}))
|
||||
|
||||
// OSD 配置变化 → 推送到 OSD 窗口(位置/字体/显示项等)
|
||||
// 防抖 200ms 合并:滑块拖动期间只推送最终状态,避免每帧 emit 整份快照
|
||||
// OSD 配置变化 → 推送配置到 OSD 窗口(低频通道,数据通道不受影响)
|
||||
// 防抖 200ms 合并:滑块拖动期间只推送最终状态,避免每帧 emit 整份配置
|
||||
// 注意:不做估算 resize——配置推送后 OSD 重渲染并测量上报实际尺寸,
|
||||
// osd-content-size 监听端原子 setBounds,是唯一尺寸/位置更新源
|
||||
// (估算 resize 会先跳到估算位置再跳到实际位置,产生闪烁)
|
||||
osdWatchStops.push(watch(osdConfig, () => {
|
||||
if (osdPushTimer) clearTimeout(osdPushTimer)
|
||||
osdPushTimer = setTimeout(() => {
|
||||
osdPushTimer = null
|
||||
if (osdConfig.value.overlayEnabled) {
|
||||
pushOsdState()
|
||||
pushOsdConfig()
|
||||
}
|
||||
}, 200)
|
||||
}, { deep: true }))
|
||||
|
||||
// 显示项数量/布局/字号变化 → 更新悬浮窗窗口尺寸(自适应内容)
|
||||
osdWatchStops.push(watch([
|
||||
() => osdConfig.value.overlayItems.length,
|
||||
() => osdConfig.value.layout,
|
||||
() => osdConfig.value.fontSize,
|
||||
], () => {
|
||||
if (osdConfig.value.overlayEnabled) {
|
||||
updateOsdWindowSize().catch(() => {})
|
||||
}
|
||||
}))
|
||||
|
||||
// 初始化悬浮窗(如果开关已开启)
|
||||
if (osdConfig.value.overlayEnabled) {
|
||||
ensureOverlayWindow().catch(e => logger.error('[OSD] 初始化悬浮窗失败: ' + e))
|
||||
@@ -1111,9 +1156,9 @@ export const useMonitorStore = defineStore('monitor', () => {
|
||||
saveOsdConfig,
|
||||
saveOsdConfigDebounced,
|
||||
pushOsdState,
|
||||
pushOsdConfig,
|
||||
ensureOverlayWindow,
|
||||
hideOverlayWindow,
|
||||
updateOsdWindowSize,
|
||||
resetOverlayPosition,
|
||||
initOsd,
|
||||
disposeOsd,
|
||||
|
||||
+199
-55
@@ -4,6 +4,7 @@ import { invoke } from '@tauri-apps/api/core'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { EVENTS } from '@/lib/constants'
|
||||
import { useDownloaderStore } from '@/stores/downloaderStore'
|
||||
// Rust 端通过 tauri-specta 生成的类型与命令绑定(bindings.ts)
|
||||
import {
|
||||
commands,
|
||||
@@ -72,6 +73,10 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
const installing = ref(false)
|
||||
const installProgress = ref<InstallProgress | null>(null)
|
||||
let progressUnlisten: UnlistenFn | null = null
|
||||
/** 当前进行中的内核安装/更新任务(取消时需等待其完全收尾,避免旧任务 finally 覆盖新任务状态) */
|
||||
let activeInstall: Promise<void> | null = null
|
||||
/** 取消下载等待的唤醒函数(cancelKernelInstall 调用,置位后下载等待立即以「已取消」返回) */
|
||||
let cancelDownload: (() => void) | null = null
|
||||
|
||||
/** 内核信息(同时尝试从 resource 提取到 cores/) */
|
||||
const refreshKernel = async () => {
|
||||
@@ -101,11 +106,15 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
const stop = async () => {
|
||||
await commands.proxyStop()
|
||||
await refreshStatus()
|
||||
// 后端关闭 mihomo 时会同步关闭系统代理,这里立即刷新 UI 状态(不等 3s 轮询)
|
||||
await refreshSystemProxy()
|
||||
}
|
||||
|
||||
const restart = async () => {
|
||||
await commands.proxyRestart()
|
||||
await refreshStatus()
|
||||
// 重启完成后刷新系统代理状态(后端失败时已同步关闭,成功时重新开启)
|
||||
await refreshSystemProxy()
|
||||
}
|
||||
|
||||
/** 等待 mihomo API 就绪(轮询 version 接口,最多等 10 秒) */
|
||||
@@ -260,12 +269,34 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新内核:复用 installKernel 的完整进度事件机制(installing/installProgress/事件监听)
|
||||
* 与 installKernel 的区别仅在于后端会先 stop mihomo(由调用方在前端控制),
|
||||
* 后端 proxy_update_kernel 与 proxy_install_kernel 共用 install_kernel 实现
|
||||
* 通过下载模块下载内核 zip,然后调用后端 apply_kernel_update 完成解压替换。
|
||||
* 下载进度通过 download-progress 事件更新,解压/替换进度通过 kernel-install-progress 事件更新。
|
||||
* 成功后自动删除下载任务。
|
||||
* @param mirrorPrefix 镜像源前缀(空串=GitHub 直连)
|
||||
* @param githubUrl GitHub 原始下载 URL(前端已通过 checkKernelUpdate 获取,为空时自动调用 checkKernelUpdate 获取)
|
||||
*/
|
||||
const updateKernel = async (mirrorPrefix: string = ''): Promise<void> => {
|
||||
const updateKernel = async (mirrorPrefix: string = '', githubUrl: string = ''): Promise<void> => {
|
||||
if (installing.value) return
|
||||
// 等待上一个任务完全收尾
|
||||
if (activeInstall) {
|
||||
try { await activeInstall } catch {}
|
||||
}
|
||||
|
||||
// 确定下载 URL
|
||||
let finalUrl = githubUrl
|
||||
if (!finalUrl) {
|
||||
try {
|
||||
const info = await commands.proxyCheckKernelUpdate()
|
||||
finalUrl = info.downloadUrl
|
||||
} catch (e) {
|
||||
throw new Error('获取更新信息失败: ' + String(e))
|
||||
}
|
||||
}
|
||||
// 应用镜像前缀
|
||||
if (mirrorPrefix) {
|
||||
finalUrl = mirrorPrefix + finalUrl
|
||||
}
|
||||
|
||||
installing.value = true
|
||||
installProgress.value = {
|
||||
stage: 'downloading',
|
||||
@@ -274,62 +305,132 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
totalBytes: null,
|
||||
message: '准备开始下载...'
|
||||
}
|
||||
if (!progressUnlisten) {
|
||||
progressUnlisten = await listen<InstallProgress>(EVENTS.kernelInstallProgress, (e) => {
|
||||
installProgress.value = e.payload
|
||||
})
|
||||
}
|
||||
try {
|
||||
await commands.proxyUpdateKernel(mirrorPrefix)
|
||||
await refreshKernel()
|
||||
} catch (e) {
|
||||
logger.error('内核更新失败: ' + e)
|
||||
throw e
|
||||
} finally {
|
||||
installing.value = false
|
||||
if (progressUnlisten) {
|
||||
progressUnlisten()
|
||||
progressUnlisten = null
|
||||
|
||||
const task = (async () => {
|
||||
let downloadProgressFn: UnlistenFn | null = null
|
||||
// 用对象持有完成事件解绑函数,避免闭包内赋值导致的 TS 类型收窄问题
|
||||
const completeHolder: { fn: UnlistenFn | null } = { fn: null }
|
||||
/** 下载阶段是否已成功完成(决定清理时是否删除文件:下载失败删除,apply 失败保留以便重试) */
|
||||
let downloadOk = false
|
||||
let taskId: string | null = null
|
||||
try {
|
||||
// 注册内核安装进度监听(解压/替换/need_stop 阶段由后端 emit)
|
||||
if (!progressUnlisten) {
|
||||
progressUnlisten = await listen<InstallProgress>(EVENTS.kernelInstallProgress, (e) => {
|
||||
installProgress.value = e.payload
|
||||
})
|
||||
}
|
||||
|
||||
// 使用下载模块添加下载任务(保持下载模块自身的代理/进度机制)
|
||||
const downloaderStore = useDownloaderStore()
|
||||
try {
|
||||
// 确保下载模块事件监听已注册(下载器 UI 与这里共用事件流)
|
||||
await downloaderStore.startEventListeners()
|
||||
} catch {
|
||||
// 忽略:本流程自己也会监听进度/完成事件
|
||||
}
|
||||
taskId = await downloaderStore.addTask(finalUrl, 'mihomo-update.zip', undefined, {}, false)
|
||||
|
||||
// 监听下载进度,转为 InstallProgress 格式
|
||||
downloadProgressFn = await listen<{
|
||||
id: string; completedSize: number; totalSize: number; speed: number; status: string
|
||||
}>('download-progress', (e) => {
|
||||
if (e.payload.id === taskId) {
|
||||
const pct = e.payload.totalSize > 0
|
||||
? Math.round((e.payload.completedSize / e.payload.totalSize) * 90)
|
||||
: 0
|
||||
installProgress.value = {
|
||||
stage: 'downloading',
|
||||
percent: pct,
|
||||
downloadedBytes: e.payload.completedSize,
|
||||
totalBytes: e.payload.totalSize,
|
||||
message: '正在下载...'
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 等待下载完成(download-complete 事件 / 初始终态 / 取消唤醒 三选一)
|
||||
const dlResult = await new Promise<{ ok: boolean; error?: string }>((resolve) => {
|
||||
let settled = false
|
||||
const finish = (r: { ok: boolean; error?: string }) => {
|
||||
if (settled) return
|
||||
settled = true
|
||||
cancelDownload = null
|
||||
resolve(r)
|
||||
}
|
||||
// 任务添加后瞬间进入终态(如探测即失败 → Error,无 complete 事件)
|
||||
const initial = downloaderStore.tasks.find(t => t.id === taskId)
|
||||
if (initial) {
|
||||
if (initial.status === 'complete') { finish({ ok: true }); return }
|
||||
if (initial.status === 'error') { finish({ ok: false, error: initial.error || '下载失败' }); return }
|
||||
}
|
||||
cancelDownload = () => finish({ ok: false, error: '下载已取消' })
|
||||
listen<{ id: string; filename: string; status: string; error: string | null }>(
|
||||
'download-complete', (e) => {
|
||||
if (e.payload.id === taskId) {
|
||||
if (e.payload.status === 'complete') finish({ ok: true })
|
||||
else finish({ ok: false, error: e.payload.error || '下载失败' })
|
||||
}
|
||||
}
|
||||
).then(fn => { completeHolder.fn = fn })
|
||||
})
|
||||
|
||||
if (!dlResult.ok) {
|
||||
throw new Error(dlResult.error || '下载失败')
|
||||
}
|
||||
downloadOk = true
|
||||
|
||||
// 获取下载任务的保存路径
|
||||
const dlTask = downloaderStore.tasks.find(t => t.id === taskId)
|
||||
if (!dlTask) throw new Error('下载任务未找到')
|
||||
const zipPath = dlTask.dir + '/' + dlTask.filename
|
||||
|
||||
// 调用后端执行解压替换(need_stop → 解压 → 替换,进度由 kernel-install-progress 事件上报)
|
||||
await commands.proxyApplyKernelUpdate(zipPath)
|
||||
await refreshKernel()
|
||||
|
||||
// 更新成功后自动删除下载任务(zip 已被后端清理,不删除磁盘文件)
|
||||
await downloaderStore.removeTask(taskId, false)
|
||||
taskId = null
|
||||
} catch (e) {
|
||||
// 清理下载任务:下载阶段失败/取消时删除文件;apply 阶段失败仅移除任务(zip 保留便于重试)
|
||||
if (taskId) {
|
||||
try {
|
||||
const downloaderStore = useDownloaderStore()
|
||||
await downloaderStore.removeTask(taskId, !downloadOk)
|
||||
} catch {
|
||||
// 忽略清理错误(任务可能已被移除)
|
||||
}
|
||||
}
|
||||
if (String(e).includes('下载已取消')) return
|
||||
logger.error('内核更新失败: ' + e)
|
||||
throw e
|
||||
} finally {
|
||||
installing.value = false
|
||||
cancelDownload = null
|
||||
if (progressUnlisten) {
|
||||
progressUnlisten()
|
||||
progressUnlisten = null
|
||||
}
|
||||
if (downloadProgressFn) downloadProgressFn()
|
||||
if (completeHolder.fn) completeHolder.fn()
|
||||
}
|
||||
})()
|
||||
activeInstall = task
|
||||
try {
|
||||
await task
|
||||
} finally {
|
||||
if (activeInstall === task) activeInstall = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次安装内核:调用后端 install_kernel,监听内核安装进度事件更新进度
|
||||
* @param mirrorPrefix 镜像源前缀(空串=GitHub 直连)
|
||||
* 完成或出错后自动取消监听并清空进度(由调用方控制何时隐藏 UI)
|
||||
* 首次安装内核:与 updateKernel 逻辑相同,但无已有 githubUrl 时自动获取。
|
||||
* 下载阶段使用下载模块,解压替换阶段使用后端 apply_kernel_update。
|
||||
*/
|
||||
const installKernel = async (mirrorPrefix: string = ''): Promise<void> => {
|
||||
if (installing.value) return
|
||||
installing.value = true
|
||||
installProgress.value = {
|
||||
stage: 'downloading',
|
||||
percent: 0,
|
||||
downloadedBytes: 0,
|
||||
totalBytes: null,
|
||||
message: '准备开始下载...'
|
||||
}
|
||||
// 注册进度事件监听
|
||||
if (!progressUnlisten) {
|
||||
progressUnlisten = await listen<InstallProgress>(EVENTS.kernelInstallProgress, (e) => {
|
||||
installProgress.value = e.payload
|
||||
})
|
||||
}
|
||||
try {
|
||||
await commands.proxyInstallKernel(mirrorPrefix)
|
||||
await refreshKernel()
|
||||
} catch (e) {
|
||||
// 错误事件已由后端 emit,这里仅记录日志
|
||||
logger.error('内核安装失败: ' + e)
|
||||
throw e
|
||||
} finally {
|
||||
// 保留 installProgress 一段时间供 UI 显示终态,由调用方负责清空
|
||||
installing.value = false
|
||||
if (progressUnlisten) {
|
||||
progressUnlisten()
|
||||
progressUnlisten = null
|
||||
}
|
||||
}
|
||||
const installKernel = async (mirrorPrefix: string = '', _githubUrl: string = ''): Promise<void> => {
|
||||
// 直接委托给 updateKernel(无 githubUrl 时内部自动获取)
|
||||
await updateKernel(mirrorPrefix, _githubUrl)
|
||||
}
|
||||
|
||||
/** 清空进度状态(UI 在动画结束后调用) */
|
||||
@@ -337,6 +438,47 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
installProgress.value = null
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认 mihomo 已停止,唤醒后端等待中的安装流程继续解压替换。
|
||||
* 需在 store.stop() 成功后再调用(解压替换时 exe 文件被占用会失败)。
|
||||
*/
|
||||
const confirmInstall = async (): Promise<void> => {
|
||||
await commands.proxyConfirmInstall()
|
||||
}
|
||||
|
||||
/**
|
||||
* 取消内核下载/安装:
|
||||
* - 下载阶段:唤醒下载等待 → 流程内移除下载任务(删除已下载文件)
|
||||
* - need_stop 等待阶段:置位后端取消标志唤醒其返回(zip 保留,便于重试)
|
||||
* 等待旧任务真正结束是关键 —— 否则旧任务的 finally 会在新任务开始后执行,
|
||||
* 解绑新任务的进度监听并复位 installing,导致新下载"点了没反应"
|
||||
*/
|
||||
const cancelKernelInstall = async (): Promise<void> => {
|
||||
// 1. 唤醒下载等待(若正在下载,下载等待立即以「已取消」返回,由流程内清理任务)
|
||||
cancelDownload?.()
|
||||
// 2. 通知后端(若处于 need_stop 等待阶段,置位取消标志唤醒其返回)
|
||||
try {
|
||||
await commands.proxyCancelKernelInstall()
|
||||
} catch (e) {
|
||||
logger.error('取消内核下载失败: ' + e)
|
||||
}
|
||||
// 3. 等待旧任务完全收尾(其内部会移除下载任务并复位状态)
|
||||
if (activeInstall) {
|
||||
try {
|
||||
await activeInstall
|
||||
} catch {
|
||||
// 旧任务错误已在任务内部处理
|
||||
}
|
||||
}
|
||||
// 4. 复位 UI 状态
|
||||
if (progressUnlisten) {
|
||||
progressUnlisten()
|
||||
progressUnlisten = null
|
||||
}
|
||||
installing.value = false
|
||||
installProgress.value = null
|
||||
}
|
||||
|
||||
return {
|
||||
// state
|
||||
kernel,
|
||||
@@ -378,6 +520,8 @@ export const useProxyStore = defineStore('proxy', () => {
|
||||
checkKernelUpdate,
|
||||
updateKernel,
|
||||
installKernel,
|
||||
clearInstallProgress
|
||||
clearInstallProgress,
|
||||
cancelKernelInstall,
|
||||
confirmInstall
|
||||
}
|
||||
})
|
||||
|
||||
@@ -8,6 +8,7 @@ import { toast } from 'vue-sonner'
|
||||
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
import type { WindowInfo } from '@/modules/screenshot/types'
|
||||
|
||||
export interface RecentCapture {
|
||||
id: string
|
||||
@@ -67,6 +68,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
let overlayReadyResolve: (() => void) | null = null
|
||||
let overlayReadyPromise: Promise<void> | null = null
|
||||
let readyListenerInit = false
|
||||
/** 上次已应用的覆盖层布局矩形(虚拟屏未变化时跳过 setPosition/setSize,省 2 次 IPC 往返) */
|
||||
let lastOverlayRectKey = ''
|
||||
|
||||
// ===== 贴图窗口 =====
|
||||
const PIN_LABEL = WINDOWS.screenshotPin
|
||||
@@ -141,7 +144,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
}
|
||||
|
||||
// ===== 截图流程 =====
|
||||
/** 启动截图:延时倒计时 → 捕获虚拟屏 → 定位常驻覆盖层 → 通知覆盖层开始 */
|
||||
/** 启动截图:延时倒计时 → 并行(捕获虚拟屏 + 枚举拾取窗口 + 计算虚拟屏矩形)→ 定位覆盖层 → 通知覆盖层开始 */
|
||||
async function startCapture() {
|
||||
if (capturing.value) return
|
||||
capturing.value = true
|
||||
@@ -163,14 +166,28 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
await new Promise<void>((r) => setTimeout(r, 1000))
|
||||
}
|
||||
}
|
||||
// 捕获虚拟屏(覆盖层隐藏 → 不会出现在截图中),仅存原始像素,不做 PNG 编码
|
||||
await commands.screenshotCaptureFullscreen()
|
||||
// 用物理像素把覆盖层对齐到虚拟屏(多显示器/混合 DPI 下保证底图 1:1 与坐标一致)
|
||||
const rect = await computeVirtualPhysicalRect()
|
||||
await overlayWin?.setPosition(new PhysicalPosition(rect.x, rect.y))
|
||||
await overlayWin?.setSize(new PhysicalSize(rect.width, rect.height))
|
||||
// 三路并行:捕获(含光标)/ 拾取窗口列表 / 虚拟屏矩形 —— 互不依赖,缩短关键路径
|
||||
//(捕获时覆盖层已隐藏 → 不会出现在截图中;窗口列表与冻结底图同一时刻生成,命中一致)
|
||||
const [start, pickWindows, rect] = await Promise.all([
|
||||
commands.screenshotCaptureFullscreen(),
|
||||
commands.screenshotPickList().catch(() => [] as WindowInfo[]),
|
||||
computeVirtualPhysicalRect(),
|
||||
])
|
||||
// 用物理像素把覆盖层对齐到虚拟屏(多显示器/混合 DPI 下保证底图 1:1 与坐标一致);
|
||||
// 矩形未变化时跳过(覆盖层仅由本流程定位,跳过安全),省 2 次 IPC 往返
|
||||
const rectKey = `${rect.x},${rect.y},${rect.width},${rect.height}`
|
||||
if (rectKey !== lastOverlayRectKey) {
|
||||
await overlayWin?.setPosition(new PhysicalPosition(rect.x, rect.y))
|
||||
await overlayWin?.setSize(new PhysicalSize(rect.width, rect.height))
|
||||
lastOverlayRectKey = rectKey
|
||||
}
|
||||
await waitOverlayReady()
|
||||
await emit(EVENTS.screenshotBegin)
|
||||
// 携带捕获时刻光标 + 窗口列表:覆盖层显示前即可完成初始高亮,无"遮罩→高亮"闪烁
|
||||
await emit(EVENTS.screenshotBegin, {
|
||||
cursorX: start.cursorX,
|
||||
cursorY: start.cursorY,
|
||||
windows: pickWindows,
|
||||
})
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 捕获失败', e)
|
||||
toast.error('截图启动失败:' + (e as Error).message)
|
||||
@@ -552,6 +569,8 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
if (pinWin) {
|
||||
try {
|
||||
if (await pinWin.isVisible()) {
|
||||
// 还原不可聚焦(贴图窗口交互时可能已置为可聚焦),避免下次 show() 激活窗口抢走当前应用焦点
|
||||
await pinWin.setFocusable(false).catch(() => {})
|
||||
await pinWin.hide()
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user