Compare commits
10
Commits
e09b0567d6
...
v26.8.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b9f71da08 | ||
|
|
28e0c4664a | ||
|
|
d21649c60e | ||
|
|
4dd60f42a1 | ||
|
|
0a19b4b38a | ||
|
|
7d49a7395f | ||
|
|
d0705b1ffe | ||
|
|
6c7897bf47 | ||
|
|
2f20161010 | ||
|
|
d09599fa95 |
@@ -7,6 +7,9 @@ yarn-error.log*
|
|||||||
pnpm-debug.log*
|
pnpm-debug.log*
|
||||||
lerna-debug.log*
|
lerna-debug.log*
|
||||||
|
|
||||||
|
# 发布暂存目录
|
||||||
|
release_stage/
|
||||||
|
|
||||||
node_modules
|
node_modules
|
||||||
dist
|
dist
|
||||||
dist-ssr
|
dist-ssr
|
||||||
|
|||||||
@@ -100,7 +100,7 @@ Thing/
|
|||||||
#### 📸 截图
|
#### 📸 截图
|
||||||
- [x] 截图及相关
|
- [x] 截图及相关
|
||||||
- [ ] 滚动截图(后续支持)
|
- [ ] 滚动截图(后续支持)
|
||||||
- [ ] 贴图(后续支持)
|
- [x] 贴图
|
||||||
|
|
||||||
#### 📊 硬件监控
|
#### 📊 硬件监控
|
||||||
- [x] 悬浮窗显示
|
- [x] 悬浮窗显示
|
||||||
@@ -111,7 +111,7 @@ Thing/
|
|||||||
- [x] 自建进程内下载引擎(多线程 HTTP/HTTPS,无需外部内核)
|
- [x] 自建进程内下载引擎(多线程 HTTP/HTTPS,无需外部内核)
|
||||||
- [x] 接管浏览器下载,浏览器扩展(Thing Extension)
|
- [x] 接管浏览器下载,浏览器扩展(Thing Extension)
|
||||||
- [x] HTTP 下载支持
|
- [x] HTTP 下载支持
|
||||||
- [ ] BT/磁力链接支持(后续支持)
|
- [x] BT/磁力链接支持(后续支持)
|
||||||
- [x] 下载任务管理(历史)
|
- [x] 下载任务管理(历史)
|
||||||
- [x] 速度限制
|
- [x] 速度限制
|
||||||
- [x] 断点续传
|
- [x] 断点续传
|
||||||
@@ -124,11 +124,11 @@ Thing/
|
|||||||
|
|
||||||
### 第三阶段:优化与完善
|
### 第三阶段:优化与完善
|
||||||
|
|
||||||
- [x] 性能优化(P1/P2:轮询随窗口可见性暂停、批量测速限并发、渲染 memo 化等,见 MODULE_REVIEW.md)
|
- [x] 性能优化(见 MODULE_REVIEW.md)
|
||||||
- [x] 错误处理与日志完善(B5 进程级全局日志器、异常兜底)
|
- [x] 错误处理与日志完善(全局日志器、异常兜底)
|
||||||
- [x] 用户体验优化(混合 DPI 定位、rAF 节流、UI 细节)
|
- [x] 用户体验优化(混合 DPI 定位、rAF 节流、UI 细节)
|
||||||
- [ ] 自动更新机制
|
- [x] 自动更新机制
|
||||||
- [ ] 打包发布
|
- [x] 打包发布
|
||||||
|
|
||||||
## 模块管理架构
|
## 模块管理架构
|
||||||
|
|
||||||
|
|||||||
@@ -66,6 +66,8 @@ internal sealed class KernelStatus
|
|||||||
{
|
{
|
||||||
public bool Ready { get; set; }
|
public bool Ready { get; set; }
|
||||||
public bool IsAdmin { get; set; }
|
public bool IsAdmin { get; set; }
|
||||||
|
/// <summary>PawnIO 驱动是否已安装(ring0 传感器读取依赖它或 WinRing0,缺失时温度/频率通常无法读取)</summary>
|
||||||
|
public bool PawnIoInstalled { get; set; }
|
||||||
public double UptimeMs { get; set; }
|
public double UptimeMs { get; set; }
|
||||||
public int GroupCount { get; set; }
|
public int GroupCount { get; set; }
|
||||||
public int SensorCount { get; set; }
|
public int SensorCount { get; set; }
|
||||||
|
|||||||
+45
-11
@@ -24,6 +24,9 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
private readonly bool _isAdmin;
|
private readonly bool _isAdmin;
|
||||||
private readonly double _coldStartMs;
|
private readonly double _coldStartMs;
|
||||||
private readonly Stopwatch _startupSw;
|
private readonly Stopwatch _startupSw;
|
||||||
|
// 传感器 ID 缓存:避免每秒为每个传感器重复拼接字符串(减少 GC 压力)
|
||||||
|
private readonly Dictionary<ISensor, string> _sensorIdCache = new();
|
||||||
|
private bool _coldStartSent;
|
||||||
private bool _ready;
|
private bool _ready;
|
||||||
private bool _closed;
|
private bool _closed;
|
||||||
private HardwareConfig _config;
|
private HardwareConfig _config;
|
||||||
@@ -84,7 +87,7 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 全量 Update 所有硬件。
|
/// 全量 Update 所有硬件。
|
||||||
/// 由 SamplingScheduler 按通道分频调用。
|
/// 仅用于构造函数首轮填充,运行期由调度器分频调用 UpdateFastOnly/UpdateSlowOnly。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void UpdateAll()
|
public void UpdateAll()
|
||||||
{
|
{
|
||||||
@@ -94,9 +97,24 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 仅 Update 快通道硬件(CPU/GPU/Memory/Network 等)。
|
||||||
|
/// 由调度器快通道 tick 高频调用,避免 SMART 等重查询拖慢采样节奏。
|
||||||
|
/// </summary>
|
||||||
|
public void UpdateFastOnly()
|
||||||
|
{
|
||||||
|
foreach (var hw in _visitor.AllHardware)
|
||||||
|
{
|
||||||
|
if (!IsSlowHardware(hw.HardwareType))
|
||||||
|
{
|
||||||
|
try { hw.Update(); } catch { /* 单个硬件 Update 失败不影响整体 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 仅 Update 慢通道硬件(Storage/PSU/Battery 等)。
|
/// 仅 Update 慢通道硬件(Storage/PSU/Battery 等)。
|
||||||
/// 快通道硬件(CPU/GPU/Memory/Network)由调度器更高频调用 UpdateAll。
|
/// 快通道硬件(CPU/GPU/Memory/Network)由调度器更高频调用 UpdateFastOnly。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public void UpdateSlowOnly()
|
public void UpdateSlowOnly()
|
||||||
{
|
{
|
||||||
@@ -123,10 +141,11 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
Ready = _ready,
|
Ready = _ready,
|
||||||
};
|
};
|
||||||
|
|
||||||
// 首个快照带上冷启动耗时,后续为 0
|
// 首个快照带上冷启动耗时,后续为 0(修复:此前每个快照都携带 ColdStartMs)
|
||||||
if (_coldStartMs > 0 && snap.Timestamp > 0)
|
if (_coldStartMs > 0 && !_coldStartSent)
|
||||||
{
|
{
|
||||||
snap.ColdStartMs = Math.Round(_coldStartMs, 1);
|
snap.ColdStartMs = Math.Round(_coldStartMs, 1);
|
||||||
|
_coldStartSent = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 重新遍历以读取最新传感器值(visitor 缓存的是 hardware 引用,sensor 值实时)
|
// 重新遍历以读取最新传感器值(visitor 缓存的是 hardware 引用,sensor 值实时)
|
||||||
@@ -156,7 +175,7 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
|
|
||||||
g.Sensors.Add(new SensorEntry
|
g.Sensors.Add(new SensorEntry
|
||||||
{
|
{
|
||||||
Id = $"{groupId}/{hw.Name}/{s.SensorType}/{s.Name}".Replace(' ', '_').ToLowerInvariant(),
|
Id = GetSensorId(s, groupId, hw.Name),
|
||||||
Name = s.Name,
|
Name = s.Name,
|
||||||
Type = sensorType,
|
Type = sensorType,
|
||||||
Value = s.Value,
|
Value = s.Value,
|
||||||
@@ -169,6 +188,21 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
return snap;
|
return snap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 获取传感器稳定 ID(带缓存)。
|
||||||
|
/// ID 格式:{groupId}/{hwName}/{sensorType}/{sensorName},空格转下划线、小写化。
|
||||||
|
/// 缓存命中直接返回,未命中(新传感器)计算后入缓存。
|
||||||
|
/// </summary>
|
||||||
|
private string GetSensorId(ISensor s, string groupId, string hwName)
|
||||||
|
{
|
||||||
|
if (!_sensorIdCache.TryGetValue(s, out var id))
|
||||||
|
{
|
||||||
|
id = $"{groupId}/{hwName}/{s.SensorType}/{s.Name}".Replace(' ', '_').ToLowerInvariant();
|
||||||
|
_sensorIdCache[s] = id;
|
||||||
|
}
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 为已启用但 LHB 未枚举到的硬件类型预创建空分组。
|
/// 为已启用但 LHB 未枚举到的硬件类型预创建空分组。
|
||||||
/// 场景:用户在设置中勾选了主板/电池/电源等,但 LHB 在当前权限或机型下检测不到对应硬件,
|
/// 场景:用户在设置中勾选了主板/电池/电源等,但 LHB 在当前权限或机型下检测不到对应硬件,
|
||||||
@@ -243,7 +277,7 @@ internal sealed class HardwareManager : IDisposable
|
|||||||
_ => "",
|
_ => "",
|
||||||
};
|
};
|
||||||
|
|
||||||
private static bool IsRunningAsAdmin()
|
internal static bool IsRunningAsAdmin()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -290,14 +324,14 @@ internal sealed class SnapshotVisitor : IVisitor
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 采样调度器:按快/慢通道分频驱动 HardwareManager.UpdateAll。
|
/// 采样调度器:按快/慢通道分频驱动 HardwareManager 的分层 Update。
|
||||||
/// 使用 Channel 向 SSE 推送层广播快照(解耦:调度器不关心有几个订阅者)。
|
/// 使用 Channel 向 SSE 推送层广播快照(解耦:调度器不关心有几个订阅者)。
|
||||||
///
|
///
|
||||||
/// 调度策略:
|
/// 调度策略:
|
||||||
/// - 快通道 tick:UpdateAll(含慢通道硬件,因 UpdateAll 成本主要在 SMART,已通过慢通道分频减少调用频率)
|
/// - 快通道 tick:UpdateFastOnly(仅 CPU/GPU/Memory/Network 等轻量硬件),
|
||||||
/// 实际优化:快通道 tick 只 Update 快通道硬件(UpdateFastOnly),慢通道单独按慢节奏 Update
|
/// 避免 SMART 等重查询每秒执行拖慢采样节奏
|
||||||
/// - 慢通道 tick:UpdateSlowOnly(仅 Storage/PSU/Motherboard 等)
|
/// - 慢通道 tick:UpdateSlowOnly(仅 Storage/PSU/Motherboard 等)
|
||||||
/// - 每个 tick 结束后构建快照并广播
|
/// - 快通道每个 tick 结束后构建快照并广播(慢通道更新后的值随下一帧带出)
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal sealed class SamplingScheduler : IDisposable
|
internal sealed class SamplingScheduler : IDisposable
|
||||||
{
|
{
|
||||||
@@ -352,7 +386,7 @@ internal sealed class SamplingScheduler : IDisposable
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_hw.UpdateAll();
|
_hw.UpdateFastOnly();
|
||||||
var snap = _hw.BuildSnapshot();
|
var snap = _hw.BuildSnapshot();
|
||||||
_cache.Update(snap);
|
_cache.Update(snap);
|
||||||
_broadcast.Writer.TryWrite(snap);
|
_broadcast.Writer.TryWrite(snap);
|
||||||
|
|||||||
@@ -44,6 +44,7 @@ internal static class HttpEndpoints
|
|||||||
{
|
{
|
||||||
Ready = hw?.Ready ?? false,
|
Ready = hw?.Ready ?? false,
|
||||||
IsAdmin = hw?.IsAdmin ?? false,
|
IsAdmin = hw?.IsAdmin ?? false,
|
||||||
|
PawnIoInstalled = PawnIoSupport.IsServiceInstalled(),
|
||||||
UptimeMs = kernel.Uptime.Elapsed.TotalMilliseconds,
|
UptimeMs = kernel.Uptime.Elapsed.TotalMilliseconds,
|
||||||
GroupCount = snap?.Groups.Count ?? 0,
|
GroupCount = snap?.Groups.Count ?? 0,
|
||||||
SensorCount = kernel.Scheduler.Cache.SensorCount,
|
SensorCount = kernel.Scheduler.Cache.SensorCount,
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using Microsoft.Win32;
|
||||||
|
|
||||||
|
namespace ThingHK;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// PawnIO 驱动支持:检测 + 静默安装。
|
||||||
|
///
|
||||||
|
/// 背景:LHM 读取 CPU 温度/频率等 ring0 数据依赖内核驱动,回退用的 WinRing0 被
|
||||||
|
/// 微软"易受攻击的驱动程序阻止列表"和部分杀软(如火绒)拦截,导致传感器缺失。
|
||||||
|
/// PawnIO 是正规签名的替代驱动(不在阻止列表、兼容 HVCI/安全启动),
|
||||||
|
/// LHM 0.9.5+ 检测到已安装时优先使用,无需任何代码开关。
|
||||||
|
///
|
||||||
|
/// 安装器约定:PawnIO_setup.exe 与 ThingHK.exe 同目录
|
||||||
|
/// (由 Tauri 侧 prepare_kernel 从资源目录随内核一起复制到 {app_data}/monitor/cores/)。
|
||||||
|
///
|
||||||
|
/// 静默参数:-install -silent(官方 CLI 参数,见 namazso/PawnIO.Setup)。
|
||||||
|
/// 退出码:0=成功;3010=成功但需重启(ERROR_SUCCESS_REBOOT_REQUIRED)。
|
||||||
|
///
|
||||||
|
/// 策略:仅在内核已提权时安装。两种提权模式(Thing 提权继承 / 仅提权 ThingHK)
|
||||||
|
/// 都只有一次 UAC,内核拿到权限后自行静默安装,避免二次弹窗。
|
||||||
|
/// serve 模式调用;scan 诊断模式不安装,保持被动。
|
||||||
|
/// </summary>
|
||||||
|
internal static class PawnIoSupport
|
||||||
|
{
|
||||||
|
/// <summary>驱动服务注册表键:存在即认为已安装</summary>
|
||||||
|
private const string ServiceKeyName = @"SYSTEM\CurrentControlSet\Services\PawnIO";
|
||||||
|
|
||||||
|
private const string SetupFileName = "PawnIO_setup.exe";
|
||||||
|
|
||||||
|
/// <summary>3010 = ERROR_SUCCESS_REBOOT_REQUIRED(安装成功但需重启生效)</summary>
|
||||||
|
private const int ExitCodeRebootRequired = 3010;
|
||||||
|
|
||||||
|
/// <summary>驱动安装通常数秒内完成,留足余量防止卡死启动流程</summary>
|
||||||
|
private const int InstallTimeoutMs = 90_000;
|
||||||
|
|
||||||
|
/// <summary>检测 PawnIO 驱动服务是否已注册</summary>
|
||||||
|
public static bool IsServiceInstalled()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var key = Registry.LocalMachine.OpenSubKey(ServiceKeyName);
|
||||||
|
return key != null;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 确保 PawnIO 就绪:已安装直接返回;未安装且当前已提权时静默安装。
|
||||||
|
/// 返回描述性结果(写入 stderr 日志 + /status 诊断)。
|
||||||
|
/// </summary>
|
||||||
|
public static string EnsureInstalled()
|
||||||
|
{
|
||||||
|
if (IsServiceInstalled())
|
||||||
|
return "already-installed";
|
||||||
|
|
||||||
|
if (!HardwareManager.IsRunningAsAdmin())
|
||||||
|
return "skipped: not elevated (温度/频率等传感器需要提权运行)";
|
||||||
|
|
||||||
|
string setupPath = Path.Combine(AppContext.BaseDirectory, SetupFileName);
|
||||||
|
if (!File.Exists(setupPath))
|
||||||
|
return $"skipped: {SetupFileName} 未找到(应随内核一起部署,见 prepare_kernel)";
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var process = Process.Start(new ProcessStartInfo
|
||||||
|
{
|
||||||
|
FileName = setupPath,
|
||||||
|
Arguments = "-install -silent",
|
||||||
|
UseShellExecute = false,
|
||||||
|
CreateNoWindow = true,
|
||||||
|
});
|
||||||
|
if (process == null)
|
||||||
|
return "failed: Process.Start 返回 null";
|
||||||
|
|
||||||
|
if (!process.WaitForExit(InstallTimeoutMs))
|
||||||
|
{
|
||||||
|
try { process.Kill(); } catch { /* 超时后进程可能已自行退出 */ }
|
||||||
|
return "failed: 安装超时";
|
||||||
|
}
|
||||||
|
|
||||||
|
int code = process.ExitCode;
|
||||||
|
if (code == ExitCodeRebootRequired)
|
||||||
|
return "installed: 需重启后生效";
|
||||||
|
|
||||||
|
if (code != 0)
|
||||||
|
return $"failed: 安装器退出码 {code}";
|
||||||
|
|
||||||
|
return IsServiceInstalled()
|
||||||
|
? "installed"
|
||||||
|
: "failed: 安装器返回 0 但服务未注册";
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return $"failed: {ex.Message}";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -87,6 +87,11 @@ internal static class Program
|
|||||||
|
|
||||||
Console.Error.WriteLine($"[ThingHK] serve 模式: port={port} config={configPath ?? "(默认)"} fast={fastMs}ms slow={slowMs}ms");
|
Console.Error.WriteLine($"[ThingHK] serve 模式: port={port} config={configPath ?? "(默认)"} fast={fastMs}ms slow={slowMs}ms");
|
||||||
|
|
||||||
|
// PawnIO:ring0 传感器读取的首选驱动(未安装且已提权时静默安装,
|
||||||
|
// 避开 WinRing0 被系统阻止列表/杀软拦截导致的温度/频率缺失)
|
||||||
|
string pawnIoResult = PawnIoSupport.EnsureInstalled();
|
||||||
|
Console.Error.WriteLine($"[ThingHK] PawnIO: {pawnIoResult}");
|
||||||
|
|
||||||
using var kernel = new KernelHost();
|
using var kernel = new KernelHost();
|
||||||
await kernel.StartAsync(configPath, fastMs, slowMs);
|
await kernel.StartAsync(configPath, fastMs, slowMs);
|
||||||
|
|
||||||
|
|||||||
@@ -25,7 +25,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.7-pre716" />
|
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.7-pre729" />
|
||||||
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
|
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "thing",
|
"name": "thing",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.1.0",
|
"version": "26.8.4",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 >nul
|
||||||
|
setlocal enabledelayedexpansion
|
||||||
|
|
||||||
|
set "SCRIPT=%~dp0release.ps1"
|
||||||
|
|
||||||
|
echo ================================================
|
||||||
|
echo Thing Build Pubilsh
|
||||||
|
echo 发布目标:https://gitea.atie.fun/LFeng/Thing
|
||||||
|
echo ================================================
|
||||||
|
echo.
|
||||||
|
|
||||||
|
:: ---------- 版本号 ----------
|
||||||
|
set "VERSION="
|
||||||
|
set /p "VERSION=请输入版本号(如 26.8.1,直接回车沿用当前版本): "
|
||||||
|
set "VER_ARG="
|
||||||
|
if not "%VERSION%"=="" set "VER_ARG=-Version %VERSION%"
|
||||||
|
|
||||||
|
:: ---------- 发布模式 ----------
|
||||||
|
echo.
|
||||||
|
echo [1] Build + Pubilsh Gitea
|
||||||
|
echo [2] Build Only
|
||||||
|
echo [3] Pubilsh Gitea
|
||||||
|
set "MODE="
|
||||||
|
set /p "MODE=请输入数字选择(回车默认 1): "
|
||||||
|
if "%MODE%"=="" set "MODE=1"
|
||||||
|
|
||||||
|
set "EXTRA="
|
||||||
|
if "%MODE%"=="2" (
|
||||||
|
set "EXTRA=-SkipPush"
|
||||||
|
) else if "%MODE%"=="3" (
|
||||||
|
set "EXTRA=-SkipBuild"
|
||||||
|
)
|
||||||
|
|
||||||
|
:: ---------- Gitea Token(仅完整发布模式需要) ----------
|
||||||
|
if "%MODE%"=="1" if not defined GITEA_TOKEN (
|
||||||
|
echo.
|
||||||
|
echo 未检测到环境变量 GITEA_TOKEN,上传到 Gitea 需要它。
|
||||||
|
echo 可在此临时输入(仅本次会话生效),留空则自动改为"只构建不上传"。
|
||||||
|
set /p "GITEA_TOKEN=请输入 Gitea Token: "
|
||||||
|
if "!GITEA_TOKEN!"=="" (
|
||||||
|
set "EXTRA=-SkipPush"
|
||||||
|
set "MODE=2"
|
||||||
|
echo [提示] 已切换为"只构建并整理产物,不上传"。
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Start:release.ps1 %VER_ARG% %EXTRA%
|
||||||
|
echo ------------------------------------------------
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %VER_ARG% %EXTRA%
|
||||||
|
set "RESULT=%ERRORLEVEL%"
|
||||||
|
|
||||||
|
echo.
|
||||||
|
if "%RESULT%"=="0" (
|
||||||
|
echo 执行完成。
|
||||||
|
) else (
|
||||||
|
echo 执行出错,请查看上方日志。
|
||||||
|
)
|
||||||
|
echo.
|
||||||
|
pause
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
# ============================================================
|
||||||
|
# Thing 构建发布脚本(目标:自建 Gitea release)
|
||||||
|
#
|
||||||
|
# 用法:
|
||||||
|
# .\scripts\release.ps1 -Version 0.2.0 # 同步版本号 + 构建 + 发布
|
||||||
|
# .\scripts\release.ps1 -Version 0.2.0 -SkipBuild # 复用现有构建产物,直接发布
|
||||||
|
# .\scripts\release.ps1 -Version 0.2.0 -SkipPush # 只构建+整理产物,不上传
|
||||||
|
#
|
||||||
|
# 发布产物(上传到 https://gitea.atie.fun/LFeng/Thing 的 v{Version} release):
|
||||||
|
# thing_{v}_x64.exe 便携免安装版(无内核)
|
||||||
|
# thing_{v}_x64.msi 安装版 MSI(去掉 tauri 默认的 _en-US 后缀)
|
||||||
|
# thing_{v}_x64-setup.exe 安装版 NSIS
|
||||||
|
# thing-hk_{v}.zip ThingHK 硬件监控内核(mihomo 继续走代理模块内置的 GitHub 下载)
|
||||||
|
#
|
||||||
|
# 前提:
|
||||||
|
# - Gitea token 已配置为环境变量 GITEA_TOKEN(-SkipPush 时不需要)
|
||||||
|
# - 可选 -NotesPath 指定 release notes 文件(Markdown 文本),
|
||||||
|
# 缺省时使用 scripts/release-notes.md(若存在),否则用简单占位文本
|
||||||
|
# ============================================================
|
||||||
|
|
||||||
|
param(
|
||||||
|
[string]$Version = '',
|
||||||
|
[switch]$SkipBuild,
|
||||||
|
[switch]$SkipPush,
|
||||||
|
[string]$NotesPath = ''
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$Root = Split-Path -Parent $PSScriptRoot
|
||||||
|
$TargetDir = Join-Path $Root 'src-tauri\target\release'
|
||||||
|
$BundleDir = Join-Path $TargetDir 'bundle'
|
||||||
|
$RepoOwner = 'LFeng'
|
||||||
|
$RepoName = 'Thing'
|
||||||
|
$ApiBase = 'https://gitea.atie.fun/api/v1'
|
||||||
|
$Product = 'thing'
|
||||||
|
|
||||||
|
function Write-Step([string]$msg) { Write-Host "`n==> $msg" -ForegroundColor Cyan }
|
||||||
|
|
||||||
|
# ---------- 0. 版本号 ----------
|
||||||
|
if ([string]::IsNullOrWhiteSpace($Version)) {
|
||||||
|
$conf = Get-Content (Join-Path $Root 'src-tauri\tauri.conf.json') -Raw | ConvertFrom-Json
|
||||||
|
$Version = $conf.version
|
||||||
|
Write-Step "未指定 -Version,沿用现有版本 $Version"
|
||||||
|
}
|
||||||
|
# 校验 X.Y.Z 格式
|
||||||
|
if ($Version -notmatch '^\d+\.\d+\.\d+$') {
|
||||||
|
throw "版本号格式错误(应为 X.Y.Z):$Version"
|
||||||
|
}
|
||||||
|
Write-Step "发布版本:v$Version"
|
||||||
|
|
||||||
|
# ---------- 1. 同步版本号到三处 ----------
|
||||||
|
$tauriConf = Join-Path $Root 'src-tauri\tauri.conf.json'
|
||||||
|
$cargoToml = Join-Path $Root 'src-tauri\Cargo.toml'
|
||||||
|
$pkgJson = Join-Path $Root 'package.json'
|
||||||
|
|
||||||
|
$t = Get-Content $tauriConf -Raw
|
||||||
|
$t = $t -replace '("version"\s*:\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||||
|
[System.IO.File]::WriteAllText($tauriConf, $t, (New-Object System.Text.UTF8Encoding($false)))
|
||||||
|
|
||||||
|
$c = Get-Content $cargoToml -Raw
|
||||||
|
$c = $c -replace '(?m)^(version\s*=\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||||
|
[System.IO.File]::WriteAllText($cargoToml, $c, (New-Object System.Text.UTF8Encoding($false)))
|
||||||
|
|
||||||
|
$p = Get-Content $pkgJson -Raw
|
||||||
|
$p = $p -replace '("version"\s*:\s*")[^"]*(")', "`${1}$Version`${2}"
|
||||||
|
[System.IO.File]::WriteAllText($pkgJson, $p, (New-Object System.Text.UTF8Encoding($false)))
|
||||||
|
Write-Step "版本号已同步:tauri.conf.json / Cargo.toml / package.json"
|
||||||
|
|
||||||
|
# ---------- 2. 构建 ----------
|
||||||
|
if (-not $SkipBuild) {
|
||||||
|
Write-Step '开始构建(bun run tauri build)...'
|
||||||
|
Push-Location $Root
|
||||||
|
try { bun run tauri build }
|
||||||
|
finally { Pop-Location }
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'tauri build 失败' }
|
||||||
|
} else {
|
||||||
|
Write-Step '跳过构建,复用现有产物'
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------- 3. 整理产物 ----------
|
||||||
|
# 版本号此时已解析,再确定暂存目录
|
||||||
|
$StageDir = Join-Path $Root "release_stage\$Version"
|
||||||
|
New-Item -ItemType Directory -Force -Path $StageDir | Out-Null
|
||||||
|
|
||||||
|
$exeSrc = Join-Path $TargetDir "$Product.exe"
|
||||||
|
$msiSrc = Join-Path $BundleDir "msi\${Product}_${Version}_x64_en-US.msi"
|
||||||
|
$nsisSrc = Join-Path $BundleDir "nsis\${Product}_${Version}_x64-setup.exe"
|
||||||
|
$hkSrc = Join-Path $Root 'src-tauri\binaries\ThingHK.exe'
|
||||||
|
|
||||||
|
$exeOut = Join-Path $StageDir "${Product}_${Version}_x64.exe"
|
||||||
|
$msiOut = Join-Path $StageDir "${Product}_${Version}_x64.msi"
|
||||||
|
$nsisOut = Join-Path $StageDir "${Product}_${Version}_x64-setup.exe"
|
||||||
|
$hkZip = Join-Path $StageDir "thing-hk_${Version}.zip"
|
||||||
|
|
||||||
|
if (Test-Path $exeSrc) { Copy-Item $exeSrc $exeOut } else { Write-Warning "缺少便携版:$exeSrc" }
|
||||||
|
if (Test-Path $msiSrc) { Copy-Item $msiSrc $msiOut } else { Write-Warning "缺少 MSI(已跳过重命名):$msiSrc" }
|
||||||
|
if (Test-Path $nsisSrc) { Copy-Item $nsisSrc $nsisOut } else { Write-Warning "缺少 NSIS:$nsisSrc" }
|
||||||
|
|
||||||
|
if (Test-Path $hkSrc) {
|
||||||
|
$tmp = Join-Path $env:TEMP "thinghk_$([guid]::NewGuid().ToString('N'))"
|
||||||
|
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
|
||||||
|
Copy-Item $hkSrc (Join-Path $tmp 'ThingHK.exe')
|
||||||
|
Compress-Archive -Path (Join-Path $tmp 'ThingHK.exe') -DestinationPath $hkZip -Force
|
||||||
|
Remove-Item -Recurse -Force $tmp
|
||||||
|
Write-Step "ThingHK 内核包:$hkZip"
|
||||||
|
} else {
|
||||||
|
Write-Warning "缺少 ThingHK.exe:$hkSrc"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Step "产物已整理到:$StageDir"
|
||||||
|
Get-ChildItem $StageDir | Select-Object Name, @{n='Size(MB)';e={[math]::Round($_.Length/1MB,1)}} | Format-Table -AutoSize
|
||||||
|
|
||||||
|
# ---------- 4. 上传到 Gitea ----------
|
||||||
|
if ($SkipPush) {
|
||||||
|
Write-Step '已跳过上传(-SkipPush)'
|
||||||
|
exit 0
|
||||||
|
}
|
||||||
|
|
||||||
|
$token = $env:GITEA_TOKEN
|
||||||
|
if ([string]::IsNullOrWhiteSpace($token)) {
|
||||||
|
throw '未设置环境变量 GITEA_TOKEN,无法发布到 Gitea(或使用 -SkipPush 跳过上传)'
|
||||||
|
}
|
||||||
|
$auth = @{ Authorization = "token $token" }
|
||||||
|
|
||||||
|
# 4.1 release notes
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($NotesPath)) {
|
||||||
|
$body = Get-Content $NotesPath -Raw
|
||||||
|
} elseif (Test-Path (Join-Path $PSScriptRoot 'release-notes.md')) {
|
||||||
|
$body = Get-Content (Join-Path $PSScriptRoot 'release-notes.md') -Raw
|
||||||
|
} else {
|
||||||
|
$body = "Thing v$Version"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 4.2 创建 release(已存在同名 tag 则复用)
|
||||||
|
Write-Step "创建 release v$Version ..."
|
||||||
|
$releaseUrl = "$ApiBase/repos/$RepoOwner/$RepoName/releases"
|
||||||
|
$releasePayload = @{
|
||||||
|
tag_name = "v$Version"
|
||||||
|
name = "Thing v$Version"
|
||||||
|
body = $body
|
||||||
|
draft = $false
|
||||||
|
prerelease = $false
|
||||||
|
} | ConvertTo-Json
|
||||||
|
|
||||||
|
try {
|
||||||
|
$release = Invoke-RestMethod -Method Post -Uri $releaseUrl -Headers $auth -ContentType 'application/json' -Body $releasePayload
|
||||||
|
} catch {
|
||||||
|
# tag 已存在:尝试用该 tag 查找现有 release,后续资产上传会追加
|
||||||
|
Write-Warning "创建 release 失败,尝试复用已有 release:$_"
|
||||||
|
$release = Invoke-RestMethod -Method Get -Uri "$releaseUrl/tags/v$Version" -Headers $auth
|
||||||
|
}
|
||||||
|
$releaseId = $release.id
|
||||||
|
Write-Step "release id=$releaseId"
|
||||||
|
|
||||||
|
# 4.3 逐个上传资产
|
||||||
|
$assets = @($exeOut, $msiOut, $nsisOut, $hkZip) | Where-Object { Test-Path $_ }
|
||||||
|
foreach ($file in $assets) {
|
||||||
|
$name = Split-Path $file -Leaf
|
||||||
|
Write-Step "上传 $name ..."
|
||||||
|
$assetUrl = "$releaseUrl/$releaseId/assets?name=$([uri]::EscapeDataString($name))"
|
||||||
|
$resp = Invoke-RestMethod -Method Post -Uri $assetUrl -Headers $auth -ContentType 'application/octet-stream' -InFile $file
|
||||||
|
Write-Host " -> $($resp.browser_download_url)" -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Step "发布完成:https://gitea.atie.fun/$RepoOwner/$RepoName/releases/tag/v$Version"
|
||||||
Generated
+1376
-24
File diff suppressed because it is too large
Load Diff
+26
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "thing"
|
name = "thing"
|
||||||
version = "0.1.0"
|
version = "26.8.4"
|
||||||
description = "A Tauri App"
|
description = "A Tauri App"
|
||||||
authors = ["you"]
|
authors = ["you"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -26,6 +26,7 @@ tauri-plugin-global-shortcut = "2"
|
|||||||
tauri-plugin-notification = "2"
|
tauri-plugin-notification = "2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
regex = "1"
|
||||||
serde_yaml = "0.9"
|
serde_yaml = "0.9"
|
||||||
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
|
specta = { version = "=2.0.0-rc.25", features = ["derive", "function", "serde_json"] }
|
||||||
specta-typescript = "0.0.12"
|
specta-typescript = "0.0.12"
|
||||||
@@ -44,6 +45,8 @@ base64 = "0.22"
|
|||||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||||
walkdir = "2"
|
walkdir = "2"
|
||||||
notify = { version = "6", features = [] }
|
notify = { version = "6", features = [] }
|
||||||
|
librqbit = "9"
|
||||||
|
bytes = "1"
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
winreg = "0.52"
|
winreg = "0.52"
|
||||||
@@ -56,6 +59,7 @@ windows-sys = { version = "0.52", features = [
|
|||||||
"Win32_System_Ole",
|
"Win32_System_Ole",
|
||||||
"Win32_System_Memory",
|
"Win32_System_Memory",
|
||||||
"Win32_System_DataExchange",
|
"Win32_System_DataExchange",
|
||||||
|
"Win32_System_SystemInformation",
|
||||||
"Win32_UI_WindowsAndMessaging",
|
"Win32_UI_WindowsAndMessaging",
|
||||||
"Win32_UI_Shell",
|
"Win32_UI_Shell",
|
||||||
"Win32_UI_HiDpi",
|
"Win32_UI_HiDpi",
|
||||||
@@ -65,7 +69,28 @@ windows-sys = { version = "0.52", features = [
|
|||||||
"Win32_Storage_Xps",
|
"Win32_Storage_Xps",
|
||||||
"Win32_Storage_FileSystem",
|
"Win32_Storage_FileSystem",
|
||||||
] }
|
] }
|
||||||
|
# Explorer 鬯ョ・ッ繝サ・キ鬮ォ・ィ繝サ・ャ郢晢スサ繝サ・ヲ鬯ョ・ョ郢晢スサ繝サ・ス繝サ・コ髣費スィ郢晢スサ・つ郢晢スサ繝サ・カ驛「譎「・ス・サ郢晢スサ繝サ・ョ鬯ョ・ッ雋翫・譚溽ケ晢スサ繝サ・「鬯ョ・ョ繝サ・」郢晢スサ繝サ・ス郢晢スサ繝サ・」郢晢スサ邵コ・、・つ鬯ョ・ョ髮懶ス」繝サ・ス繝サ・ャ鬮ッ・キ髣鯉スィ繝サ・ス繝サ・キ驛「譎「・ス・サ郢晢スサ繝サ・シ鬩幢ス「隴趣ス「繝サ・ス繝サ・サShellWindows COM鬩幢ス「隴趣ス「繝サ・ス繝サ・サ鬮」雋サ・ス・ィ髯樊サゑスス・イ郢晢スサ繝サ・ス郢晢スサ繝サ・シ鬮ッ讖ク・ス・「郢晢スサ繝サ・サ驛「譎「・ス・サ郢晢スサ繝サ・サ鬩幢ス「隴趣ス「繝サ・ス繝サ・サ驛「譎「・ス・サ郢晢スサ繝サ・シ鬮ッ・キ髢ァ・エ繝サ・コ陋滂ス・郢晢スサ鬯ッ・ィ繝サ・セ髯具スケ郢晢スサ繝サ・ス繝サ・ス郢晢スサ繝サ・ィ鬯ョ・ッ陷茨スキ繝サ・ス繝サ・サ驛「譎「・ス・サ郢晢スサ繝サ・ー鬯ッ・ィ繝サ・セ郢晢スサ繝サ・ァ鬩幢ス「隴趣ス「繝サ・ス繝サ・サfeature鬩幢ス「隴趣ス「繝サ・ス繝サ・サ鬮ォ・エ繝サ・エ郢晢スサ繝サ・ァ鬯ョ・「繝サ・ー髴托スケ陞「・シ繝サ・エ髴域鱒繝サ郢晢スサ繝サ・カ鬯ッ・ゥ陝カ蟷「・ス・ク陝カ蜷カ繝サ驛「譎「・ス・サ郢晢スサ繝サ・ッ鬮ッ・キ繝サ・ソ郢晢スサ繝サ・ー驛「譎「・ス・サ郢晢スサ繝サ・ス鬯ッ・ェ繝サ・ー髯キ闌ィ・ス・キ郢晢スサ繝サ・ス郢晢スサ繝サ・ァ驛「譎「・ス・サ郢晢スサ繝サ・ッ
|
||||||
|
windows = { version = "0.52", features = [
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_System_Com",
|
||||||
|
"Win32_System_Ole",
|
||||||
|
"Win32_System_Variant",
|
||||||
|
"Win32_UI_Shell",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
] }
|
||||||
|
|
||||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||||
tauri-plugin-autostart = "2"
|
tauri-plugin-autostart = "2"
|
||||||
|
|
||||||
|
# ===== 驛帛・・ッ蜿ー・シ莨懷密 =====
|
||||||
|
# dev 隴ォ繝サ・サ・コ陷キ・ッ騾包スィ陟・ィ」纃シ驛帛・・ッ繝サ+ 髯ヲ謔滓差驛、・ァ髫ケ繝サ・ッ蛹・スシ蝓溽スイ鬨セ貊捺た陜ィ・ー髴托スュ闔会ス」繝サ莨夲スシ蠕。・サ繝サ・ス・ア陷ゥ繝サ`tauri dev`
|
||||||
|
|
||||||
|
[profile.dev]
|
||||||
|
incremental = true
|
||||||
|
debug = "line-tables-only"
|
||||||
|
|
||||||
|
# release 髫エ・ォ郢晢スサ繝サ・サ繝サ・コ鬨セ蜴・スス・ヲ鬮エ繝サ・ス・ォ郢晢スサ陞「・シ隰碑崟蝨キ繝サ・ヲ髯キ・ソ繝サ・キ + LTO郢晢スサ隰疲コ倩ゥ宣劑繝サ・ク讖ク・ス・ョ髣・スス繝サ・」郢晢スサ隴ッ竏ャ謚・ェー蜈キ・ス・ァ繝サ・ッ
|
||||||
|
[profile.release]
|
||||||
|
strip = true
|
||||||
|
lto = true
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "clipboard-preview",
|
||||||
|
"description": "Capability for clipboard independent preview window",
|
||||||
|
"windows": ["clipboard-preview"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-hide",
|
||||||
|
"core:window:allow-show",
|
||||||
|
"core:window:allow-set-focus",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:window:allow-set-theme",
|
||||||
|
"core:window:allow-set-effects",
|
||||||
|
"core:window:allow-set-background-color",
|
||||||
|
"core:event:allow-listen",
|
||||||
|
"core:event:allow-emit",
|
||||||
|
"snap-layout:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
|
"identifier": "download-window",
|
||||||
|
"description": "Capability for the per-download one-time window",
|
||||||
|
"windows": ["download-window-*"],
|
||||||
|
"permissions": [
|
||||||
|
"core:default",
|
||||||
|
"core:window:allow-hide",
|
||||||
|
"core:window:allow-show",
|
||||||
|
"core:window:allow-set-focus",
|
||||||
|
"core:window:allow-minimize",
|
||||||
|
"core:window:allow-unminimize",
|
||||||
|
"core:window:allow-set-title",
|
||||||
|
"core:window:allow-set-size",
|
||||||
|
"core:window:allow-start-dragging",
|
||||||
|
"core:window:allow-set-always-on-top",
|
||||||
|
"core:window:allow-set-skip-taskbar",
|
||||||
|
"core:window:allow-set-theme",
|
||||||
|
"core:window:allow-set-effects",
|
||||||
|
"core:window:allow-set-background-color",
|
||||||
|
"core:window:allow-close",
|
||||||
|
"core:event:allow-emit",
|
||||||
|
"core:event:allow-listen",
|
||||||
|
"snap-layout:default"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"$schema": "../gen/schemas/desktop-schema.json",
|
"$schema": "../gen/schemas/desktop-schema.json",
|
||||||
"identifier": "screenshot",
|
"identifier": "screenshot",
|
||||||
"description": "Capability for screenshot overlay and editor windows",
|
"description": "Capability for screenshot overlay, editor and pin windows",
|
||||||
"windows": ["screenshot-overlay*", "screenshot-editor-*"],
|
"windows": ["screenshot-overlay*", "screenshot-editor-*", "screenshot-pin"],
|
||||||
"permissions": [
|
"permissions": [
|
||||||
"core:default",
|
"core:default",
|
||||||
"core:window:allow-hide",
|
"core:window:allow-hide",
|
||||||
@@ -11,6 +11,7 @@
|
|||||||
"core:window:allow-start-dragging",
|
"core:window:allow-start-dragging",
|
||||||
"core:window:allow-set-position",
|
"core:window:allow-set-position",
|
||||||
"core:window:allow-set-size",
|
"core:window:allow-set-size",
|
||||||
|
"core:window:allow-set-resizable",
|
||||||
"core:window:allow-set-always-on-top",
|
"core:window:allow-set-always-on-top",
|
||||||
"core:window:allow-set-skip-taskbar",
|
"core:window:allow-set-skip-taskbar",
|
||||||
"core:window:allow-set-decorations",
|
"core:window:allow-set-decorations",
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ const DEFAULT_CONFIG = {
|
|||||||
interceptDownload: true,
|
interceptDownload: true,
|
||||||
minSize: 0,
|
minSize: 0,
|
||||||
excludeDomains: [],
|
excludeDomains: [],
|
||||||
showNotifications: true,
|
|
||||||
// 嗅探开关
|
// 嗅探开关
|
||||||
sniffEnabled: true,
|
sniffEnabled: true,
|
||||||
// 嗅探的资源类型:只保留视频/音频/图片/压缩包/种子/安装包
|
// 嗅探的资源类型:只保留视频/音频/图片/压缩包/种子/安装包
|
||||||
@@ -359,6 +358,11 @@ async function addDownload(url, filename, referer, cookies, headers) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ===== 下载拦截 =====
|
// ===== 下载拦截 =====
|
||||||
|
// 处理中的 URL(防止同一 URL 并发/重入,也避免与引擎去重检查竞态)
|
||||||
|
const processingUrls = new Set()
|
||||||
|
// 我们自己用 chrome.downloads.download 回退创建的下载 URL(短时间内跳过,防止再次被拦截形成死循环)
|
||||||
|
const fallbackUrls = new Map() // url -> 过期时间戳
|
||||||
|
|
||||||
async function shouldIntercept(downloadItem) {
|
async function shouldIntercept(downloadItem) {
|
||||||
const config = await getConfig()
|
const config = await getConfig()
|
||||||
if (!config.interceptDownload) return false
|
if (!config.interceptDownload) return false
|
||||||
@@ -374,42 +378,94 @@ async function shouldIntercept(downloadItem) {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为"历史下载"(安装插件之前就已存在、随后被浏览器恢复的旧下载)
|
||||||
|
* 这类下载一律不接管,交给浏览器原生处理,实现"只接管以后的下载,历史都不管"
|
||||||
|
*/
|
||||||
|
async function isHistoricalDownload(item) {
|
||||||
|
// 1) canResume=true 表示已存在有效的部分文件,说明浏览器在恢复旧下载
|
||||||
|
if (item.canResume) return true
|
||||||
|
// 2) 开始时间早于插件首次安装时间(浏览器重启后恢复的旧下载会保留原来的开始时间)
|
||||||
|
try {
|
||||||
|
const start = item.startTime ? new Date(item.startTime).getTime() : 0
|
||||||
|
if (start > 0) {
|
||||||
|
const stored = await chrome.storage.local.get('installTime')
|
||||||
|
const installTime = stored.installTime || 0
|
||||||
|
if (installTime > 0 && start < installTime) return true
|
||||||
|
}
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询引擎是否已有同 URL 的非终态任务(活跃/排队/暂停)
|
||||||
|
* 用于防止同一下载被重复转发、重复下载
|
||||||
|
*/
|
||||||
|
async function hasExistingTask(url) {
|
||||||
|
try {
|
||||||
|
const tasks = await apiRequest('/api/downloads')
|
||||||
|
return tasks.some(t => {
|
||||||
|
const s = t.status
|
||||||
|
if (s === 'complete' || s === 'error') return false
|
||||||
|
return t.url === url
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleDownloadCreated(downloadItem) {
|
async function handleDownloadCreated(downloadItem) {
|
||||||
|
const url = downloadItem.finalUrl || downloadItem.url
|
||||||
|
|
||||||
|
// 回退下载:我们自己用 chrome.downloads.download 创建的,直接跳过,避免无限循环
|
||||||
|
const fbExp = fallbackUrls.get(url)
|
||||||
|
if (fbExp && Date.now() < fbExp) {
|
||||||
|
fallbackUrls.delete(url)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 历史下载(安装前的旧下载被浏览器恢复)一律不接管
|
||||||
|
if (await isHistoricalDownload(downloadItem)) return
|
||||||
|
|
||||||
if (!await shouldIntercept(downloadItem)) return
|
if (!await shouldIntercept(downloadItem)) return
|
||||||
|
|
||||||
|
// 同一 URL 已在处理中,跳过(防并发/防重复转发)
|
||||||
|
if (processingUrls.has(url)) return
|
||||||
|
|
||||||
|
// 引擎不可达时不接管(保留浏览器原生下载),避免取消后下载无处可去
|
||||||
|
let connected = false
|
||||||
|
try { connected = await testConnection() } catch { connected = false }
|
||||||
|
if (!connected) return
|
||||||
|
|
||||||
|
// 引擎已有同 URL 的非终态任务,不重复转发
|
||||||
|
if (await hasExistingTask(url)) return
|
||||||
|
|
||||||
|
processingUrls.add(url)
|
||||||
|
try {
|
||||||
try {
|
try {
|
||||||
await chrome.downloads.cancel(downloadItem.id)
|
await chrome.downloads.cancel(downloadItem.id)
|
||||||
await chrome.downloads.erase({ id: downloadItem.id })
|
await chrome.downloads.erase({ id: downloadItem.id })
|
||||||
} catch { /* ignore */ }
|
} catch { /* ignore */ }
|
||||||
|
|
||||||
const url = downloadItem.finalUrl || downloadItem.url
|
|
||||||
const filename = downloadItem.filename || ''
|
const filename = downloadItem.filename || ''
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const id = await addDownload(url, filename, downloadItem.referrer, '')
|
await addDownload(url, filename, downloadItem.referrer, '')
|
||||||
await notify('已添加到 Thing', `${filename || url}`)
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await notify('Thing 添加失败', `${filename || url}\n${e.message}`)
|
// 添加失败:回退为浏览器自带下载,并标记该 URL 短时间内跳过,防止再次被拦截形成死循环
|
||||||
|
fallbackUrls.set(url, Date.now() + 3000)
|
||||||
try { await chrome.downloads.download({ url }) } catch { /* ignore */ }
|
try { await chrome.downloads.download({ url }) } catch { /* ignore */ }
|
||||||
}
|
}
|
||||||
|
} finally {
|
||||||
|
processingUrls.delete(url)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 通知 =====
|
// ===== 右键菜单 & 安装标记 =====
|
||||||
async function notify(title, message) {
|
chrome.runtime.onInstalled.addListener(async (details) => {
|
||||||
const config = await getConfig()
|
// 记录首次安装时间:用于区分"安装前的历史下载"(被浏览器恢复的旧下载)与"安装后的新下载"
|
||||||
if (!config.showNotifications) return
|
if (details.reason === 'install') {
|
||||||
try {
|
await chrome.storage.local.set({ installTime: Date.now() })
|
||||||
await chrome.notifications.create({
|
|
||||||
type: 'basic',
|
|
||||||
iconUrl: 'icons/icon-128.png',
|
|
||||||
title,
|
|
||||||
message
|
|
||||||
})
|
|
||||||
} catch { /* ignore */ }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 右键菜单 =====
|
|
||||||
chrome.runtime.onInstalled.addListener(() => {
|
|
||||||
chrome.contextMenus.create({
|
chrome.contextMenus.create({
|
||||||
id: 'thing-download-link',
|
id: 'thing-download-link',
|
||||||
title: '使用 Thing 下载此链接',
|
title: '使用 Thing 下载此链接',
|
||||||
@@ -428,10 +484,7 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
|||||||
const filename = url.split('/').pop()?.split('?')[0] || ''
|
const filename = url.split('/').pop()?.split('?')[0] || ''
|
||||||
try {
|
try {
|
||||||
await addDownload(url, filename, info.pageUrl, '')
|
await addDownload(url, filename, info.pageUrl, '')
|
||||||
await notify('已添加到 Thing', `${filename || url}`)
|
} catch (e) { /* 忽略:添加失败时不打扰用户 */ }
|
||||||
} catch (e) {
|
|
||||||
await notify('Thing 添加失败', `${e.message}`)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"manifest_version": 3,
|
"manifest_version": 3,
|
||||||
"name": "Thing Extension",
|
"name": "Thing Extension",
|
||||||
"version": "0.2.0",
|
"version": "0.30",
|
||||||
"description": "发送浏览器下载到 Thing 下载引擎,嗅探网页资源。",
|
"description": "发送浏览器下载到 Thing 下载引擎,嗅探网页资源。",
|
||||||
"icons": {
|
"icons": {
|
||||||
"16": "icons/icon-16.png",
|
"16": "icons/icon-16.png",
|
||||||
@@ -11,9 +11,7 @@
|
|||||||
"permissions": [
|
"permissions": [
|
||||||
"downloads",
|
"downloads",
|
||||||
"storage",
|
"storage",
|
||||||
"notifications",
|
|
||||||
"webRequest",
|
"webRequest",
|
||||||
"webNavigation",
|
|
||||||
"contextMenus",
|
"contextMenus",
|
||||||
"tabs",
|
"tabs",
|
||||||
"scripting"
|
"scripting"
|
||||||
|
|||||||
@@ -87,11 +87,6 @@
|
|||||||
<span>启用资源嗅探</span>
|
<span>启用资源嗅探</span>
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<label class="checkbox">
|
|
||||||
<input type="checkbox" id="showNotifications" />
|
|
||||||
<span>显示桌面通知</span>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>下载最小文件大小(字节,0=全部)</span>
|
<span>下载最小文件大小(字节,0=全部)</span>
|
||||||
<input type="number" id="minSize" min="0" placeholder="0" />
|
<input type="number" id="minSize" min="0" placeholder="0" />
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ const DEFAULT_CONFIG = {
|
|||||||
interceptDownload: true,
|
interceptDownload: true,
|
||||||
minSize: 0,
|
minSize: 0,
|
||||||
excludeDomains: [],
|
excludeDomains: [],
|
||||||
showNotifications: true,
|
|
||||||
sniffEnabled: true,
|
sniffEnabled: true,
|
||||||
sniffTypes: ['video', 'audio', 'image', 'archive', 'torrent', 'installer'],
|
sniffTypes: ['video', 'audio', 'image', 'archive', 'torrent', 'installer'],
|
||||||
sniffMaxItems: 200,
|
sniffMaxItems: 200,
|
||||||
@@ -57,7 +56,6 @@ function fillForm(config) {
|
|||||||
$('secret').value = config.secret || ''
|
$('secret').value = config.secret || ''
|
||||||
$('interceptDownload').checked = config.interceptDownload !== false
|
$('interceptDownload').checked = config.interceptDownload !== false
|
||||||
$('sniffEnabled').checked = config.sniffEnabled !== false
|
$('sniffEnabled').checked = config.sniffEnabled !== false
|
||||||
$('showNotifications').checked = config.showNotifications !== false
|
|
||||||
$('minSize').value = config.minSize || 0
|
$('minSize').value = config.minSize || 0
|
||||||
$('sniffMinSize').value = config.sniffMinSize ?? DEFAULT_CONFIG.sniffMinSize
|
$('sniffMinSize').value = config.sniffMinSize ?? DEFAULT_CONFIG.sniffMinSize
|
||||||
$('excludeDomains').value = (config.excludeDomains || []).join(',')
|
$('excludeDomains').value = (config.excludeDomains || []).join(',')
|
||||||
@@ -69,7 +67,6 @@ function readForm() {
|
|||||||
secret: $('secret').value.trim(),
|
secret: $('secret').value.trim(),
|
||||||
interceptDownload: $('interceptDownload').checked,
|
interceptDownload: $('interceptDownload').checked,
|
||||||
sniffEnabled: $('sniffEnabled').checked,
|
sniffEnabled: $('sniffEnabled').checked,
|
||||||
showNotifications: $('showNotifications').checked,
|
|
||||||
minSize: parseInt($('minSize').value, 10) || 0,
|
minSize: parseInt($('minSize').value, 10) || 0,
|
||||||
sniffMinSize: parseInt($('sniffMinSize').value, 10) || 0,
|
sniffMinSize: parseInt($('sniffMinSize').value, 10) || 0,
|
||||||
excludeDomains: $('excludeDomains').value
|
excludeDomains: $('excludeDomains').value
|
||||||
|
|||||||
Binary file not shown.
@@ -7,7 +7,7 @@ use specta::Type;
|
|||||||
use tauri::{AppHandle, State};
|
use tauri::{AppHandle, State};
|
||||||
|
|
||||||
use super::manager::{ClipboardManager, ClipboardSettings};
|
use super::manager::{ClipboardManager, ClipboardSettings};
|
||||||
use super::reader::dib_to_png;
|
use super::reader::{dib_to_png, dib_to_thumbnail};
|
||||||
use super::storage::{ClipboardItem, ClipboardItemDetail};
|
use super::storage::{ClipboardItem, ClipboardItemDetail};
|
||||||
|
|
||||||
#[derive(Serialize, Type)]
|
#[derive(Serialize, Type)]
|
||||||
@@ -95,6 +95,21 @@ pub async fn clipboard_get_item(
|
|||||||
.map_err(|e| format!("查询任务失败: {}", e))
|
.map_err(|e| format!("查询任务失败: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 获取图片缩略图 PNG base64(弹窗悬停预览用,避免加载全尺寸图片)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_get_thumb(
|
||||||
|
id: i64,
|
||||||
|
manager: State<'_, ClipboardManager>,
|
||||||
|
) -> Result<Option<String>, String> {
|
||||||
|
let storage = manager.storage().clone();
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
storage.get_thumb(id, |dib| dib_to_thumbnail(dib, 256))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("查询任务失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn clipboard_set_pinned(
|
pub async fn clipboard_set_pinned(
|
||||||
@@ -162,25 +177,44 @@ pub async fn clipboard_save_settings(
|
|||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
manager: State<'_, ClipboardManager>,
|
manager: State<'_, ClipboardManager>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let prev_enabled = manager.get_settings().enabled;
|
let prev = manager.get_settings();
|
||||||
let prev_shortcut = manager.get_settings().shortcut.clone();
|
let prev_enabled = prev.enabled;
|
||||||
|
let prev_shortcut = prev.shortcut.clone();
|
||||||
|
|
||||||
|
// 快捷键变化且新值非空:先注册(原子化 + 冲突检测),成功后才保存设置。
|
||||||
|
// 注册失败时恢复旧快捷键并中止保存,避免设置被写入无法生效的组合键、旧键丢失。
|
||||||
|
if settings.shortcut != prev_shortcut && !settings.shortcut.trim().is_empty() {
|
||||||
|
if let Err(e) = crate::shortcut::register_shortcut(&app, "剪贴板", &settings.shortcut, |a| {
|
||||||
|
super::popup::show_popup(a)
|
||||||
|
}) {
|
||||||
|
// register_shortcut 内部已注销旧快捷键,失败时需重新注册旧键以恢复
|
||||||
|
if !prev_shortcut.trim().is_empty() {
|
||||||
|
let _ = crate::shortcut::register_shortcut(&app, "剪贴板", &prev_shortcut, |a| {
|
||||||
|
super::popup::show_popup(a)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
// 新快捷键非空时确保弹窗/预览窗口已预创建
|
||||||
|
super::popup::ensure_popup_window(&app);
|
||||||
|
super::popup::ensure_preview_window(&app);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存设置
|
||||||
manager.save_settings(settings.clone());
|
manager.save_settings(settings.clone());
|
||||||
|
|
||||||
// 监听开关变化时联动启停
|
// 监听开关变化时联动启停
|
||||||
if settings.enabled && !prev_enabled {
|
if settings.enabled && !prev_enabled {
|
||||||
manager.start(&app);
|
manager.start(&app);
|
||||||
} else if !settings.enabled && prev_enabled {
|
} else if !settings.enabled && prev_enabled {
|
||||||
manager.stop();
|
manager.stop();
|
||||||
}
|
}
|
||||||
// 快捷键变化时重新注册(共享工具模块,原子化 + 冲突检测)
|
|
||||||
if settings.shortcut != prev_shortcut {
|
// 快捷键改为空字符串(禁用):注销旧快捷键
|
||||||
crate::shortcut::register_shortcut(&app, "剪贴板", &settings.shortcut, |a| {
|
if settings.shortcut.trim().is_empty() && settings.shortcut != prev_shortcut {
|
||||||
super::popup::show_popup(a)
|
crate::shortcut::unregister_shortcut(&app, "剪贴板");
|
||||||
})?;
|
|
||||||
// 新快捷键非空时确保弹窗窗口已预创建
|
|
||||||
if !settings.shortcut.trim().is_empty() {
|
|
||||||
super::popup::ensure_popup_window(&app);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,3 +296,52 @@ pub async fn clipboard_paste_to_target(app: AppHandle) -> Result<(), String> {
|
|||||||
super::popup::paste_to_target(&app);
|
super::popup::paste_to_target(&app);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 在弹窗旁显示独立预览窗口(悬停/键盘选中时调用)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_show_preview(app: AppHandle, id: i64) -> Result<(), String> {
|
||||||
|
super::popup::show_preview(&app, id);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 隐藏独立预览窗口
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_hide_preview(app: AppHandle) -> Result<(), String> {
|
||||||
|
super::popup::hide_preview(&app);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按内容自适应调整预览窗大小(逻辑像素)。前端加载内容(文本测高、图片按宽高比)后调用,
|
||||||
|
/// 窗口贴合内容消除留白;后端按弹窗所在屏工作区钳制并重新对齐弹窗。
|
||||||
|
/// allow_flip:初始落位为 true(优先侧放不下可换侧);放大/还原为 false(保持原侧)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_resize_preview(
|
||||||
|
app: AppHandle,
|
||||||
|
width: f64,
|
||||||
|
height: f64,
|
||||||
|
allow_flip: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
super::popup::resize_preview(&app, width, height, allow_flip);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 显示已就绪的预览窗口。前端完成内容加载与 resize 后调用,窗口以最终尺寸出现,
|
||||||
|
/// 消除"先以上次尺寸(可能是放大态大窗)显示再缩回"的闪烁。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_reveal_preview(app: AppHandle) -> Result<(), String> {
|
||||||
|
super::popup::reveal_preview(&app);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 预览窗交互锁定:前端预览窗收到 mousedown(放大/缩小、复制、选择文本)时调用。
|
||||||
|
/// 此后弹窗+预览不因失焦/鼠标离开而关闭,仅当点击外部或弹窗重新聚焦时退出锁定。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn clipboard_preview_interacted(app: AppHandle) -> Result<(), String> {
|
||||||
|
super::popup::preview_interacted(&app);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use specta::Type;
|
|||||||
use super::monitor::start_monitor;
|
use super::monitor::start_monitor;
|
||||||
use super::reader::{write_dib, write_files, write_text};
|
use super::reader::{write_dib, write_files, write_text};
|
||||||
use super::storage::Storage;
|
use super::storage::Storage;
|
||||||
|
use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
|
||||||
|
|
||||||
/// 剪贴板设置(持久化到 clipboard/settings.json)
|
/// 剪贴板设置(持久化到 clipboard/settings.json)
|
||||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||||
@@ -55,7 +56,8 @@ impl Default for ClipboardSettings {
|
|||||||
pub struct ClipboardManager {
|
pub struct ClipboardManager {
|
||||||
storage: Arc<Storage>,
|
storage: Arc<Storage>,
|
||||||
settings: Arc<Mutex<ClipboardSettings>>,
|
settings: Arc<Mutex<ClipboardSettings>>,
|
||||||
suppress: Arc<AtomicBool>,
|
/// 本应用 copy_back 写入后的剪贴板序列号,用于跳过自身写入产生的记录
|
||||||
|
suppress: Arc<Mutex<Option<u32>>>,
|
||||||
monitor_stop: Arc<AtomicBool>,
|
monitor_stop: Arc<AtomicBool>,
|
||||||
monitor_handle: Mutex<Option<JoinHandle<()>>>,
|
monitor_handle: Mutex<Option<JoinHandle<()>>>,
|
||||||
settings_path: PathBuf,
|
settings_path: PathBuf,
|
||||||
@@ -73,7 +75,7 @@ impl ClipboardManager {
|
|||||||
};
|
};
|
||||||
let settings_path = clip_dir.join("settings.json");
|
let settings_path = clip_dir.join("settings.json");
|
||||||
let settings = Arc::new(Mutex::new(load_settings(&settings_path)));
|
let settings = Arc::new(Mutex::new(load_settings(&settings_path)));
|
||||||
let suppress = Arc::new(AtomicBool::new(false));
|
let suppress = Arc::new(Mutex::new(None));
|
||||||
let monitor_stop = Arc::new(AtomicBool::new(true));
|
let monitor_stop = Arc::new(AtomicBool::new(true));
|
||||||
Self {
|
Self {
|
||||||
storage,
|
storage,
|
||||||
@@ -139,13 +141,12 @@ impl ClipboardManager {
|
|||||||
save_settings(&self.settings_path, &s);
|
save_settings(&self.settings_path, &s);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 将某条历史写回剪贴板。写回前置 suppress 标志以避免再次记录。
|
/// 将某条历史写回剪贴板。写回成功后记录剪贴板序列号,供监听跳过自身写入。
|
||||||
pub fn copy_back(&self, id: i64) -> Result<(), String> {
|
pub fn copy_back(&self, id: i64) -> Result<(), String> {
|
||||||
let (kind, content, blob) = self
|
let (kind, content, blob) = self
|
||||||
.storage
|
.storage
|
||||||
.get_raw_for_copy(id)
|
.get_raw_for_copy(id)
|
||||||
.ok_or_else(|| "条目不存在".to_string())?;
|
.ok_or_else(|| "条目不存在".to_string())?;
|
||||||
self.suppress.store(true, Ordering::SeqCst);
|
|
||||||
let ok = match kind.as_str() {
|
let ok = match kind.as_str() {
|
||||||
"text" => content.as_deref().map(write_text).unwrap_or(false),
|
"text" => content.as_deref().map(write_text).unwrap_or(false),
|
||||||
"image" => blob.as_deref().map(write_dib).unwrap_or(false),
|
"image" => blob.as_deref().map(write_dib).unwrap_or(false),
|
||||||
@@ -163,10 +164,12 @@ impl ClipboardManager {
|
|||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
if ok {
|
if ok {
|
||||||
|
// 绑定到写入完成后的剪贴板序列号:仅跳过本次写入产生的记录,
|
||||||
|
// 用户后续复制(序列号不同)不会被误吞。
|
||||||
|
let seq = unsafe { GetClipboardSequenceNumber() };
|
||||||
|
*self.suppress.lock().unwrap_or_else(|e| e.into_inner()) = Some(seq);
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
// 写入失败也清除 suppress,避免误吞下次复制
|
|
||||||
self.suppress.store(false, Ordering::SeqCst);
|
|
||||||
Err("写回剪贴板失败".into())
|
Err("写回剪贴板失败".into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,9 +9,12 @@ pub mod storage;
|
|||||||
|
|
||||||
pub use commands::{
|
pub use commands::{
|
||||||
clipboard_clear, clipboard_copy_back, clipboard_count, clipboard_delete, clipboard_get_history,
|
clipboard_clear, clipboard_copy_back, clipboard_count, clipboard_delete, clipboard_get_history,
|
||||||
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_hide_popup,
|
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_get_thumb,
|
||||||
clipboard_paste_to_target, clipboard_register_shortcut, clipboard_save_settings, clipboard_search,
|
clipboard_hide_popup, clipboard_hide_preview, clipboard_paste_to_target,
|
||||||
clipboard_set_pinned, clipboard_show_popup, clipboard_show_window, clipboard_start,
|
clipboard_preview_interacted, clipboard_register_shortcut,
|
||||||
|
clipboard_reveal_preview,
|
||||||
|
clipboard_save_settings, clipboard_search, clipboard_set_pinned, clipboard_resize_preview,
|
||||||
|
clipboard_show_popup, clipboard_show_preview, clipboard_show_window, clipboard_start,
|
||||||
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
||||||
};
|
};
|
||||||
pub use manager::ClipboardManager;
|
pub use manager::ClipboardManager;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! 剪贴板监听线程:基于 GetClipboardSequenceNumber 轮询
|
//! 剪贴板监听线程:基于 GetClipboardSequenceNumber 轮询
|
||||||
//!
|
//!
|
||||||
//! 选用轮询而非 AddClipboardFormatListener 消息窗口:实现更简单、无需消息循环,
|
//! 选用轮询而非 AddClipboardFormatListener 消息窗口:实现更简单、无需消息循环,
|
||||||
//! 800ms 间隔对剪贴板场景延迟可接受,且 GetClipboardSequenceNumber 不需要 OpenClipboard,开销极小。
|
//! 250ms 间隔兼顾响应速度与开销,且 GetClipboardSequenceNumber 不需要 OpenClipboard,开销极小。
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
@@ -15,18 +15,19 @@ use super::storage::{NewItem, Storage};
|
|||||||
use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
|
use windows_sys::Win32::System::DataExchange::GetClipboardSequenceNumber;
|
||||||
|
|
||||||
/// 启动监听线程,返回 JoinHandle。
|
/// 启动监听线程,返回 JoinHandle。
|
||||||
|
/// `suppress` 记录本应用 copy_back 写入后的剪贴板序列号,用于跳过自身写入产生的记录。
|
||||||
pub fn start_monitor(
|
pub fn start_monitor(
|
||||||
storage: Arc<Storage>,
|
storage: Arc<Storage>,
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
settings: Arc<Mutex<super::manager::ClipboardSettings>>,
|
settings: Arc<Mutex<super::manager::ClipboardSettings>>,
|
||||||
suppress: Arc<AtomicBool>,
|
suppress: Arc<Mutex<Option<u32>>>,
|
||||||
stop: Arc<AtomicBool>,
|
stop: Arc<AtomicBool>,
|
||||||
) -> thread::JoinHandle<()> {
|
) -> thread::JoinHandle<()> {
|
||||||
thread::spawn(move || loop {
|
thread::spawn(move || loop {
|
||||||
if stop.load(Ordering::SeqCst) {
|
if stop.load(Ordering::SeqCst) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
thread::sleep(Duration::from_millis(800));
|
thread::sleep(Duration::from_millis(250));
|
||||||
if stop.load(Ordering::SeqCst) {
|
if stop.load(Ordering::SeqCst) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -40,11 +41,14 @@ pub fn start_monitor(
|
|||||||
if seq == last {
|
if seq == last {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// 序列号变化,处理一次
|
// 序列号变化:仅当变化来自本应用 copy_back(序列号精确匹配)时跳过,
|
||||||
if suppress.swap(false, Ordering::SeqCst) {
|
// 避免旧布尔标志在用户后续复制时被误吞。
|
||||||
// 由本应用 copy_back 触发,跳过记录
|
if let Ok(mut s) = suppress.lock() {
|
||||||
|
if *s == Some(seq) {
|
||||||
|
*s = None;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
let (rec_text, rec_image, rec_files, max_items, max_image_kb, dedup) = {
|
let (rec_text, rec_image, rec_files, max_items, max_image_kb, dedup) = {
|
||||||
let s = settings.lock().unwrap_or_else(|e| e.into_inner());
|
let s = settings.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
(
|
(
|
||||||
@@ -99,6 +103,7 @@ fn build_text_item(t: &str) -> NewItem {
|
|||||||
kind: "text".into(),
|
kind: "text".into(),
|
||||||
content: Some(t.to_string()),
|
content: Some(t.to_string()),
|
||||||
blob: None,
|
blob: None,
|
||||||
|
thumb: None,
|
||||||
preview: make_preview(t, 200),
|
preview: make_preview(t, 200),
|
||||||
size: t.len() as i64,
|
size: t.len() as i64,
|
||||||
hash: hash_str(t),
|
hash: hash_str(t),
|
||||||
@@ -110,6 +115,7 @@ fn build_image_item(dib: &[u8], w: u32, h: u32) -> NewItem {
|
|||||||
kind: "image".into(),
|
kind: "image".into(),
|
||||||
content: None,
|
content: None,
|
||||||
blob: Some(dib.to_vec()),
|
blob: Some(dib.to_vec()),
|
||||||
|
thumb: super::reader::dib_to_thumbnail(dib, 256),
|
||||||
preview: format!("图片 {}×{}", w, h),
|
preview: format!("图片 {}×{}", w, h),
|
||||||
size: dib.len() as i64,
|
size: dib.len() as i64,
|
||||||
hash: hash_bytes(dib),
|
hash: hash_bytes(dib),
|
||||||
@@ -132,6 +138,7 @@ fn build_files_item(files: &[String]) -> NewItem {
|
|||||||
kind: "files".into(),
|
kind: "files".into(),
|
||||||
content: Some(content),
|
content: Some(content),
|
||||||
blob: None,
|
blob: None,
|
||||||
|
thumb: None,
|
||||||
preview,
|
preview,
|
||||||
size: files.iter().map(|f| f.len()).sum::<usize>() as i64,
|
size: files.iter().map(|f| f.len()).sum::<usize>() as i64,
|
||||||
hash,
|
hash,
|
||||||
|
|||||||
@@ -10,12 +10,27 @@
|
|||||||
|
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, Emitter};
|
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder, Emitter};
|
||||||
use tauri::window::{Effect, EffectsBuilder};
|
use tauri::window::{Effect, EffectsBuilder};
|
||||||
|
|
||||||
/// 弹窗窗口标签
|
/// 弹窗窗口标签
|
||||||
pub const POPUP_LABEL: &str = "clipboard-popup";
|
pub const POPUP_LABEL: &str = "clipboard-popup";
|
||||||
|
|
||||||
|
/// 预览窗口标签(悬停/键盘选中条目时在弹窗旁显示内容)
|
||||||
|
pub const PREVIEW_LABEL: &str = "clipboard-preview";
|
||||||
|
|
||||||
|
/// 预览窗口初始逻辑尺寸(后续由前端按内容自适应调整,见 resize_preview)
|
||||||
|
const PREVIEW_W: f64 = 340.0;
|
||||||
|
const PREVIEW_H: f64 = 300.0;
|
||||||
|
|
||||||
|
/// 预览窗口最小逻辑尺寸(防止内容过小时窗口退化)
|
||||||
|
const PREVIEW_MIN_W: f64 = 240.0;
|
||||||
|
const PREVIEW_MIN_H: f64 = 160.0;
|
||||||
|
|
||||||
|
/// 弹窗与预览窗之间的可视间距(逻辑像素,左右对称)
|
||||||
|
const PREVIEW_GAP: f64 = 12.0;
|
||||||
|
|
||||||
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
||||||
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
||||||
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||||
@@ -24,6 +39,50 @@ static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
|||||||
/// 避免窗口重建后仍停留在屏幕外 (-10000, -10000)。
|
/// 避免窗口重建后仍停留在屏幕外 (-10000, -10000)。
|
||||||
static PENDING_POS: Mutex<Option<(f64, f64)>> = Mutex::new(None);
|
static PENDING_POS: Mutex<Option<(f64, f64)>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 弹窗当前是否可见(同步单一事实来源)。
|
||||||
|
/// show_preview 用它代替 popup.is_visible():后者在 hide 异步在途时可能返回过期 true,
|
||||||
|
/// 导致"弹窗已隐藏但残留的悬停/键盘请求重新弹出孤立预览窗"。该标志在隐藏路径
|
||||||
|
/// 同步置 false,任何在途请求都会直接拒绝。
|
||||||
|
static POPUP_VISIBLE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 预览窗当前是否可见(同步标志,与 POPUP_VISIBLE 同理:预览窗以原生
|
||||||
|
/// SW_SHOWNOACTIVATE 显示,Tauri 的 is_visible() 可能与其真实状态不同步,
|
||||||
|
/// 故用该标志代替 is_visible 判断预览交互状态)。
|
||||||
|
static PREVIEW_VISIBLE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 弹窗因预览交互(光标位于预览窗内)而推迟隐藏的标记:
|
||||||
|
/// 点击预览窗(选择/复制文本、放大图片)时,弹窗会收到 Focused(false),但用户正在
|
||||||
|
/// 预览窗内交互,此时不应隐藏弹窗。置该标记后保持弹窗显示,待用户离开预览窗
|
||||||
|
/// (hide_preview)时再连同弹窗一起隐藏,避免"点击预览即关闭弹窗"导致无法交互。
|
||||||
|
static POPUP_DEFER_HIDE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 失焦隐藏的宽限期:WebView2 透明窗口在 show 后激活期间焦点可能短暂弹跳
|
||||||
|
/// (与快速面板同因),导致 Focused(false) 紧跟在 show 之后触发并立即隐藏刚显示的弹窗。
|
||||||
|
const SHOW_GRACE: Duration = Duration::from_millis(500);
|
||||||
|
|
||||||
|
/// 最近一次 show 的时间,用于失焦宽限期判断。
|
||||||
|
static LAST_SHOWN: Mutex<Option<Instant>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 标记"已发起显示",并记录时间供失焦宽限期使用。
|
||||||
|
fn mark_shown() {
|
||||||
|
if let Ok(mut t) = LAST_SHOWN.lock() {
|
||||||
|
*t = Some(Instant::now());
|
||||||
|
}
|
||||||
|
POPUP_VISIBLE.store(true, Ordering::SeqCst);
|
||||||
|
// 重新显示弹窗时复位推迟隐藏标记(上一轮预览交互的遗留状态不应影响本轮)
|
||||||
|
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 判断距上次 show 是否仍在宽限期内(是则忽略失焦自动隐藏)。
|
||||||
|
fn within_show_grace() -> bool {
|
||||||
|
LAST_SHOWN
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| *t)
|
||||||
|
.map(|t| t.elapsed() < SHOW_GRACE)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
/// 创建弹窗窗口(隐藏状态)并注册失焦监听。
|
/// 创建弹窗窗口(隐藏状态)并注册失焦监听。
|
||||||
/// 位置默认在屏幕外,show_popup 时会重新定位。
|
/// 位置默认在屏幕外,show_popup 时会重新定位。
|
||||||
/// 预创建后首次按快捷键走"窗口已存在"分支直接 show,避免首次创建的时序问题。
|
/// 预创建后首次按快捷键走"窗口已存在"分支直接 show,避免首次创建的时序问题。
|
||||||
@@ -54,14 +113,42 @@ fn create_popup_window(app: &AppHandle) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 监听窗口失焦:自动隐藏
|
// 监听窗口失焦:自动隐藏(同时隐藏预览窗)
|
||||||
let app_handle = app.clone();
|
let app_handle = app.clone();
|
||||||
let win_handle = win.clone();
|
let win_handle = win.clone();
|
||||||
win.on_window_event(move |event| {
|
win.on_window_event(move |event| {
|
||||||
if let tauri::WindowEvent::Focused(false) = event {
|
match event {
|
||||||
|
tauri::WindowEvent::Focused(false) => {
|
||||||
|
// 失焦宽限期:show 后激活期间的焦点弹跳不隐藏弹窗,避免弹窗刚显示就被隐藏
|
||||||
|
if within_show_grace() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 交互锁定模式(点击过预览窗):弹窗与预览保持显示,仅由看护线程在
|
||||||
|
// "点击外部"时关闭;此处的失焦是点击预览窗(NoActivate)所致,不隐藏。
|
||||||
|
if POPUP_INTERACTED.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 鼠标当前位于预览窗或弹窗内(用户正在交互:选择/复制文本、放大图片、或
|
||||||
|
// 已移回弹窗准备继续浏览):弹窗失焦是点击预览窗或焦点反弹所致,不应隐藏弹窗。
|
||||||
|
// 置推迟标记保持弹窗显示,待用户离开整个区域(hide_preview / 再次失焦)再隐藏。
|
||||||
|
if is_cursor_in_preview(&app_handle) || is_cursor_in_popup(&app_handle) {
|
||||||
|
POPUP_DEFER_HIDE.store(true, Ordering::SeqCst);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 先同步标记弹窗不可见,再隐藏窗口/预览:异步 hide 在途时,残留的
|
||||||
|
// show_preview 请求会因该标志为 false 而拒绝,预览窗不会孤立残留。
|
||||||
|
POPUP_VISIBLE.store(false, Ordering::SeqCst);
|
||||||
|
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||||
let _ = win_handle.hide();
|
let _ = win_handle.hide();
|
||||||
|
hide_preview(&app_handle);
|
||||||
let _ = app_handle.emit(crate::constants::events::CLIPBOARD_POPUP_HIDE, ());
|
let _ = app_handle.emit(crate::constants::events::CLIPBOARD_POPUP_HIDE, ());
|
||||||
}
|
}
|
||||||
|
tauri::WindowEvent::Focused(true) => {
|
||||||
|
// 弹窗重新获得焦点(用户点击/移回弹窗):取消推迟隐藏状态
|
||||||
|
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
crate::logger::log_info("clipboard", "弹窗窗口已预创建(隐藏状态)");
|
crate::logger::log_info("clipboard", "弹窗窗口已预创建(隐藏状态)");
|
||||||
@@ -112,6 +199,7 @@ pub fn show_popup(app: &AppHandle) {
|
|||||||
y: y as i32,
|
y: y as i32,
|
||||||
}));
|
}));
|
||||||
let _ = win.show();
|
let _ = win.show();
|
||||||
|
mark_shown();
|
||||||
let _ = win.set_focus();
|
let _ = win.set_focus();
|
||||||
// 通知前端刷新数据
|
// 通知前端刷新数据
|
||||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||||
@@ -143,17 +231,27 @@ pub fn show_window(app: &AppHandle) {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
let _ = win.show();
|
let _ = win.show();
|
||||||
|
mark_shown();
|
||||||
let _ = win.set_focus();
|
let _ = win.set_focus();
|
||||||
// 通知前端刷新数据
|
// 通知前端刷新数据
|
||||||
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_SHOW, ());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 隐藏弹窗(不销毁,保留复用)
|
/// 隐藏弹窗(不销毁,保留复用),并通知前端清理悬停定时器/预览。
|
||||||
pub fn hide_popup(app: &AppHandle) {
|
pub fn hide_popup(app: &AppHandle) {
|
||||||
|
// 复位推迟隐藏标记(先于 hide_preview,避免 hide_preview 重入 hide_popup 形成递归)
|
||||||
|
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||||
|
// 复位交互锁定:弹窗关闭后下次呼出恢复"失焦即隐藏"的常规模式
|
||||||
|
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||||
|
// 同步标记弹窗不可见,拒绝此后在途的 show_preview 请求
|
||||||
|
POPUP_VISIBLE.store(false, Ordering::SeqCst);
|
||||||
|
hide_preview(app);
|
||||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||||
let _ = win.hide();
|
let _ = win.hide();
|
||||||
}
|
}
|
||||||
|
// 通知前端:取消悬停定时器并隐藏预览,避免弹窗隐藏后残留定时器重新弹出预览窗
|
||||||
|
let _ = app.emit(crate::constants::events::CLIPBOARD_POPUP_HIDE, ());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 隐藏弹窗后延迟模拟 Ctrl+V 粘贴到之前聚焦的窗口。
|
/// 隐藏弹窗后延迟模拟 Ctrl+V 粘贴到之前聚焦的窗口。
|
||||||
@@ -207,6 +305,434 @@ fn simulate_paste() {
|
|||||||
// 非 Windows 平台暂不支持自动粘贴
|
// 非 Windows 平台暂不支持自动粘贴
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== 独立预览窗口 =====
|
||||||
|
|
||||||
|
/// 创建预览窗口(隐藏状态),应用 NoActivate 样式避免抢焦点。
|
||||||
|
fn create_preview_window(app: &AppHandle) {
|
||||||
|
let win = match WebviewWindowBuilder::new(
|
||||||
|
app,
|
||||||
|
PREVIEW_LABEL,
|
||||||
|
WebviewUrl::App("index.html#clipboard-preview".into()),
|
||||||
|
)
|
||||||
|
.title("预览")
|
||||||
|
.inner_size(PREVIEW_W, PREVIEW_H)
|
||||||
|
.position(-10000.0, -10000.0) // 屏幕外,避免隐藏时一闪
|
||||||
|
.decorations(false)
|
||||||
|
.transparent(true)
|
||||||
|
.shadow(true)
|
||||||
|
.always_on_top(true)
|
||||||
|
.skip_taskbar(true)
|
||||||
|
.resizable(false)
|
||||||
|
.visible(false)
|
||||||
|
.focused(false) // 不抢占焦点
|
||||||
|
.effects(EffectsBuilder::new().effects(vec![Effect::Mica]).build())
|
||||||
|
.build()
|
||||||
|
{
|
||||||
|
Ok(w) => w,
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_error("clipboard", &format!("创建预览窗失败: {}", e));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// NoActivate:预览窗可交互但不激活,弹窗保持前台(键盘导航/粘贴不受影响)
|
||||||
|
// 圆角:NoActivate 悬浮窗系统不自动圆角,显式指定 DWMWCP_ROUND 与弹窗外观统一
|
||||||
|
#[cfg(windows)]
|
||||||
|
if let Ok(hwnd) = win.hwnd() {
|
||||||
|
crate::win32_util::apply_no_activate(hwnd.0 as isize);
|
||||||
|
crate::win32_util::apply_rounded_corners(hwnd.0 as isize);
|
||||||
|
}
|
||||||
|
|
||||||
|
crate::logger::log_info("clipboard", "预览窗口已预创建(隐藏状态)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用启动时预创建预览窗口(隐藏),随弹窗一起就绪。
|
||||||
|
pub fn ensure_preview_window(app: &AppHandle) {
|
||||||
|
if app.get_webview_window(PREVIEW_LABEL).is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
create_preview_window(app);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 预览当前所在侧(default=右,left=左),供放大/还原重定位沿用同侧。
|
||||||
|
#[derive(Clone, Copy, PartialEq)]
|
||||||
|
enum PreviewSide {
|
||||||
|
Right,
|
||||||
|
Left,
|
||||||
|
}
|
||||||
|
|
||||||
|
static PREVIEW_SIDE: Mutex<Option<PreviewSide>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 最近一次显示预览时的鼠标 Y 锚点(物理像素)。预览窗垂直中线对齐该位置
|
||||||
|
/// (贴近鼠标所悬停的条目),resize(切换条目/放大还原)时沿用,保持中线稳定不跳变。
|
||||||
|
static PREVIEW_ANCHOR_Y: Mutex<Option<i32>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 弹窗离开看护线程是否已在运行(防重入,见 spawn_popup_leave_watch)。
|
||||||
|
static POPUP_LEAVE_WATCH: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 交互锁定模式:用户点击过预览窗(放大/缩小、复制文本等)后置位。
|
||||||
|
/// 该模式下弹窗与预览不因失焦/鼠标离开而关闭,仅当点击弹窗+预览之外的
|
||||||
|
/// 区域(看护线程检测鼠标按下沿)或弹窗重新聚焦(恢复正常模式)时才复位。
|
||||||
|
static POPUP_INTERACTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 重新定位预览窗口(物理像素)。preferred 指定优先放置侧,返回实际落位侧。
|
||||||
|
/// anchor_y 为鼠标 Y 锚点:预览窗垂直中线对齐该位置(贴近悬停条目),
|
||||||
|
/// 上下 clamp 到工作区;None 时退回弹窗顶部对齐。
|
||||||
|
///
|
||||||
|
/// 无边框+阴影窗口(tao 实现)的外框矩形在客户区四周各留一条不可见边框
|
||||||
|
/// (SM_CXSIZEFRAME+SM_CXPADDEDBORDER,典型 8px):outer_position/outer_size 均含该边框,
|
||||||
|
/// 而可视内容仅占客户区。若直接用外框尺寸计算右侧落位,右侧可视间距会比左侧多出
|
||||||
|
/// 两侧边框之和(约 16px)。这里以"可视边缘"对齐:frame = (外框宽 - 客户区宽) / 2,
|
||||||
|
/// 左右两侧使用同一 GAP,保证两侧可视间距一致。
|
||||||
|
fn reposition_preview(
|
||||||
|
popup: &tauri::WebviewWindow,
|
||||||
|
win: &tauri::WebviewWindow,
|
||||||
|
vw: i32,
|
||||||
|
vh: i32,
|
||||||
|
preferred: PreviewSide,
|
||||||
|
anchor_y: Option<i32>,
|
||||||
|
allow_flip: bool,
|
||||||
|
) -> PreviewSide {
|
||||||
|
// 弹窗当前物理位置与尺寸(外框,含不可见边框)
|
||||||
|
let Ok(pos) = popup.outer_position() else { return preferred };
|
||||||
|
let Ok(osz) = popup.outer_size() else { return preferred };
|
||||||
|
let Ok(isz) = popup.inner_size() else { return preferred };
|
||||||
|
let (px, py) = (pos.x, pos.y);
|
||||||
|
let pw = osz.width as i32;
|
||||||
|
// 不可见边框宽度(外框与客户区之差的一半;无阴影窗口为 0)
|
||||||
|
let frame = ((osz.width.saturating_sub(isz.width)) / 2) as i32;
|
||||||
|
|
||||||
|
// 弹窗所在显示器工作区
|
||||||
|
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(px, py)
|
||||||
|
.unwrap_or((0, 0, 1920, 1040));
|
||||||
|
|
||||||
|
let gap = (PREVIEW_GAP * popup.scale_factor().unwrap_or(1.0)).round() as i32;
|
||||||
|
|
||||||
|
// 可视边缘对齐:
|
||||||
|
// 右侧落位 = 弹窗可视右缘(px+pw-frame) + GAP - 预览窗自身左边框(frame)
|
||||||
|
// 左侧落位 = 弹窗可视左缘(px+frame) - GAP - 预览可视宽(vw) - 预览窗左边框(frame)
|
||||||
|
// (frame 两两抵消,与旧公式一致)
|
||||||
|
let right_x = px + pw - 2 * frame + gap;
|
||||||
|
let left_x = px - gap - vw;
|
||||||
|
// 可视区域(含预览窗自身边框偏移)不越工作区
|
||||||
|
let fits_right = right_x + frame + vw <= wa_right;
|
||||||
|
let fits_left = left_x + frame >= wa_left;
|
||||||
|
let mut x = match preferred {
|
||||||
|
PreviewSide::Right => right_x,
|
||||||
|
PreviewSide::Left => left_x,
|
||||||
|
};
|
||||||
|
// 仅初始落位(allow_flip=true)允许换侧:优先侧放不下时切到另一侧。
|
||||||
|
// 内容尺寸变化(放大/还原,allow_flip=false)不允许换侧:窗口跳到另一侧会使
|
||||||
|
// 鼠标瞬间落在窗外,误触发 mouseleave 而关闭预览/弹窗;此时保持原侧并靠
|
||||||
|
// 工作区 clamp(大图可能覆盖弹窗边缘,属合理取舍,鼠标仍在预览窗内可交互)。
|
||||||
|
if allow_flip {
|
||||||
|
match preferred {
|
||||||
|
PreviewSide::Right => {
|
||||||
|
if !fits_right {
|
||||||
|
x = left_x;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PreviewSide::Left => {
|
||||||
|
if !fits_left {
|
||||||
|
x = right_x;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
x = (x + frame).max(wa_left).min(wa_right - vw) - frame;
|
||||||
|
// 仅初始落位(allow_flip)按最终位置更新所在侧(换侧时位置在弹窗另一侧,判定正确);
|
||||||
|
// 放大/还原(不允许换侧)时即使被工作区 clamp 覆盖到弹窗上方,语义上仍属原侧,
|
||||||
|
// 必须沿用 preferred——否则 clamp 后按位置误判为另一侧并存档,缩小后会跳侧。
|
||||||
|
let side = if allow_flip {
|
||||||
|
if x + vw <= px { PreviewSide::Left } else { PreviewSide::Right }
|
||||||
|
} else {
|
||||||
|
preferred
|
||||||
|
};
|
||||||
|
// 垂直定位:预览窗中线对齐鼠标 Y 锚点(贴近悬停条目),上下 clamp 到工作区;
|
||||||
|
// 无锚点时退回弹窗顶部对齐
|
||||||
|
let y = match anchor_y {
|
||||||
|
Some(ay) => (ay - vh / 2).max(wa_top).min(wa_bottom - vh),
|
||||||
|
None => py.max(wa_top).min(wa_bottom - vh),
|
||||||
|
};
|
||||||
|
|
||||||
|
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition { x, y }));
|
||||||
|
if let Ok(mut s) = PREVIEW_SIDE.lock() {
|
||||||
|
*s = Some(side);
|
||||||
|
}
|
||||||
|
side
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 通知预览前端加载指定条目。窗口此时保持隐藏:前端测得内容尺寸后先调用
|
||||||
|
/// resize_preview(隐藏状态下完成尺寸/位置调整)再 reveal_preview 显示,
|
||||||
|
/// 避免"先以上次尺寸(可能是放大态大窗)显示再缩回"的闪烁。
|
||||||
|
pub fn show_preview(app: &AppHandle, id: i64) {
|
||||||
|
// 弹窗已隐藏(或隐藏中)时拒绝显示预览:同步标志消除 is_visible() 的异步时序竞态,
|
||||||
|
// 保证"弹窗失焦消失后预览窗不会孤立残留"。
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if app.get_webview_window(PREVIEW_LABEL).is_none() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(popup) = app.get_webview_window(POPUP_LABEL) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// 弹窗不可见时不显示预览:避免弹窗隐藏后仍在途的悬停请求重新弹出孤立的预览窗
|
||||||
|
if !popup.is_visible().unwrap_or(false) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录鼠标 Y 锚点:预览窗中线对齐鼠标所悬停的条目位置;resize 时沿用
|
||||||
|
if let Some((_, y)) = get_cursor_pos() {
|
||||||
|
if let Ok(mut a) = PREVIEW_ANCHOR_Y.lock() {
|
||||||
|
*a = Some(y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 通知前端加载条目内容(前端完成后自行 resize + reveal)
|
||||||
|
let _ = app.emit(crate::constants::events::CLIPBOARD_PREVIEW_SHOW, id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 显示已就绪的预览窗口(前端完成内容加载与 resize 后调用)。
|
||||||
|
/// 显示前重查弹窗可见性,消除内容加载期间弹窗已隐藏的竞态。
|
||||||
|
pub fn reveal_preview(app: &AppHandle) {
|
||||||
|
// 弹窗已隐藏:在途请求作废
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 已可见则跳过(放大/还原触发的重复 reveal)
|
||||||
|
if PREVIEW_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 同步标记预览窗可见(以原生方式显示,Tauri 的 is_visible 可能不同步)
|
||||||
|
PREVIEW_VISIBLE.store(true, Ordering::SeqCst);
|
||||||
|
// 不激活显示(SW_SHOWNOACTIVATE),弹窗保持前台
|
||||||
|
#[cfg(windows)]
|
||||||
|
if let Ok(hwnd) = win.hwnd() {
|
||||||
|
crate::win32_util::show_no_activate(hwnd.0 as isize);
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
let _ = win.show();
|
||||||
|
|
||||||
|
// 显示期间弹窗可能已被隐藏(失焦/关闭):立即收回预览。
|
||||||
|
// 关闭初次检查与真正 show 之间的竞态——失焦处理器先置 POPUP_VISIBLE=false
|
||||||
|
// 再隐藏,这里 show 之后重查一次,若已被隐藏则收回预览,避免孤立残留。
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
PREVIEW_VISIBLE.store(false, Ordering::SeqCst);
|
||||||
|
let _ = win.hide();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按内容自适应调整预览窗大小(逻辑像素),位置沿用当前所在侧并重新对齐弹窗。
|
||||||
|
/// 前端加载/切换内容(文本测高、图片按宽高比)后调用,窗口贴合内容消除留白。
|
||||||
|
/// allow_flip:初始落位为 true(优先侧放不下可换侧);放大/还原为 false
|
||||||
|
/// (保持原侧靠工作区 clamp,避免窗口跳侧使鼠标落在窗外误触发隐藏)。
|
||||||
|
pub fn resize_preview(app: &AppHandle, width: f64, height: f64, allow_flip: bool) {
|
||||||
|
// 弹窗不可见时忽略(无对齐基准)
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(popup) = app.get_webview_window(POPUP_LABEL) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
let scale = popup.scale_factor().unwrap_or(1.0);
|
||||||
|
// 以弹窗所在屏工作区为上限钳制(逻辑像素),并保证不小于最小可视尺寸
|
||||||
|
let (wa_left, wa_top, wa_right, wa_bottom) = popup
|
||||||
|
.outer_position()
|
||||||
|
.ok()
|
||||||
|
.and_then(|p| get_work_area_at_point(p.x, p.y))
|
||||||
|
.unwrap_or((0, 0, 1920, 1040));
|
||||||
|
let max_w = ((wa_right - wa_left).max(0) as f64 / scale).floor().max(PREVIEW_MIN_W);
|
||||||
|
let max_h = ((wa_bottom - wa_top).max(0) as f64 / scale).floor().max(PREVIEW_MIN_H);
|
||||||
|
let w = width.clamp(PREVIEW_MIN_W, max_w);
|
||||||
|
let h = height.clamp(PREVIEW_MIN_H, max_h);
|
||||||
|
let vw = (w * scale).round() as i32;
|
||||||
|
let vh = (h * scale).round() as i32;
|
||||||
|
|
||||||
|
let side = PREVIEW_SIDE.lock().ok().and_then(|s| *s).unwrap_or(PreviewSide::Right);
|
||||||
|
// 沿用最近一次的鼠标 Y 锚点:高度变化时中线保持对齐悬停条目,不产生跳变
|
||||||
|
let anchor_y = PREVIEW_ANCHOR_Y.lock().ok().and_then(|a| *a);
|
||||||
|
reposition_preview(&popup, &win, vw, vh, side, anchor_y, allow_flip);
|
||||||
|
let _ = win.set_size(tauri::Size::Physical(tauri::PhysicalSize { width: vw as u32, height: vh as u32 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 交互锁定模式入口:前端预览窗收到 mousedown(放大/缩小、复制、选择文本)时调用。
|
||||||
|
/// 置位锁定标志并启动看护线程:此后弹窗+预览不因失焦/鼠标离开而关闭,
|
||||||
|
/// 仅当点击弹窗+预览之外的区域或弹窗重新聚焦时退出锁定。
|
||||||
|
pub fn preview_interacted(app: &AppHandle) {
|
||||||
|
POPUP_INTERACTED.store(true, Ordering::SeqCst);
|
||||||
|
// 交互锁定取代推迟隐藏模式:清除可能残留的 DEFER 标记,
|
||||||
|
// 避免后续取消钉住时 hide_preview 走 DEFER 分支误关弹窗
|
||||||
|
POPUP_DEFER_HIDE.store(false, Ordering::SeqCst);
|
||||||
|
spawn_popup_leave_watch(app.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 隐藏预览窗口(保留复用),并通知前端清空内容。
|
||||||
|
pub fn hide_preview(app: &AppHandle) {
|
||||||
|
// 交互锁定模式:弹窗仍显示时预览保持(生命周期由看护线程管理,点击外部才
|
||||||
|
// 随弹窗一起关闭),忽略常规隐藏请求(条目离开、键盘切换等)。
|
||||||
|
if POPUP_INTERACTED.load(Ordering::SeqCst) && POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||||
|
// 若此前因预览交互推迟了弹窗隐藏(弹窗已失焦但保持显示),现在用户离开预览窗,
|
||||||
|
// 需判断去向:光标已回到弹窗内(继续浏览弹窗)→ 仅隐藏预览、保持弹窗显示;
|
||||||
|
// 光标在弹窗之外(离开整个区域)→ 连同弹窗一起隐藏。
|
||||||
|
// (hide_popup 会先复位该标记,故此处 swap(false) 后调用不会递归重入)
|
||||||
|
if POPUP_DEFER_HIDE.swap(false, Ordering::SeqCst) {
|
||||||
|
if !is_cursor_in_popup(app) {
|
||||||
|
hide_popup(app);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 光标已回到弹窗内。若弹窗仍持有焦点(曾点击弹窗重新激活),仅隐藏预览即可,
|
||||||
|
// 后续失焦仍走 Focused(false) 正常关闭;若弹窗已失焦(点击预览窗所致),
|
||||||
|
// 它不会再收到 Focused(false) 事件——光标一旦离开弹窗区域,弹窗将永远
|
||||||
|
// 无法关闭(无焦点残留窗口)。启动看护线程兜底关闭。
|
||||||
|
let focused = app
|
||||||
|
.get_webview_window(POPUP_LABEL)
|
||||||
|
.map(|w| w.is_focused().unwrap_or(false))
|
||||||
|
.unwrap_or(false);
|
||||||
|
if !focused {
|
||||||
|
spawn_popup_leave_watch(app.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PREVIEW_VISIBLE.store(false, Ordering::SeqCst);
|
||||||
|
if let Some(win) = app.get_webview_window(PREVIEW_LABEL) {
|
||||||
|
let _ = win.hide();
|
||||||
|
// 预览窗以原生 SW_SHOWNOACTIVATE 方式显示,Tauri 内部可见性状态可能与其
|
||||||
|
// 不同步;补一次原生 SW_HIDE,确保任何路径下都被可靠隐藏。
|
||||||
|
#[cfg(windows)]
|
||||||
|
if let Ok(hwnd) = win.hwnd() {
|
||||||
|
crate::win32_util::hide_window(hwnd.0 as isize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = app.emit(crate::constants::events::CLIPBOARD_PREVIEW_HIDE, ());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 弹窗失焦但保持显示时的看护线程(防重入单例)。
|
||||||
|
///
|
||||||
|
/// 两种工作模式(每轮动态读取 POPUP_INTERACTED,可中途切换):
|
||||||
|
/// - 常规模式(未点击过预览窗):光标连续 ~300ms 既不在弹窗也不在预览窗内
|
||||||
|
/// (连续计数防"穿越弹窗-预览间隙"时的瞬时离开误判)→ 关闭弹窗;
|
||||||
|
/// - 交互锁定模式(点击过预览窗的放大/缩小/复制等):弹窗已失焦不会再收到
|
||||||
|
/// Focused(false),检测"鼠标按下沿且按下位置在弹窗+预览之外"→ 点击外部,关闭弹窗。
|
||||||
|
///
|
||||||
|
/// 公共退出条件:弹窗已隐藏/销毁(其他路径关闭);弹窗重新获得焦点(用户点击
|
||||||
|
/// 弹窗,恢复正常失焦关闭路径,并复位交互锁定);超时兜底防线程泄漏
|
||||||
|
/// (常规 30s;交互锁定为事件驱动,放宽至 10min)。
|
||||||
|
fn spawn_popup_leave_watch(app: AppHandle) {
|
||||||
|
// 防重入:已有看护在运行则跳过
|
||||||
|
if POPUP_LEAVE_WATCH.swap(true, Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let start = Instant::now();
|
||||||
|
let mut outside = 0u32;
|
||||||
|
let mut was_down = false;
|
||||||
|
loop {
|
||||||
|
std::thread::sleep(Duration::from_millis(30));
|
||||||
|
// 弹窗已隐藏或被销毁:看护结束
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst)
|
||||||
|
|| app.get_webview_window(POPUP_LABEL).is_none()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
// 弹窗重新获得焦点(用户点击弹窗):恢复正常失焦关闭路径,复位交互锁定
|
||||||
|
if app
|
||||||
|
.get_webview_window(POPUP_LABEL)
|
||||||
|
.map(|w| w.is_focused().unwrap_or(false))
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
POPUP_INTERACTED.store(false, Ordering::SeqCst);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let interacted = POPUP_INTERACTED.load(Ordering::SeqCst);
|
||||||
|
// 超长兜底:避免异常路径下看护线程无限轮询
|
||||||
|
let timeout = if interacted {
|
||||||
|
Duration::from_secs(600)
|
||||||
|
} else {
|
||||||
|
Duration::from_secs(30)
|
||||||
|
};
|
||||||
|
if start.elapsed() > timeout {
|
||||||
|
hide_popup(&app);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let cursor_in = is_cursor_in_popup(&app) || is_cursor_in_preview(&app);
|
||||||
|
if interacted {
|
||||||
|
// 交互锁定:左键按下沿发生在弹窗+预览之外 → 点击外部,关闭弹窗+预览。
|
||||||
|
// 按下沿判定(上一轮未按下、本轮按下)配合 30ms 轮询,可捕获常规点击;
|
||||||
|
// 在弹窗/预览内按下后拖出再松开不算外部点击(以按下位置为准)。
|
||||||
|
let down = crate::win32_util::is_left_button_down();
|
||||||
|
if down && !was_down && !cursor_in {
|
||||||
|
hide_popup(&app);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
was_down = down;
|
||||||
|
} else if cursor_in {
|
||||||
|
outside = 0;
|
||||||
|
} else {
|
||||||
|
outside += 1;
|
||||||
|
// 连续 ~300ms 不在弹窗/预览区域(排除穿越间隙的瞬时状态)才关闭
|
||||||
|
if outside >= 10 {
|
||||||
|
hide_popup(&app);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
POPUP_LEAVE_WATCH.store(false, Ordering::SeqCst);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 鼠标当前是否位于弹窗矩形内(弹窗可见且光标在其窗口范围内)。
|
||||||
|
/// 用于 hide_preview 判断"用户是回到弹窗继续浏览,还是离开整个区域"。
|
||||||
|
fn is_cursor_in_popup(app: &AppHandle) -> bool {
|
||||||
|
if !POPUP_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(win) = app.get_webview_window(POPUP_LABEL) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Ok(pos) = win.outer_position() else { return false };
|
||||||
|
let Ok(size) = win.outer_size() else { return false };
|
||||||
|
let Some((cx, cy)) = crate::win32_util::get_cursor_pos() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let x = pos.x;
|
||||||
|
let y = pos.y;
|
||||||
|
let w = size.width as i32;
|
||||||
|
let h = size.height as i32;
|
||||||
|
cx >= x && cx <= x + w && cy >= y && cy <= y + h
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 鼠标当前是否位于预览窗矩形内(预览窗可见且光标在其窗口范围内)。
|
||||||
|
/// 用于弹窗失焦时判断是否因预览交互所致,决定是否推迟隐藏弹窗。
|
||||||
|
fn is_cursor_in_preview(app: &AppHandle) -> bool {
|
||||||
|
if !PREVIEW_VISIBLE.load(Ordering::SeqCst) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(win) = app.get_webview_window(PREVIEW_LABEL) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Ok(pos) = win.outer_position() else { return false };
|
||||||
|
let Ok(size) = win.outer_size() else { return false };
|
||||||
|
let Some((cx, cy)) = crate::win32_util::get_cursor_pos() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let x = pos.x;
|
||||||
|
let y = pos.y;
|
||||||
|
let w = size.width as i32;
|
||||||
|
let h = size.height as i32;
|
||||||
|
cx >= x && cx <= x + w && cy >= y && cy <= y + h
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 屏幕/光标/DPI 工具已迁移至 crate::win32_util(跨模块共享) =====
|
// ===== 屏幕/光标/DPI 工具已迁移至 crate::win32_util(跨模块共享) =====
|
||||||
|
|
||||||
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
||||||
|
|||||||
@@ -295,3 +295,29 @@ pub fn dib_to_png(dib: &[u8]) -> Option<Vec<u8>> {
|
|||||||
.ok()?;
|
.ok()?;
|
||||||
Some(buf)
|
Some(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 生成缩略图 PNG(最长边不超过 max_dim 像素)。
|
||||||
|
/// 小图直接复用 `dib_to_png` 结果;大图降采样后重新编码,供弹窗悬停预览使用。
|
||||||
|
pub fn dib_to_thumbnail(dib: &[u8], max_dim: u32) -> Option<Vec<u8>> {
|
||||||
|
use image::codecs::png::PngEncoder;
|
||||||
|
use image::GenericImageView;
|
||||||
|
use image::ImageEncoder;
|
||||||
|
|
||||||
|
let png = dib_to_png(dib)?;
|
||||||
|
let img = image::load_from_memory(&png).ok()?;
|
||||||
|
let (w, h) = img.dimensions();
|
||||||
|
if w.max(h) <= max_dim {
|
||||||
|
return Some(png); // 小图直接使用,避免重复编码
|
||||||
|
}
|
||||||
|
// 让 image 库在 max_dim×max_dim 边界内自动等比缩放,避免手算 nw/nh 与库内部
|
||||||
|
// resize_dimensions 的取整不一致(如手算 256x10 而库实际输出 250x10),
|
||||||
|
// 否则 write_image 的缓冲区长度断言会失败。
|
||||||
|
let resized = img.resize(max_dim, max_dim, image::imageops::FilterType::Triangle);
|
||||||
|
let (rw, rh) = resized.dimensions();
|
||||||
|
let rgba = resized.to_rgba8();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
let enc = PngEncoder::new(&mut buf);
|
||||||
|
enc.write_image(rgba.as_raw(), rw, rh, image::ExtendedColorType::Rgba8)
|
||||||
|
.ok()?;
|
||||||
|
Some(buf)
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
//!
|
//!
|
||||||
//! 表结构见 `init_db`。所有方法线程安全(内部 Mutex 包裹 Connection)。
|
//! 表结构见 `init_db`。所有方法线程安全(内部 Mutex 包裹 Connection)。
|
||||||
|
|
||||||
|
use base64::Engine as _;
|
||||||
use rusqlite::{params, Connection, OptionalExtension};
|
use rusqlite::{params, Connection, OptionalExtension};
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
@@ -38,6 +39,8 @@ pub struct NewItem {
|
|||||||
pub kind: String,
|
pub kind: String,
|
||||||
pub content: Option<String>,
|
pub content: Option<String>,
|
||||||
pub blob: Option<Vec<u8>>,
|
pub blob: Option<Vec<u8>>,
|
||||||
|
/// 图片缩略图 PNG(仅 image 类型,供弹窗悬停预览)
|
||||||
|
pub thumb: Option<Vec<u8>>,
|
||||||
pub preview: String,
|
pub preview: String,
|
||||||
pub size: i64,
|
pub size: i64,
|
||||||
pub hash: String,
|
pub hash: String,
|
||||||
@@ -88,6 +91,19 @@ impl Storage {
|
|||||||
CREATE INDEX IF NOT EXISTS idx_hash ON clipboard_history(hash);
|
CREATE INDEX IF NOT EXISTS idx_hash ON clipboard_history(hash);
|
||||||
CREATE INDEX IF NOT EXISTS idx_kind ON clipboard_history(kind);",
|
CREATE INDEX IF NOT EXISTS idx_kind ON clipboard_history(kind);",
|
||||||
);
|
);
|
||||||
|
// 迁移:老库无 thumb 列(图片缩略图,供弹窗悬停预览),补列
|
||||||
|
let has_thumb = conn
|
||||||
|
.prepare("PRAGMA table_info(clipboard_history)")
|
||||||
|
.ok()
|
||||||
|
.map(|mut stmt| {
|
||||||
|
stmt.query_map([], |r| r.get::<_, String>(1))
|
||||||
|
.map(|rows| rows.filter_map(|c| c.ok()).any(|c| c == "thumb"))
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
.unwrap_or(false);
|
||||||
|
if !has_thumb {
|
||||||
|
let _ = conn.execute("ALTER TABLE clipboard_history ADD COLUMN thumb BLOB", []);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 插入新条目;若 dedup 为 true 且 hash 已存在则仅更新 created_at,返回条目 id。
|
/// 插入新条目;若 dedup 为 true 且 hash 已存在则仅更新 created_at,返回条目 id。
|
||||||
@@ -120,12 +136,13 @@ impl Storage {
|
|||||||
let now = now_ms();
|
let now = now_ms();
|
||||||
let res = conn.execute(
|
let res = conn.execute(
|
||||||
"INSERT INTO clipboard_history
|
"INSERT INTO clipboard_history
|
||||||
(kind, content, blob, preview, size, hash, pinned, pinned_order, created_at)
|
(kind, content, blob, thumb, preview, size, hash, pinned, pinned_order, created_at)
|
||||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, 0, NULL, ?7)",
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 0, NULL, ?8)",
|
||||||
params![
|
params![
|
||||||
item.kind,
|
item.kind,
|
||||||
item.content,
|
item.content,
|
||||||
item.blob.as_deref(),
|
item.blob.as_deref(),
|
||||||
|
item.thumb.as_deref(),
|
||||||
item.preview,
|
item.preview,
|
||||||
item.size,
|
item.size,
|
||||||
item.hash,
|
item.hash,
|
||||||
@@ -249,6 +266,26 @@ impl Storage {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 获取图片缩略图 PNG base64(弹窗悬停预览用)。
|
||||||
|
/// 老数据无缩略图时回退为 `thumb_from_dib` 现场生成。
|
||||||
|
pub fn get_thumb(&self, id: i64, thumb_from_dib: impl Fn(&[u8]) -> Option<Vec<u8>>) -> Option<String> {
|
||||||
|
let (thumb, blob) = {
|
||||||
|
let conn = self.conn.lock().ok()?;
|
||||||
|
conn.query_row(
|
||||||
|
"SELECT thumb, blob FROM clipboard_history WHERE id = ?1 AND kind = 'image'",
|
||||||
|
params![id],
|
||||||
|
|r| Ok((r.get::<_, Option<Vec<u8>>>(0)?, r.get::<_, Option<Vec<u8>>>(1)?)),
|
||||||
|
)
|
||||||
|
.ok()?
|
||||||
|
};
|
||||||
|
// conn 已在此处释放
|
||||||
|
let png = match thumb {
|
||||||
|
Some(t) if !t.is_empty() => Some(t),
|
||||||
|
_ => blob.as_deref().and_then(|b| thumb_from_dib(b)),
|
||||||
|
};
|
||||||
|
png.map(|p| base64::engine::general_purpose::STANDARD.encode(&p))
|
||||||
|
}
|
||||||
|
|
||||||
/// 获取原始字段供 copy_back 写回(避免 base64 转换开销)
|
/// 获取原始字段供 copy_back 写回(避免 base64 转换开销)
|
||||||
pub fn get_raw_for_copy(&self, id: i64) -> Option<(String, Option<String>, Option<Vec<u8>>)> {
|
pub fn get_raw_for_copy(&self, id: i64) -> Option<(String, Option<String>, Option<Vec<u8>>)> {
|
||||||
let conn = self.conn.lock().ok()?;
|
let conn = self.conn.lock().ok()?;
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ pub mod windows {
|
|||||||
pub const OSD_OVERLAY: &str = "osd-overlay";
|
pub const OSD_OVERLAY: &str = "osd-overlay";
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
pub const SCREENSHOT_OVERLAY: &str = "screenshot-overlay";
|
pub const SCREENSHOT_OVERLAY: &str = "screenshot-overlay";
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub const SCREENSHOT_PIN: &str = "screenshot-pin";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
/// Tauri 事件名(与前端 constants::EVENTS 对应)
|
||||||
@@ -24,9 +26,14 @@ pub mod events {
|
|||||||
pub const CLIPBOARD_CHANGED: &str = "clipboard-changed";
|
pub const CLIPBOARD_CHANGED: &str = "clipboard-changed";
|
||||||
pub const CLIPBOARD_POPUP_SHOW: &str = "clipboard-popup-show";
|
pub const CLIPBOARD_POPUP_SHOW: &str = "clipboard-popup-show";
|
||||||
pub const CLIPBOARD_POPUP_HIDE: &str = "clipboard-popup-hide";
|
pub const CLIPBOARD_POPUP_HIDE: &str = "clipboard-popup-hide";
|
||||||
|
pub const CLIPBOARD_PREVIEW_SHOW: &str = "clipboard-preview-show";
|
||||||
|
pub const CLIPBOARD_PREVIEW_HIDE: &str = "clipboard-preview-hide";
|
||||||
// 快速面板
|
// 快速面板
|
||||||
pub const QUICKPANEL_SHOW: &str = "quickpanel-show";
|
pub const QUICKPANEL_SHOW: &str = "quickpanel-show";
|
||||||
pub const QUICKPANEL_HIDE: &str = "quickpanel-hide";
|
pub const QUICKPANEL_HIDE: &str = "quickpanel-hide";
|
||||||
|
pub const QUICKPANEL_EXTRACT_PROGRESS: &str = "quickpanel-extract-progress";
|
||||||
|
/// 文件索引构建完成(闲时自动建立/重建、手动构建),负载为条目数
|
||||||
|
pub const QUICKPANEL_INDEX_UPDATED: &str = "quickpanel-index-updated";
|
||||||
// 监控
|
// 监控
|
||||||
pub const MONITOR_DATA: &str = "monitor-data";
|
pub const MONITOR_DATA: &str = "monitor-data";
|
||||||
pub const MONITOR_NETWORK: &str = "monitor-network";
|
pub const MONITOR_NETWORK: &str = "monitor-network";
|
||||||
@@ -37,13 +44,24 @@ pub mod events {
|
|||||||
// OSD 窗口
|
// OSD 窗口
|
||||||
pub const OSD_SYSTEM_UI_ACTIVE: &str = "osd-system-ui-active";
|
pub const OSD_SYSTEM_UI_ACTIVE: &str = "osd-system-ui-active";
|
||||||
pub const OSD_SYSTEM_UI_INACTIVE: &str = "osd-system-ui-inactive";
|
pub const OSD_SYSTEM_UI_INACTIVE: &str = "osd-system-ui-inactive";
|
||||||
|
pub const OSD_GAME_ACTIVE: &str = "osd-game-active";
|
||||||
|
pub const OSD_GAME_INACTIVE: &str = "osd-game-inactive";
|
||||||
pub const OSD_START_DRAG: &str = "osd-start-drag";
|
pub const OSD_START_DRAG: &str = "osd-start-drag";
|
||||||
pub const OSD_END_DRAG: &str = "osd-end-drag";
|
pub const OSD_END_DRAG: &str = "osd-end-drag";
|
||||||
// 截图
|
// 截图
|
||||||
pub const SCREENSHOT_SHORTCUT: &str = "screenshot-shortcut";
|
pub const SCREENSHOT_SHORTCUT: &str = "screenshot-shortcut";
|
||||||
|
pub const SCREENSHOT_PIN_SHORTCUT: &str = "screenshot-pin-shortcut";
|
||||||
// 内核安装进度
|
// 内核安装进度
|
||||||
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
pub const KERNEL_INSTALL_PROGRESS: &str = "kernel-install-progress";
|
||||||
|
// 后端自动切换节点完成(前端据以刷新节点列表并提示)
|
||||||
|
pub const PROXY_AUTO_SWITCH: &str = "proxy-auto-switch";
|
||||||
|
// 应用更新进度
|
||||||
|
pub const UPDATE_PROGRESS: &str = "update-progress";
|
||||||
// 进程与下载
|
// 进程与下载
|
||||||
pub const PROCESS_STATUS_CHANGED: &str = "process-status-changed";
|
pub const PROCESS_STATUS_CHANGED: &str = "process-status-changed";
|
||||||
pub const DOWNLOAD_ADDED: &str = "download-added";
|
pub const DOWNLOAD_ADDED: &str = "download-added";
|
||||||
|
/// 任务被删除(浏览器扩展通过 HTTP API 删除任务时发出,前端据此刷新任务列表)
|
||||||
|
pub const DOWNLOAD_REMOVED: &str = "download-removed";
|
||||||
|
/// 浏览器扩展通过 HTTP API 新增下载(负载 { id },前端据以为该任务创建专属下载窗口)
|
||||||
|
pub const DOWNLOAD_EXTENSION_ADDED: &str = "download-extension-added";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use tauri::{AppHandle, State};
|
use tauri::{AppHandle, Manager, State};
|
||||||
use tauri_plugin_opener::OpenerExt;
|
use tauri_plugin_opener::OpenerExt;
|
||||||
|
|
||||||
use super::engine::{CheckUrlResult, DownloadEngine};
|
use super::engine::{CheckUrlResult, DownloadEngine};
|
||||||
use super::task::{DownloadTask, DownloaderSettings};
|
use super::task::{DownloadTask, DownloaderSettings};
|
||||||
|
use super::torrent::TorrentInfo;
|
||||||
|
|
||||||
/// 获取所有任务
|
/// 获取所有任务
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -13,6 +14,20 @@ pub fn downloader_get_tasks(engine: State<'_, DownloadEngine>) -> Vec<DownloadTa
|
|||||||
engine.get_tasks()
|
engine.get_tasks()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 解析磁力链 / .torrent 文件,返回种子信息(名称 / infohash / 文件列表),供前端做文件勾选
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn downloader_inspect(engine: State<'_, DownloadEngine>, input: String) -> Result<TorrentInfo, String> {
|
||||||
|
engine.inspect(&input).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn downloader_select_bt_files(engine: State<'_, DownloadEngine>, id: String, only_files: Vec<u32>) -> Result<(), String> {
|
||||||
|
engine.select_bt_files(&id, only_files).await
|
||||||
|
}
|
||||||
|
|
||||||
/// 检查 URL 重复性并探测文件信息(添加下载前调用)
|
/// 检查 URL 重复性并探测文件信息(添加下载前调用)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
@@ -57,8 +72,9 @@ pub async fn downloader_add_task(
|
|||||||
dir: Option<String>,
|
dir: Option<String>,
|
||||||
headers: Option<HashMap<String, String>>,
|
headers: Option<HashMap<String, String>>,
|
||||||
auto_rename: Option<bool>,
|
auto_rename: Option<bool>,
|
||||||
|
only_files: Option<Vec<u32>>,
|
||||||
) -> Result<String, String> {
|
) -> Result<String, String> {
|
||||||
engine.add_task(url, filename, dir, headers.unwrap_or_default(), auto_rename.unwrap_or(false)).await
|
engine.add_task(url, filename, dir, headers.unwrap_or_default(), auto_rename.unwrap_or(false), only_files).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 暂停任务
|
/// 暂停任务
|
||||||
@@ -75,6 +91,20 @@ pub fn downloader_resume_task(engine: State<'_, DownloadEngine>, id: String) ->
|
|||||||
engine.resume_task(&id)
|
engine.resume_task(&id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 取消任务(置为已取消,清空进度并删除下载文件,但保留记录)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn downloader_cancel_task(engine: State<'_, DownloadEngine>, id: String) -> Result<(), String> {
|
||||||
|
engine.cancel_task(&id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 重新下载已取消/出错的任务
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn downloader_redownload(engine: State<'_, DownloadEngine>, id: String) -> Result<(), String> {
|
||||||
|
engine.redownload(&id).await
|
||||||
|
}
|
||||||
|
|
||||||
/// 移除任务
|
/// 移除任务
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
@@ -141,3 +171,24 @@ pub fn downloader_open_url(app: AppHandle, url: String) -> Result<(), String> {
|
|||||||
.open_url(url, None::<&str>)
|
.open_url(url, None::<&str>)
|
||||||
.map_err(|e| format!("打开链接失败: {}", e))
|
.map_err(|e| format!("打开链接失败: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 将指定 label 的下载窗口显示并强制置为前台。
|
||||||
|
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制(尤其下载窗口由后台进程创建、
|
||||||
|
/// 或创建到非主显示器时更明显),改用原生 SetForegroundWindow + BringWindowToTop
|
||||||
|
/// (模拟 Alt 键重置前台锁定),保证开始/完成下载时窗口能正确定位到前台。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn downloader_focus_window(app: AppHandle, label: String) -> Result<(), String> {
|
||||||
|
let Some(window) = app.get_webview_window(&label) else {
|
||||||
|
return Ok(()); // 窗口已关闭则忽略
|
||||||
|
};
|
||||||
|
window.show().map_err(|e| e.to_string())?;
|
||||||
|
window.unminimize().map_err(|e| e.to_string())?;
|
||||||
|
match window.hwnd() {
|
||||||
|
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||||
|
Err(_) => {
|
||||||
|
window.set_focus().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -21,27 +21,68 @@ const READ_STALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3
|
|||||||
/// HTTP/HTTPS 下载器
|
/// HTTP/HTTPS 下载器
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct HttpDownloader {
|
pub struct HttpDownloader {
|
||||||
client: Client,
|
/// 默认客户端:尊重系统代理(reqwest 默认行为,mihomo 开启系统代理时经其转发)
|
||||||
|
system_client: Client,
|
||||||
|
/// 直连客户端:强制禁用系统代理(no_proxy)
|
||||||
|
direct_client: Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HttpDownloader {
|
impl HttpDownloader {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
let client = Client::builder()
|
let system_client = Client::builder()
|
||||||
.build()
|
.build()
|
||||||
.unwrap_or_else(|_| Client::new());
|
.unwrap_or_else(|_| Client::new());
|
||||||
Self { client }
|
let direct_client = Client::builder()
|
||||||
|
// 强制直连:即使系统代理已开启,下载也不经过代理
|
||||||
|
.no_proxy()
|
||||||
|
.build()
|
||||||
|
.unwrap_or_else(|_| Client::new());
|
||||||
|
Self {
|
||||||
|
system_client,
|
||||||
|
direct_client,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 根据 use_proxy 选择客户端
|
||||||
|
fn client(&self, use_proxy: bool) -> &Client {
|
||||||
|
if use_proxy {
|
||||||
|
&self.system_client
|
||||||
|
} else {
|
||||||
|
&self.direct_client
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 探测下载资源信息(大小、是否支持 Range、文件名)
|
/// 探测下载资源信息(大小、是否支持 Range、文件名)
|
||||||
/// 优先用 GET + Range: bytes=0-0(返回 206 + Content-Range),回退到 HEAD
|
/// 优先用 GET + Range: bytes=0-0(返回 206 + Content-Range),回退到 HEAD。
|
||||||
|
/// 代理降级:use_proxy=true 时先走系统代理,失败则回退 no_proxy 直连重试一次
|
||||||
pub async fn probe(
|
pub async fn probe(
|
||||||
&self,
|
&self,
|
||||||
url: &str,
|
url: &str,
|
||||||
headers: &HashMap<String, String>,
|
headers: &HashMap<String, String>,
|
||||||
|
use_proxy: bool,
|
||||||
|
) -> Result<ProbeResult, String> {
|
||||||
|
let first = self.client(use_proxy);
|
||||||
|
match self.probe_with_client(first, url, headers).await {
|
||||||
|
Ok(r) => return Ok(r),
|
||||||
|
Err(e) if use_proxy => {
|
||||||
|
let direct = self.client(false);
|
||||||
|
self.probe_with_client(direct, url, headers)
|
||||||
|
.await
|
||||||
|
.map_err(|e2| format!("代理探测失败({}),直连重试也失败({})", e, e2))
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 用指定 client 执行探测(GET Range → 回退 HEAD),供代理降级复用
|
||||||
|
async fn probe_with_client(
|
||||||
|
&self,
|
||||||
|
client: &Client,
|
||||||
|
url: &str,
|
||||||
|
headers: &HashMap<String, String>,
|
||||||
) -> Result<ProbeResult, String> {
|
) -> Result<ProbeResult, String> {
|
||||||
// 先尝试 Range 请求(能同时判断 Accept-Ranges 和获取大小)
|
// 先尝试 Range 请求(能同时判断 Accept-Ranges 和获取大小)
|
||||||
let mut req = self
|
let mut req = client
|
||||||
.client
|
|
||||||
.get(url)
|
.get(url)
|
||||||
.header("Range", "bytes=0-0")
|
.header("Range", "bytes=0-0")
|
||||||
.header("User-Agent", "Thing-Download-Engine/1.0");
|
.header("User-Agent", "Thing-Download-Engine/1.0");
|
||||||
@@ -97,7 +138,7 @@ impl HttpDownloader {
|
|||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// GET 失败,尝试 HEAD 作为回退
|
// GET 失败,尝试 HEAD 作为回退
|
||||||
let mut head_req = self.client.head(url);
|
let mut head_req = client.head(url);
|
||||||
for (k, v) in headers {
|
for (k, v) in headers {
|
||||||
head_req = head_req.header(k, v);
|
head_req = head_req.header(k, v);
|
||||||
}
|
}
|
||||||
@@ -132,6 +173,7 @@ impl HttpDownloader {
|
|||||||
/// - `cancel`: 取消标志
|
/// - `cancel`: 取消标志
|
||||||
/// - `progress`: 每个分段的已下载字节(AtomicU64,与 segments 一一对应)
|
/// - `progress`: 每个分段的已下载字节(AtomicU64,与 segments 一一对应)
|
||||||
/// - `limiter`: 全局限速器
|
/// - `limiter`: 全局限速器
|
||||||
|
/// - `use_proxy`: 是否使用系统代理(false=强制直连)
|
||||||
pub async fn download(
|
pub async fn download(
|
||||||
&self,
|
&self,
|
||||||
url: &str,
|
url: &str,
|
||||||
@@ -141,6 +183,37 @@ impl HttpDownloader {
|
|||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
progress: &[Arc<AtomicU64>],
|
progress: &[Arc<AtomicU64>],
|
||||||
limiter: Arc<RateLimiter>,
|
limiter: Arc<RateLimiter>,
|
||||||
|
use_proxy: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
// 代理降级:仅当 use_proxy=true 才有"走代理→失败回退直连"的意义。
|
||||||
|
// use_proxy=false 直接用直连客户端,无需回退。
|
||||||
|
// 注意:用户主动暂停/取消(返回"已取消")必须原样透传,不能触发代理回退,
|
||||||
|
// 否则会把"已取消"包装成"代理失败",导致引擎将其误判为错误而非暂停。
|
||||||
|
let first = self.client(use_proxy);
|
||||||
|
match self.download_with_client(first, url, headers, segments, file_path, cancel.clone(), progress, &limiter).await {
|
||||||
|
Ok(()) => return Ok(()),
|
||||||
|
Err(e) if use_proxy && e != "已取消" => {
|
||||||
|
// 回退直连重试(不继承 use_proxy,保证用 no_proxy 客户端)
|
||||||
|
let direct = self.client(false);
|
||||||
|
self.download_with_client(direct, url, headers, segments, file_path, cancel, progress, &limiter)
|
||||||
|
.await
|
||||||
|
.map_err(|e2| format!("代理下载失败({}),直连重试也失败({})", e, e2))
|
||||||
|
}
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 用指定 client 执行下载(支持单线程与多线程分段),供代理降级复用
|
||||||
|
async fn download_with_client(
|
||||||
|
&self,
|
||||||
|
client: &Client,
|
||||||
|
url: &str,
|
||||||
|
headers: &HashMap<String, String>,
|
||||||
|
segments: &[Segment],
|
||||||
|
file_path: &Path,
|
||||||
|
cancel: Arc<AtomicBool>,
|
||||||
|
progress: &[Arc<AtomicU64>],
|
||||||
|
limiter: &Arc<RateLimiter>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let total_size = segments.iter().map(|s| s.len()).sum();
|
let total_size = segments.iter().map(|s| s.len()).sum();
|
||||||
|
|
||||||
@@ -167,7 +240,7 @@ impl HttpDownloader {
|
|||||||
// 单线程下载(不支持 Range 或文件太小)
|
// 单线程下载(不支持 Range 或文件太小)
|
||||||
let seg = &segments[0];
|
let seg = &segments[0];
|
||||||
let prog = &progress[0];
|
let prog = &progress[0];
|
||||||
self.download_segment(url, headers, seg, file_path, cancel.clone(), prog.clone(), limiter)
|
self.download_segment(url, headers, seg, file_path, cancel.clone(), prog.clone(), limiter.clone(), client)
|
||||||
.await?;
|
.await?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -187,7 +260,7 @@ impl HttpDownloader {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let limiter = limiter.clone();
|
let limiter = limiter.clone();
|
||||||
let file_path = file_path.to_path_buf();
|
let file_path = file_path.to_path_buf();
|
||||||
let client = self.client.clone();
|
let client = client.clone();
|
||||||
|
|
||||||
join_set.spawn(async move {
|
join_set.spawn(async move {
|
||||||
download_segment_with_client(
|
download_segment_with_client(
|
||||||
@@ -241,9 +314,10 @@ impl HttpDownloader {
|
|||||||
cancel: Arc<AtomicBool>,
|
cancel: Arc<AtomicBool>,
|
||||||
progress: Arc<AtomicU64>,
|
progress: Arc<AtomicU64>,
|
||||||
limiter: Arc<RateLimiter>,
|
limiter: Arc<RateLimiter>,
|
||||||
|
client: &Client,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
download_segment_with_client(
|
download_segment_with_client(
|
||||||
&self.client,
|
client,
|
||||||
url,
|
url,
|
||||||
headers,
|
headers,
|
||||||
seg,
|
seg,
|
||||||
@@ -366,6 +440,15 @@ async fn download_segment_with_client(
|
|||||||
limiter.consume(buf.len() as u64).await;
|
limiter.consume(buf.len() as u64).await;
|
||||||
buf.clear();
|
buf.clear();
|
||||||
}
|
}
|
||||||
|
// 校验:已知大小的分段若流提前结束(收到的字节数不足分段长度),
|
||||||
|
// 说明服务器提前断开或返回不完整内容,不能标记为完成,否则文件会被截断
|
||||||
|
if !unknown_size && local_completed < seg.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"文件不完整:已接收 {} / {} 字节,服务器提前结束连接",
|
||||||
|
local_completed,
|
||||||
|
seg.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
|
|||||||
@@ -5,10 +5,11 @@ pub mod rate_limit;
|
|||||||
pub mod server;
|
pub mod server;
|
||||||
pub mod storage;
|
pub mod storage;
|
||||||
pub mod task;
|
pub mod task;
|
||||||
|
pub mod torrent;
|
||||||
|
|
||||||
pub use commands::{
|
pub use commands::{
|
||||||
downloader_add_task, downloader_check_url, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks,
|
downloader_add_task, downloader_cancel_task, downloader_check_url, downloader_focus_window, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks, downloader_inspect, downloader_select_bt_files,
|
||||||
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_remove_task,
|
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_redownload, downloader_remove_task,
|
||||||
downloader_resume_task, downloader_save_settings, downloader_status,
|
downloader_resume_task, downloader_save_settings, downloader_status,
|
||||||
};
|
};
|
||||||
pub use engine::DownloadEngine;
|
pub use engine::DownloadEngine;
|
||||||
|
|||||||
@@ -9,9 +9,10 @@ use axum::{
|
|||||||
Router,
|
Router,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tauri::{AppHandle, Emitter};
|
||||||
|
|
||||||
use super::engine::DownloadEngine;
|
use super::engine::DownloadEngine;
|
||||||
use super::task::DownloadTask;
|
use super::task::{DownloadTask, TaskStatus};
|
||||||
|
|
||||||
/// 扩展 HTTP API 服务器
|
/// 扩展 HTTP API 服务器
|
||||||
pub struct ExtensionServer;
|
pub struct ExtensionServer;
|
||||||
@@ -45,14 +46,18 @@ struct ErrorResponse {
|
|||||||
|
|
||||||
impl ExtensionServer {
|
impl ExtensionServer {
|
||||||
/// 启动 HTTP API 服务器(绑定到 127.0.0.1:port)
|
/// 启动 HTTP API 服务器(绑定到 127.0.0.1:port)
|
||||||
pub async fn start(engine: DownloadEngine, port: u16, secret: String) {
|
pub async fn start(engine: DownloadEngine, port: u16, secret: String, app_handle: AppHandle) {
|
||||||
let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().expect("无效端口");
|
let addr: SocketAddr = format!("127.0.0.1:{}", port).parse().expect("无效端口");
|
||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/health", get(health))
|
.route("/health", get(health))
|
||||||
.route("/api/downloads", post(create_download).get(list_downloads))
|
.route("/api/downloads", post(create_download).get(list_downloads))
|
||||||
.route("/api/downloads/:id", axum::routing::delete(remove_download))
|
.route("/api/downloads/:id", axum::routing::delete(remove_download))
|
||||||
.with_state(AppState { engine, secret });
|
.with_state(AppState {
|
||||||
|
engine,
|
||||||
|
secret,
|
||||||
|
app_handle,
|
||||||
|
});
|
||||||
|
|
||||||
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
let listener = match tokio::net::TcpListener::bind(&addr).await {
|
||||||
Ok(l) => l,
|
Ok(l) => l,
|
||||||
@@ -74,6 +79,7 @@ impl ExtensionServer {
|
|||||||
struct AppState {
|
struct AppState {
|
||||||
engine: DownloadEngine,
|
engine: DownloadEngine,
|
||||||
secret: String,
|
secret: String,
|
||||||
|
app_handle: AppHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 鉴权检查:如果配置了 secret,校验 Bearer token
|
/// 鉴权检查:如果配置了 secret,校验 Bearer token
|
||||||
@@ -108,8 +114,24 @@ async fn create_download(
|
|||||||
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
||||||
}
|
}
|
||||||
|
|
||||||
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true).await {
|
// 去重:同 URL 已有非终态任务(活跃/排队/暂停)时直接返回既有任务,
|
||||||
Ok(id) => Ok(Json(CreateDownloadResponse { id })),
|
// 避免浏览器重复转发同一下载造成重复下载
|
||||||
|
if let Some(existing) = state.engine.get_tasks().into_iter().find(|t| {
|
||||||
|
matches!(t.status, TaskStatus::Active | TaskStatus::Queued | TaskStatus::Paused) && t.url == req.url
|
||||||
|
}) {
|
||||||
|
return Ok(Json(CreateDownloadResponse { id: existing.id }));
|
||||||
|
}
|
||||||
|
|
||||||
|
match state.engine.add_task(req.url, req.filename, req.dir, req.headers, true, None).await {
|
||||||
|
Ok(id) => {
|
||||||
|
// 浏览器扩展发起下载:不再置前主窗口,改为带 task id 通知前端,
|
||||||
|
// 由前端为该任务创建一个专属的一次性下载窗口(不打断主界面)
|
||||||
|
let _ = state.app_handle.emit(
|
||||||
|
crate::constants::events::DOWNLOAD_EXTENSION_ADDED,
|
||||||
|
serde_json::json!({ "id": id }),
|
||||||
|
);
|
||||||
|
Ok(Json(CreateDownloadResponse { id }))
|
||||||
|
}
|
||||||
Err(e) => Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e }))),
|
Err(e) => Err((StatusCode::BAD_REQUEST, Json(ErrorResponse { error: e }))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,7 +155,11 @@ async fn remove_download(
|
|||||||
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
return Err((StatusCode::UNAUTHORIZED, Json(ErrorResponse { error: "未授权".into() })));
|
||||||
}
|
}
|
||||||
match state.engine.remove_task(&id, false) {
|
match state.engine.remove_task(&id, false) {
|
||||||
Ok(()) => Ok(StatusCode::NO_CONTENT),
|
Ok(()) => {
|
||||||
|
// 通知前端刷新任务列表(扩展删除时前端无从感知,否则列表残留已删除任务)
|
||||||
|
let _ = state.app_handle.emit(crate::constants::events::DOWNLOAD_REMOVED, serde_json::json!({ "id": id }));
|
||||||
|
Ok(StatusCode::NO_CONTENT)
|
||||||
|
}
|
||||||
Err(e) => Err((StatusCode::NOT_FOUND, Json(ErrorResponse { error: e }))),
|
Err(e) => Err((StatusCode::NOT_FOUND, Json(ErrorResponse { error: e }))),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,17 @@ use serde::{Deserialize, Serialize};
|
|||||||
use specta::Type;
|
use specta::Type;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// 任务下载协议类型
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Type, Default)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum TaskProtocol {
|
||||||
|
/// HTTP/HTTPS 直链
|
||||||
|
#[default]
|
||||||
|
Http,
|
||||||
|
/// BitTorrent(磁力链 / .torrent 文件)
|
||||||
|
BitTorrent,
|
||||||
|
}
|
||||||
|
|
||||||
/// 任务状态
|
/// 任务状态
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Type)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Type)]
|
||||||
#[serde(rename_all = "lowercase")]
|
#[serde(rename_all = "lowercase")]
|
||||||
@@ -16,6 +27,8 @@ pub enum TaskStatus {
|
|||||||
Complete,
|
Complete,
|
||||||
/// 错误
|
/// 错误
|
||||||
Error,
|
Error,
|
||||||
|
/// 已取消(用户取消:进度与文件已清除,仅保留记录,只能再次下载)
|
||||||
|
Cancelled,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 下载分段(多线程 Range 下载 / 断点续传用)
|
/// 下载分段(多线程 Range 下载 / 断点续传用)
|
||||||
@@ -37,24 +50,57 @@ impl Segment {
|
|||||||
pub fn len(&self) -> u64 {
|
pub fn len(&self) -> u64 {
|
||||||
self.end.saturating_sub(self.start) + 1
|
self.end.saturating_sub(self.start) + 1
|
||||||
}
|
}
|
||||||
|
/// 是否为未知大小哨兵段(start=0, end=0,表示不支持 Range 或未探测到大小)
|
||||||
|
pub fn is_unknown_size(&self) -> bool {
|
||||||
|
self.start == 0 && self.end == 0
|
||||||
|
}
|
||||||
/// 是否已完成
|
/// 是否已完成
|
||||||
pub fn is_done(&self) -> bool {
|
pub fn is_done(&self) -> bool {
|
||||||
|
// 未知大小段无法用长度判断是否完成,由流结束(Ok(None))判定;
|
||||||
|
// 若按 len()=1 判断,暂停/恢复后 completed>=1 会误判为已完成,导致文件被截断
|
||||||
|
if self.is_unknown_size() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
self.completed >= self.len()
|
self.completed >= self.len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// BT 种子内文件条目(多文件任务用;阶段1下载全部文件,但保留列表供 UI 展示)
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct BtFileInfo {
|
||||||
|
/// 文件在种子内的索引
|
||||||
|
pub index: u32,
|
||||||
|
/// 相对种子根目录的路径(如 "sub/file.mkv")
|
||||||
|
pub path: String,
|
||||||
|
/// 文件大小(字节)
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
/// 下载任务
|
/// 下载任务
|
||||||
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct DownloadTask {
|
pub struct DownloadTask {
|
||||||
/// 任务 ID(自增 hex 字符串)
|
/// 任务 ID(自增 hex 字符串)
|
||||||
pub id: String,
|
pub id: String,
|
||||||
/// 下载地址
|
/// 下载地址(HTTP URL 或磁力链接)
|
||||||
pub url: String,
|
pub url: String,
|
||||||
/// 文件名
|
/// 文件名(HTTP:目标文件名;BT:种子名称)
|
||||||
pub filename: String,
|
pub filename: String,
|
||||||
/// 保存目录(绝对路径)
|
/// 保存目录(绝对路径)
|
||||||
pub dir: String,
|
pub dir: String,
|
||||||
|
/// 协议类型
|
||||||
|
#[serde(default)]
|
||||||
|
pub protocol: TaskProtocol,
|
||||||
|
/// BT 种子 infohash(协议=BitTorrent 时存在)
|
||||||
|
#[serde(default)]
|
||||||
|
pub info_hash: Option<String>,
|
||||||
|
/// BT 种子内文件列表(协议=BitTorrent 时存在)
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_files: Vec<BtFileInfo>,
|
||||||
|
/// BT 元数据是否已解析就绪(异步添加时:后台解析完成前为 false,调度器跳过)
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_metadata_ready: bool,
|
||||||
/// 状态
|
/// 状态
|
||||||
pub status: TaskStatus,
|
pub status: TaskStatus,
|
||||||
/// 文件总大小(字节),0=未知
|
/// 文件总大小(字节),0=未知
|
||||||
@@ -129,6 +175,21 @@ pub struct DownloaderSettings {
|
|||||||
/// 添加下载前检查重复(URL 或文件名重复时询问)
|
/// 添加下载前检查重复(URL 或文件名重复时询问)
|
||||||
#[serde(default = "default_true")]
|
#[serde(default = "default_true")]
|
||||||
pub check_duplicate: bool,
|
pub check_duplicate: bool,
|
||||||
|
/// 下载是否使用代理:true=尊重系统代理(mihomo 开启系统代理时经其转发),false=强制直连
|
||||||
|
#[serde(default = "default_true")]
|
||||||
|
pub use_proxy: bool,
|
||||||
|
/// BitTorrent 上传限速 KB/s(0=不限)
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_upload_limit_kb: u64,
|
||||||
|
/// BitTorrent 下载完成后是否继续做种上传(false=下载完即停止上传)
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_seed_after_download: bool,
|
||||||
|
/// BitTorrent 监听端口(0=自动选择)
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_listen_port: u16,
|
||||||
|
/// BitTorrent 使用代理下载:开启后自动使用代理模块(mihomo)的 SOCKS5 端口;代理不可用时降级直连
|
||||||
|
#[serde(default)]
|
||||||
|
pub bt_use_proxy: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_max_concurrent() -> u32 {
|
fn default_max_concurrent() -> u32 {
|
||||||
@@ -167,6 +228,11 @@ impl Default for DownloaderSettings {
|
|||||||
extension_secret: String::new(),
|
extension_secret: String::new(),
|
||||||
delete_files_on_remove: false,
|
delete_files_on_remove: false,
|
||||||
check_duplicate: true,
|
check_duplicate: true,
|
||||||
|
use_proxy: true,
|
||||||
|
bt_upload_limit_kb: 0,
|
||||||
|
bt_seed_after_download: false,
|
||||||
|
bt_listen_port: 0,
|
||||||
|
bt_use_proxy: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,477 @@
|
|||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{Arc, Mutex, RwLock};
|
||||||
|
|
||||||
|
// 会话字段专用 tokio 异步互斥(与 std 互斥区分开):
|
||||||
|
// 创建 Session 是 async 操作,必须持锁跨 await,否则"双重检查"在 await 期间失效,
|
||||||
|
// 并发首次添加 BT 任务可能各建一个全局会话,产生孤儿会话与跨会话无效句柄。
|
||||||
|
use tokio::sync::Mutex as AsyncMutex;
|
||||||
|
|
||||||
|
use librqbit::api::TorrentIdOrHash;
|
||||||
|
use librqbit::{AddTorrent, AddTorrentOptions, AddTorrentResponse, ManagedTorrent, Session};
|
||||||
|
|
||||||
|
use super::task::BtFileInfo;
|
||||||
|
|
||||||
|
/// 磁力元数据解析超时(秒):依赖 DHT/tracker 拉取,过短易误报,过长体验差
|
||||||
|
pub(crate) const INSPECT_TIMEOUT_SECS: u64 = 60;
|
||||||
|
|
||||||
|
/// 每日 tracker 同步源(XIU2/TrackersListCollection,官方新域名 cf.trackerslist.com)。
|
||||||
|
/// 注意:GitHub 仓库 raw 路径(raw.githubusercontent.com/...trackers_best.txt)已随项目
|
||||||
|
/// 迁移失效(404),不要再用 GitHub 代理镜像。以下为官方 Cloudflare 分发地址,
|
||||||
|
/// 国内直连通常可达,按顺序尝试、首个成功即用。
|
||||||
|
const TRACKER_SYNC_SOURCES: &[&str] = &[
|
||||||
|
"https://cf.trackerslist.com/best.txt",
|
||||||
|
"https://trackerslist.com/best.txt",
|
||||||
|
"https://cf.trackerslist.com/all.txt",
|
||||||
|
];
|
||||||
|
/// 动态 tracker 持久化文件与同步元数据
|
||||||
|
const TRACKERS_FILE: &str = "bt_trackers.txt";
|
||||||
|
const TRACKERS_META_FILE: &str = "bt_trackers_meta.json";
|
||||||
|
|
||||||
|
/// 常用公共 tracker:磁力链接本身可能只带很少 tracker,追加这些可提升解析成功率。
|
||||||
|
/// 混合 UDP/HTTP(S)/WebSocket,覆盖 UDP 被屏蔽但 HTTP 可用的网络环境。
|
||||||
|
pub const PUBLIC_TRACKERS: &[&str] = &[
|
||||||
|
// UDP
|
||||||
|
"udp://tracker.opentrackr.org:1337/announce",
|
||||||
|
"udp://open.tracker.cl:1337/announce",
|
||||||
|
"udp://tracker.openbittorrent.com:6969/announce",
|
||||||
|
"udp://tracker.torrent.eu.org:451/announce",
|
||||||
|
"udp://open.stealth.si:80/announce",
|
||||||
|
"udp://exodus.desync.com:6969/announce",
|
||||||
|
"udp://tracker.tiny-vps.com:6969/announce",
|
||||||
|
"udp://open.demonii.com:1337/announce",
|
||||||
|
"udp://tracker.moeking.me:6969/announce",
|
||||||
|
"udp://ipv4.tracker.harry.lu:80/announce",
|
||||||
|
"udp://explodie.org:6969/announce",
|
||||||
|
"udp://tracker.birkenfeld.ru:7496/announce",
|
||||||
|
"udp://tracker.pomf.se:80/announce",
|
||||||
|
"udp://tracker.tamersunion.org:6969/announce",
|
||||||
|
"udp://retracker.lanta-net.ru:2710/announce",
|
||||||
|
// HTTP(S)
|
||||||
|
"http://tracker.opentrackr.org:1337/announce",
|
||||||
|
"http://tracker.openbittorrent.com:80/announce",
|
||||||
|
"http://tracker1.itzmx.com:8080/announce",
|
||||||
|
"http://tracker4.itzmx.com:2710/announce",
|
||||||
|
"https://tracker.gbitt.info:443/announce",
|
||||||
|
"https://tracker.nanoha.org:443/announce",
|
||||||
|
"http://tracker.bt4g.com:2095/announce",
|
||||||
|
"http://tracker.gbitt.info:80/announce",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// 种子信息(inspect 解析结果,供命令返回给前端做文件勾选)
|
||||||
|
#[derive(Debug, Clone, serde::Serialize, specta::Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct TorrentInfo {
|
||||||
|
/// 种子名称
|
||||||
|
pub name: String,
|
||||||
|
/// infohash(hex 小写字符串)
|
||||||
|
pub info_hash: String,
|
||||||
|
/// 种子内全部文件总大小(字节)
|
||||||
|
pub total_size: u64,
|
||||||
|
/// 种子内文件列表
|
||||||
|
pub files: Vec<BtFileInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// BitTorrent 下载器:封装 librqbit 全局会话(多任务共享 DHT / 监听端口 / tracker 缓存)。
|
||||||
|
/// 会话懒创建:只有真正添加 BT 任务时才初始化,避免引擎启动即拉起 BT 内核。
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct TorrentDownloader {
|
||||||
|
/// 全局会话(懒创建;tokio 异步互斥保证并发首次添加只创建一个会话)
|
||||||
|
session: Arc<AsyncMutex<Option<Arc<Session>>>>,
|
||||||
|
/// 会话默认输出目录(每个任务用 AddTorrentOptions.output_folder 覆盖)
|
||||||
|
base_dir: PathBuf,
|
||||||
|
/// 上传限速 bytes/s(0=不限),per-torrent 应用
|
||||||
|
upload_limit_bps: Arc<std::sync::atomic::AtomicU64>,
|
||||||
|
/// 监听端口(0=自动)
|
||||||
|
listen_port: Arc<std::sync::atomic::AtomicU16>,
|
||||||
|
/// SOCKS5 代理地址(None=直连;来自代理模块,不可用时降级直连)
|
||||||
|
proxy_addr: Arc<Mutex<Option<String>>>,
|
||||||
|
/// 动态公共 tracker(每日从外部列表同步,叠加到内置列表)
|
||||||
|
dynamic_trackers: Arc<RwLock<Vec<String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TorrentDownloader {
|
||||||
|
pub fn new(base_dir: PathBuf) -> Self {
|
||||||
|
Self {
|
||||||
|
session: Arc::new(AsyncMutex::new(None)),
|
||||||
|
base_dir,
|
||||||
|
upload_limit_bps: Arc::new(std::sync::atomic::AtomicU64::new(0)),
|
||||||
|
listen_port: Arc::new(std::sync::atomic::AtomicU16::new(0)),
|
||||||
|
proxy_addr: Arc::new(Mutex::new(None)),
|
||||||
|
dynamic_trackers: Arc::new(RwLock::new(Vec::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新 BT 专属设置(上传限速 KB/s、监听端口、SOCKS5 代理地址)— 会话创建时生效
|
||||||
|
pub fn set_settings(&self, upload_limit_kb: u64, listen_port: u16, proxy_addr: Option<String>) {
|
||||||
|
self.upload_limit_bps
|
||||||
|
.store(upload_limit_kb.saturating_mul(1024), std::sync::atomic::Ordering::SeqCst);
|
||||||
|
self.listen_port
|
||||||
|
.store(listen_port, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
*self.proxy_addr.lock().unwrap_or_else(|e| e.into_inner()) = proxy_addr;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置动态 tracker(合并去重)
|
||||||
|
pub fn add_dynamic_trackers(&self, list: Vec<String>) {
|
||||||
|
if list.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut g = self.dynamic_trackers.write().unwrap_or_else(|e| e.into_inner());
|
||||||
|
for t in list {
|
||||||
|
let t = t.trim().to_string();
|
||||||
|
if !t.is_empty() && !g.contains(&t) {
|
||||||
|
g.push(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前动态 tracker 数量
|
||||||
|
pub fn dynamic_count(&self) -> usize {
|
||||||
|
self.dynamic_trackers.read().unwrap_or_else(|e| e.into_inner()).len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 合并内置 + 动态 tracker(去重),供 inspect / add_async 共用
|
||||||
|
fn build_trackers(&self) -> Vec<String> {
|
||||||
|
let dyn_trackers = self.dynamic_trackers.read().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
let mut trackers: Vec<String> = PUBLIC_TRACKERS.iter().map(|s| s.to_string()).collect();
|
||||||
|
for t in dyn_trackers {
|
||||||
|
if !trackers.contains(&t) {
|
||||||
|
trackers.push(t);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
trackers
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 每日同步动态 tracker:读取本地缓存 → 判断今天是否已同步 → 未同步则拉取更新。
|
||||||
|
/// 失败静默降级:保留上次成功的列表。
|
||||||
|
pub async fn sync_dynamic_trackers(&self, data_dir: &Path) {
|
||||||
|
fn parse_list(text: &str) -> Vec<String> {
|
||||||
|
text.lines()
|
||||||
|
.map(|l| l.trim())
|
||||||
|
.filter(|l| l.starts_with("http://") || l.starts_with("https://") || l.starts_with("udp://") || l.starts_with("ws://") || l.starts_with("wss://"))
|
||||||
|
.map(|l| l.to_string())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
let trackers_path = data_dir.join(TRACKERS_FILE);
|
||||||
|
let meta_path = data_dir.join(TRACKERS_META_FILE);
|
||||||
|
let today = chrono::Local::now().format("%Y-%m-%d").to_string();
|
||||||
|
|
||||||
|
// 1. 先加载上次成功保存的列表到内存(覆盖"重启后内存被清空")
|
||||||
|
if let Ok(s) = std::fs::read_to_string(&trackers_path) {
|
||||||
|
self.add_dynamic_trackers(parse_list(&s));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 今天已同步过则不再下载
|
||||||
|
if let Ok(meta) = std::fs::read_to_string(&meta_path) {
|
||||||
|
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&meta) {
|
||||||
|
if v.get("date").and_then(|d| d.as_str()) == Some(&today) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 依次尝试各镜像源(记录每个源的失败原因,便于判断是 DNS 还是连接超时)
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.timeout(std::time::Duration::from_secs(10))
|
||||||
|
.build()
|
||||||
|
.ok();
|
||||||
|
for url in TRACKER_SYNC_SOURCES {
|
||||||
|
let Some(c) = &client else { break };
|
||||||
|
match c.get(*url).send().await {
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源不可达 {}: {}", url, e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Ok(resp) => {
|
||||||
|
let text = match resp.text().await {
|
||||||
|
Ok(t) => t,
|
||||||
|
Err(e) => {
|
||||||
|
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源读取失败 {}: {}", url, e));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let list = parse_list(&text);
|
||||||
|
if list.is_empty() {
|
||||||
|
crate::logger::log_line("download", crate::logger::LogLevel::Debug, &format!("动态 tracker 源返回空列表 {}", url));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 保存列表与同步元数据
|
||||||
|
let _ = std::fs::write(&trackers_path, format!("{}\n", list.join("\n")));
|
||||||
|
let _ = std::fs::write(&meta_path, serde_json::json!({ "date": today }).to_string());
|
||||||
|
self.add_dynamic_trackers(list);
|
||||||
|
crate::logger::log_info("download", &format!("已同步动态 tracker(共 {} 条)", self.dynamic_count()));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
crate::logger::log_warn("download", "动态 tracker 全部同步源不可达,使用上次成功列表或内置列表(不影响磁力解析,公共 tracker 仍会生效)");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 会话级公共 tracker(HashSet<Url>,供 SessionOptions.trackers 使用)。
|
||||||
|
/// 注意:librqbit 对磁力链接只采用 magnet URL 自带的 tr= 参数,完全忽略
|
||||||
|
/// AddTorrentOptions.trackers(见 librqbit session.rs 的 magnet 分支),导致
|
||||||
|
/// 纯磁力(无自带 tr)解析元数据时 "trackers list is empty"。而会话级
|
||||||
|
/// SessionOptions.trackers 会在 make_peer_rx 中合并进每个种子(含磁力),
|
||||||
|
/// 因此必须放到这里才能让磁力链接真正带上公共 tracker。
|
||||||
|
fn session_trackers(&self) -> std::collections::HashSet<url::Url> {
|
||||||
|
self.build_trackers()
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|t| url::Url::parse(&t).ok())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取或创建全局会话。
|
||||||
|
/// 持 tokio 互斥锁覆盖整个构造过程:并发调用在此串行化,
|
||||||
|
/// 先进入者创建并写入,后续者锁内二次检查直接复用(避免多会话竞态)。
|
||||||
|
/// 开启代理时先尝试用代理初始化;失败则降级为直连(记录下来供 add 重试判断)。
|
||||||
|
async fn get_session(&self) -> Result<Arc<Session>, String> {
|
||||||
|
let mut guard = self.session.lock().await;
|
||||||
|
if let Some(s) = guard.as_ref() {
|
||||||
|
return Ok(s.clone());
|
||||||
|
}
|
||||||
|
let _ = std::fs::create_dir_all(&self.base_dir);
|
||||||
|
let port = self.listen_port.load(std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let proxy = self.proxy_addr.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
let connect_opt = proxy.as_ref().map(|p| librqbit::ConnectionOptions { proxy_url: Some(p.clone()), ..Default::default() });
|
||||||
|
let had_proxy = connect_opt.is_some();
|
||||||
|
|
||||||
|
// 构造带代理(若启用)+ 监听端口 + 会话级公共 tracker 的会话选项
|
||||||
|
let mut opts = lib_session_options();
|
||||||
|
opts.trackers = self.session_trackers();
|
||||||
|
if connect_opt.is_some() {
|
||||||
|
opts.connect = connect_opt;
|
||||||
|
}
|
||||||
|
if port > 0 {
|
||||||
|
if let Ok(addr) = format!("0.0.0.0:{}", port).parse::<std::net::SocketAddr>() {
|
||||||
|
opts.listen = Some(librqbit::ListenerOptions {
|
||||||
|
listen_addr: addr,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
crate::logger::log_error("download", &format!("BT 监听端口 {} 无效,使用自动端口", port));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 尝试创建会话:先按配置(可能带代理),失败且有代理则降级直连重试
|
||||||
|
let s = match Session::new_with_opts(self.base_dir.clone(), opts).await {
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(e) => {
|
||||||
|
if had_proxy {
|
||||||
|
crate::logger::log_error("download", &format!("BT 代理会话初始化失败({}),降级为直连", e));
|
||||||
|
let mut m = lib_session_options();
|
||||||
|
m.trackers = self.session_trackers();
|
||||||
|
if port > 0 {
|
||||||
|
if let Ok(addr) = format!("0.0.0.0:{}", port).parse::<std::net::SocketAddr>() {
|
||||||
|
m.listen = Some(librqbit::ListenerOptions { listen_addr: addr, ..Default::default() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Session::new_with_opts(self.base_dir.clone(), m).await.map_err(|e2| format!("初始化 BitTorrent 会话失败: {}", e2))?
|
||||||
|
} else {
|
||||||
|
return Err(format!("初始化 BitTorrent 会话失败: {}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
*guard = Some(s.clone());
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 解析磁力链 / 本地 .torrent 文件,返回种子信息(不开始下载)。
|
||||||
|
/// list_only 模式:仅获取元数据,不加入会话,因此不影响后续真正添加。
|
||||||
|
/// 磁力元数据依赖 DHT/tracker 拉取,无超时会永久等待,故加超时。
|
||||||
|
pub async fn inspect(&self, input: &str) -> Result<TorrentInfo, String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
let trackers = self.build_trackers();
|
||||||
|
// 磁力:需从网络拉取元数据,可能较慢(取决于种子热度与网络连通性);
|
||||||
|
// 本地 .torrent / http(s) .torrent URL:元数据在文件内,from_cli_argument 会读取/下载并解析
|
||||||
|
let add = AddTorrent::from_cli_argument(input).map_err(|e| format!("无效的种子输入: {}", e))?;
|
||||||
|
let add_fut = session.add_torrent(
|
||||||
|
add,
|
||||||
|
Some(AddTorrentOptions {
|
||||||
|
list_only: true,
|
||||||
|
trackers: Some(trackers),
|
||||||
|
..Default::default()
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let resp = tokio::time::timeout(std::time::Duration::from_secs(INSPECT_TIMEOUT_SECS), add_fut)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "解析磁力元数据超时:未能从 DHT/Tracker 获取种子信息,请确认种子有做种源或网络可直连 BT".to_string())?
|
||||||
|
.map_err(|e| format!("解析种子失败: {}", e))?;
|
||||||
|
|
||||||
|
let AddTorrentResponse::ListOnly(lo) = resp else {
|
||||||
|
return Err("该链接未返回有效的种子元数据".to_string());
|
||||||
|
};
|
||||||
|
|
||||||
|
let info = lo.info.info();
|
||||||
|
let name = info
|
||||||
|
.name
|
||||||
|
.as_ref()
|
||||||
|
.map(|b| String::from_utf8_lossy(b.as_ref()).into_owned())
|
||||||
|
.or_else(|| lo.info.name().map(|c| c.to_string()))
|
||||||
|
.unwrap_or_else(|| "未命名种子".to_string());
|
||||||
|
|
||||||
|
let mut files = Vec::new();
|
||||||
|
let mut total_size = 0u64;
|
||||||
|
if let Some(fs) = &info.files {
|
||||||
|
for (i, f) in fs.iter().enumerate() {
|
||||||
|
let path = f
|
||||||
|
.path
|
||||||
|
.iter()
|
||||||
|
.map(|p| String::from_utf8_lossy(p.as_ref()).into_owned())
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("/");
|
||||||
|
files.push(BtFileInfo {
|
||||||
|
index: i as u32,
|
||||||
|
path,
|
||||||
|
size: f.length,
|
||||||
|
});
|
||||||
|
total_size += f.length;
|
||||||
|
}
|
||||||
|
} else if let Some(len) = info.length {
|
||||||
|
// 单文件种子
|
||||||
|
files.push(BtFileInfo {
|
||||||
|
index: 0,
|
||||||
|
path: name.clone(),
|
||||||
|
size: len,
|
||||||
|
});
|
||||||
|
total_size = len;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(TorrentInfo {
|
||||||
|
name,
|
||||||
|
info_hash: hex_encode(&lo.info_hash.0),
|
||||||
|
total_size,
|
||||||
|
files,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 异步添加种子:立即返回句柄(不等待元数据),由调用方后台解析。
|
||||||
|
/// 附加公共 tracker 提升磁力元数据解析成功率;上传限速 per-torrent 应用。
|
||||||
|
pub async fn add_async(
|
||||||
|
&self,
|
||||||
|
input: &str,
|
||||||
|
output_dir: &str,
|
||||||
|
) -> Result<(usize, Arc<ManagedTorrent>), String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
std::fs::create_dir_all(output_dir).map_err(|e| format!("创建下载目录失败: {}", e))?;
|
||||||
|
let up = self.upload_limit_bps.load(std::sync::atomic::Ordering::SeqCst);
|
||||||
|
let upload_bps = std::num::NonZeroU32::new(up.min(u32::MAX as u64) as u32);
|
||||||
|
let trackers = self.build_trackers();
|
||||||
|
let opts = AddTorrentOptions {
|
||||||
|
paused: true,
|
||||||
|
output_folder: Some(output_dir.to_string()),
|
||||||
|
overwrite: true,
|
||||||
|
trackers: Some(trackers),
|
||||||
|
ratelimits: librqbit::limits::LimitsConfig {
|
||||||
|
upload_bps,
|
||||||
|
download_bps: None,
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let add = AddTorrent::from_cli_argument(input).map_err(|e| format!("无效的种子输入: {}", e))?;
|
||||||
|
let resp = session
|
||||||
|
.add_torrent(add, Some(opts))
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("添加种子失败: {}", e))?;
|
||||||
|
match resp {
|
||||||
|
AddTorrentResponse::Added(id, handle) => Ok((id, handle)),
|
||||||
|
AddTorrentResponse::AlreadyManaged(id, handle) => Ok((id, handle)),
|
||||||
|
_ => Err("种子已存在或元数据无效".to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 等待种子元数据初始化就绪(磁力需要从网络拉取,带超时)
|
||||||
|
pub async fn wait_initialized(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||||
|
tokio::time::timeout(
|
||||||
|
std::time::Duration::from_secs(INSPECT_TIMEOUT_SECS),
|
||||||
|
handle.wait_until_initialized(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "解析磁力元数据超时:未能从 DHT/Tracker 获取种子信息,请确认种子有做种源或网络可直连 BT".to_string())?
|
||||||
|
.map_err(|e| format!("获取种子元数据失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置要下载的种子文件子集(用户文件勾选;传全部索引则全选)
|
||||||
|
pub async fn set_only_files(&self, handle: &Arc<ManagedTorrent>, files: &[u32]) -> Result<(), String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
let set: std::collections::HashSet<usize> = files.iter().map(|&i| i as usize).collect();
|
||||||
|
session
|
||||||
|
.update_only_files(handle, &set)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("设置下载文件失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取句柄当前进度:返回 (已下载字节, 总字节, 每文件已下载字节)
|
||||||
|
/// `file_progress` 与种子文件一一对应,供前端详情页展示单文件进度。
|
||||||
|
pub fn progress_full(handle: &Arc<ManagedTorrent>) -> (u64, u64, Vec<u64>) {
|
||||||
|
let s = handle.stats();
|
||||||
|
(s.progress_bytes, s.total_bytes, s.file_progress.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 暂停种子(下载中的连接会停止,已下载片段保留,可继续)
|
||||||
|
pub async fn pause(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
session
|
||||||
|
.pause(handle)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("暂停种子失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 继续种子(幂等):恢复已暂停的种子。
|
||||||
|
/// 若种子本已处于 Live(例如 select_bt_files 的 set_only_files 内部已恢复过、
|
||||||
|
/// 或暂停期间被其他逻辑恢复),直接视为成功,避免 librqbit 报 "torrent is already live"
|
||||||
|
/// 而导致 pause→resume 链路被误判为失败。
|
||||||
|
pub async fn unpause(&self, handle: &Arc<ManagedTorrent>) -> Result<(), String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
match handle.stats().state {
|
||||||
|
librqbit::TorrentStatsState::Live => Ok(()),
|
||||||
|
librqbit::TorrentStatsState::Error => Err("种子处于错误状态,无法继续".to_string()),
|
||||||
|
librqbit::TorrentStatsState::Paused
|
||||||
|
| librqbit::TorrentStatsState::Initializing { .. } => session
|
||||||
|
.unpause(handle)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("继续种子失败: {}", e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 删除种子(info_hash 为 hex 字符串;delete_files 是否同时删除已下载文件)
|
||||||
|
pub async fn delete(&self, info_hash: &str, delete_files: bool) -> Result<(), String> {
|
||||||
|
let session = self.get_session().await?;
|
||||||
|
let id = TorrentIdOrHash::parse(info_hash)
|
||||||
|
.map_err(|_| format!("无效的 infohash: {}", info_hash))?;
|
||||||
|
session
|
||||||
|
.delete(id, delete_files)
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("删除种子失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取句柄当前下载进度 (已下载字节, 总字节)
|
||||||
|
pub fn progress(handle: &Arc<ManagedTorrent>) -> (u64, u64) {
|
||||||
|
let s = handle.stats();
|
||||||
|
(s.progress_bytes, s.total_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 停止全局会话(应用退出时调用)
|
||||||
|
pub async fn stop(&self) {
|
||||||
|
let session = {
|
||||||
|
let mut guard = self.session.lock().await;
|
||||||
|
guard.take()
|
||||||
|
};
|
||||||
|
if let Some(s) = session {
|
||||||
|
let _ = s.stop().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 字节数组转小写十六进制字符串(librqbit 的 Id 未实现 Display)
|
||||||
|
pub(crate) fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
|
for &b in bytes {
|
||||||
|
out.push(HEX[(b >> 4) as usize] as char);
|
||||||
|
out.push(HEX[(b & 0x0f) as usize] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 默认会话选项(后续如需新增 DHT/缓存等可在此统一配置)
|
||||||
|
fn lib_session_options() -> librqbit::SessionOptions {
|
||||||
|
librqbit::SessionOptions::default()
|
||||||
|
}
|
||||||
+114
-52
@@ -15,34 +15,36 @@ mod setup;
|
|||||||
mod shortcut;
|
mod shortcut;
|
||||||
mod snap_fix;
|
mod snap_fix;
|
||||||
mod tray_menu;
|
mod tray_menu;
|
||||||
|
mod updater;
|
||||||
mod win32_util;
|
mod win32_util;
|
||||||
|
|
||||||
use download_engine::{
|
use download_engine::{
|
||||||
DownloadEngine,
|
DownloadEngine,
|
||||||
downloader_add_task, downloader_check_url, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks,
|
downloader_add_task, downloader_cancel_task, downloader_check_url, downloader_focus_window, downloader_get_extension_info, downloader_get_settings, downloader_get_tasks, downloader_inspect, downloader_select_bt_files,
|
||||||
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_remove_task,
|
downloader_open_dir, downloader_open_url, downloader_pause_task, downloader_redownload, downloader_remove_task,
|
||||||
downloader_resume_task, downloader_save_settings, downloader_status,
|
downloader_resume_task, downloader_save_settings, downloader_status,
|
||||||
};
|
};
|
||||||
use logger::{
|
use logger::{
|
||||||
log_clear, log_info_state, log_list, log_message,
|
log_clear, log_info_state, log_list, log_message,
|
||||||
};
|
};
|
||||||
use mihomo_manager::{
|
use mihomo_manager::{
|
||||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy, proxy_close_connection, proxy_delete_profile,
|
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||||
proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
||||||
proxy_import_profile, proxy_install_kernel, proxy_kernel_info, proxy_patch_configs, proxy_restart, proxy_save_settings,
|
proxy_import_profile, proxy_kernel_info, proxy_patch_configs, proxy_restart, proxy_save_settings,
|
||||||
proxy_select_proxy, proxy_set_system_proxy, proxy_start, proxy_status, proxy_stop,
|
proxy_select_proxy, proxy_set_system_proxy, proxy_start, proxy_status, proxy_stop, proxy_traffic,
|
||||||
proxy_test_delay, proxy_update_kernel, proxy_update_profile, proxy_version, MihomoManager,
|
proxy_test_delay, proxy_update_profile, proxy_version, MihomoManager,
|
||||||
};
|
};
|
||||||
use monitor_kernel::{
|
use monitor_kernel::{
|
||||||
monitor_elevate_self, monitor_get_elevate_on_launch, monitor_get_hardware_config,
|
monitor_elevate_self, monitor_get_auto_start, monitor_get_elevate_on_launch,
|
||||||
monitor_get_snapshot, monitor_get_status, monitor_kernel_info, monitor_set_elevate_on_launch,
|
monitor_get_hardware_config, monitor_get_snapshot, monitor_get_status, monitor_kernel_info,
|
||||||
monitor_set_hardware_config, monitor_start, monitor_start_elevated, monitor_status,
|
monitor_set_auto_start, monitor_set_elevate_on_launch, monitor_set_hardware_config,
|
||||||
monitor_stop, MonitorKernel,
|
monitor_start, monitor_start_elevated, monitor_status, monitor_stop, MonitorKernel,
|
||||||
};
|
};
|
||||||
use network_monitor::network_status;
|
use network_monitor::network_status;
|
||||||
use osd_window::{
|
use osd_window::{
|
||||||
osd_apply_overlay_style, osd_begin_drag, osd_set_click_through, osd_set_topmost,
|
osd_apply_overlay_style, osd_begin_drag, osd_set_bounds, osd_set_click_through,
|
||||||
osd_start_drag_watch, osd_start_topmost_watch, osd_stop_watch,
|
osd_set_topmost, osd_start_drag_watch, osd_start_game_watch, osd_start_topmost_watch,
|
||||||
|
osd_stop_watch,
|
||||||
};
|
};
|
||||||
use process_manager::{
|
use process_manager::{
|
||||||
process_all_status, process_start, process_status,
|
process_all_status, process_start, process_status,
|
||||||
@@ -54,28 +56,39 @@ use screenshot::commands::{
|
|||||||
screenshot_crop_stored, screenshot_cursor_pos, screenshot_delete_cache,
|
screenshot_crop_stored, screenshot_cursor_pos, screenshot_delete_cache,
|
||||||
screenshot_disable_transitions, screenshot_enum_windows, screenshot_fullscreen_png,
|
screenshot_disable_transitions, screenshot_enum_windows, screenshot_fullscreen_png,
|
||||||
screenshot_get_editor_image, screenshot_get_fullscreen_bmp, screenshot_load_cache,
|
screenshot_get_editor_image, screenshot_get_fullscreen_bmp, screenshot_load_cache,
|
||||||
screenshot_register_shortcut, screenshot_save_cache, screenshot_save_png,
|
screenshot_load_cache_raw, screenshot_pick_list, screenshot_register_pin_shortcut,
|
||||||
screenshot_set_editor_image, screenshot_unregister_shortcut, screenshot_window_from_point,
|
screenshot_register_shortcut,
|
||||||
|
screenshot_save_cache, screenshot_save_png, screenshot_set_editor_image,
|
||||||
|
screenshot_show_overlay, screenshot_unregister_pin_shortcut,
|
||||||
|
screenshot_unregister_shortcut,
|
||||||
};
|
};
|
||||||
use clipboard::{
|
use clipboard::{
|
||||||
ClipboardManager,
|
ClipboardManager,
|
||||||
clipboard_clear, clipboard_copy_back, clipboard_count, clipboard_delete, clipboard_get_history,
|
clipboard_clear, clipboard_copy_back, clipboard_count, clipboard_delete, clipboard_get_history,
|
||||||
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_hide_popup,
|
clipboard_get_item, clipboard_get_pinned, clipboard_get_settings, clipboard_get_thumb,
|
||||||
clipboard_paste_to_target, clipboard_register_shortcut, clipboard_save_settings, clipboard_search,
|
clipboard_hide_popup, clipboard_hide_preview, clipboard_paste_to_target,
|
||||||
clipboard_set_pinned, clipboard_show_popup, clipboard_show_window, clipboard_start,
|
clipboard_preview_interacted, clipboard_register_shortcut,
|
||||||
|
clipboard_reveal_preview,
|
||||||
|
clipboard_save_settings, clipboard_search, clipboard_set_pinned, clipboard_resize_preview,
|
||||||
|
clipboard_show_popup, clipboard_show_preview, clipboard_show_window, clipboard_start,
|
||||||
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
clipboard_status, clipboard_stop, clipboard_unregister_shortcut,
|
||||||
};
|
};
|
||||||
use quickpanel::{
|
use quickpanel::{
|
||||||
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_build_file_index,
|
||||||
|
quickpanel_clear_app_icon_cache, quickpanel_delete_file, quickpanel_delete_files,
|
||||||
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
||||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
||||||
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
|
quickpanel_list_archives, quickpanel_list_dir, quickpanel_lock_screen, quickpanel_open_file,
|
||||||
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
|
quickpanel_open_special, quickpanel_preview_rename, quickpanel_register_shortcut,
|
||||||
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
|
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||||
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
|
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||||
quickpanel_unregister_shortcut,
|
quickpanel_show_window, quickpanel_unregister_shortcut, quickpanel_focus_main_window,
|
||||||
};
|
};
|
||||||
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
|
use tray_menu::{tray_menu_action, tray_menu_hide, tray_menu_ready};
|
||||||
|
use updater::{
|
||||||
|
app_version, update_check, update_install, update_thinghk_apply, update_thinghk_cancel,
|
||||||
|
update_thinghk_confirm, ThinghkUpdateState,
|
||||||
|
};
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
fn quit_app(app: tauri::AppHandle) {
|
fn quit_app(app: tauri::AppHandle) {
|
||||||
@@ -100,13 +113,16 @@ fn export_bindings() {
|
|||||||
// 生成命令失败时直接 throw,与原生 invoke 一致,前端无需解包 helper
|
// 生成命令失败时直接 throw,与原生 invoke 一致,前端无需解包 helper
|
||||||
.error_handling(ErrorHandlingMode::Throw)
|
.error_handling(ErrorHandlingMode::Throw)
|
||||||
.commands(collect_commands![
|
.commands(collect_commands![
|
||||||
|
// 应用更新(6)
|
||||||
|
app_version, update_check, update_install, update_thinghk_apply,
|
||||||
|
update_thinghk_confirm, update_thinghk_cancel,
|
||||||
// proxy(20)
|
// proxy(20)
|
||||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy,
|
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||||
proxy_close_connection, proxy_delete_profile, proxy_get_settings,
|
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_settings,
|
||||||
proxy_get_system_proxy, proxy_import_profile, proxy_install_kernel,
|
proxy_get_system_proxy, proxy_import_profile, proxy_kernel_info,
|
||||||
proxy_kernel_info, proxy_restart, proxy_save_settings,
|
proxy_restart, proxy_save_settings,
|
||||||
proxy_select_proxy, proxy_set_system_proxy, proxy_start, proxy_status, proxy_stop,
|
proxy_select_proxy, proxy_set_system_proxy, proxy_start, proxy_status, proxy_stop, proxy_traffic,
|
||||||
proxy_test_delay, proxy_update_kernel, proxy_update_profile,
|
proxy_test_delay, proxy_update_profile,
|
||||||
// quickpanel(22)
|
// quickpanel(22)
|
||||||
quickpanel_get_settings, quickpanel_save_settings, quickpanel_register_shortcut,
|
quickpanel_get_settings, quickpanel_save_settings, quickpanel_register_shortcut,
|
||||||
quickpanel_unregister_shortcut, quickpanel_show_popup, quickpanel_hide_popup,
|
quickpanel_unregister_shortcut, quickpanel_show_popup, quickpanel_hide_popup,
|
||||||
@@ -115,25 +131,30 @@ fn export_bindings() {
|
|||||||
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
quickpanel_scan_apps, quickpanel_get_app_icon, quickpanel_clear_app_icon_cache,
|
||||||
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
|
quickpanel_reveal_in_explorer, quickpanel_open_file, quickpanel_get_special_locations,
|
||||||
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
quickpanel_open_special, quickpanel_delete_file, quickpanel_run_custom_command,
|
||||||
quickpanel_run_system_command,
|
quickpanel_run_system_command, quickpanel_list_archives, quickpanel_list_dir,
|
||||||
// clipboard(20)
|
quickpanel_batch_extract, quickpanel_preview_rename, quickpanel_apply_rename,
|
||||||
|
quickpanel_delete_files, quickpanel_focus_main_window,
|
||||||
|
// clipboard(23)
|
||||||
clipboard_get_history, clipboard_get_pinned, clipboard_search, clipboard_get_item,
|
clipboard_get_history, clipboard_get_pinned, clipboard_search, clipboard_get_item,
|
||||||
clipboard_set_pinned, clipboard_delete, clipboard_clear, clipboard_copy_back,
|
clipboard_get_thumb, clipboard_set_pinned, clipboard_delete, clipboard_clear,
|
||||||
clipboard_count, clipboard_get_settings, clipboard_save_settings, clipboard_status,
|
clipboard_copy_back, clipboard_count, clipboard_get_settings, clipboard_save_settings,
|
||||||
clipboard_start, clipboard_stop, clipboard_register_shortcut,
|
clipboard_status, clipboard_start, clipboard_stop, clipboard_register_shortcut,
|
||||||
clipboard_unregister_shortcut, clipboard_show_popup, clipboard_hide_popup,
|
clipboard_unregister_shortcut, clipboard_show_popup, clipboard_hide_popup,
|
||||||
clipboard_show_window, clipboard_paste_to_target,
|
clipboard_show_window, clipboard_paste_to_target, clipboard_show_preview,
|
||||||
|
clipboard_hide_preview, clipboard_resize_preview, clipboard_reveal_preview,
|
||||||
|
clipboard_preview_interacted,
|
||||||
// download_engine(10,豁免 2)
|
// download_engine(10,豁免 2)
|
||||||
downloader_get_tasks, downloader_check_url, downloader_add_task, downloader_pause_task,
|
downloader_get_tasks, downloader_check_url, downloader_add_task, downloader_pause_task,
|
||||||
downloader_resume_task, downloader_remove_task, downloader_get_settings,
|
downloader_resume_task, downloader_cancel_task, downloader_redownload, downloader_remove_task, downloader_get_settings,
|
||||||
downloader_save_settings, downloader_open_dir, downloader_open_url,
|
downloader_save_settings, downloader_open_dir, downloader_open_url, downloader_focus_window, downloader_inspect, downloader_select_bt_files,
|
||||||
// screenshot(19,豁免 2:get_fullscreen_bmp 返回 ipc::Response、compose_copy 接收 ipc::Request)
|
// screenshot(22,豁免 3:get_fullscreen_bmp / load_cache_raw 返回 ipc::Response、compose_copy 接收 ipc::Request)
|
||||||
screenshot_disable_transitions, screenshot_register_shortcut,
|
screenshot_disable_transitions, screenshot_show_overlay, screenshot_register_shortcut,
|
||||||
screenshot_unregister_shortcut, screenshot_capture_fullscreen, screenshot_fullscreen_png,
|
screenshot_unregister_shortcut, screenshot_register_pin_shortcut,
|
||||||
screenshot_clear_fullscreen, screenshot_crop_stored, screenshot_crop_copy_stored,
|
screenshot_unregister_pin_shortcut, screenshot_capture_fullscreen,
|
||||||
screenshot_window_from_point, screenshot_cursor_pos, screenshot_enum_windows,
|
screenshot_fullscreen_png, screenshot_clear_fullscreen, screenshot_crop_stored,
|
||||||
screenshot_capture_window, screenshot_set_editor_image, screenshot_get_editor_image,
|
screenshot_crop_copy_stored, screenshot_pick_list, screenshot_cursor_pos,
|
||||||
screenshot_copy_image, screenshot_save_png,
|
screenshot_enum_windows, screenshot_capture_window, screenshot_set_editor_image,
|
||||||
|
screenshot_get_editor_image, screenshot_copy_image, screenshot_save_png,
|
||||||
screenshot_save_cache, screenshot_load_cache, screenshot_delete_cache,
|
screenshot_save_cache, screenshot_load_cache, screenshot_delete_cache,
|
||||||
])
|
])
|
||||||
.export(Typescript::default(), "../src/lib/bindings.ts")
|
.export(Typescript::default(), "../src/lib/bindings.ts")
|
||||||
@@ -159,8 +180,15 @@ pub fn run() {
|
|||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
.manage(ProcessManager::new())
|
.manage(ProcessManager::new())
|
||||||
|
.manage(ThinghkUpdateState::new())
|
||||||
.invoke_handler(tauri::generate_handler![
|
.invoke_handler(tauri::generate_handler![
|
||||||
quit_app,
|
quit_app,
|
||||||
|
app_version,
|
||||||
|
update_check,
|
||||||
|
update_install,
|
||||||
|
update_thinghk_apply,
|
||||||
|
update_thinghk_confirm,
|
||||||
|
update_thinghk_cancel,
|
||||||
process_start,
|
process_start,
|
||||||
process_stop,
|
process_stop,
|
||||||
process_status,
|
process_status,
|
||||||
@@ -174,11 +202,13 @@ pub fn run() {
|
|||||||
proxy_save_settings,
|
proxy_save_settings,
|
||||||
proxy_kernel_info,
|
proxy_kernel_info,
|
||||||
proxy_check_kernel_update,
|
proxy_check_kernel_update,
|
||||||
proxy_update_kernel,
|
proxy_apply_kernel_update,
|
||||||
proxy_install_kernel,
|
proxy_cancel_kernel_install,
|
||||||
|
proxy_confirm_install,
|
||||||
proxy_status,
|
proxy_status,
|
||||||
proxy_start,
|
proxy_start,
|
||||||
proxy_stop,
|
proxy_stop,
|
||||||
|
proxy_traffic,
|
||||||
proxy_restart,
|
proxy_restart,
|
||||||
proxy_version,
|
proxy_version,
|
||||||
proxy_get_proxies,
|
proxy_get_proxies,
|
||||||
@@ -204,21 +234,27 @@ pub fn run() {
|
|||||||
monitor_get_snapshot,
|
monitor_get_snapshot,
|
||||||
monitor_get_elevate_on_launch,
|
monitor_get_elevate_on_launch,
|
||||||
monitor_set_elevate_on_launch,
|
monitor_set_elevate_on_launch,
|
||||||
|
monitor_get_auto_start,
|
||||||
|
monitor_set_auto_start,
|
||||||
monitor_get_hardware_config,
|
monitor_get_hardware_config,
|
||||||
monitor_set_hardware_config,
|
monitor_set_hardware_config,
|
||||||
network_status,
|
network_status,
|
||||||
osd_apply_overlay_style,
|
osd_apply_overlay_style,
|
||||||
osd_begin_drag,
|
osd_begin_drag,
|
||||||
|
osd_set_bounds,
|
||||||
osd_set_click_through,
|
osd_set_click_through,
|
||||||
osd_set_topmost,
|
osd_set_topmost,
|
||||||
osd_start_drag_watch,
|
osd_start_drag_watch,
|
||||||
osd_start_topmost_watch,
|
osd_start_topmost_watch,
|
||||||
|
osd_start_game_watch,
|
||||||
osd_stop_watch,
|
osd_stop_watch,
|
||||||
downloader_get_tasks,
|
downloader_get_tasks,
|
||||||
downloader_add_task,
|
downloader_add_task,
|
||||||
downloader_check_url,
|
downloader_check_url,
|
||||||
downloader_pause_task,
|
downloader_pause_task,
|
||||||
downloader_resume_task,
|
downloader_resume_task,
|
||||||
|
downloader_cancel_task,
|
||||||
|
downloader_redownload,
|
||||||
downloader_remove_task,
|
downloader_remove_task,
|
||||||
downloader_get_settings,
|
downloader_get_settings,
|
||||||
downloader_save_settings,
|
downloader_save_settings,
|
||||||
@@ -226,10 +262,14 @@ pub fn run() {
|
|||||||
downloader_get_extension_info,
|
downloader_get_extension_info,
|
||||||
downloader_open_dir,
|
downloader_open_dir,
|
||||||
downloader_open_url,
|
downloader_open_url,
|
||||||
|
downloader_focus_window,
|
||||||
|
downloader_inspect,
|
||||||
|
downloader_select_bt_files,
|
||||||
clipboard_get_history,
|
clipboard_get_history,
|
||||||
clipboard_get_pinned,
|
clipboard_get_pinned,
|
||||||
clipboard_search,
|
clipboard_search,
|
||||||
clipboard_get_item,
|
clipboard_get_item,
|
||||||
|
clipboard_get_thumb,
|
||||||
clipboard_set_pinned,
|
clipboard_set_pinned,
|
||||||
clipboard_delete,
|
clipboard_delete,
|
||||||
clipboard_clear,
|
clipboard_clear,
|
||||||
@@ -246,6 +286,11 @@ pub fn run() {
|
|||||||
clipboard_show_window,
|
clipboard_show_window,
|
||||||
clipboard_hide_popup,
|
clipboard_hide_popup,
|
||||||
clipboard_paste_to_target,
|
clipboard_paste_to_target,
|
||||||
|
clipboard_show_preview,
|
||||||
|
clipboard_hide_preview,
|
||||||
|
clipboard_resize_preview,
|
||||||
|
clipboard_reveal_preview,
|
||||||
|
clipboard_preview_interacted,
|
||||||
quickpanel_get_settings,
|
quickpanel_get_settings,
|
||||||
quickpanel_save_settings,
|
quickpanel_save_settings,
|
||||||
quickpanel_register_shortcut,
|
quickpanel_register_shortcut,
|
||||||
@@ -264,10 +309,17 @@ pub fn run() {
|
|||||||
quickpanel_reveal_in_explorer,
|
quickpanel_reveal_in_explorer,
|
||||||
quickpanel_open_file,
|
quickpanel_open_file,
|
||||||
quickpanel_delete_file,
|
quickpanel_delete_file,
|
||||||
|
quickpanel_delete_files,
|
||||||
quickpanel_run_custom_command,
|
quickpanel_run_custom_command,
|
||||||
quickpanel_run_system_command,
|
quickpanel_run_system_command,
|
||||||
quickpanel_get_special_locations,
|
quickpanel_get_special_locations,
|
||||||
quickpanel_open_special,
|
quickpanel_open_special,
|
||||||
|
quickpanel_list_archives,
|
||||||
|
quickpanel_list_dir,
|
||||||
|
quickpanel_batch_extract,
|
||||||
|
quickpanel_preview_rename,
|
||||||
|
quickpanel_apply_rename,
|
||||||
|
quickpanel_focus_main_window,
|
||||||
tray_menu_action,
|
tray_menu_action,
|
||||||
tray_menu_hide,
|
tray_menu_hide,
|
||||||
tray_menu_ready,
|
tray_menu_ready,
|
||||||
@@ -278,7 +330,8 @@ pub fn run() {
|
|||||||
screenshot_clear_fullscreen,
|
screenshot_clear_fullscreen,
|
||||||
screenshot_crop_stored,
|
screenshot_crop_stored,
|
||||||
screenshot_crop_copy_stored,
|
screenshot_crop_copy_stored,
|
||||||
screenshot_window_from_point,
|
screenshot_pick_list,
|
||||||
|
screenshot_show_overlay,
|
||||||
screenshot_cursor_pos,
|
screenshot_cursor_pos,
|
||||||
screenshot_enum_windows,
|
screenshot_enum_windows,
|
||||||
screenshot_capture_window,
|
screenshot_capture_window,
|
||||||
@@ -288,18 +341,25 @@ pub fn run() {
|
|||||||
screenshot_save_png,
|
screenshot_save_png,
|
||||||
screenshot_save_cache,
|
screenshot_save_cache,
|
||||||
screenshot_load_cache,
|
screenshot_load_cache,
|
||||||
|
screenshot_load_cache_raw,
|
||||||
screenshot_delete_cache,
|
screenshot_delete_cache,
|
||||||
screenshot_register_shortcut,
|
screenshot_register_shortcut,
|
||||||
screenshot_unregister_shortcut,
|
screenshot_unregister_shortcut,
|
||||||
|
screenshot_register_pin_shortcut,
|
||||||
|
screenshot_unregister_pin_shortcut,
|
||||||
screenshot_disable_transitions,
|
screenshot_disable_transitions,
|
||||||
screenshot_compose_copy
|
screenshot_compose_copy
|
||||||
])
|
])
|
||||||
.setup(setup::init)
|
.setup(setup::init)
|
||||||
.on_window_event(|window, event| {
|
.on_window_event(|window, event| {
|
||||||
|
// 仅主窗口拦截关闭(隐藏到托盘)。其他窗口(截图编辑器/OSD 等)
|
||||||
|
// 调用 close() 是真实销毁语义,全局拦截会导致隐藏窗口累积泄漏。
|
||||||
|
if window.label() == constants::windows::MAIN {
|
||||||
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
||||||
window.hide().ok();
|
window.hide().ok();
|
||||||
api.prevent_close();
|
api.prevent_close();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.build(tauri::generate_context!())
|
.build(tauri::generate_context!())
|
||||||
.expect("error while building tauri application")
|
.expect("error while building tauri application")
|
||||||
@@ -313,16 +373,18 @@ pub fn run() {
|
|||||||
}
|
}
|
||||||
if let Some(monitor) = app.try_state::<MonitorKernel>() {
|
if let Some(monitor) = app.try_state::<MonitorKernel>() {
|
||||||
// cleanup_on_exit 是 async;在事件循环回调中直接 block_on 有 panic 风险且阻塞退出,
|
// cleanup_on_exit 是 async;在事件循环回调中直接 block_on 有 panic 风险且阻塞退出,
|
||||||
// 放到独立 OS 线程执行并限时等待(与托盘旧实现同模式)。
|
// 放到独立 OS 线程执行并通过 channel 限时等待 3s,超时放弃等待直接退出
|
||||||
|
// (进程终止时 OS 回收残留资源),避免清理挂起导致退出卡死。
|
||||||
let app_clone = app.clone();
|
let app_clone = app.clone();
|
||||||
let monitor_clone = monitor.inner().clone();
|
let monitor_clone = monitor.inner().clone();
|
||||||
|
let (tx, rx) = std::sync::mpsc::channel::<()>();
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
tauri::async_runtime::block_on(async move {
|
tauri::async_runtime::block_on(async move {
|
||||||
monitor_clone.cleanup_on_exit(&app_clone).await;
|
monitor_clone.cleanup_on_exit(&app_clone).await;
|
||||||
});
|
});
|
||||||
})
|
let _ = tx.send(());
|
||||||
.join()
|
});
|
||||||
.ok();
|
let _ = rx.recv_timeout(std::time::Duration::from_secs(3));
|
||||||
}
|
}
|
||||||
if let Some(clip) = app.try_state::<ClipboardManager>() {
|
if let Some(clip) = app.try_state::<ClipboardManager>() {
|
||||||
clip.stop();
|
clip.stop();
|
||||||
|
|||||||
@@ -0,0 +1,192 @@
|
|||||||
|
//! 自动切换节点:后端调度,独立于前端模块是否处于激活状态。
|
||||||
|
//! 应用启动后由 `setup.rs` 启动后台任务,按用户设置的间隔周期性测速并切换到当前最优节点,
|
||||||
|
//! 切换完成后通过 `proxy-auto-switch` 事件通知前端刷新界面。
|
||||||
|
//! 节点候选(目标组 + 地区筛选 + 伪节点过滤)与择优逻辑对前端、后台调度、托盘三处保持一致。
|
||||||
|
|
||||||
|
use futures_util::future::join_all;
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager, State};
|
||||||
|
|
||||||
|
use super::{MihomoManager, ProxySettings};
|
||||||
|
use crate::constants::events::PROXY_AUTO_SWITCH;
|
||||||
|
use crate::process_manager::{ProcessManager, ProcessStatus};
|
||||||
|
|
||||||
|
/// 测速目标(同前端/托盘),用于判断节点可用性
|
||||||
|
const TEST_URL: &str = "http://www.gstatic.com/generate_204";
|
||||||
|
/// 单节点测速超时(毫秒)
|
||||||
|
const TEST_TIMEOUT: u32 = 5000;
|
||||||
|
/// 调度轮询粒度(秒)
|
||||||
|
const CHECK_INTERVAL: u64 = 30;
|
||||||
|
|
||||||
|
/// 后端启动自动切换调度任务(幂等,可安全多次调用)。
|
||||||
|
/// 仅在用户开启「自动切换节点」且 mihomo 运行时才会真正执行测速与切换。
|
||||||
|
pub fn start_auto_switch_loop(app: AppHandle) {
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
let mut last_run: Option<Instant> = None;
|
||||||
|
loop {
|
||||||
|
tokio::time::sleep(Duration::from_secs(CHECK_INTERVAL)).await;
|
||||||
|
|
||||||
|
let enabled = app
|
||||||
|
.try_state::<MihomoManager>()
|
||||||
|
.map(|m: State<'_, MihomoManager>| m.load_settings().auto_switch_enabled)
|
||||||
|
.unwrap_or(false);
|
||||||
|
if !enabled {
|
||||||
|
last_run = None;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let interval_secs = app
|
||||||
|
.try_state::<MihomoManager>()
|
||||||
|
.map(|m: State<'_, MihomoManager>| m.load_settings().auto_switch_interval.max(1) as u64)
|
||||||
|
.unwrap_or(5)
|
||||||
|
* 60;
|
||||||
|
|
||||||
|
let due = match last_run {
|
||||||
|
Some(t) => t.elapsed().as_secs() >= interval_secs,
|
||||||
|
None => true,
|
||||||
|
};
|
||||||
|
if !due {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((group, name, delay)) = perform_auto_switch(&app).await {
|
||||||
|
let _ = app.emit(
|
||||||
|
PROXY_AUTO_SWITCH,
|
||||||
|
serde_json::json!({
|
||||||
|
"switched": true,
|
||||||
|
"group": group,
|
||||||
|
"name": name,
|
||||||
|
"delay": delay,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
last_run = Some(Instant::now());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行一次自动切换:若当前不是最优节点则切换并返回 `(组名, 节点名, 延迟)`,否则返回 `None`。
|
||||||
|
/// 供后台调度任务使用(模块内私有)。
|
||||||
|
async fn perform_auto_switch(app: &AppHandle) -> Option<(String, String, u32)> {
|
||||||
|
let mihomo = app.state::<MihomoManager>();
|
||||||
|
let pm = app.state::<ProcessManager>();
|
||||||
|
|
||||||
|
// 仅在 mihomo 运行时执行
|
||||||
|
let running = matches!(
|
||||||
|
pm.get_status("proxy").map(|p| p.status),
|
||||||
|
Some(ProcessStatus::Running)
|
||||||
|
);
|
||||||
|
if !running {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let settings = mihomo.load_settings();
|
||||||
|
if !settings.auto_switch_enabled {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (group, name, delay, now) = pick_best(&mihomo, &settings).await.ok()??;
|
||||||
|
|
||||||
|
if name != now && mihomo.select_proxy(&group, &name).await.is_ok() {
|
||||||
|
return Some((group, name, delay));
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 按自动切换设置确定候选组与地区,并发测速并返回当前最优节点(不执行切换)。
|
||||||
|
/// `Some((组名, 最优节点, 延迟, 当前节点))`;无候选或全部超时返回 `Ok(None)`。
|
||||||
|
/// 当自动切换关闭时自动切换目标组为空、地区为空,故退化为「主组 + 全部节点」全量择优,
|
||||||
|
/// 托盘「开启代理」与调度任务复用此函数保证行为一致。
|
||||||
|
pub async fn pick_best(
|
||||||
|
mihomo: &MihomoManager,
|
||||||
|
settings: &ProxySettings,
|
||||||
|
) -> Result<Option<(String, String, u32, String)>, String> {
|
||||||
|
let proxies = mihomo.get_proxies().await?;
|
||||||
|
let map = proxies
|
||||||
|
.get("proxies")
|
||||||
|
.and_then(|v| v.as_object())
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| "无法解析代理数据".to_string())?;
|
||||||
|
|
||||||
|
let group_name = if !settings.auto_switch_group.is_empty() {
|
||||||
|
settings.auto_switch_group.clone()
|
||||||
|
} else {
|
||||||
|
match main_selector_group(&map) {
|
||||||
|
Some(g) => g,
|
||||||
|
None => return Ok(None),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let group = match map.get(&group_name) {
|
||||||
|
Some(g) => g,
|
||||||
|
None => return Ok(None),
|
||||||
|
};
|
||||||
|
let now = group
|
||||||
|
.get("now")
|
||||||
|
.and_then(|v| v.as_str())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let mut nodes: Vec<String> = group
|
||||||
|
.get("all")
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|arr| arr.iter().filter_map(|n| n.as_str().map(|s| s.to_string())).collect())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if nodes.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 过滤伪节点(DIRECT、REJECT、流量、套餐等)
|
||||||
|
nodes.retain(|n| !super::is_pseudo_node(n));
|
||||||
|
// 地区筛选
|
||||||
|
if !settings.auto_switch_region.is_empty() {
|
||||||
|
let region = settings.auto_switch_region.clone();
|
||||||
|
nodes.retain(|n| extract_region(n) == region);
|
||||||
|
}
|
||||||
|
if nodes.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 并发测速
|
||||||
|
let futures = nodes.iter().map(|name| async move {
|
||||||
|
let d = mihomo.test_delay(name, TEST_URL, TEST_TIMEOUT).await.ok();
|
||||||
|
(name.clone(), d)
|
||||||
|
}).collect::<Vec<_>>();
|
||||||
|
let results = join_all(futures).await;
|
||||||
|
let best = results
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|(n, d)| d.filter(|x| *x > 0).map(|x| (n, x)))
|
||||||
|
.min_by_key(|(_, d)| *d);
|
||||||
|
|
||||||
|
Ok(best.map(|(name, delay)| (group_name, name, delay, now)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 主选择分组:选取名为 PROXY/Proxy/节点选择/代理 的 Selector 组;找不到时回退到第一个 Selector 组
|
||||||
|
fn main_selector_group(map: &Map<String, Value>) -> Option<String> {
|
||||||
|
let mut preferred: Option<String> = None;
|
||||||
|
let mut first_selector: Option<String> = None;
|
||||||
|
for (name, val) in map {
|
||||||
|
let kind = val.get("type").and_then(|v| v.as_str()).unwrap_or("");
|
||||||
|
if kind != "Selector" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if first_selector.is_none() {
|
||||||
|
first_selector = Some(name.clone());
|
||||||
|
}
|
||||||
|
if preferred.is_none() && ["PROXY", "Proxy", "节点选择", "代理"].contains(&name.as_str()) {
|
||||||
|
preferred = Some(name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
preferred.or(first_selector)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 提取节点地区(与前端 extractRegion 保持一致):取名称中第一个数字/符号分隔符之前的文本
|
||||||
|
fn extract_region(name: &str) -> String {
|
||||||
|
for (idx, ch) in name.char_indices() {
|
||||||
|
if ch.is_ascii_digit() || matches!(ch, '|' | '-' | '-' | '—' | '(' | '(' | '【') {
|
||||||
|
return name[..idx].trim().to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name.trim().to_string()
|
||||||
|
}
|
||||||
@@ -4,10 +4,18 @@ use tauri::{AppHandle, State};
|
|||||||
|
|
||||||
use super::system_proxy::{clear_system_proxy_windows, get_system_proxy_windows, set_system_proxy_windows};
|
use super::system_proxy::{clear_system_proxy_windows, get_system_proxy_windows, set_system_proxy_windows};
|
||||||
use super::{
|
use super::{
|
||||||
KernelInfo, KernelUpdateInfo, MihomoManager, ProfileMeta, ProxySettings, ProxyStatus,
|
KernelInfo, KernelUpdateInfo, MihomoManager, ProfileMeta, ProxySettings, ProxyStatus, TrafficSnapshot,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::process_manager::{ProcessInfo, ProcessManager};
|
use crate::process_manager::{ProcessInfo, ProcessManager, ProcessStatus};
|
||||||
|
|
||||||
|
/// 判断 mihomo 进程是否处于运行状态
|
||||||
|
fn mihomo_running(pm: &ProcessManager) -> bool {
|
||||||
|
matches!(
|
||||||
|
pm.get_status("proxy").map(|p| p.status),
|
||||||
|
Some(ProcessStatus::Running)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
@@ -41,25 +49,33 @@ pub async fn proxy_check_kernel_update(
|
|||||||
state.check_kernel_update().await
|
state.check_kernel_update().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 取消内核下载/安装(设置取消标志,下载循环轮询后中止)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn proxy_update_kernel(
|
pub fn proxy_cancel_kernel_install(state: State<'_, MihomoManager>) -> Result<(), String> {
|
||||||
state: State<'_, MihomoManager>,
|
state.cancel_kernel_install();
|
||||||
app: AppHandle,
|
Ok(())
|
||||||
mirror_prefix: Option<String>,
|
|
||||||
) -> Result<KernelInfo, String> {
|
|
||||||
state.install_kernel(&app, mirror_prefix.unwrap_or_default()).await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 首次安装内核(与 update_kernel 共用 install_kernel 实现,语义独立便于前端区分场景)
|
/// 前端确认 mihomo 已停止,唤醒等待中的安装流程继续解压替换。
|
||||||
|
/// (下载阶段允许 mihomo 运行以便走系统代理,解压替换前必须停止 mihomo,否则 exe 被占用)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn proxy_install_kernel(
|
pub fn proxy_confirm_install(state: State<'_, MihomoManager>) -> Result<(), String> {
|
||||||
|
state.confirm_install();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用内核更新:下载阶段已由下载模块完成,本方法仅做 need_stop → 解压 → 替换。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn proxy_apply_kernel_update(
|
||||||
state: State<'_, MihomoManager>,
|
state: State<'_, MihomoManager>,
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
mirror_prefix: Option<String>,
|
zip_path: String,
|
||||||
) -> Result<KernelInfo, String> {
|
) -> Result<KernelInfo, String> {
|
||||||
state.install_kernel(&app, mirror_prefix.unwrap_or_default()).await
|
let path = std::path::PathBuf::from(zip_path);
|
||||||
|
state.apply_kernel_update(&app, path).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -87,12 +103,19 @@ pub fn proxy_start(
|
|||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
) -> Result<ProcessInfo, String> {
|
) -> Result<ProcessInfo, String> {
|
||||||
let params = state.prepare_for_start(&app)?;
|
let params = state.prepare_for_start(&app)?;
|
||||||
pm.start(params)
|
let info = pm.start(params)?;
|
||||||
|
// 手动启动也遵循「启动时自动开启系统代理」设置
|
||||||
|
state.apply_auto_system_proxy();
|
||||||
|
Ok(info)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn proxy_stop(pm: State<'_, ProcessManager>) -> Result<(), String> {
|
pub fn proxy_stop(state: State<'_, MihomoManager>, pm: State<'_, ProcessManager>) -> Result<(), String> {
|
||||||
|
// 关闭 mihomo 时同步关闭系统代理(若开启),避免系统代理指向已停止的端口导致断网
|
||||||
|
if get_system_proxy_windows() {
|
||||||
|
let _ = state.disable_system_proxy();
|
||||||
|
}
|
||||||
pm.stop("proxy")
|
pm.stop("proxy")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,8 +133,65 @@ pub async fn proxy_restart(
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("sleep 失败: {}", e))?;
|
.map_err(|e| format!("sleep 失败: {}", e))?;
|
||||||
let params = state.prepare_for_start(&app)?;
|
|
||||||
pm.start(params)
|
// 启动并等待 API 就绪,带有限重试(共 3 次):
|
||||||
|
// - 冷加载大订阅(首次解析 + geo 下载)可能远超过前端 waitForApi 的 10s 预算,
|
||||||
|
// 这里在命令内等满就绪,避免重启成功后仍被前端误判为「重启失败」导致节点不刷新。
|
||||||
|
// - 偶发的端口未及时释放 / 启动瞬间退出,通过重试自愈。
|
||||||
|
let mut last_err = "mihomo 启动失败".to_string();
|
||||||
|
for _ in 0..3 {
|
||||||
|
match start_and_wait(state.inner(), pm.inner(), &app).await {
|
||||||
|
Ok(info) => return Ok(info),
|
||||||
|
Err(e) => {
|
||||||
|
last_err = e;
|
||||||
|
// 上个实例刚退出,多等一会儿释放端口再重试
|
||||||
|
tauri::async_runtime::spawn_blocking(|| {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(1200));
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|x| format!("sleep 失败: {}", x))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 所有启动尝试均失败:mihomo 已停止,同步关闭系统代理(若开启),避免代理指向已停止端口导致断网
|
||||||
|
if get_system_proxy_windows() {
|
||||||
|
let _ = state.disable_system_proxy();
|
||||||
|
}
|
||||||
|
Err(last_err)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动 mihomo 并等待其 HTTP API 就绪(最多 20s)。
|
||||||
|
/// - 若启动后进程立即退出,快速返回(不白等满预算),便于外层尽早重试。
|
||||||
|
/// - 若 pm.start 返回「已在运行中」,说明崩溃监控已抢先拉起进程,同样等待其 API 就绪即可。
|
||||||
|
async fn start_and_wait(
|
||||||
|
state: &MihomoManager,
|
||||||
|
pm: &ProcessManager,
|
||||||
|
app: &AppHandle,
|
||||||
|
) -> Result<ProcessInfo, String> {
|
||||||
|
let params = state.prepare_for_start(app)?;
|
||||||
|
if let Err(e) = pm.start(params) {
|
||||||
|
// "已在运行中" = 崩溃监控已拉起,不算失败;其余为上抛
|
||||||
|
if !e.contains("运行中") {
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||||
|
loop {
|
||||||
|
// 进程已退出且 API 未就绪 → 启动失败(快速失败,交外层重试)
|
||||||
|
if let Some(st) = pm.get_status("proxy") {
|
||||||
|
if !matches!(st.status, ProcessStatus::Running) {
|
||||||
|
return Err("mihomo 启动后立即退出".to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if state.get_version().await.is_ok() {
|
||||||
|
return pm.get_status("proxy").ok_or_else(|| "mihomo 进程不存在".to_string());
|
||||||
|
}
|
||||||
|
if tokio::time::Instant::now() >= deadline {
|
||||||
|
return Err("mihomo 启动超时,API 无响应".to_string());
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -158,6 +238,14 @@ pub async fn proxy_get_connections(
|
|||||||
state.get_connections().await
|
state.get_connections().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn proxy_traffic(
|
||||||
|
state: State<'_, MihomoManager>,
|
||||||
|
) -> Result<TrafficSnapshot, String> {
|
||||||
|
state.traffic_snapshot().await
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn proxy_close_connection(
|
pub async fn proxy_close_connection(
|
||||||
@@ -220,7 +308,12 @@ pub fn proxy_activate_profile(
|
|||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn proxy_set_system_proxy(
|
pub fn proxy_set_system_proxy(
|
||||||
state: State<'_, MihomoManager>,
|
state: State<'_, MihomoManager>,
|
||||||
|
pm: State<'_, ProcessManager>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
|
// 停机时禁止开启系统代理:否则系统代理指向已停止的端口,会导致所有网络请求失败
|
||||||
|
if !mihomo_running(&pm) {
|
||||||
|
return Err("mihomo 未运行,无法开启系统代理".into());
|
||||||
|
}
|
||||||
let settings = state.load_settings();
|
let settings = state.load_settings();
|
||||||
let addr = format!("127.0.0.1:{}", settings.mixed_port);
|
let addr = format!("127.0.0.1:{}", settings.mixed_port);
|
||||||
set_system_proxy_windows(&addr)?;
|
set_system_proxy_windows(&addr)?;
|
||||||
|
|||||||
@@ -1,15 +1,18 @@
|
|||||||
//! 内核(mihomo.exe)安装 / 更新 / 版本查询。
|
//! 内核(mihomo.exe)安装 / 更新 / 版本查询。
|
||||||
//! 子模块通过 `impl super::MihomoManager` 为管理器追加方法,可访问父模块私有字段。
|
//! 子模块通过 `impl super::MihomoManager` 为管理器追加方法,可访问父模块私有字段。
|
||||||
|
|
||||||
use futures_util::StreamExt;
|
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
use tauri::{AppHandle, Emitter, Manager};
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
|
||||||
use crate::constants::events::KERNEL_INSTALL_PROGRESS;
|
use crate::constants::events::KERNEL_INSTALL_PROGRESS;
|
||||||
use super::{InstallProgress, KernelInfo, KernelUpdateInfo, MihomoManager};
|
use super::{InstallProgress, KernelInfo, KernelUpdateInfo, MihomoManager};
|
||||||
|
|
||||||
|
/// 用户主动取消下载的标记错误信息(前端据此静默处理,不弹错误 toast)
|
||||||
|
const KERNEL_CANCELLED: &str = "下载已取消";
|
||||||
|
|
||||||
impl MihomoManager {
|
impl MihomoManager {
|
||||||
// ---------- 内核 ----------
|
// ---------- 内核 ----------
|
||||||
pub fn kernel_info(&self) -> KernelInfo {
|
pub fn kernel_info(&self) -> KernelInfo {
|
||||||
@@ -203,15 +206,15 @@ impl MihomoManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 下载并安装内核(首次安装与更新共用此方法)
|
/// 应用内核更新:下载阶段已由下载模块完成,本方法仅做 need_stop → 解压 → 替换。
|
||||||
/// - mirror_prefix: 用户选择的镜像源前缀(空串=直连 GitHub)
|
/// zip_path: 下载模块下载完成的 zip 文件路径。
|
||||||
/// - 流式下载:实时推送下载进度到前端
|
/// 任何阶段失败都会 emit error 事件,避免前端进度卡住。
|
||||||
/// - zip crate 解压:替代 PowerShell,避免执行策略问题
|
pub async fn apply_kernel_update(&self, app: &AppHandle, zip_path: PathBuf) -> Result<KernelInfo, String> {
|
||||||
/// - 备份旧内核:替换前备份为 .bak
|
self.kernel_cancel.store(false, Ordering::SeqCst);
|
||||||
/// 任何阶段失败都会 emit error 事件,避免前端进度卡在初始状态
|
let _ = self.kernel_cancel_tx.send(false);
|
||||||
pub async fn install_kernel(&self, app: &AppHandle, mirror_prefix: String) -> Result<KernelInfo, String> {
|
let result = self.apply_kernel_inner(app, zip_path).await;
|
||||||
let result = self.install_kernel_inner(app, mirror_prefix).await;
|
|
||||||
if let Err(ref e) = result {
|
if let Err(ref e) = result {
|
||||||
|
if e != KERNEL_CANCELLED {
|
||||||
let _ = app.emit(
|
let _ = app.emit(
|
||||||
KERNEL_INSTALL_PROGRESS,
|
KERNEL_INSTALL_PROGRESS,
|
||||||
InstallProgress {
|
InstallProgress {
|
||||||
@@ -223,49 +226,46 @@ impl MihomoManager {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
self.kernel_cancel.store(false, Ordering::SeqCst);
|
||||||
|
let _ = self.kernel_cancel_tx.send(false);
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn install_kernel_inner(&self, app: &AppHandle, mirror_prefix: String) -> Result<KernelInfo, String> {
|
async fn apply_kernel_inner(&self, app: &AppHandle, zip_path: PathBuf) -> Result<KernelInfo, String> {
|
||||||
let info = self.check_kernel_update().await?;
|
|
||||||
let zip_path = self.cores_dir().join("mihomo-update.zip");
|
|
||||||
let extract_dir = self.cores_dir().join("mihomo-update-tmp");
|
let extract_dir = self.cores_dir().join("mihomo-update-tmp");
|
||||||
|
|
||||||
// 拼接用户选择的镜像源 URL
|
// 检查 zip 文件是否存在
|
||||||
let url = if mirror_prefix.is_empty() {
|
if !zip_path.exists() {
|
||||||
info.download_url.clone()
|
return Err(format!("下载文件不存在: {}", zip_path.display()));
|
||||||
} else {
|
}
|
||||||
format!("{}{}", mirror_prefix, info.download_url)
|
|
||||||
};
|
|
||||||
let label = if mirror_prefix.is_empty() { "GitHub 直连".to_string() } else { mirror_prefix.clone() };
|
|
||||||
let _ = app.emit(
|
|
||||||
KERNEL_INSTALL_PROGRESS,
|
|
||||||
InstallProgress {
|
|
||||||
stage: "downloading".into(),
|
|
||||||
percent: 0,
|
|
||||||
downloaded_bytes: 0,
|
|
||||||
total_bytes: None,
|
|
||||||
message: format!("正在下载:{}", label),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
// 单源下载(用户已选择)
|
// 解压替换前需要等待前端确认 mihomo 已停止(否则 exe 文件被占用)
|
||||||
match self.download_with_progress(app, &url, &zip_path).await {
|
if self.kernel_cancel.load(Ordering::SeqCst) {
|
||||||
Ok(()) => {}
|
return Err(KERNEL_CANCELLED.to_string());
|
||||||
Err(e) => {
|
}
|
||||||
let msg = format!("下载失败({}):{}", label, e);
|
|
||||||
let _ = app.emit(
|
let _ = app.emit(
|
||||||
KERNEL_INSTALL_PROGRESS,
|
KERNEL_INSTALL_PROGRESS,
|
||||||
InstallProgress {
|
InstallProgress {
|
||||||
stage: "error".into(),
|
stage: "need_stop".into(),
|
||||||
percent: 0,
|
percent: 90,
|
||||||
downloaded_bytes: 0,
|
downloaded_bytes: 0,
|
||||||
total_bytes: None,
|
total_bytes: None,
|
||||||
message: msg.clone(),
|
message: "需要停止 mihomo 才能继续安装".into(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let _ = fs::remove_file(&zip_path);
|
// 创建 oneshot 通道等待前端确认
|
||||||
return Err(msg);
|
let (tx, mut rx) = tokio::sync::oneshot::channel::<()>();
|
||||||
|
*self.install_confirm.lock().unwrap() = Some(tx);
|
||||||
|
let mut cancel_rx = self.kernel_cancel_tx.subscribe();
|
||||||
|
loop {
|
||||||
|
if self.kernel_cancel.load(Ordering::SeqCst) {
|
||||||
|
*self.install_confirm.lock().unwrap() = None;
|
||||||
|
return Err(KERNEL_CANCELLED.to_string());
|
||||||
|
}
|
||||||
|
tokio::select! {
|
||||||
|
_ = &mut rx => break,
|
||||||
|
_ = cancel_rx.changed() => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,8 +299,6 @@ impl MihomoManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 在解压目录中递归查找 exe 文件
|
// 在解压目录中递归查找 exe 文件
|
||||||
// mihomo zip 内的 exe 名字通常与 zip 同名(如 mihomo-windows-amd64-v3-v1.19.13.exe),
|
|
||||||
// 不是固定的 mihomo.exe,所以查找唯一的 .exe 文件即可
|
|
||||||
let new_exe = self
|
let new_exe = self
|
||||||
.find_exe_in_dir(&extract_dir)
|
.find_exe_in_dir(&extract_dir)
|
||||||
.ok_or_else(|| "解压后未找到任何 .exe 文件".to_string())?;
|
.ok_or_else(|| "解压后未找到任何 .exe 文件".to_string())?;
|
||||||
@@ -313,7 +311,7 @@ impl MihomoManager {
|
|||||||
percent: 96,
|
percent: 96,
|
||||||
downloaded_bytes: 0,
|
downloaded_bytes: 0,
|
||||||
total_bytes: None,
|
total_bytes: None,
|
||||||
message: "正在安装...".into(),
|
message: "正在替换内核...".into(),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
let kernel = self.kernel_path();
|
let kernel = self.kernel_path();
|
||||||
@@ -345,57 +343,6 @@ impl MihomoManager {
|
|||||||
Ok(final_info)
|
Ok(final_info)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 流式下载并实时推送进度事件
|
|
||||||
async fn download_with_progress(
|
|
||||||
&self,
|
|
||||||
app: &AppHandle,
|
|
||||||
url: &str,
|
|
||||||
dest: &PathBuf,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let resp = self
|
|
||||||
.client
|
|
||||||
.get(url)
|
|
||||||
.header("User-Agent", "thing-app")
|
|
||||||
.timeout(std::time::Duration::from_secs(30))
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.map_err(|e| format!("请求失败: {}", e))?;
|
|
||||||
if !resp.status().is_success() {
|
|
||||||
return Err(format!("HTTP {}", resp.status()));
|
|
||||||
}
|
|
||||||
let total = resp.content_length();
|
|
||||||
let mut stream = resp.bytes_stream();
|
|
||||||
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {}", e))?;
|
|
||||||
let mut downloaded: u64 = 0;
|
|
||||||
let mut last_percent: u8 = 0;
|
|
||||||
while let Some(chunk) = stream.next().await {
|
|
||||||
let chunk = chunk.map_err(|e| format!("读取流失败: {}", e))?;
|
|
||||||
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {}", e))?;
|
|
||||||
downloaded += chunk.len() as u64;
|
|
||||||
// 下载占总进度的 0-90%
|
|
||||||
let percent = match total {
|
|
||||||
Some(t) if t > 0 => ((downloaded as f64 / t as f64) * 90.0) as u8,
|
|
||||||
_ => 0,
|
|
||||||
};
|
|
||||||
// 仅在变化超过 1% 时 emit,避免事件轰炸
|
|
||||||
if percent >= last_percent + 1 {
|
|
||||||
last_percent = percent;
|
|
||||||
let _ = app.emit(
|
|
||||||
KERNEL_INSTALL_PROGRESS,
|
|
||||||
InstallProgress {
|
|
||||||
stage: "downloading".into(),
|
|
||||||
percent,
|
|
||||||
downloaded_bytes: downloaded,
|
|
||||||
total_bytes: total,
|
|
||||||
message: format!("已下载 {:.2} MB", downloaded as f64 / 1024.0 / 1024.0),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
file.flush().map_err(|e| format!("flush 失败: {}", e))?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 用 zip crate 解压(纯 Rust,避免 PowerShell 执行策略问题)
|
/// 用 zip crate 解压(纯 Rust,避免 PowerShell 执行策略问题)
|
||||||
fn extract_zip(&self, zip_path: &PathBuf, dest: &PathBuf) -> Result<(), String> {
|
fn extract_zip(&self, zip_path: &PathBuf, dest: &PathBuf) -> Result<(), String> {
|
||||||
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
//! - [`system_proxy`]:Windows 系统代理开关
|
//! - [`system_proxy`]:Windows 系统代理开关
|
||||||
//! - [`commands`]:Tauri 命令层
|
//! - [`commands`]:Tauri 命令层
|
||||||
|
|
||||||
|
mod autoswitch;
|
||||||
mod commands;
|
mod commands;
|
||||||
mod kernel;
|
mod kernel;
|
||||||
mod profiles;
|
mod profiles;
|
||||||
@@ -13,21 +14,24 @@ mod pseudo;
|
|||||||
mod system_proxy;
|
mod system_proxy;
|
||||||
mod types;
|
mod types;
|
||||||
|
|
||||||
|
pub use autoswitch::{pick_best, start_auto_switch_loop};
|
||||||
pub use pseudo::is_pseudo_node;
|
pub use pseudo::is_pseudo_node;
|
||||||
pub use types::{InstallProgress, KernelInfo, KernelUpdateInfo, ProfileMeta, ProxySettings, ProxyStatus};
|
pub use system_proxy::get_system_proxy_windows;
|
||||||
|
pub use types::{InstallProgress, KernelInfo, KernelUpdateInfo, ProfileMeta, ProxySettings, ProxyStatus, TrafficSnapshot};
|
||||||
pub use commands::{
|
pub use commands::{
|
||||||
proxy_activate_profile, proxy_check_kernel_update, proxy_clear_system_proxy, proxy_close_connection,
|
proxy_activate_profile, proxy_apply_kernel_update, proxy_cancel_kernel_install, proxy_check_kernel_update, proxy_clear_system_proxy,
|
||||||
proxy_delete_profile, proxy_get_connections, proxy_get_proxies, proxy_get_settings, proxy_get_system_proxy,
|
proxy_close_connection, proxy_confirm_install, proxy_delete_profile, proxy_get_connections, proxy_get_proxies,
|
||||||
proxy_import_profile, proxy_install_kernel, proxy_kernel_info, proxy_patch_configs, proxy_restart,
|
proxy_get_settings, proxy_get_system_proxy, proxy_import_profile, proxy_kernel_info, proxy_traffic,
|
||||||
proxy_save_settings, proxy_select_proxy, proxy_set_system_proxy, proxy_start, proxy_status, proxy_stop,
|
proxy_patch_configs, proxy_restart, proxy_save_settings, proxy_select_proxy, proxy_set_system_proxy,
|
||||||
proxy_test_delay, proxy_update_kernel, proxy_update_profile, proxy_version,
|
proxy_start, proxy_status, proxy_stop, proxy_test_delay, proxy_update_profile, proxy_version,
|
||||||
};
|
};
|
||||||
|
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_yaml::Value as YamlValue;
|
use serde_yaml::Value as YamlValue;
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Mutex;
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
|
|
||||||
@@ -41,10 +45,29 @@ struct SettingsCacheEntry {
|
|||||||
settings: ProxySettings,
|
settings: ProxySettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 流量速率差分基线:记录上次采样的会话总量与时刻,用于计算实时速率
|
||||||
|
struct TrafficBaseline {
|
||||||
|
download_total: u64,
|
||||||
|
upload_total: u64,
|
||||||
|
at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct MihomoManager {
|
pub struct MihomoManager {
|
||||||
root: PathBuf,
|
root: PathBuf,
|
||||||
client: Client,
|
client: Client,
|
||||||
settings_cache: Mutex<Option<SettingsCacheEntry>>,
|
settings_cache: Mutex<Option<SettingsCacheEntry>>,
|
||||||
|
/// 流量速率差分基线:记录上次采样总量与时刻,由两次 /connections 总量差异计算实时速率
|
||||||
|
traffic_baseline: Mutex<Option<TrafficBaseline>>,
|
||||||
|
/// 内核安装/更新的取消标志(前端「停止下载」置位,下载循环轮询后中止)
|
||||||
|
kernel_cancel: Arc<AtomicBool>,
|
||||||
|
/// 取消唤醒通道:让停滞在流式读取(stream.next 最多等 30s)中的下载立即感知取消,
|
||||||
|
/// 否则旧任务会残留最长 30s,期间可能与新任务并发写临时文件/互相重置取消标志
|
||||||
|
kernel_cancel_tx: tokio::sync::watch::Sender<bool>,
|
||||||
|
/// 下载完成后解压替换前的确认通道:mihomo 运行时下载不受影响,但解压替换前
|
||||||
|
/// 必须等前端确认已停止 mihomo(否则 exe 文件被占用)。前端确认后通过
|
||||||
|
/// proxy_confirm_install 命令发送信号唤醒等待。
|
||||||
|
/// 用 std Mutex 而非 tokio Mutex:锁只短暂存取 sender,不跨 await 持有。
|
||||||
|
install_confirm: std::sync::Mutex<Option<tokio::sync::oneshot::Sender<()>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl MihomoManager {
|
impl MihomoManager {
|
||||||
@@ -61,6 +84,24 @@ impl MihomoManager {
|
|||||||
.build()
|
.build()
|
||||||
.unwrap_or_else(|_| Client::new()),
|
.unwrap_or_else(|_| Client::new()),
|
||||||
settings_cache: Mutex::new(None),
|
settings_cache: Mutex::new(None),
|
||||||
|
traffic_baseline: Mutex::new(None),
|
||||||
|
kernel_cancel: Arc::new(AtomicBool::new(false)),
|
||||||
|
kernel_cancel_tx: tokio::sync::watch::channel(false).0,
|
||||||
|
install_confirm: std::sync::Mutex::new(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求取消内核安装/更新(由 proxy_cancel_kernel_install 命令调用)
|
||||||
|
pub fn cancel_kernel_install(&self) {
|
||||||
|
self.kernel_cancel.store(true, Ordering::SeqCst);
|
||||||
|
// 唤醒停滞的流式下载循环,使其立即中止而不是等 30s 超时
|
||||||
|
let _ = self.kernel_cancel_tx.send(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 前端确认 mihomo 已停止,唤醒等待中的安装流程继续解压替换(由 proxy_confirm_install 命令调用)
|
||||||
|
pub fn confirm_install(&self) {
|
||||||
|
if let Some(tx) = self.install_confirm.lock().unwrap().take() {
|
||||||
|
let _ = tx.send(());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -273,6 +314,29 @@ impl MihomoManager {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// mihomo 启动成功后,若配置了「启动时自动开启系统代理」且当前未开,则开启系统代理。
|
||||||
|
/// 手动启动与 App 自启共用,保证设置语义一致(mihomo 运行期间自动跟随系统代理)。
|
||||||
|
pub fn apply_auto_system_proxy(&self) {
|
||||||
|
let settings = self.load_settings();
|
||||||
|
if !settings.auto_system_proxy {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// 以注册表实际状态为准判断是否已开启:settings.system_proxy 是会话内标志,
|
||||||
|
// 上次退出 cleanup_on_exit 只清注册表不会回写该标志,重启后会残留 true,
|
||||||
|
// 若用它做守卫会导致「启动时自动开启系统代理」永远被短路而不生效。
|
||||||
|
if system_proxy::get_system_proxy_windows() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let addr = format!("127.0.0.1:{}", settings.mixed_port);
|
||||||
|
if let Err(e) = system_proxy::set_system_proxy_windows(&addr) {
|
||||||
|
crate::logger::log_warn("mihomo", &format!("自动开启系统代理失败: {}", e));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut s = settings;
|
||||||
|
s.system_proxy = true;
|
||||||
|
let _ = self.save_settings(&s);
|
||||||
|
}
|
||||||
|
|
||||||
/// 应用启动时检查是否需要自动启动 mihomo 和系统代理
|
/// 应用启动时检查是否需要自动启动 mihomo 和系统代理
|
||||||
pub fn auto_start_on_launch(&self, app: &AppHandle, pm: &ProcessManager) {
|
pub fn auto_start_on_launch(&self, app: &AppHandle, pm: &ProcessManager) {
|
||||||
let settings = self.load_settings();
|
let settings = self.load_settings();
|
||||||
@@ -283,13 +347,9 @@ impl MihomoManager {
|
|||||||
Ok(params) => {
|
Ok(params) => {
|
||||||
if let Err(e) = pm.start(params) {
|
if let Err(e) = pm.start(params) {
|
||||||
crate::logger::log_error("mihomo", &format!("自动启动失败: {}", e));
|
crate::logger::log_error("mihomo", &format!("自动启动失败: {}", e));
|
||||||
} else if settings.auto_system_proxy {
|
} else {
|
||||||
// 启动成功后开启系统代理
|
// 启动成功后按「启动时自动开启系统代理」设置决定是否开启系统代理
|
||||||
let addr = format!("127.0.0.1:{}", settings.mixed_port);
|
self.apply_auto_system_proxy();
|
||||||
let _ = system_proxy::set_system_proxy_windows(&addr);
|
|
||||||
let mut s = settings;
|
|
||||||
s.system_proxy = true;
|
|
||||||
let _ = self.save_settings(&s);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@@ -407,6 +467,48 @@ impl MihomoManager {
|
|||||||
self.api_get("/connections").await
|
self.api_get("/connections").await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 拉取 /connections 并计算实时流量快照。
|
||||||
|
/// 速率由两次采样的会话总量差分得出;mihomo 重启导致总量回退时自动重置基线。
|
||||||
|
pub async fn traffic_snapshot(&self) -> Result<TrafficSnapshot, String> {
|
||||||
|
let conns = self.get_connections().await?;
|
||||||
|
let upload_total = conns["uploadTotal"].as_u64().unwrap_or(0);
|
||||||
|
let download_total = conns["downloadTotal"].as_u64().unwrap_or(0);
|
||||||
|
let active_connections = conns["connections"].as_array().map(|a| a.len()).unwrap_or(0);
|
||||||
|
|
||||||
|
let (upload_speed, download_speed) = {
|
||||||
|
let base = self.traffic_baseline.lock().unwrap();
|
||||||
|
match base.as_ref() {
|
||||||
|
// 正常差分:总量单调递增才计算速率
|
||||||
|
Some(b) if upload_total >= b.upload_total && download_total >= b.download_total => {
|
||||||
|
let dt = b.at.elapsed().as_secs_f64();
|
||||||
|
if dt > 0.0 {
|
||||||
|
let up = ((upload_total - b.upload_total) as f64 / dt).max(0.0) as u64;
|
||||||
|
let down = ((download_total - b.download_total) as f64 / dt).max(0.0) as u64;
|
||||||
|
(up, down)
|
||||||
|
} else {
|
||||||
|
(0, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 无基线或总量回退(mihomo 重启):本帧速率为 0,下方重置基线
|
||||||
|
_ => (0, 0),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
*self.traffic_baseline.lock().unwrap() = Some(TrafficBaseline {
|
||||||
|
download_total,
|
||||||
|
upload_total,
|
||||||
|
at: Instant::now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(TrafficSnapshot {
|
||||||
|
download_total,
|
||||||
|
upload_total,
|
||||||
|
download_speed,
|
||||||
|
upload_speed,
|
||||||
|
active_connections,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn close_connection(&self, id: &str) -> Result<(), String> {
|
pub async fn close_connection(&self, id: &str) -> Result<(), String> {
|
||||||
self.api_request(
|
self.api_request(
|
||||||
reqwest::Method::DELETE,
|
reqwest::Method::DELETE,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub(crate) fn get_system_proxy_windows() -> bool {
|
pub fn get_system_proxy_windows() -> bool {
|
||||||
use winreg::enums::*;
|
use winreg::enums::*;
|
||||||
use winreg::RegKey;
|
use winreg::RegKey;
|
||||||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||||||
@@ -67,7 +67,7 @@ pub(crate) fn clear_system_proxy_windows() -> Result<(), String> {
|
|||||||
Err("系统代理仅支持 Windows".into())
|
Err("系统代理仅支持 Windows".into())
|
||||||
}
|
}
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
pub(crate) fn get_system_proxy_windows() -> bool {
|
pub fn get_system_proxy_windows() -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -124,6 +124,22 @@ pub struct ProxyStatus {
|
|||||||
pub restart_count: u32,
|
pub restart_count: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 实时流量快照(由 /connections 的会话总量差分得出实时速率)
|
||||||
|
#[derive(Serialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct TrafficSnapshot {
|
||||||
|
/// 本次会话累计下载字节数
|
||||||
|
pub download_total: u64,
|
||||||
|
/// 本次会话累计上传字节数
|
||||||
|
pub upload_total: u64,
|
||||||
|
/// 实时下载速率(字节/秒)
|
||||||
|
pub download_speed: u64,
|
||||||
|
/// 实时上传速率(字节/秒)
|
||||||
|
pub upload_speed: u64,
|
||||||
|
/// 当前活跃连接数
|
||||||
|
pub active_connections: usize,
|
||||||
|
}
|
||||||
|
|
||||||
/// 内核安装进度事件载荷
|
/// 内核安装进度事件载荷
|
||||||
/// - stage: downloading | extracting | replacing | done | error
|
/// - stage: downloading | extracting | replacing | done | error
|
||||||
/// - percent: 0-100(无 total_bytes 时为 0,前端按 downloadedBytes 显示)
|
/// - percent: 0-100(无 total_bytes 时为 0,前端按 downloadedBytes 显示)
|
||||||
|
|||||||
@@ -132,6 +132,41 @@ pub fn is_thing_elevated() -> bool {
|
|||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===================== 监控设置持久化 =====================
|
||||||
|
|
||||||
|
/// 监控模块设置(存储于 {app_data_dir}/monitor/settings.json)
|
||||||
|
/// 参照代理模块 ProxySettings 的模式,仅包含需要持久化的运行时开关。
|
||||||
|
#[derive(Serialize, Deserialize, Clone, Default)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct MonitorSettings {
|
||||||
|
/// 应用启动时自动启动监控内核(默认 false)
|
||||||
|
#[serde(default)]
|
||||||
|
pub auto_start: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 监控设置文件路径: {app_data_dir}/monitor/settings.json
|
||||||
|
fn settings_path(app_data_dir: &std::path::Path) -> PathBuf {
|
||||||
|
app_data_dir.join("monitor").join("settings.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 读取监控设置(文件不存在或解析失败时返回默认值)
|
||||||
|
pub fn load_monitor_settings(app_data_dir: &std::path::Path) -> MonitorSettings {
|
||||||
|
fs::read_to_string(settings_path(app_data_dir))
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| serde_json::from_str::<MonitorSettings>(&s).ok())
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入监控设置
|
||||||
|
pub fn save_monitor_settings(app_data_dir: &std::path::Path, settings: &MonitorSettings) -> Result<(), String> {
|
||||||
|
let path = settings_path(app_data_dir);
|
||||||
|
if let Some(parent) = path.parent() {
|
||||||
|
fs::create_dir_all(parent).map_err(|e| format!("创建目录失败: {}", e))?;
|
||||||
|
}
|
||||||
|
let content = serde_json::to_string_pretty(settings).map_err(|e| format!("序列化设置失败: {}", e))?;
|
||||||
|
fs::write(path, content).map_err(|e| format!("写入设置失败: {}", e))
|
||||||
|
}
|
||||||
|
|
||||||
// ===================== 永久提权标志持久化 =====================
|
// ===================== 永久提权标志持久化 =====================
|
||||||
|
|
||||||
/// 永久提权标志文件路径: {app_data_dir}/monitor/elevate.json
|
/// 永久提权标志文件路径: {app_data_dir}/monitor/elevate.json
|
||||||
@@ -193,6 +228,8 @@ pub fn check_and_relaunch_if_needed(app_data_dir: &std::path::Path) -> bool {
|
|||||||
pub struct KernelStatus {
|
pub struct KernelStatus {
|
||||||
pub ready: bool,
|
pub ready: bool,
|
||||||
pub is_admin: bool,
|
pub is_admin: bool,
|
||||||
|
/// PawnIO 驱动是否已安装;旧版内核无此字段,Option 兼容
|
||||||
|
pub pawn_io_installed: Option<bool>,
|
||||||
pub uptime_ms: f64,
|
pub uptime_ms: f64,
|
||||||
pub group_count: u32,
|
pub group_count: u32,
|
||||||
pub sensor_count: u32,
|
pub sensor_count: u32,
|
||||||
@@ -295,6 +332,32 @@ impl MonitorKernel {
|
|||||||
write_elevate_flag(&self.root.join("elevate.json"), enabled)
|
write_elevate_flag(&self.root.join("elevate.json"), enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 读取监控设置(auto_start 等)
|
||||||
|
pub fn load_settings(&self) -> MonitorSettings {
|
||||||
|
load_monitor_settings(&self.root.parent().unwrap_or(&self.root).to_path_buf())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 写入监控设置
|
||||||
|
pub fn save_settings(&self, settings: &MonitorSettings) -> Result<(), String> {
|
||||||
|
save_monitor_settings(&self.root.parent().unwrap_or(&self.root).to_path_buf(), settings)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用启动时检查是否需要自动启动监控内核
|
||||||
|
pub fn auto_start_on_launch(&self, app: &AppHandle) {
|
||||||
|
let settings = self.load_settings();
|
||||||
|
if !settings.auto_start {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let monitor = self.clone();
|
||||||
|
let app_handle = app.clone();
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
match monitor.start_with_subscription(&app_handle).await {
|
||||||
|
Ok(info) => crate::logger::log_info("monitor", &format!("自动启动成功, pid={:?}", info.pid)),
|
||||||
|
Err(e) => crate::logger::log_warn("monitor", &format!("自动启动跳过: {}", e)),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn cores_dir(&self) -> PathBuf {
|
fn cores_dir(&self) -> PathBuf {
|
||||||
self.root.join("cores")
|
self.root.join("cores")
|
||||||
}
|
}
|
||||||
@@ -309,7 +372,9 @@ impl MonitorKernel {
|
|||||||
self.root.join("hardware-config.json")
|
self.root.join("hardware-config.json")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 确保内核就位:若 cores/ 无内核或版本过期(源文件较新),从资源目录复制
|
/// 确保内核就位:若 cores/ 无内核或版本过期(源文件较新),从资源目录复制。
|
||||||
|
/// 同时把 PawnIO_setup.exe(可选资源)复制过去——内核提权启动时会静默安装它,
|
||||||
|
/// 作为 WinRing0 被系统/杀软拦截时读取温度/频率的替代驱动。
|
||||||
pub fn prepare_kernel(&self, app: &AppHandle) -> Result<MonitorKernelInfo, String> {
|
pub fn prepare_kernel(&self, app: &AppHandle) -> Result<MonitorKernelInfo, String> {
|
||||||
let kernel = self.kernel_path();
|
let kernel = self.kernel_path();
|
||||||
if let Ok(src) = app.path().resolve("binaries/ThingHK.exe", BaseDirectory::Resource) {
|
if let Ok(src) = app.path().resolve("binaries/ThingHK.exe", BaseDirectory::Resource) {
|
||||||
@@ -324,6 +389,24 @@ impl MonitorKernel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// PawnIO 安装器:可选资源,缺失时仅影响自动安装能力(不影响内核运行)
|
||||||
|
if let Ok(setup_src) = app.path().resolve("binaries/PawnIO_setup.exe", BaseDirectory::Resource) {
|
||||||
|
if setup_src.exists() {
|
||||||
|
let setup_dest = self.cores_dir().join("PawnIO_setup.exe");
|
||||||
|
let need_copy = !setup_dest.exists()
|
||||||
|
|| fs::metadata(&setup_src)
|
||||||
|
.and_then(|s| fs::metadata(&setup_dest).map(|d| s.len() != d.len()))
|
||||||
|
.unwrap_or(true);
|
||||||
|
if need_copy {
|
||||||
|
fs::create_dir_all(self.cores_dir()).ok();
|
||||||
|
if let Err(e) = fs::copy(&setup_src, &setup_dest) {
|
||||||
|
crate::logger::log_warn("monitor", &format!("复制 PawnIO_setup.exe 失败: {}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(MonitorKernelInfo {
|
Ok(MonitorKernelInfo {
|
||||||
path: kernel.to_string_lossy().to_string(),
|
path: kernel.to_string_lossy().to_string(),
|
||||||
exists: kernel.exists(),
|
exists: kernel.exists(),
|
||||||
@@ -428,12 +511,20 @@ impl MonitorKernel {
|
|||||||
Ok(resp) if resp.status().is_success() => {
|
Ok(resp) if resp.status().is_success() => {
|
||||||
match resp.json::<KernelStatus>().await {
|
match resp.json::<KernelStatus>().await {
|
||||||
Ok(s) if s.ready => {
|
Ok(s) if s.ready => {
|
||||||
|
// PawnIO 诊断:已提权但驱动缺失时,温度/频率等 ring0 传感器大概率无法读取
|
||||||
|
if s.is_admin && s.pawn_io_installed == Some(false) {
|
||||||
|
crate::logger::log_warn(
|
||||||
|
"monitor",
|
||||||
|
"Kernel 已提权但 PawnIO 驱动未安装,CPU 温度/频率可能无法读取(检查 cores/PawnIO_setup.exe 是否随包部署)",
|
||||||
|
);
|
||||||
|
}
|
||||||
let _ = app.emit(
|
let _ = app.emit(
|
||||||
crate::constants::events::MONITOR_READY,
|
crate::constants::events::MONITOR_READY,
|
||||||
serde_json::json!({
|
serde_json::json!({
|
||||||
"isAdmin": s.is_admin,
|
"isAdmin": s.is_admin,
|
||||||
"sensorCount": s.sensor_count,
|
"sensorCount": s.sensor_count,
|
||||||
"providers": s.providers,
|
"providers": s.providers,
|
||||||
|
"pawnIoInstalled": s.pawn_io_installed,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -950,6 +1041,25 @@ pub fn monitor_set_elevate_on_launch(
|
|||||||
state.set_elevate_on_launch(enabled)
|
state.set_elevate_on_launch(enabled)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 查询"应用启动时自动启动监控内核"是否已启用
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn monitor_get_auto_start(
|
||||||
|
state: tauri::State<'_, MonitorKernel>,
|
||||||
|
) -> bool {
|
||||||
|
state.load_settings().auto_start
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 设置/清除"应用启动时自动启动监控内核"开关
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn monitor_set_auto_start(
|
||||||
|
state: tauri::State<'_, MonitorKernel>,
|
||||||
|
enabled: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let mut settings = state.load_settings();
|
||||||
|
settings.auto_start = enabled;
|
||||||
|
state.save_settings(&settings)
|
||||||
|
}
|
||||||
|
|
||||||
/// 查询硬件监控配置(透传 Kernel GET /config/hardware)。
|
/// 查询硬件监控配置(透传 Kernel GET /config/hardware)。
|
||||||
/// 返回当前配置 + 可用硬件/传感器类型清单,供前端 Dialog 渲染。
|
/// 返回当前配置 + 可用硬件/传感器类型清单,供前端 Dialog 渲染。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
|
|||||||
+196
-6
@@ -15,9 +15,12 @@ use tauri::{AppHandle, Emitter};
|
|||||||
static DRAG_STOP: OnceLock<Arc<AtomicBool>> = OnceLock::new();
|
static DRAG_STOP: OnceLock<Arc<AtomicBool>> = OnceLock::new();
|
||||||
/// 任务栏覆盖监视线程停止标志
|
/// 任务栏覆盖监视线程停止标志
|
||||||
static TOPMOST_STOP: OnceLock<Arc<AtomicBool>> = OnceLock::new();
|
static TOPMOST_STOP: OnceLock<Arc<AtomicBool>> = OnceLock::new();
|
||||||
|
/// 游戏全屏监视线程停止标志
|
||||||
|
static GAME_STOP: OnceLock<Arc<AtomicBool>> = OnceLock::new();
|
||||||
/// 监视线程句柄(用于停止时 join,避免 sleep 猜测式等待 + 线程泄漏)
|
/// 监视线程句柄(用于停止时 join,避免 sleep 猜测式等待 + 线程泄漏)
|
||||||
static DRAG_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
static DRAG_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
||||||
static TOPMOST_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
static TOPMOST_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
||||||
|
static GAME_HANDLE: Mutex<Option<JoinHandle<()>>> = Mutex::new(None);
|
||||||
|
|
||||||
fn drag_stop() -> &'static Arc<AtomicBool> {
|
fn drag_stop() -> &'static Arc<AtomicBool> {
|
||||||
DRAG_STOP.get_or_init(|| Arc::new(AtomicBool::new(true)))
|
DRAG_STOP.get_or_init(|| Arc::new(AtomicBool::new(true)))
|
||||||
@@ -27,6 +30,10 @@ fn topmost_stop() -> &'static Arc<AtomicBool> {
|
|||||||
TOPMOST_STOP.get_or_init(|| Arc::new(AtomicBool::new(true)))
|
TOPMOST_STOP.get_or_init(|| Arc::new(AtomicBool::new(true)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn game_stop() -> &'static Arc<AtomicBool> {
|
||||||
|
GAME_STOP.get_or_init(|| Arc::new(AtomicBool::new(true)))
|
||||||
|
}
|
||||||
|
|
||||||
/// 停止右键拖动监视线程并等待其退出(标志置位后线程最迟一个轮询周期退出)
|
/// 停止右键拖动监视线程并等待其退出(标志置位后线程最迟一个轮询周期退出)
|
||||||
fn stop_drag_thread() {
|
fn stop_drag_thread() {
|
||||||
drag_stop().store(true, Ordering::SeqCst);
|
drag_stop().store(true, Ordering::SeqCst);
|
||||||
@@ -51,18 +58,35 @@ fn stop_topmost_thread() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 停止游戏全屏监视线程并等待其退出
|
||||||
|
fn stop_game_thread() {
|
||||||
|
game_stop().store(true, Ordering::SeqCst);
|
||||||
|
if let Some(h) = GAME_HANDLE
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|e| e.into_inner())
|
||||||
|
.take()
|
||||||
|
{
|
||||||
|
let _ = h.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
mod win_api {
|
mod win_api {
|
||||||
use tauri::{AppHandle, Manager};
|
use tauri::{AppHandle, Manager};
|
||||||
use windows_sys::Win32::Foundation::{POINT, RECT};
|
use windows_sys::Win32::Foundation::{POINT, RECT};
|
||||||
|
use windows_sys::Win32::Graphics::Gdi::{
|
||||||
|
GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST,
|
||||||
|
};
|
||||||
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_RBUTTON};
|
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_RBUTTON};
|
||||||
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||||
GetClassNameW, GetCursorPos, GetForegroundWindow, GetWindowLongPtrW,
|
GetClassNameW, GetCursorPos, GetForegroundWindow, GetWindowLongPtrW, GetWindowLongW,
|
||||||
GetWindowRect, SendMessageW, SetWindowLongPtrW, SetWindowPos,
|
GetWindowRect, GetWindowThreadProcessId, SendMessageW, SetWindowLongPtrW, SetWindowPos,
|
||||||
GWL_EXSTYLE, HTCAPTION, HWND_NOTOPMOST, HWND_TOPMOST, SWP_NOACTIVATE, SWP_NOMOVE,
|
GWL_EXSTYLE, GWL_STYLE, HTCAPTION, HWND_NOTOPMOST, HWND_TOPMOST, SWP_NOACTIVATE,
|
||||||
SWP_NOSIZE, SWP_SHOWWINDOW, WM_NCLBUTTONDOWN, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
|
SWP_NOMOVE, SWP_NOSIZE, SWP_NOZORDER, WM_NCLBUTTONDOWN, WS_EX_NOACTIVATE,
|
||||||
WS_EX_TRANSPARENT,
|
WS_EX_TOOLWINDOW, WS_EX_TRANSPARENT,
|
||||||
};
|
};
|
||||||
|
/// 供模块外全屏判定使用的窗口样式常量(pub re-export)
|
||||||
|
pub use windows_sys::Win32::UI::WindowsAndMessaging::WS_CAPTION;
|
||||||
|
|
||||||
/// windows-sys 的 HWND 类型别名(isize)
|
/// windows-sys 的 HWND 类型别名(isize)
|
||||||
pub type Hwnd = isize;
|
pub type Hwnd = isize;
|
||||||
@@ -165,6 +189,10 @@ mod win_api {
|
|||||||
} else {
|
} else {
|
||||||
HWND_NOTOPMOST
|
HWND_NOTOPMOST
|
||||||
};
|
};
|
||||||
|
// 注意:不传 SWP_SHOWWINDOW,仅调整 Z 序,绝不改变窗口可见性。
|
||||||
|
// 否则当 OSD 被 .hide() 隐藏后,任务栏覆盖监视线程在系统 UI 前景切换时
|
||||||
|
// (点击任务栏/托盘关闭主界面、打开托盘菜单)会重新显示已隐藏的 OSD,
|
||||||
|
// 表现为"托盘关闭 OSD 无效 / 关闭主界面后 OSD 又出现"。
|
||||||
SetWindowPos(
|
SetWindowPos(
|
||||||
hwnd,
|
hwnd,
|
||||||
insert_after,
|
insert_after,
|
||||||
@@ -172,7 +200,7 @@ mod win_api {
|
|||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
0,
|
0,
|
||||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW,
|
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,6 +218,24 @@ mod win_api {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 原子设置窗口位置与尺寸(物理像素)
|
||||||
|
///
|
||||||
|
/// 一次 SetWindowPos 调用同时更新 x/y/w/h,避免 setSize + setPosition
|
||||||
|
/// 两次调用之间出现"宽度已变、位置未动"的中间帧(视觉闪烁)。
|
||||||
|
pub fn set_bounds(hwnd: Hwnd, x: i32, y: i32, w: i32, h: i32) {
|
||||||
|
unsafe {
|
||||||
|
SetWindowPos(
|
||||||
|
hwnd,
|
||||||
|
0, // 不改 Z 序
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
w,
|
||||||
|
h,
|
||||||
|
SWP_NOACTIVATE | SWP_NOZORDER,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 判断窗口类名是否为系统 UI(任务栏、开始菜单、通知区域等)
|
/// 判断窗口类名是否为系统 UI(任务栏、开始菜单、通知区域等)
|
||||||
pub fn is_system_ui_class(class_name: &str) -> bool {
|
pub fn is_system_ui_class(class_name: &str) -> bool {
|
||||||
matches!(
|
matches!(
|
||||||
@@ -203,6 +249,41 @@ mod win_api {
|
|||||||
| "Windows.UI.Shell.ShellFlyoutWindow" // Win11 Shell 弹出
|
| "Windows.UI.Shell.ShellFlyoutWindow" // Win11 Shell 弹出
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 获取窗口样式(GWL_STYLE)
|
||||||
|
pub fn get_window_style(hwnd: Hwnd) -> isize {
|
||||||
|
unsafe { GetWindowLongW(hwnd, GWL_STYLE) as isize }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 判断窗口是否属于本进程(Thing 自身窗口不参与全屏判定)
|
||||||
|
pub fn is_own_process(hwnd: Hwnd) -> bool {
|
||||||
|
let mut pid: u32 = 0;
|
||||||
|
unsafe {
|
||||||
|
GetWindowThreadProcessId(hwnd, &mut pid);
|
||||||
|
}
|
||||||
|
pid != 0 && pid == std::process::id()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取窗口所在显示器(最近匹配)的矩形(物理像素)
|
||||||
|
pub fn get_monitor_rect(hwnd: Hwnd) -> Option<RECT> {
|
||||||
|
let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
|
||||||
|
if monitor == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut info = MONITORINFO {
|
||||||
|
cbSize: std::mem::size_of::<MONITORINFO>() as u32,
|
||||||
|
rcMonitor: RECT { left: 0, top: 0, right: 0, bottom: 0 },
|
||||||
|
rcWork: RECT { left: 0, top: 0, right: 0, bottom: 0 },
|
||||||
|
dwFlags: 0,
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
if GetMonitorInfoW(monitor, &mut info) != 0 {
|
||||||
|
Some(info.rcMonitor)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 应用 OSD 悬浮窗的原生样式(NoActivate + ToolWindow)
|
/// 应用 OSD 悬浮窗的原生样式(NoActivate + ToolWindow)
|
||||||
@@ -347,11 +428,98 @@ pub fn osd_start_topmost_watch(app: AppHandle) -> Result<(), String> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 判断窗口是否为全屏应用(无边框/独占全屏游戏)
|
||||||
|
///
|
||||||
|
/// 判定条件(全部满足):
|
||||||
|
/// 1. 无 WS_CAPTION 样式 —— 排除普通应用的"最大化"(即使系统任务栏设为自动隐藏,
|
||||||
|
/// 最大化窗口覆盖率也接近 100%,但它们带标题栏,靠样式即可区分)
|
||||||
|
/// 2. 非本进程窗口(Thing 主窗口/悬浮窗自身)
|
||||||
|
/// 3. 窗口矩形与所在显示器矩形的交集覆盖率 ≥ 95%(兼容缩放/1px 误差)
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn is_fullscreen_game_window(hwnd: isize) -> bool {
|
||||||
|
if win_api::get_window_style(hwnd) & (win_api::WS_CAPTION as isize) != 0 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if win_api::is_own_process(hwnd) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let (Some(win_rect), Some(mon_rect)) = (
|
||||||
|
win_api::get_window_rect(hwnd),
|
||||||
|
win_api::get_monitor_rect(hwnd),
|
||||||
|
) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let iw = (win_rect.right.min(mon_rect.right) - win_rect.left.max(mon_rect.left)).max(0) as i64;
|
||||||
|
let ih = (win_rect.bottom.min(mon_rect.bottom) - win_rect.top.max(mon_rect.top)).max(0) as i64;
|
||||||
|
let mw = (mon_rect.right - mon_rect.left).max(0) as i64;
|
||||||
|
let mh = (mon_rect.bottom - mon_rect.top).max(0) as i64;
|
||||||
|
let mon_area = (mw * mh).max(1);
|
||||||
|
iw * ih * 100 >= mon_area * 95
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 启动游戏全屏监视
|
||||||
|
///
|
||||||
|
/// 轮询检测前景窗口是否为全屏应用(无边框/独占全屏游戏),
|
||||||
|
/// 状态变化时发出 `osd-game-active` / `osd-game-inactive` 事件。
|
||||||
|
/// 前端据此隐藏/恢复 OSD:透明置顶 WebView 悬浮窗会占用 DWM 合成路径,
|
||||||
|
/// 禁用游戏的独立翻转(MPO),是游戏中掉帧的根源;隐藏悬浮窗即可排除影响。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn osd_start_game_watch(app: AppHandle) -> Result<(), String> {
|
||||||
|
// 停止旧线程,等待其退出后再启动新线程
|
||||||
|
stop_game_thread();
|
||||||
|
let stop_flag = game_stop().clone();
|
||||||
|
stop_flag.store(false, Ordering::SeqCst);
|
||||||
|
|
||||||
|
let app_handle = app.clone();
|
||||||
|
|
||||||
|
let handle = thread::spawn(move || {
|
||||||
|
let mut fullscreen_active = false;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if stop_flag.load(Ordering::SeqCst) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let fg = win_api::get_foreground_window();
|
||||||
|
let fullscreen = fg != 0
|
||||||
|
&& win_api::get_class_name(fg)
|
||||||
|
.map_or(false, |c| !win_api::is_system_ui_class(&c))
|
||||||
|
&& is_fullscreen_game_window(fg);
|
||||||
|
|
||||||
|
if fullscreen != fullscreen_active {
|
||||||
|
fullscreen_active = fullscreen;
|
||||||
|
let event = if fullscreen {
|
||||||
|
crate::constants::events::OSD_GAME_ACTIVE
|
||||||
|
} else {
|
||||||
|
crate::constants::events::OSD_GAME_INACTIVE
|
||||||
|
};
|
||||||
|
let _ = app_handle.emit(event, ());
|
||||||
|
crate::logger::log_info(
|
||||||
|
"osd",
|
||||||
|
&format!("全屏应用前台: {}", if fullscreen { "是 → 隐藏 OSD" } else { "否 → 恢复 OSD" }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
thread::sleep(Duration::from_millis(1000));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Ok(mut guard) = GAME_HANDLE.lock() {
|
||||||
|
*guard = Some(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// 停止所有 OSD 监视线程
|
/// 停止所有 OSD 监视线程
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn osd_stop_watch() {
|
pub fn osd_stop_watch() {
|
||||||
stop_drag_thread();
|
stop_drag_thread();
|
||||||
stop_topmost_thread();
|
stop_topmost_thread();
|
||||||
|
stop_game_thread();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 设置点击穿透(Rust 侧原生 WS_EX_TRANSPARENT,比 JS setIgnoreCursorEvents 更可靠)
|
/// 设置点击穿透(Rust 侧原生 WS_EX_TRANSPARENT,比 JS setIgnoreCursorEvents 更可靠)
|
||||||
@@ -378,6 +546,28 @@ pub fn osd_set_topmost(label: String, topmost: bool, app: AppHandle) -> Result<(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 原子设置窗口位置与尺寸(物理像素)
|
||||||
|
///
|
||||||
|
/// 一次调用同时更新位置和尺寸,避免 setSize + setPosition 两次 IPC 之间的
|
||||||
|
/// 中间帧(宽度已变、位置未动 → 视觉闪烁)。前端传入物理像素坐标。
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn osd_set_bounds(
|
||||||
|
label: String,
|
||||||
|
x: i32,
|
||||||
|
y: i32,
|
||||||
|
w: i32,
|
||||||
|
h: i32,
|
||||||
|
app: AppHandle,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
let hwnd = win_api::get_hwnd(&label, &app)
|
||||||
|
.ok_or_else(|| format!("窗口 {} 不存在", label))?;
|
||||||
|
win_api::set_bounds(hwnd, x, y, w, h);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// 启动原生拖动(右键长按触发)
|
/// 启动原生拖动(右键长按触发)
|
||||||
///
|
///
|
||||||
/// 同步关闭点击穿透(WS_EX_TRANSPARENT),然后在独立线程中调用
|
/// 同步关闭点击穿透(WS_EX_TRANSPARENT),然后在独立线程中调用
|
||||||
|
|||||||
@@ -11,6 +11,11 @@ use tauri::{AppHandle, Emitter, Manager};
|
|||||||
// CREATE_NO_WINDOW = 0x08000000,阻止子进程创建新的控制台窗口
|
// CREATE_NO_WINDOW = 0x08000000,阻止子进程创建新的控制台窗口
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
pub const CREATE_NO_WINDOW: u32 = 0x08000000;
|
pub const CREATE_NO_WINDOW: u32 = 0x08000000;
|
||||||
|
// CREATE_NEW_CONSOLE = 0x00000010,强制为控制台类子进程新开一个可见控制台窗口。
|
||||||
|
// 从 GUI 宿主(无控制台)直接 spawn cmd/powershell 等控制台程序时若不设置,
|
||||||
|
// 子进程会挂到隐藏控制台/不显示窗口,表现为"点击没反应"。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub const CREATE_NEW_CONSOLE: u32 = 0x00000010;
|
||||||
|
|
||||||
// Windows Job Object 相关常量,用于异常退出时自动清理子进程
|
// Windows Job Object 相关常量,用于异常退出时自动清理子进程
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
|||||||
@@ -0,0 +1,344 @@
|
|||||||
|
//! 快速面板:基于 7-Zip(binaries/7z.exe)的批量文件操作。
|
||||||
|
//!
|
||||||
|
//! - 批量解压:逐文件调用 7z 控制台,支持一次传入统一密码(`-p`),
|
||||||
|
//! 每完成一个文件通过事件推送进度,前端可实时展示。
|
||||||
|
//! - 批量重命名:`regex` 匹配文件名生成预览,确认后执行 `fs::rename`。
|
||||||
|
//! - 目录列表:供前端展示当前目录的压缩包 / 文件列表。
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use specta::Type;
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
|
||||||
|
use crate::constants::events::QUICKPANEL_EXTRACT_PROGRESS;
|
||||||
|
|
||||||
|
/// 7z 可执行文件名(与 7z.dll 同目录,位于 resources/binaries)。
|
||||||
|
const _7Z_EXE: &str = "binaries/7z.exe";
|
||||||
|
|
||||||
|
/// 支持的压缩包扩展名(解压面板中列出)。
|
||||||
|
const ARCHIVE_EXTS: &[&str] = &[
|
||||||
|
".zip", ".7z", ".rar", ".tar", ".gz", ".tgz", ".bz2", ".tbz", ".xz", ".txz", ".zst",
|
||||||
|
".tzst", ".cab", ".lzma",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// 定位 7z 可执行文件(resources/binaries/7z.exe)。
|
||||||
|
fn locate_7z(app: &AppHandle) -> Option<PathBuf> {
|
||||||
|
let path = app
|
||||||
|
.path()
|
||||||
|
.resolve(_7Z_EXE, tauri::path::BaseDirectory::Resource)
|
||||||
|
.ok()?;
|
||||||
|
if path.exists() {
|
||||||
|
Some(path)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ArchiveInfo {
|
||||||
|
pub name: String,
|
||||||
|
pub path: String,
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct FileEntry {
|
||||||
|
pub name: String,
|
||||||
|
pub path: String,
|
||||||
|
pub is_dir: bool,
|
||||||
|
pub size: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ExtractResult {
|
||||||
|
pub name: String,
|
||||||
|
pub path: String,
|
||||||
|
pub ok: bool,
|
||||||
|
pub error: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ExtractProgress {
|
||||||
|
pub done: usize,
|
||||||
|
pub total: usize,
|
||||||
|
pub current: String,
|
||||||
|
pub ok: bool,
|
||||||
|
pub error: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RenamePreview {
|
||||||
|
pub path: String,
|
||||||
|
pub old_name: String,
|
||||||
|
pub new_name: String,
|
||||||
|
pub error: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RenameItem {
|
||||||
|
pub path: String,
|
||||||
|
pub old_name: String,
|
||||||
|
pub new_name: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct RenameResult {
|
||||||
|
pub old_name: String,
|
||||||
|
pub new_name: String,
|
||||||
|
pub ok: bool,
|
||||||
|
pub error: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_archive(name: &str) -> bool {
|
||||||
|
let lower = name.to_lowercase();
|
||||||
|
ARCHIVE_EXTS.iter().any(|ext| lower.ends_with(ext))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出目录下的压缩包文件(供批量解压面板使用)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_list_archives(dir: String) -> Result<Vec<ArchiveInfo>, String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let d = Path::new(&dir);
|
||||||
|
if !d.is_dir() {
|
||||||
|
return Err(format!("目录不存在: {dir}"));
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
|
||||||
|
let Ok(entry) = entry else { continue };
|
||||||
|
let path = entry.path();
|
||||||
|
if !path.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if is_archive(&name) {
|
||||||
|
let size = path.metadata().map(|m| m.len()).unwrap_or(0);
|
||||||
|
out.push(ArchiveInfo {
|
||||||
|
name,
|
||||||
|
path: path.to_string_lossy().to_string(),
|
||||||
|
size,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||||
|
Ok(out)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("读取压缩包失败: {e}"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_list_dir(dir: String) -> Result<Vec<FileEntry>, String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let d = Path::new(&dir);
|
||||||
|
if !d.is_dir() {
|
||||||
|
return Err(format!("目录不存在: {dir}"));
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for entry in std::fs::read_dir(d).map_err(|e| format!("读取目录失败: {e}"))? {
|
||||||
|
let Ok(entry) = entry else { continue };
|
||||||
|
let path = entry.path();
|
||||||
|
let is_dir = path.is_dir();
|
||||||
|
let name = path
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let size = if is_dir {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
path.metadata().map(|m| m.len()).unwrap_or(0)
|
||||||
|
};
|
||||||
|
out.push(FileEntry {
|
||||||
|
name,
|
||||||
|
path: path.to_string_lossy().to_string(),
|
||||||
|
is_dir,
|
||||||
|
size,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.sort_by(|a, b| {
|
||||||
|
b.is_dir
|
||||||
|
.cmp(&a.is_dir)
|
||||||
|
.then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
|
||||||
|
});
|
||||||
|
Ok(out)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("读取目录失败: {e}"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_one(
|
||||||
|
exe: &Path,
|
||||||
|
archive: &str,
|
||||||
|
dest: &str,
|
||||||
|
password: Option<&str>,
|
||||||
|
into_subfolder: bool,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let archive_path = Path::new(archive);
|
||||||
|
let mut cmd = Command::new(exe);
|
||||||
|
cmd.arg("x").arg(archive_path);
|
||||||
|
if into_subfolder {
|
||||||
|
// 解压到「压缩包同名子文件夹」,避免文件散落在当前目录。
|
||||||
|
let sub = archive_path
|
||||||
|
.file_stem()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_else(|| "extracted".into());
|
||||||
|
let sub_dir = Path::new(dest).join(&sub);
|
||||||
|
std::fs::create_dir_all(&sub_dir).map_err(|e| format!("创建目录 {sub} 失败: {e}"))?;
|
||||||
|
cmd.arg(format!("-o{}", sub_dir.display()));
|
||||||
|
} else {
|
||||||
|
cmd.arg(format!("-o{}", dest));
|
||||||
|
}
|
||||||
|
cmd.arg("-y"); // 全自动覆盖确认
|
||||||
|
if let Some(p) = password.filter(|p| !p.is_empty()) {
|
||||||
|
cmd.arg(format!("-p{p}"));
|
||||||
|
}
|
||||||
|
// 静默普通输出,仅错误进 stderr,逐文件粒度足够时无需 -bsp1 进度。
|
||||||
|
cmd.arg("-bso0").arg("-bse1").arg("-bsp0");
|
||||||
|
// 以 7z.exe 所在目录为工作目录,确保同目录的 7z.dll 可被加载。
|
||||||
|
if let Some(dir) = exe.parent() {
|
||||||
|
cmd.current_dir(dir);
|
||||||
|
}
|
||||||
|
let output = cmd.output().map_err(|e| format!("启动 7-Zip 失败: {e}"))?;
|
||||||
|
if output.status.success() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
let msg = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||||
|
let code = output.status.code().unwrap_or(-1);
|
||||||
|
Err(if msg.is_empty() {
|
||||||
|
format!("退出码 {code}")
|
||||||
|
} else {
|
||||||
|
msg
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
|
||||||
|
/// `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
|
||||||
|
/// 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_batch_extract(
|
||||||
|
app: AppHandle,
|
||||||
|
files: Vec<String>,
|
||||||
|
dest_dir: String,
|
||||||
|
password: Option<String>,
|
||||||
|
into_subfolder: bool,
|
||||||
|
) -> Result<Vec<ExtractResult>, String> {
|
||||||
|
let exe = locate_7z(&app).ok_or("未找到 7-Zip 组件(binaries/7z.exe),请重新安装")?;
|
||||||
|
let total = files.len();
|
||||||
|
let results = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let mut results = Vec::with_capacity(total);
|
||||||
|
for (idx, file) in files.iter().enumerate() {
|
||||||
|
let err = extract_one(&exe, file, &dest_dir, password.as_deref(), into_subfolder);
|
||||||
|
let name = Path::new(file)
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_else(|| file.clone());
|
||||||
|
let (ok, error) = match err {
|
||||||
|
Ok(()) => (true, String::new()),
|
||||||
|
Err(e) => (false, e),
|
||||||
|
};
|
||||||
|
results.push(ExtractResult {
|
||||||
|
name,
|
||||||
|
path: file.clone(),
|
||||||
|
ok,
|
||||||
|
error: error.clone(),
|
||||||
|
});
|
||||||
|
let _ = app.emit(
|
||||||
|
QUICKPANEL_EXTRACT_PROGRESS,
|
||||||
|
ExtractProgress {
|
||||||
|
done: idx + 1,
|
||||||
|
total,
|
||||||
|
current: results[idx].name.clone(),
|
||||||
|
ok,
|
||||||
|
error,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
results
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("解压任务异常终止: {e}"))?;
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 正则批量重命名预览:对每个文件名应用 `pattern → replacement`,
|
||||||
|
/// 仅返回有匹配的文件,`newName` 为替换结果。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_preview_rename(
|
||||||
|
files: Vec<String>,
|
||||||
|
pattern: String,
|
||||||
|
replacement: String,
|
||||||
|
) -> Result<Vec<RenamePreview>, String> {
|
||||||
|
let re = regex::Regex::new(&pattern).map_err(|e| format!("正则表达式无效: {e}"))?;
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for file in files {
|
||||||
|
let name = Path::new(&file)
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if !re.is_match(&name) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let new_name = re.replace_all(&name, replacement.as_str()).to_string();
|
||||||
|
let error = if new_name.is_empty() || new_name == name {
|
||||||
|
"名称未变化".to_string()
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
out.push(RenamePreview {
|
||||||
|
path: file,
|
||||||
|
old_name: name,
|
||||||
|
new_name,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 执行重命名。同一目录下若目标已存在则跳过该项。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_apply_rename(items: Vec<RenameItem>) -> Result<Vec<RenameResult>, String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for item in items {
|
||||||
|
let result = (|| -> Result<(), String> {
|
||||||
|
if item.new_name.is_empty() {
|
||||||
|
return Err("新文件名为空".into());
|
||||||
|
}
|
||||||
|
if item.new_name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
|
||||||
|
return Err("文件名包含非法字符".into());
|
||||||
|
}
|
||||||
|
let old = Path::new(&item.path);
|
||||||
|
let parent = old.parent().unwrap_or(Path::new("."));
|
||||||
|
let new_path = parent.join(&item.new_name);
|
||||||
|
if new_path.exists() {
|
||||||
|
return Err("目标已存在".into());
|
||||||
|
}
|
||||||
|
std::fs::rename(old, &new_path).map_err(|e| format!("重命名失败: {e}"))?;
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
out.push(RenameResult {
|
||||||
|
old_name: item.old_name,
|
||||||
|
new_name: item.new_name,
|
||||||
|
ok: result.is_ok(),
|
||||||
|
error: result.err().unwrap_or_default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
@@ -1,10 +1,20 @@
|
|||||||
//! Tauri 命令:快速面板模块
|
//! Tauri 命令:快速面板模块
|
||||||
|
|
||||||
use tauri::AppHandle;
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
|
||||||
use super::popup::{self, QuickPanelSettings};
|
use super::popup::{self, QuickPanelSettings};
|
||||||
use super::{file_index, app_scanner, icon_extractor};
|
use super::{file_index, app_scanner, icon_extractor};
|
||||||
|
|
||||||
|
/// 批量删除单个条目的结果。
|
||||||
|
#[derive(serde::Serialize, serde::Deserialize, specta::Type, Clone)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct DeleteResult {
|
||||||
|
pub name: String,
|
||||||
|
pub path: String,
|
||||||
|
pub ok: bool,
|
||||||
|
pub error: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// 读取快速面板设置(快捷键等)
|
/// 读取快速面板设置(快捷键等)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
@@ -12,14 +22,17 @@ pub async fn quickpanel_get_settings(app: AppHandle) -> Result<QuickPanelSetting
|
|||||||
Ok(popup::load_settings(&app))
|
Ok(popup::load_settings(&app))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口
|
/// 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口,
|
||||||
|
/// 索引目录变化时闲时自动重建索引。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn quickpanel_save_settings(
|
pub async fn quickpanel_save_settings(
|
||||||
settings: QuickPanelSettings,
|
settings: QuickPanelSettings,
|
||||||
app: AppHandle,
|
app: AppHandle,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let prev_shortcut = popup::load_settings(&app).shortcut;
|
let prev = popup::load_settings(&app);
|
||||||
|
let prev_shortcut = prev.shortcut.clone();
|
||||||
|
let dirs_changed = prev.index_dirs != settings.index_dirs;
|
||||||
popup::save_settings(&app, &settings)?;
|
popup::save_settings(&app, &settings)?;
|
||||||
// 快捷键变化时重新注册(共享工具模块,原子化 + 冲突检测)
|
// 快捷键变化时重新注册(共享工具模块,原子化 + 冲突检测)
|
||||||
if settings.shortcut != prev_shortcut {
|
if settings.shortcut != prev_shortcut {
|
||||||
@@ -31,6 +44,10 @@ pub async fn quickpanel_save_settings(
|
|||||||
popup::ensure_window(&app);
|
popup::ensure_window(&app);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 索引目录变更:闲时自动重建(新增/移除路径后无需手动点"构建索引")
|
||||||
|
if dirs_changed {
|
||||||
|
schedule_auto_build(app, true);
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,6 +93,26 @@ pub async fn quickpanel_show_window(app: AppHandle) -> Result<(), String> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 显示主窗口并强制置为前台。
|
||||||
|
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||||
|
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_focus_main_window(app: AppHandle) -> Result<(), String> {
|
||||||
|
use crate::constants::windows::MAIN;
|
||||||
|
if let Some(window) = app.get_webview_window(MAIN) {
|
||||||
|
window.show().map_err(|e| e.to_string())?;
|
||||||
|
window.unminimize().map_err(|e| e.to_string())?;
|
||||||
|
match window.hwnd() {
|
||||||
|
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||||
|
Err(_) => {
|
||||||
|
window.set_focus().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗)
|
/// 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
@@ -95,25 +132,100 @@ pub fn quickpanel_lock_screen() -> Result<(), String> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 初始化文件索引数据库(应用启动时调用)
|
/// 闲时自动建立索引的启动延迟(秒):避开应用启动/模块加载的 IO 高峰
|
||||||
|
const AUTO_BUILD_START_DELAY: u64 = 6;
|
||||||
|
/// 判定"系统空闲"的阈值(毫秒):用户停止输入超过该时长才执行构建
|
||||||
|
const AUTO_BUILD_IDLE_MS: u64 = 3000;
|
||||||
|
/// 等待系统空闲的最长轮询次数(每次间隔 2s,约 60s 上限,超时后不再等待直接构建)
|
||||||
|
const AUTO_BUILD_MAX_WAIT_ITERS: u32 = 30;
|
||||||
|
|
||||||
|
/// 解析要索引的目录:设置为空时用默认(桌面/文档/下载)
|
||||||
|
fn resolve_index_dirs(app: &AppHandle) -> Vec<String> {
|
||||||
|
let settings = popup::load_settings(app);
|
||||||
|
if settings.index_dirs.is_empty() {
|
||||||
|
popup::QuickPanelSettings::default().index_dirs
|
||||||
|
} else {
|
||||||
|
settings.index_dirs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 闲时自动建立/重建文件索引。
|
||||||
|
/// - `force=false`:仅首次(从未构建过)自动建立
|
||||||
|
/// - `force=true`:忽略是否已构建,直接重建(索引目录变更后调用)
|
||||||
|
///
|
||||||
|
/// 流程:先延迟避开启动 IO 高峰,再轮询等待系统空闲(用户停止输入),
|
||||||
|
/// 空闲后才开始构建,避免与应用运行/用户操作抢 IO 导致卡顿。
|
||||||
|
/// 构建完成后向前端广播 `quickpanel-index-updated` 事件(负载为条目数),
|
||||||
|
/// 供设置页刷新统计、弹窗启用文件搜索。
|
||||||
|
fn schedule_auto_build(app: AppHandle, force: bool) {
|
||||||
|
tauri::async_runtime::spawn(async move {
|
||||||
|
// 1. 启动延迟:避开应用启动、模块加载等 IO 高峰
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(AUTO_BUILD_START_DELAY)).await;
|
||||||
|
// 2. 轮询等待系统空闲(判定阈值见 AUTO_BUILD_IDLE_MS)
|
||||||
|
for _ in 0..AUTO_BUILD_MAX_WAIT_ITERS {
|
||||||
|
if crate::win32_util::get_idle_time_ms() >= AUTO_BUILD_IDLE_MS {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
|
||||||
|
}
|
||||||
|
// 3. 非强制模式:已构建过则跳过(幂等,避免每次启动重建)
|
||||||
|
if !force {
|
||||||
|
file_index::ensure_initialized(&app);
|
||||||
|
let stats = file_index::stats();
|
||||||
|
if stats.last_built_at > 0 && !stats.last_built_dirs.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 4. 构建(build_index 内部有并发保护,重复调度/手动构建并发时幂等跳过)
|
||||||
|
let dirs = resolve_index_dirs(&app);
|
||||||
|
match tauri::async_runtime::spawn_blocking(move || file_index::build_index(&dirs)).await {
|
||||||
|
Ok(Ok(count)) => {
|
||||||
|
crate::logger::log_info(
|
||||||
|
"quickpanel",
|
||||||
|
&format!("闲时自动索引完成,共 {} 条", count),
|
||||||
|
);
|
||||||
|
let _ = app.emit(crate::constants::events::QUICKPANEL_INDEX_UPDATED, count);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
crate::logger::log_error("quickpanel", "闲时自动索引失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 初始化文件索引数据库(应用启动时调用)。
|
||||||
|
/// 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
|
||||||
|
/// 无需重建即可继续自动同步文件变更。
|
||||||
|
/// 若从未构建过(首次运行),闲时自动建立索引,无需用户手动点"构建索引"。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn quickpanel_init_file_index(app: AppHandle) -> Result<(), String> {
|
pub async fn quickpanel_init_file_index(app: AppHandle) -> Result<(), String> {
|
||||||
tauri::async_runtime::spawn_blocking(move || file_index::init(&app))
|
let app_for_build = app.clone();
|
||||||
|
let need_auto_build = tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
file_index::init(&app_for_build);
|
||||||
|
let stats = file_index::stats();
|
||||||
|
if stats.last_built_at > 0 && !stats.last_built_dirs.is_empty() {
|
||||||
|
file_index::start_watcher(&stats.last_built_dirs);
|
||||||
|
}
|
||||||
|
// 从未构建过索引 → 需要闲时自动建立
|
||||||
|
stats.last_built_at == 0 || stats.last_built_dirs.is_empty()
|
||||||
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("索引初始化任务失败: {}", e))
|
.map_err(|e| format!("索引初始化任务失败: {}", e))?;
|
||||||
|
|
||||||
|
if need_auto_build {
|
||||||
|
schedule_auto_build(app, false);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用)
|
/// 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String> {
|
pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String> {
|
||||||
let settings = popup::load_settings(&app);
|
let dirs = resolve_index_dirs(&app);
|
||||||
let dirs = if settings.index_dirs.is_empty() {
|
// 懒加载:首次构建时自动初始化 DB 连接
|
||||||
popup::QuickPanelSettings::default().index_dirs
|
file_index::ensure_initialized(&app);
|
||||||
} else {
|
|
||||||
settings.index_dirs
|
|
||||||
};
|
|
||||||
// 阻塞操作放到 spawn_blocking
|
// 阻塞操作放到 spawn_blocking
|
||||||
tauri::async_runtime::spawn_blocking(move || file_index::build_index(&dirs))
|
tauri::async_runtime::spawn_blocking(move || file_index::build_index(&dirs))
|
||||||
.await
|
.await
|
||||||
@@ -126,7 +238,10 @@ pub async fn quickpanel_build_file_index(app: AppHandle) -> Result<i64, String>
|
|||||||
pub async fn quickpanel_search_files(
|
pub async fn quickpanel_search_files(
|
||||||
query: String,
|
query: String,
|
||||||
limit: Option<i64>,
|
limit: Option<i64>,
|
||||||
|
app: AppHandle,
|
||||||
) -> Result<Vec<file_index::FileRecord>, String> {
|
) -> Result<Vec<file_index::FileRecord>, String> {
|
||||||
|
// 懒加载:首次搜索时自动初始化 DB 连接
|
||||||
|
file_index::ensure_initialized(&app);
|
||||||
tauri::async_runtime::spawn_blocking(move || file_index::search(&query, limit.unwrap_or(50)))
|
tauri::async_runtime::spawn_blocking(move || file_index::search(&query, limit.unwrap_or(50)))
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("搜索任务失败: {}", e))
|
.map_err(|e| format!("搜索任务失败: {}", e))
|
||||||
@@ -135,7 +250,9 @@ pub async fn quickpanel_search_files(
|
|||||||
/// 获取索引状态
|
/// 获取索引状态
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn quickpanel_file_index_stats() -> file_index::IndexStats {
|
pub async fn quickpanel_file_index_stats(app: AppHandle) -> file_index::IndexStats {
|
||||||
|
// 懒加载:查询状态前确保 DB 已初始化(未初始化时 stats 返回全 0)
|
||||||
|
file_index::ensure_initialized(&app);
|
||||||
file_index::stats()
|
file_index::stats()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -298,6 +415,69 @@ fn delete_file_impl(path: &str) -> Result<(), String> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
|
||||||
|
/// 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
|
||||||
|
/// 锁定的文件仍会失败并返回原因)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn quickpanel_delete_files(
|
||||||
|
paths: Vec<String>,
|
||||||
|
force: bool,
|
||||||
|
) -> Result<Vec<DeleteResult>, String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for path in paths {
|
||||||
|
let name = std::path::Path::new(&path)
|
||||||
|
.file_name()
|
||||||
|
.map(|s| s.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_else(|| path.clone());
|
||||||
|
let result = if force {
|
||||||
|
delete_force_impl(&path)
|
||||||
|
} else {
|
||||||
|
delete_file_impl(&path)
|
||||||
|
};
|
||||||
|
out.push(DeleteResult {
|
||||||
|
name,
|
||||||
|
path: path.clone(),
|
||||||
|
ok: result.is_ok(),
|
||||||
|
error: result.err().unwrap_or_default(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("删除任务失败: {e}"))?
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 强行删除:递归清除只读属性后永久删除(不经过回收站)。
|
||||||
|
fn delete_force_impl(path: &str) -> Result<(), String> {
|
||||||
|
let p = std::path::Path::new(path);
|
||||||
|
clear_readonly(p);
|
||||||
|
if p.is_dir() {
|
||||||
|
std::fs::remove_dir_all(p).map_err(|e| format!("删除失败: {e}"))
|
||||||
|
} else {
|
||||||
|
std::fs::remove_file(p).map_err(|e| format!("删除失败: {e}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 递归清除只读属性(只读文件/目录无法直接删除)。
|
||||||
|
fn clear_readonly(path: &std::path::Path) {
|
||||||
|
if let Ok(meta) = std::fs::metadata(path) {
|
||||||
|
if meta.permissions().readonly() {
|
||||||
|
let mut perms = meta.permissions();
|
||||||
|
perms.set_readonly(false);
|
||||||
|
let _ = std::fs::set_permissions(path, perms);
|
||||||
|
}
|
||||||
|
if meta.is_dir() {
|
||||||
|
if let Ok(rd) = std::fs::read_dir(path) {
|
||||||
|
for entry in rd.flatten() {
|
||||||
|
clear_readonly(&entry.path());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 运行自定义命令(执行可执行文件 + 参数)
|
/// 运行自定义命令(执行可执行文件 + 参数)
|
||||||
/// .lnk 快捷方式不能直接 spawn(os error 193),需通过 cmd /C 启动
|
/// .lnk 快捷方式不能直接 spawn(os error 193),需通过 cmd /C 启动
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@@ -325,11 +505,35 @@ pub fn quickpanel_run_custom_command(command: String, args: Vec<String>) -> Resu
|
|||||||
|
|
||||||
/// 运行系统命令(不设置 CREATE_NO_WINDOW,使 cmd/powershell/regedit 等显示自身窗口)
|
/// 运行系统命令(不设置 CREATE_NO_WINDOW,使 cmd/powershell/regedit 等显示自身窗口)
|
||||||
/// 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
/// 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
||||||
|
/// - 控制台类交互程序(cmd/powershell/pwsh)额外设置 CREATE_NEW_CONSOLE,
|
||||||
|
/// 否则从 GUI 宿主启动时无可见控制台窗口(表现为"点击没反应")。
|
||||||
|
/// - .msc 控制台文件(如 devmgmt.msc)不可被 CreateProcess 直接执行,
|
||||||
|
/// 改由 mmc 打开(路径解析到 System32,不受当前工作目录影响)。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn quickpanel_run_system_command(command: String, args: Vec<String>) -> Result<(), String> {
|
pub fn quickpanel_run_system_command(command: String, args: Vec<String>) -> Result<(), String> {
|
||||||
|
let lower = command.to_lowercase();
|
||||||
|
if lower.ends_with(".msc") {
|
||||||
|
// 控制台文件:通过 mmc 打开(GUI 程序,无需新控制台)
|
||||||
|
let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| "C:\\Windows".into());
|
||||||
|
let path = format!("{}\\System32\\{}", system_root, command);
|
||||||
|
let mut c = std::process::Command::new("mmc");
|
||||||
|
c.arg(&path);
|
||||||
|
return c
|
||||||
|
.spawn()
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|e| format!("运行系统命令失败: {}", e));
|
||||||
|
}
|
||||||
let mut cmd = std::process::Command::new(&command);
|
let mut cmd = std::process::Command::new(&command);
|
||||||
cmd.args(&args);
|
cmd.args(&args);
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
let c = lower;
|
||||||
|
if c == "cmd" || c == "powershell" || c == "pwsh" {
|
||||||
|
cmd.creation_flags(crate::process_manager::CREATE_NEW_CONSOLE);
|
||||||
|
}
|
||||||
|
}
|
||||||
cmd.spawn().map_err(|e| format!("运行系统命令失败: {}", e))?;
|
cmd.spawn().map_err(|e| format!("运行系统命令失败: {}", e))?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
//! 快速面板:检测前台 Explorer 窗口的当前目录。
|
||||||
|
//!
|
||||||
|
//! 必须在快捷键回调(`show_popup`)内调用:此时前台窗口仍是资源管理器,
|
||||||
|
//! 面板尚未取得焦点,`GetForegroundWindow` 拿到的才是 Explorer 主窗口;
|
||||||
|
//! 若等面板显示后再调用,前台就变成面板自身了。
|
||||||
|
//!
|
||||||
|
//! 思路(Listary / PowerToys Run 同款):前台窗口 HWND 匹配 `IShellWindows`
|
||||||
|
//! 中某个 Shell 窗口 → 取其 `LocationURL`(file:///...)→ 转成本地路径。
|
||||||
|
//!
|
||||||
|
//! Win11 多选项卡:同一顶层窗口下每个选项卡都是独立的 `IShellWindows` 条目,
|
||||||
|
//! 共享顶层 HWND。活动选项卡的内容窗口(`ShellTabWindowClass`)在子窗口
|
||||||
|
//! z-order 顶层,用 `IID_IShellBrowser` 作为 `QueryService` 的 service ID 获取
|
||||||
|
//! 每个选项卡自己的 `IShellBrowser`(而非 `SID_STopLevelBrowser` 返回的顶层
|
||||||
|
//! browser),再通过 `GetWindow()` 拿到该选项卡的内容窗口句柄,与活动选项卡
|
||||||
|
//! 的内容窗口比对,从而定位当前正在浏览的选项卡(`IsWindowVisible` 对所有
|
||||||
|
//! 选项卡都成立,不可用)。
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::core::ComInterface;
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::Win32::Foundation::HWND;
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::Win32::System::Com::{
|
||||||
|
CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_ALL, COINIT_APARTMENTTHREADED,
|
||||||
|
IServiceProvider,
|
||||||
|
};
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::Win32::System::Variant::{VARIANT, VT_I4};
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::Win32::UI::Shell::{
|
||||||
|
IWebBrowserApp, IShellBrowser, IShellWindows, ShellWindows,
|
||||||
|
};
|
||||||
|
#[cfg(windows)]
|
||||||
|
use windows::Win32::UI::WindowsAndMessaging::{
|
||||||
|
GetClassNameW, GetForegroundWindow, GetWindow, GW_CHILD, GW_HWNDNEXT,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// 检测前台 Explorer 窗口的当前目录。
|
||||||
|
/// 返回 `None`:前台不是 Explorer / COM 初始化失败 / URL 无法转路径。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn detect_explorer_folder() -> Option<String> {
|
||||||
|
// 首次 COM 初始化失败(例如已在 MTA 线程)时,后续 COM 调用一般仍可用,忽略错误继续。
|
||||||
|
let _ = unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED) };
|
||||||
|
let fg = unsafe { GetForegroundWindow() };
|
||||||
|
let result = if fg.0 == 0 {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
unsafe { find_folder_for_hwnd(fg) }
|
||||||
|
};
|
||||||
|
unsafe { CoUninitialize() };
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe fn find_folder_for_hwnd(fg: HWND) -> Option<String> {
|
||||||
|
let shell: IShellWindows = CoCreateInstance(&ShellWindows, None, CLSCTX_ALL).ok()?;
|
||||||
|
let count = shell.Count().ok()?;
|
||||||
|
// Win11 多选项卡:活动选项卡的内容窗口(ShellTabWindowClass)在子窗口 z-order
|
||||||
|
// 顶层。在 IShellWindows 条目中,用 IShellBrowser::GetWindow() 取到的内容窗口
|
||||||
|
// HWND 与它比对,即可定位当前正在浏览的选项卡(IsWindowVisible 对所有选项卡
|
||||||
|
// 都成立,不可用)。
|
||||||
|
let active_tab = find_active_shell_tab(fg);
|
||||||
|
for i in 0..count {
|
||||||
|
// 索引过期的窗口会返回失败,跳过继续即可,不能 `?` 提前结束整个循环。
|
||||||
|
// 0.52 的 Win32 VARIANT 无 From<i32>,手动构造 VT_I4 变体。
|
||||||
|
let mut index = VARIANT::default();
|
||||||
|
{
|
||||||
|
let value = &mut *index.Anonymous.Anonymous;
|
||||||
|
value.vt = VT_I4;
|
||||||
|
value.Anonymous.lVal = i;
|
||||||
|
}
|
||||||
|
let Ok(dispatch) = shell.Item(index) else { continue };
|
||||||
|
let Ok(app) = dispatch.cast::<IWebBrowserApp>() else { continue };
|
||||||
|
// 只考虑前台顶层窗口对应的条目;同一窗口的多个选项卡条目共享顶层句柄。
|
||||||
|
let Ok(hwnd) = app.HWND() else { continue };
|
||||||
|
if HWND(hwnd.0) != fg {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// 有选项卡时,必须匹配活动选项卡的内容窗口;否则退化为任意条目(旧版无选项卡)。
|
||||||
|
if let Some(active) = active_tab {
|
||||||
|
let Ok(svc) = app.cast::<IServiceProvider>() else { continue };
|
||||||
|
let Ok(browser) = svc.QueryService::<IShellBrowser>(&IShellBrowser::IID) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Ok(this_tab) = browser.GetWindow() else { continue };
|
||||||
|
if this_tab != active {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(url) = app.LocationURL() {
|
||||||
|
return url_to_path(&url.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 枚举前台窗口的子窗口(z-order 自上而下),返回第一个类名为 `ShellTabWindowClass`
|
||||||
|
/// 的窗口句柄,即 Win11 资源管理器活动选项卡的内容窗口;无选项卡时返回 `None`。
|
||||||
|
#[cfg(windows)]
|
||||||
|
unsafe fn find_active_shell_tab(fg: HWND) -> Option<HWND> {
|
||||||
|
const CLASS: &str = "ShellTabWindowClass";
|
||||||
|
let mut hwnd = GetWindow(fg, GW_CHILD);
|
||||||
|
while hwnd.0 != 0 {
|
||||||
|
let mut buf = [0u16; 64];
|
||||||
|
let len = GetClassNameW(hwnd, &mut buf);
|
||||||
|
if len > 0 {
|
||||||
|
let name = String::from_utf16_lossy(&buf[..len as usize]);
|
||||||
|
if name == CLASS {
|
||||||
|
return Some(hwnd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hwnd = GetWindow(hwnd, GW_HWNDNEXT);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 把 `file:///C:/xxx`(可能带百分号编码)转成本地路径,仅接受目录。
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn url_to_path(url: &str) -> Option<String> {
|
||||||
|
if !url.starts_with("file:") {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let parsed = url::Url::parse(url).ok()?;
|
||||||
|
let path = parsed.to_file_path().ok()?;
|
||||||
|
let path = Path::new(&path);
|
||||||
|
if path.is_dir() {
|
||||||
|
Some(path.to_string_lossy().to_string())
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 非 Windows 平台占位:保持模块可编译。
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn detect_explorer_folder() -> Option<String> {
|
||||||
|
None
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::time::UNIX_EPOCH;
|
use std::time::UNIX_EPOCH;
|
||||||
|
|
||||||
use rusqlite::{params, Connection};
|
use rusqlite::{params, Connection};
|
||||||
@@ -93,6 +94,17 @@ pub fn init(app: &AppHandle) {
|
|||||||
crate::logger::log_info("quickpanel", &format!("文件索引 DB 已就绪: {}", path.display()));
|
crate::logger::log_info("quickpanel", &format!("文件索引 DB 已就绪: {}", path.display()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 懒加载:首次访问文件索引时自动初始化(若尚未初始化)。
|
||||||
|
/// 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。
|
||||||
|
pub fn ensure_initialized(app: &AppHandle) {
|
||||||
|
let guard = index_slot().lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if guard.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
drop(guard);
|
||||||
|
init(app);
|
||||||
|
}
|
||||||
|
|
||||||
/// 判断索引是否已初始化
|
/// 判断索引是否已初始化
|
||||||
fn with_conn<F, R>(f: F) -> Option<R>
|
fn with_conn<F, R>(f: F) -> Option<R>
|
||||||
where
|
where
|
||||||
@@ -107,10 +119,37 @@ where
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 构建锁:防止手动构建与闲时自动构建并发执行(全量重建含 DELETE+INSERT,
|
||||||
|
/// 两个构建交错会互相清空对方刚写入的数据,导致索引残缺)。
|
||||||
|
static BUILDING: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// 尝试开始构建;已在构建中则返回 false。
|
||||||
|
pub fn try_begin_build() -> bool {
|
||||||
|
BUILDING
|
||||||
|
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||||
|
.is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 构建结束(成功/失败)后调用,释放构建锁。
|
||||||
|
pub fn end_build() {
|
||||||
|
BUILDING.store(false, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
/// 遍历指定目录列表建立索引(全量重建)。
|
/// 遍历指定目录列表建立索引(全量重建)。
|
||||||
/// 返回索引条目数。在 spawn_blocking 中调用。
|
/// 返回索引条目数。在 spawn_blocking 中调用。
|
||||||
/// 重建完成后自动启动 notify 监听器做增量更新。
|
/// 重建完成后自动启动 notify 监听器做增量更新。
|
||||||
|
/// 若已有构建正在进行(手动/自动并发),直接返回 Ok(0),由进行中的构建负责更新索引。
|
||||||
pub fn build_index(dirs: &[String]) -> Result<i64, String> {
|
pub fn build_index(dirs: &[String]) -> Result<i64, String> {
|
||||||
|
if !try_begin_build() {
|
||||||
|
crate::logger::log_info("quickpanel", "索引构建已在进行中,跳过本次请求");
|
||||||
|
return Ok(0);
|
||||||
|
}
|
||||||
|
let result = build_index_inner(dirs);
|
||||||
|
end_build();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_index_inner(dirs: &[String]) -> Result<i64, String> {
|
||||||
// 清空旧数据
|
// 清空旧数据
|
||||||
let cleared = with_conn(|conn| {
|
let cleared = with_conn(|conn| {
|
||||||
conn.execute("DELETE FROM files", []).ok()
|
conn.execute("DELETE FROM files", []).ok()
|
||||||
@@ -333,16 +372,51 @@ pub fn start_watcher(dirs: &[String]) {
|
|||||||
crate::logger::log_info("quickpanel", &format!("notify 监听已启动,监听 {} 个目录", dirs.len()));
|
crate::logger::log_info("quickpanel", &format!("notify 监听已启动,监听 {} 个目录", dirs.len()));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 处理文件系统事件:创建/修改 → upsert,删除 → remove,重命名 → remove + upsert
|
/// 处理文件系统事件:
|
||||||
|
/// - 创建/数据或元数据修改 → upsert
|
||||||
|
/// - 重命名:旧路径(From) → remove,新路径(To) → upsert
|
||||||
|
/// - 删除 → remove
|
||||||
fn handle_fs_event(event: ¬ify::Event) {
|
fn handle_fs_event(event: ¬ify::Event) {
|
||||||
|
use notify::event::{ModifyKind, RenameMode};
|
||||||
|
|
||||||
match event.kind {
|
match event.kind {
|
||||||
EventKind::Create(_) | EventKind::Modify(_) => {
|
// 创建、数据/元数据修改、类型未知 → upsert
|
||||||
|
EventKind::Create(_)
|
||||||
|
| EventKind::Modify(ModifyKind::Data(_))
|
||||||
|
| EventKind::Modify(ModifyKind::Metadata(_))
|
||||||
|
| EventKind::Modify(ModifyKind::Other)
|
||||||
|
| EventKind::Modify(ModifyKind::Any) => {
|
||||||
for path in &event.paths {
|
for path in &event.paths {
|
||||||
if path.exists() {
|
if path.exists() {
|
||||||
upsert_path(path);
|
upsert_path(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 重命名旧路径 → 删除旧记录(含目录子项,避免索引残留失效路径)
|
||||||
|
EventKind::Modify(ModifyKind::Name(RenameMode::From)) => {
|
||||||
|
for path in &event.paths {
|
||||||
|
remove_path(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 重命名新路径 → 写入新记录
|
||||||
|
EventKind::Modify(ModifyKind::Name(RenameMode::To)) => {
|
||||||
|
for path in &event.paths {
|
||||||
|
if path.exists() {
|
||||||
|
upsert_path(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 重命名模式未知:存在则写入,不存在则删除(幂等兜底)
|
||||||
|
EventKind::Modify(ModifyKind::Name(RenameMode::Any | RenameMode::Both)) => {
|
||||||
|
for path in &event.paths {
|
||||||
|
if path.exists() {
|
||||||
|
upsert_path(path);
|
||||||
|
} else {
|
||||||
|
remove_path(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 删除 → remove(含子项)
|
||||||
EventKind::Remove(_) => {
|
EventKind::Remove(_) => {
|
||||||
for path in &event.paths {
|
for path in &event.paths {
|
||||||
remove_path(path);
|
remove_path(path);
|
||||||
|
|||||||
@@ -4,21 +4,27 @@
|
|||||||
//! Phase 2:fuzzy + 拼音引擎,command/calc/web/system Provider
|
//! Phase 2:fuzzy + 拼音引擎,command/calc/web/system Provider
|
||||||
//! Phase 3:文件索引(walkdir + rusqlite)、应用扫描、剪贴板历史复用
|
//! Phase 3:文件索引(walkdir + rusqlite)、应用扫描、剪贴板历史复用
|
||||||
|
|
||||||
|
pub mod actions;
|
||||||
pub mod app_scanner;
|
pub mod app_scanner;
|
||||||
pub mod commands;
|
pub mod commands;
|
||||||
|
pub mod explorer;
|
||||||
pub mod file_index;
|
pub mod file_index;
|
||||||
pub mod icon_extractor;
|
pub mod icon_extractor;
|
||||||
pub mod popup;
|
pub mod popup;
|
||||||
pub mod special_locations;
|
pub mod special_locations;
|
||||||
|
|
||||||
|
pub use actions::{
|
||||||
|
quickpanel_apply_rename, quickpanel_batch_extract, quickpanel_list_archives,
|
||||||
|
quickpanel_list_dir, quickpanel_preview_rename,
|
||||||
|
};
|
||||||
pub use commands::{
|
pub use commands::{
|
||||||
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
quickpanel_build_file_index, quickpanel_clear_app_icon_cache, quickpanel_delete_file,
|
||||||
quickpanel_file_index_stats, quickpanel_get_app_icon, quickpanel_get_settings,
|
quickpanel_delete_files, quickpanel_file_index_stats, quickpanel_focus_main_window,
|
||||||
quickpanel_get_special_locations, quickpanel_hide_popup, quickpanel_init_file_index,
|
quickpanel_get_app_icon, quickpanel_get_settings, quickpanel_get_special_locations,
|
||||||
quickpanel_lock_screen, quickpanel_open_file, quickpanel_open_special,
|
quickpanel_hide_popup, quickpanel_init_file_index, quickpanel_lock_screen,
|
||||||
quickpanel_register_shortcut, quickpanel_reveal_in_explorer, quickpanel_run_custom_command,
|
quickpanel_open_file, quickpanel_open_special, quickpanel_register_shortcut,
|
||||||
quickpanel_run_system_command, quickpanel_save_settings, quickpanel_scan_apps,
|
quickpanel_reveal_in_explorer, quickpanel_run_custom_command, quickpanel_run_system_command,
|
||||||
quickpanel_search_files, quickpanel_show_popup, quickpanel_show_window,
|
quickpanel_save_settings, quickpanel_scan_apps, quickpanel_search_files, quickpanel_show_popup,
|
||||||
quickpanel_unregister_shortcut,
|
quickpanel_show_window, quickpanel_unregister_shortcut,
|
||||||
};
|
};
|
||||||
pub use popup::{ensure_window, load_settings};
|
pub use popup::{ensure_window, load_settings};
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
|
use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
|
||||||
@@ -20,6 +21,8 @@ use tauri::window::{Effect, EffectsBuilder};
|
|||||||
|
|
||||||
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
use crate::win32_util::{get_cursor_pos, get_work_area_at_point, get_dpi_for_point};
|
||||||
|
|
||||||
|
use super::explorer;
|
||||||
|
|
||||||
use specta::Type;
|
use specta::Type;
|
||||||
|
|
||||||
/// 弹窗窗口标签
|
/// 弹窗窗口标签
|
||||||
@@ -29,6 +32,24 @@ pub const POPUP_LABEL: &str = "quick-panel";
|
|||||||
const WIN_W: f64 = 600.0;
|
const WIN_W: f64 = 600.0;
|
||||||
const WIN_H: f64 = 420.0;
|
const WIN_H: f64 = 420.0;
|
||||||
|
|
||||||
|
/// `quickpanel-show` 事件负载:携带快捷键按下时检测到的 Explorer 当前目录,
|
||||||
|
/// 前端据此渲染"当前目录"文件操作分组。
|
||||||
|
#[derive(Clone, Serialize)]
|
||||||
|
pub struct QuickPanelShowPayload {
|
||||||
|
pub dir: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检测前台 Explorer 目录并连同 show 事件一起下发。
|
||||||
|
/// 必须在快捷键回调内调用:此时前台窗口仍是 Explorer,面板尚未抢焦点。
|
||||||
|
fn emit_show(app: &AppHandle) {
|
||||||
|
let dir = explorer::detect_explorer_folder();
|
||||||
|
crate::logger::log_info("quickpanel", &format!("show_popup: explorer_dir={:?}", dir));
|
||||||
|
let _ = app.emit(
|
||||||
|
crate::constants::events::QUICKPANEL_SHOW,
|
||||||
|
QuickPanelShowPayload { dir },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
/// 标志:show_popup 兜底创建路径设为 true,前端 onMounted 回调 show_window 时据此判断是否显示。
|
||||||
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
/// 预创建路径不设置,避免应用启动时弹窗自动弹出。
|
||||||
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
||||||
@@ -37,6 +58,48 @@ static POPUP_PENDING_SHOW: AtomicBool = AtomicBool::new(false);
|
|||||||
/// 避免窗口重建后仍停留在屏幕外 (-10000, -10000)。
|
/// 避免窗口重建后仍停留在屏幕外 (-10000, -10000)。
|
||||||
static PENDING_POS: Mutex<Option<(f64, f64)>> = Mutex::new(None);
|
static PENDING_POS: Mutex<Option<(f64, f64)>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 失焦隐藏的宽限期:show 后窗口激活期间焦点可能短暂弹跳(透明 + focus:false 的
|
||||||
|
/// WebView2 窗口在透明激活时尤其容易出现),导致 Focused(false) 紧跟在 show 之后
|
||||||
|
/// 触发并把刚显示的窗口立即隐藏。距上次 show 不足该时长的失焦事件直接忽略。
|
||||||
|
const SHOW_GRACE: Duration = Duration::from_millis(500);
|
||||||
|
|
||||||
|
/// 最近一次 show 的时间,用于失焦宽限期判断。
|
||||||
|
static LAST_SHOWN: Mutex<Option<Instant>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// 标记"已发起显示",并记录时间供失焦宽限期使用。
|
||||||
|
fn mark_shown() {
|
||||||
|
if let Ok(mut t) = LAST_SHOWN.lock() {
|
||||||
|
*t = Some(Instant::now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 判断距上次 show 是否仍在宽限期内(是则忽略失焦自动隐藏)。
|
||||||
|
fn within_show_grace() -> bool {
|
||||||
|
LAST_SHOWN
|
||||||
|
.lock()
|
||||||
|
.ok()
|
||||||
|
.and_then(|t| *t)
|
||||||
|
.map(|t| t.elapsed() < SHOW_GRACE)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 显示窗口并确保其到达前台。
|
||||||
|
/// set_focus 受 Windows 前台锁定限制,可能静默失败;此时用 win32_util::force_foreground
|
||||||
|
/// (模拟 Alt 释放重置前台锁定 + SetForegroundWindow + BringWindowToTop)兜底。
|
||||||
|
fn show_and_focus(win: &tauri::WebviewWindow) {
|
||||||
|
if let Err(e) = win.show() {
|
||||||
|
crate::logger::log_error("quickpanel", &format!("show popup failed: {}", e));
|
||||||
|
}
|
||||||
|
mark_shown();
|
||||||
|
let focused = win.set_focus();
|
||||||
|
if focused.is_err() {
|
||||||
|
// set_focus 被前台锁定拒绝时,退回到强制置前(与主窗口焦点命令同法)
|
||||||
|
if let Ok(hwnd) = win.hwnd() {
|
||||||
|
crate::win32_util::force_foreground(hwnd.0 as isize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 自定义命令
|
/// 自定义命令
|
||||||
#[derive(Clone, Serialize, Deserialize, Type)]
|
#[derive(Clone, Serialize, Deserialize, Type)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
@@ -164,10 +227,14 @@ fn create_popup_window(app: &AppHandle) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 监听窗口失焦:自动隐藏
|
// 监听窗口失焦:自动隐藏
|
||||||
|
// 距上次 show 不足宽限期(激活中焦点弹跳)的失焦事件忽略,避免弹窗刚显示就被隐藏
|
||||||
let app_handle = app.clone();
|
let app_handle = app.clone();
|
||||||
let win_handle = win.clone();
|
let win_handle = win.clone();
|
||||||
win.on_window_event(move |event| {
|
win.on_window_event(move |event| {
|
||||||
if let tauri::WindowEvent::Focused(false) = event {
|
if let tauri::WindowEvent::Focused(false) = event {
|
||||||
|
if within_show_grace() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let _ = win_handle.hide();
|
let _ = win_handle.hide();
|
||||||
let _ = app_handle.emit(crate::constants::events::QUICKPANEL_HIDE, ());
|
let _ = app_handle.emit(crate::constants::events::QUICKPANEL_HIDE, ());
|
||||||
}
|
}
|
||||||
@@ -189,6 +256,7 @@ pub fn ensure_window(app: &AppHandle) {
|
|||||||
/// popup_position = "cursor" 时在鼠标位置附近显示,否则在鼠标所在显示器中央显示。
|
/// popup_position = "cursor" 时在鼠标位置附近显示,否则在鼠标所在显示器中央显示。
|
||||||
/// 窗口不存在则创建(隐藏状态,等前端挂载后调用 show_window 显示)。
|
/// 窗口不存在则创建(隐藏状态,等前端挂载后调用 show_window 显示)。
|
||||||
pub fn show_popup(app: &AppHandle) {
|
pub fn show_popup(app: &AppHandle) {
|
||||||
|
crate::logger::log_info("quickpanel", "show_popup triggered");
|
||||||
let settings = load_settings(app);
|
let settings = load_settings(app);
|
||||||
let cursor_mode = settings.popup_position == "cursor";
|
let cursor_mode = settings.popup_position == "cursor";
|
||||||
|
|
||||||
@@ -226,14 +294,14 @@ pub fn show_popup(app: &AppHandle) {
|
|||||||
|
|
||||||
// 窗口已存在:移动 + 显示 + 请求焦点
|
// 窗口已存在:移动 + 显示 + 请求焦点
|
||||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||||
|
// 必须先于窗口显示/聚焦检测 Explorer 目录:show/set_focus 会立即抢走前台焦点,
|
||||||
|
// 之后调用 GetForegroundWindow 拿到的就是面板自身了。
|
||||||
|
emit_show(app);
|
||||||
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition {
|
let _ = win.set_position(tauri::Position::Physical(tauri::PhysicalPosition {
|
||||||
x: x as i32,
|
x: x as i32,
|
||||||
y: y as i32,
|
y: y as i32,
|
||||||
}));
|
}));
|
||||||
let _ = win.show();
|
show_and_focus(&win);
|
||||||
let _ = win.set_focus();
|
|
||||||
// 通知前端刷新数据
|
|
||||||
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,12 +314,24 @@ pub fn show_popup(app: &AppHandle) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 显示已创建的弹窗窗口(由前端 onMounted 后调用)。
|
/// 显示已创建的弹窗窗口(由前端 onMounted 后调用)。
|
||||||
/// 预创建路径下前端 onMounted 也会调用此函数,但 POPUP_PENDING_SHOW 为 false 时直接跳过,
|
///
|
||||||
/// 避免应用启动时弹窗自动弹出。仅 show_popup 兜底创建路径才真正显示。
|
/// 两个路径:
|
||||||
|
/// 1. 预创建路径(POPUP_PENDING_SHOW = false):show_popup 已调用 show_and_focus 显示窗口,
|
||||||
|
/// 但若 Vue 尚未挂载,quickpanel-show 事件可能丢失。检查窗口是否可见,若可见则重新发送事件。
|
||||||
|
/// 2. 兜底创建路径(POPUP_PENDING_SHOW = true):窗口尚未显示,位置为 PENDING_POS,
|
||||||
|
/// 先定位再发事件最后显示+聚焦。
|
||||||
pub fn show_window(app: &AppHandle) {
|
pub fn show_window(app: &AppHandle) {
|
||||||
if !POPUP_PENDING_SHOW.swap(false, Ordering::SeqCst) {
|
if !POPUP_PENDING_SHOW.swap(false, Ordering::SeqCst) {
|
||||||
|
// 预创建路径:窗口已由 show_popup 显示,但事件可能因前端未挂载而丢失。
|
||||||
|
// 窗口可见时重新发送事件,让刚注册的监听器处理(清空输入、聚焦、刷新等)。
|
||||||
|
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||||
|
if win.is_visible().unwrap_or(false) {
|
||||||
|
emit_show(app);
|
||||||
|
}
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// 兜底创建路径:show_popup 兜底重建,窗口尚未显示
|
||||||
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
if let Some(win) = app.get_webview_window(POPUP_LABEL) {
|
||||||
// 应用 show_popup 计算的兜底位置(物理坐标),避免停留在屏幕外
|
// 应用 show_popup 计算的兜底位置(物理坐标),避免停留在屏幕外
|
||||||
let pos = PENDING_POS.lock().ok().and_then(|p| *p);
|
let pos = PENDING_POS.lock().ok().and_then(|p| *p);
|
||||||
@@ -261,10 +341,9 @@ pub fn show_window(app: &AppHandle) {
|
|||||||
y: y as i32,
|
y: y as i32,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
let _ = win.show();
|
// 同样先检测 Explorer 目录再显示,避免面板抢焦点导致检测失败。
|
||||||
let _ = win.set_focus();
|
emit_show(app);
|
||||||
// 通知前端刷新数据
|
show_and_focus(&win);
|
||||||
let _ = app.emit(crate::constants::events::QUICKPANEL_SHOW, ());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,8 @@
|
|||||||
//! 实现:
|
//! 实现:
|
||||||
//! - 全屏(虚拟屏)捕获:BitBlt 从屏幕 DC 拷贝到兼容位图,GetDIBits 取像素
|
//! - 全屏(虚拟屏)捕获:BitBlt 从屏幕 DC 拷贝到兼容位图,GetDIBits 取像素
|
||||||
//! - 窗口捕获:PrintWindow(PW_RENDERFULLCONTENT) 捕获 DWM 内容(覆盖硬件加速窗口)
|
//! - 窗口捕获:PrintWindow(PW_RENDERFULLCONTENT) 捕获 DWM 内容(覆盖硬件加速窗口)
|
||||||
//! - 窗口拾取:EnumWindows 按 Z 序命中测试(排除本进程窗口,避免命中覆盖层自身)
|
//! - 窗口拾取:pick_windows 枚举 Z 序窗口列表(排除本进程,避免命中覆盖层自身),
|
||||||
|
//! 前端缓存列表后本地命中测试
|
||||||
//! - 顶层窗口枚举:EnumWindows
|
//! - 顶层窗口枚举:EnumWindows
|
||||||
//! - 像素 → PNG / CF_DIB 转换
|
//! - 像素 → PNG / CF_DIB 转换
|
||||||
//!
|
//!
|
||||||
@@ -276,18 +277,16 @@ pub fn capture_window(hwnd: isize) -> Result<CapturedImage, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取指定屏幕坐标下的顶层窗口(窗口拾取)
|
/// 枚举可拾取的顶层窗口(Z 序顶→底)
|
||||||
///
|
///
|
||||||
/// 入参 x/y 为物理屏幕坐标(前端需按显示器 scaleFactor 从逻辑坐标换算)。
|
/// 与逐点拾取同语义:排除本进程窗口(覆盖层/主窗口/编辑器)、不可见窗口、工具窗口。
|
||||||
///
|
/// 前端在截图开始时缓存该列表,鼠标移动时在 JS 侧做命中测试(rect 包含点,取 Z 序
|
||||||
/// 不能直接用 WindowFromPoint:覆盖层是 alwaysOnTop 全屏窗口,会命中覆盖层自身。
|
/// 最顶的第一个命中),消除逐帧 window_from_point 的 IPC 往返;且列表与冻结底图
|
||||||
/// 改为 EnumWindows 按 Z 序(顶→底)枚举顶层窗口做命中测试,并排除本进程
|
/// 同一时刻生成,命中结果与画面严格一致。
|
||||||
/// (覆盖层/主窗口/编辑器)的窗口,从而取到覆盖层下面的目标窗口。
|
pub fn pick_windows() -> Vec<WindowInfo> {
|
||||||
pub fn window_from_point(x: i32, y: i32) -> Option<WindowInfo> {
|
|
||||||
struct PickContext {
|
struct PickContext {
|
||||||
my_pid: u32,
|
my_pid: u32,
|
||||||
pt: POINT,
|
out: Vec<WindowInfo>,
|
||||||
found: Option<WindowInfo>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "system" fn enum_proc(hwnd: HWND, lparam: isize) -> i32 {
|
extern "system" fn enum_proc(hwnd: HWND, lparam: isize) -> i32 {
|
||||||
@@ -311,30 +310,24 @@ pub fn window_from_point(x: i32, y: i32) -> Option<WindowInfo> {
|
|||||||
if GetWindowRect(hwnd, &mut rect) == 0 {
|
if GetWindowRect(hwnd, &mut rect) == 0 {
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
// 命中测试(物理坐标),Z 序最顶层的第一个命中即为目标
|
ctx.out.push(WindowInfo {
|
||||||
let pt = ctx.pt;
|
|
||||||
if pt.x >= rect.left && pt.x < rect.right && pt.y >= rect.top && pt.y < rect.bottom {
|
|
||||||
ctx.found = Some(WindowInfo {
|
|
||||||
hwnd,
|
hwnd,
|
||||||
title: get_window_title(hwnd),
|
title: get_window_title(hwnd),
|
||||||
rect: ScreenRect::from(rect),
|
rect: ScreenRect::from(rect),
|
||||||
visual_rect: extended_frame_bounds(hwnd),
|
visual_rect: extended_frame_bounds(hwnd),
|
||||||
});
|
});
|
||||||
return 0; // 停止枚举
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
1
|
1
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut ctx = PickContext {
|
let mut ctx = PickContext {
|
||||||
my_pid: std::process::id(),
|
my_pid: std::process::id(),
|
||||||
pt: POINT { x, y },
|
out: Vec::new(),
|
||||||
found: None,
|
|
||||||
};
|
};
|
||||||
unsafe {
|
unsafe {
|
||||||
EnumWindows(Some(enum_proc), &mut ctx as *mut _ as isize);
|
EnumWindows(Some(enum_proc), &mut ctx as *mut _ as isize);
|
||||||
}
|
}
|
||||||
ctx.found
|
ctx.out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取当前鼠标物理屏幕坐标(覆盖层打开时定位初始悬停窗口)
|
/// 获取当前鼠标物理屏幕坐标(覆盖层打开时定位初始悬停窗口)
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
//! Tauri 命令:截图模块
|
//! Tauri 命令:截图模块
|
||||||
//!
|
//!
|
||||||
//! 命令清单:
|
//! 命令清单:
|
||||||
//! - screenshot_capture_fullscreen:捕获虚拟屏并存入静态(不做 PNG 编码)
|
//! - screenshot_capture_fullscreen:捕获虚拟屏并存入静态(不做 PNG 编码),返回捕获时刻光标坐标
|
||||||
//! - screenshot_get_fullscreen_bmp:取出全屏捕获的 BMP 原始字节(raw IPC,覆盖层显示用,不移除)
|
//! - screenshot_get_fullscreen_bmp:取出全屏捕获的 BMP 原始字节(raw IPC,覆盖层显示用,不移除)
|
||||||
//! - screenshot_fullscreen_png:全屏捕获编码 PNG base64 并清除(全屏截图进编辑器用)
|
//! - screenshot_fullscreen_png:全屏捕获编码 PNG base64 并清除(全屏截图进编辑器用)
|
||||||
//! - screenshot_clear_fullscreen:清除静态全屏捕获(覆盖层关闭时)
|
//! - screenshot_clear_fullscreen:清除静态全屏捕获(覆盖层关闭时)
|
||||||
//! - screenshot_crop_stored:按物理像素裁剪已存储的全屏捕获
|
//! - screenshot_crop_stored:按物理像素裁剪已存储的全屏捕获
|
||||||
//! - screenshot_window_from_point:拾取指定屏幕坐标下的顶层窗口
|
//! - screenshot_pick_list:枚举可拾取顶层窗口(Z 序,前端缓存后本地命中测试)
|
||||||
|
//! - screenshot_show_overlay:一次 IPC 完成覆盖层 show + focus(关键路径减少往返)
|
||||||
//! - screenshot_enum_windows:枚举可见顶层窗口
|
//! - screenshot_enum_windows:枚举可见顶层窗口
|
||||||
//! - screenshot_capture_window:按 hwnd 捕获指定窗口
|
//! - screenshot_capture_window:按 hwnd 捕获指定窗口
|
||||||
//! - screenshot_set_editor_image / screenshot_get_editor_image:编辑器图片传递
|
//! - screenshot_set_editor_image / screenshot_get_editor_image:编辑器图片传递
|
||||||
@@ -14,7 +15,7 @@
|
|||||||
//! - screenshot_save_png:写入文件
|
//! - screenshot_save_png:写入文件
|
||||||
//! - screenshot_disable_transitions:禁用窗口显示/隐藏过渡动画(消除覆盖层缩放动画)
|
//! - screenshot_disable_transitions:禁用窗口显示/隐藏过渡动画(消除覆盖层缩放动画)
|
||||||
|
|
||||||
use super::{CaptureData, WindowInfo};
|
use super::{CaptureData, CaptureStart, WindowInfo};
|
||||||
use tauri::{Emitter, Manager};
|
use tauri::{Emitter, Manager};
|
||||||
|
|
||||||
/// 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画
|
/// 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画
|
||||||
@@ -67,16 +68,40 @@ pub async fn screenshot_unregister_shortcut(app: tauri::AppHandle) -> Result<(),
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码
|
/// 注册(或切换)贴图全局快捷键。传入空字符串则禁用快捷键。
|
||||||
|
/// 按下时 emit 'screenshot-pin-shortcut',由前端切换贴图窗口显示/隐藏。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn screenshot_capture_fullscreen() -> Result<(), String> {
|
pub async fn screenshot_register_pin_shortcut(
|
||||||
|
app: tauri::AppHandle,
|
||||||
|
shortcut: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
crate::shortcut::register_shortcut(&app, "贴图", &shortcut, |a| {
|
||||||
|
let _ = a.emit(crate::constants::events::SCREENSHOT_PIN_SHORTCUT, ());
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 注销贴图全局快捷键
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn screenshot_unregister_pin_shortcut(app: tauri::AppHandle) -> Result<(), String> {
|
||||||
|
crate::shortcut::unregister_shortcut(&app, "贴图");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码。
|
||||||
|
/// 同时返回捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返)。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn screenshot_capture_fullscreen() -> Result<CaptureStart, String> {
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
{
|
{
|
||||||
// 屏幕捕获涉及 GDI 调用,放线程池避免阻塞 async 调度
|
// 屏幕捕获涉及 GDI 调用,放线程池避免阻塞 async 调度
|
||||||
tauri::async_runtime::spawn_blocking(|| {
|
tauri::async_runtime::spawn_blocking(|| {
|
||||||
let img = super::capture::capture_virtual_screen()?;
|
let img = super::capture::capture_virtual_screen()?;
|
||||||
super::capture::store_fullscreen(img)
|
super::capture::store_fullscreen(img)?;
|
||||||
|
let (cursor_x, cursor_y) = super::capture::cursor_pos().unwrap_or((0, 0));
|
||||||
|
Ok(CaptureStart { cursor_x, cursor_y })
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("捕获任务失败: {}", e))?
|
.map_err(|e| format!("捕获任务失败: {}", e))?
|
||||||
@@ -184,29 +209,39 @@ pub async fn screenshot_crop_copy_stored(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 拾取指定物理屏幕坐标下的顶层窗口
|
/// 枚举可拾取的顶层窗口(Z 序顶→底,排除本进程/不可见/工具窗口)。
|
||||||
|
/// 前端在截图开始时缓存列表,鼠标移动时在 JS 侧本地命中测试,消除逐帧 IPC 往返。
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn screenshot_window_from_point(
|
pub async fn screenshot_pick_list() -> Result<Vec<WindowInfo>, String> {
|
||||||
x: i32,
|
|
||||||
y: i32,
|
|
||||||
) -> Result<Option<WindowInfo>, String> {
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
{
|
{
|
||||||
tauri::async_runtime::spawn_blocking(move || {
|
tauri::async_runtime::spawn_blocking(super::capture::pick_windows)
|
||||||
Ok(super::capture::window_from_point(x, y))
|
|
||||||
})
|
|
||||||
.await
|
.await
|
||||||
.map_err(|e| format!("查询失败: {}", e))?
|
.map_err(|e| format!("枚举失败: {}", e))
|
||||||
}
|
}
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
{
|
{
|
||||||
let _ = (x, y);
|
Ok(vec![])
|
||||||
Ok(None)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取当前鼠标物理屏幕坐标(覆盖层打开时定位初始悬停窗口)
|
/// 一次 IPC 完成指定窗口的显示与聚焦(截图覆盖层显示关键路径,减少串行往返)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn screenshot_show_overlay(
|
||||||
|
app: tauri::AppHandle,
|
||||||
|
label: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let win = app
|
||||||
|
.get_webview_window(&label)
|
||||||
|
.ok_or_else(|| format!("窗口不存在: {}", label))?;
|
||||||
|
win.show().map_err(|e| format!("显示窗口失败: {}", e))?;
|
||||||
|
win.set_focus().map_err(|e| format!("聚焦窗口失败: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取当前鼠标物理屏幕坐标(贴图窗口拖动跟随等场景使用)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub async fn screenshot_cursor_pos() -> Result<(i32, i32), String> {
|
pub async fn screenshot_cursor_pos() -> Result<(i32, i32), String> {
|
||||||
@@ -349,17 +384,17 @@ pub async fn screenshot_save_png(png_base64: String, path: String) -> Result<(),
|
|||||||
.map_err(|e| format!("保存任务失败: {}", e))?
|
.map_err(|e| format!("保存任务失败: {}", e))?
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 截图历史缓存:完整 PNG 落盘缓存目录,内存只保留缩略图 =====
|
// ===== 截图历史缓存:完整 PNG 落盘到应用数据目录(持久化,随历史保留数量清理),内存只保留缩略图 =====
|
||||||
|
|
||||||
/// 历史缓存根目录(app_cache_dir/screenshot/history)
|
/// 历史根目录(app_data_dir/screenshot/history)
|
||||||
fn history_cache_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {
|
fn history_cache_dir(app: &tauri::AppHandle) -> Result<std::path::PathBuf, String> {
|
||||||
let dir = app
|
let dir = app
|
||||||
.path()
|
.path()
|
||||||
.app_cache_dir()
|
.app_data_dir()
|
||||||
.map_err(|e| format!("获取缓存目录失败: {}", e))?
|
.map_err(|e| format!("获取应用数据目录失败: {}", e))?
|
||||||
.join("screenshot")
|
.join("screenshot")
|
||||||
.join("history");
|
.join("history");
|
||||||
std::fs::create_dir_all(&dir).map_err(|e| format!("创建缓存目录失败: {}", e))?;
|
std::fs::create_dir_all(&dir).map_err(|e| format!("创建历史目录失败: {}", e))?;
|
||||||
Ok(dir)
|
Ok(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -412,6 +447,22 @@ pub async fn screenshot_load_cache(
|
|||||||
.map_err(|e| format!("读取缓存任务失败: {}", e))?
|
.map_err(|e| format!("读取缓存任务失败: {}", e))?
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 读取历史缓存 PNG 原始字节(raw IPC → 前端 ArrayBuffer,贴图窗口显示用:
|
||||||
|
/// 跳过 base64 编码,IPC 传输与前端内存占用均省 ~33%;同 get_fullscreen_bmp 豁免 specta)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn screenshot_load_cache_raw(
|
||||||
|
app: tauri::AppHandle,
|
||||||
|
path: String,
|
||||||
|
) -> Result<tauri::ipc::Response, String> {
|
||||||
|
tauri::async_runtime::spawn_blocking(move || {
|
||||||
|
let p = ensure_in_history_dir(&app, &path)?;
|
||||||
|
let bytes = std::fs::read(&p).map_err(|e| format!("读取缓存失败: {}", e))?;
|
||||||
|
Ok(tauri::ipc::Response::new(bytes))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("读取缓存任务失败: {}", e))?
|
||||||
|
}
|
||||||
|
|
||||||
/// 删除历史缓存文件(历史项移除/清空时调用,静默忽略不存在文件)
|
/// 删除历史缓存文件(历史项移除/清空时调用,静默忽略不存在文件)
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
|
|||||||
@@ -20,6 +20,14 @@ pub struct CaptureData {
|
|||||||
pub height: i32,
|
pub height: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 截图启动信息:捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返)
|
||||||
|
#[derive(serde::Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct CaptureStart {
|
||||||
|
pub cursor_x: i32,
|
||||||
|
pub cursor_y: i32,
|
||||||
|
}
|
||||||
|
|
||||||
/// 窗口信息(窗口拾取 / 枚举)
|
/// 窗口信息(窗口拾取 / 枚举)
|
||||||
#[derive(serde::Serialize, Type)]
|
#[derive(serde::Serialize, Type)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
|
|||||||
+12
-13
@@ -66,8 +66,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let server_engine = engine.clone();
|
let server_engine = engine.clone();
|
||||||
let server_port = settings.extension_port;
|
let server_port = settings.extension_port;
|
||||||
let server_secret = settings.extension_secret.clone();
|
let server_secret = settings.extension_secret.clone();
|
||||||
|
let server_app = app.handle().clone();
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
ExtensionServer::start(server_engine, server_port, server_secret).await;
|
ExtensionServer::start(server_engine, server_port, server_secret, server_app).await;
|
||||||
});
|
});
|
||||||
|
|
||||||
// ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 =====
|
// ===== 剪贴板模块:监听 + 快捷键 + 预创建弹窗 =====
|
||||||
@@ -87,11 +88,15 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
||||||
crate::clipboard::popup::ensure_popup_window(&app_handle);
|
crate::clipboard::popup::ensure_popup_window(&app_handle);
|
||||||
|
// 同时预创建独立预览窗口(隐藏),弹窗悬停条目时直接显示
|
||||||
|
crate::clipboard::popup::ensure_preview_window(&app_handle);
|
||||||
}
|
}
|
||||||
app.manage(clipboard);
|
app.manage(clipboard);
|
||||||
|
|
||||||
// ===== 快速面板:快捷键 + 预创建弹窗 + 文件索引 =====
|
// ===== 快速面板:快捷键 + 预创建弹窗 =====
|
||||||
// defaultEnabled:true 假设启用;用户在设置页禁用模块时由前端 onDisable 钩子注销快捷键。
|
// defaultEnabled:true 假设启用;用户在设置页禁用模块时由前端 onDisable 钩子注销快捷键。
|
||||||
|
// 文件索引 DB 连接改为懒加载(首次搜索/构建时由 commands 中的 ensure_initialized 触发),
|
||||||
|
// 避免应用启动时即打开 SQLite 连接,降低启动 IO 开销。
|
||||||
let qp_settings = crate::quickpanel::load_settings(&app.handle());
|
let qp_settings = crate::quickpanel::load_settings(&app.handle());
|
||||||
if !qp_settings.shortcut.trim().is_empty() {
|
if !qp_settings.shortcut.trim().is_empty() {
|
||||||
let app_handle = app.handle().clone();
|
let app_handle = app.handle().clone();
|
||||||
@@ -106,8 +111,6 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
// 预创建弹窗窗口(隐藏),首次按快捷键时直接 show,避免首次创建时序问题
|
||||||
crate::quickpanel::ensure_window(&app_handle);
|
crate::quickpanel::ensure_window(&app_handle);
|
||||||
}
|
}
|
||||||
// 初始化文件索引数据库(不立即构建,由前端设置页或首次唤起时触发)
|
|
||||||
crate::quickpanel::file_index::init(&app.handle());
|
|
||||||
|
|
||||||
// ===== 托盘菜单 =====
|
// ===== 托盘菜单 =====
|
||||||
crate::tray_menu::create_tray_menu(app.handle())?;
|
crate::tray_menu::create_tray_menu(app.handle())?;
|
||||||
@@ -115,6 +118,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
// ===== 进程监控线程 =====
|
// ===== 进程监控线程 =====
|
||||||
start_monitoring_thread(app.handle().clone());
|
start_monitoring_thread(app.handle().clone());
|
||||||
|
|
||||||
|
// ===== 代理:自动切换节点后台调度(独立于模块激活状态) =====
|
||||||
|
crate::mihomo_manager::start_auto_switch_loop(app.handle().clone());
|
||||||
|
|
||||||
// ===== 自动启动(随应用启动,不依赖模块启用) =====
|
// ===== 自动启动(随应用启动,不依赖模块启用) =====
|
||||||
// mihomo:用户在设置中开启"自动启动"时随应用启动
|
// mihomo:用户在设置中开启"自动启动"时随应用启动
|
||||||
if let Some(mihomo) = app.try_state::<MihomoManager>() {
|
if let Some(mihomo) = app.try_state::<MihomoManager>() {
|
||||||
@@ -123,16 +129,9 @@ pub fn init(app: &mut App<Wry>) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// monitor Kernel:硬件监控默认启用,被动读取无副作用
|
// monitor Kernel:用户在设置中开启"自动启动"时随应用启动
|
||||||
if let Some(monitor) = app.try_state::<MonitorKernel>() {
|
if let Some(monitor) = app.try_state::<MonitorKernel>() {
|
||||||
let monitor = monitor.inner().clone();
|
monitor.auto_start_on_launch(app.handle());
|
||||||
let app_handle = app.handle().clone();
|
|
||||||
tauri::async_runtime::spawn(async move {
|
|
||||||
match monitor.start_with_subscription(&app_handle).await {
|
|
||||||
Ok(info) => crate::logger::log_info("monitor", &format!("自动启动成功, pid={:?}", info.pid)),
|
|
||||||
Err(e) => crate::logger::log_warn("monitor", &format!("自动启动跳过: {}", e)),
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 截图快捷键由前端 screenshotStore 启动时调用 screenshot_register_shortcut 注册
|
// 截图快捷键由前端 screenshotStore 启动时调用 screenshot_register_shortcut 注册
|
||||||
|
|||||||
+164
-102
@@ -21,10 +21,10 @@ use tauri::{
|
|||||||
static LAST_SHOW_TIME: Mutex<Option<Instant>> = Mutex::new(None);
|
static LAST_SHOW_TIME: Mutex<Option<Instant>> = Mutex::new(None);
|
||||||
|
|
||||||
/// 保存最近一次右键时计算出的定位参数(物理坐标),供 `tray_menu_ready` 使用
|
/// 保存最近一次右键时计算出的定位参数(物理坐标),供 `tray_menu_ready` 使用
|
||||||
/// (x, tray_top, wa_top, wa_bottom, scale)
|
/// (x, cursor_y, screen_top, screen_bottom, scale)
|
||||||
static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(None);
|
static LAST_MENU_LAYOUT: Mutex<Option<(f64, f64, f64, f64, f64)>> = Mutex::new(None);
|
||||||
|
|
||||||
use crate::win32_util::{get_work_area, get_work_area_at_point, get_dpi_for_point};
|
use crate::win32_util::{get_work_area, get_monitor_bounds_at_point, get_dpi_for_point};
|
||||||
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
|
use crate::mihomo_manager::{MihomoManager, is_pseudo_node};
|
||||||
use crate::monitor_kernel::MonitorKernel;
|
use crate::monitor_kernel::MonitorKernel;
|
||||||
use crate::process_manager::{ProcessManager, ProcessStatus};
|
use crate::process_manager::{ProcessManager, ProcessStatus};
|
||||||
@@ -46,6 +46,7 @@ pub struct ProxyNodeInfo {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct TrayMenuState {
|
pub struct TrayMenuState {
|
||||||
pub proxy_running: bool,
|
pub proxy_running: bool,
|
||||||
|
pub system_proxy: bool,
|
||||||
pub monitor_running: bool,
|
pub monitor_running: bool,
|
||||||
pub proxy_group: Option<String>,
|
pub proxy_group: Option<String>,
|
||||||
pub proxy_nodes: Vec<ProxyNodeInfo>,
|
pub proxy_nodes: Vec<ProxyNodeInfo>,
|
||||||
@@ -147,9 +148,29 @@ async fn fetch_proxy_nodes(app: &AppHandle) -> Option<(String, Vec<(String, Opti
|
|||||||
|
|
||||||
// ===== 获取菜单状态 =====
|
// ===== 获取菜单状态 =====
|
||||||
|
|
||||||
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
/// 基础状态(不含代理节点)。托盘菜单显示不应受 mihomo API 慢/卡死影响,
|
||||||
|
/// 因此先秒发基础状态让菜单立即出现,代理节点随后异步补充。
|
||||||
|
fn get_base_tray_state(app: &AppHandle) -> TrayMenuState {
|
||||||
let proxy_running = is_proxy_running(app);
|
let proxy_running = is_proxy_running(app);
|
||||||
let monitor_running = is_monitor_running(app);
|
let monitor_running = is_monitor_running(app);
|
||||||
|
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
|
||||||
|
let system_proxy = crate::mihomo_manager::get_system_proxy_windows();
|
||||||
|
TrayMenuState {
|
||||||
|
proxy_running,
|
||||||
|
system_proxy,
|
||||||
|
monitor_running,
|
||||||
|
proxy_group: None,
|
||||||
|
proxy_nodes: vec![],
|
||||||
|
proxy_current: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 完整状态(含代理节点)。可能因调用 mihomo /proxies 而耗时(最长 10s)。
|
||||||
|
async fn get_full_tray_state(app: &AppHandle) -> TrayMenuState {
|
||||||
|
let proxy_running = is_proxy_running(app);
|
||||||
|
let monitor_running = is_monitor_running(app);
|
||||||
|
// 读取 Windows 注册表中的真实系统代理状态(不依赖 settings.json 缓存)
|
||||||
|
let system_proxy = crate::mihomo_manager::get_system_proxy_windows();
|
||||||
|
|
||||||
let (proxy_group, proxy_nodes, proxy_current) = if proxy_running {
|
let (proxy_group, proxy_nodes, proxy_current) = if proxy_running {
|
||||||
match fetch_proxy_nodes(app).await {
|
match fetch_proxy_nodes(app).await {
|
||||||
@@ -172,6 +193,7 @@ pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
|||||||
|
|
||||||
TrayMenuState {
|
TrayMenuState {
|
||||||
proxy_running,
|
proxy_running,
|
||||||
|
system_proxy,
|
||||||
monitor_running,
|
monitor_running,
|
||||||
proxy_group,
|
proxy_group,
|
||||||
proxy_nodes,
|
proxy_nodes,
|
||||||
@@ -179,6 +201,10 @@ pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn get_tray_menu_state(app: &AppHandle) -> TrayMenuState {
|
||||||
|
get_full_tray_state(app).await
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 显示/隐藏托盘菜单窗口 =====
|
// ===== 显示/隐藏托盘菜单窗口 =====
|
||||||
|
|
||||||
/// 托盘菜单窗口尺寸(逻辑像素)
|
/// 托盘菜单窗口尺寸(逻辑像素)
|
||||||
@@ -245,29 +271,30 @@ pub fn precreate_tray_menu_window(app: &AppHandle) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 右键托盘时调用:计算定位参数、发送状态给前端,但不立即显示窗口。
|
/// 右键托盘时调用:计算定位参数、发送状态给前端,但不立即显示窗口。
|
||||||
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部精确对齐托盘图标。
|
/// 窗口等待前端测量内容高度后调用 `tray_menu_ready` 才显示,确保底部对齐鼠标点击位置。
|
||||||
///
|
///
|
||||||
/// `cursor_pos`: 事件报告的鼠标物理坐标;`tray_rect`: 托盘图标区域(物理像素)。
|
/// `cursor_pos`: 事件报告的鼠标物理坐标。
|
||||||
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64, f64, f64, f64)) {
|
pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64)) {
|
||||||
let (mx, my) = (cursor_pos.0, cursor_pos.1);
|
let (mx, my) = (cursor_pos.0, cursor_pos.1);
|
||||||
let tray_top = tray_rect.1;
|
|
||||||
|
|
||||||
// 获取光标所在显示器的工作区(物理像素)
|
// 获取光标所在显示器的完整边界(含任务栏,物理像素)。
|
||||||
let (wa_left, wa_top, wa_right, wa_bottom) = get_work_area_at_point(mx as i32, my as i32)
|
// 托盘图标位于任务栏上,菜单需在鼠标位置弹出,因此用屏幕边界而非工作区做 clamp,
|
||||||
.unwrap_or((0, 0, 1920, 1040));
|
// 否则会被工作区底部(任务栏顶部)截断,导致菜单整体被推到任务栏上方。
|
||||||
|
let (scr_left, scr_top, scr_right, scr_bottom) = get_monitor_bounds_at_point(mx as i32, my as i32)
|
||||||
|
.unwrap_or((0, 0, 1920, 1080));
|
||||||
|
|
||||||
// 光标所在显示器的 DPI:菜单宽度按物理像素换算
|
// 光标所在显示器的 DPI:菜单宽度按物理像素换算
|
||||||
let dpi = get_dpi_for_point(mx as i32, my as i32).unwrap_or(96);
|
let dpi = get_dpi_for_point(mx as i32, my as i32).unwrap_or(96);
|
||||||
let scale = dpi as f64 / 96.0;
|
let scale = dpi as f64 / 96.0;
|
||||||
let menu_w_px = MENU_W * scale;
|
let menu_w_px = MENU_W * scale;
|
||||||
|
|
||||||
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出右边界则左移(物理坐标)
|
// 水平:菜单左边缘对齐鼠标 X(向右延伸),超出屏幕右边界则左移(物理坐标)
|
||||||
let x = mx.max(wa_left as f64).min(wa_right as f64 - menu_w_px);
|
let x = mx.max(scr_left as f64).min(scr_right as f64 - menu_w_px);
|
||||||
|
|
||||||
// 保存布局参数(全部物理坐标 + scale,供 tray_menu_ready 换算前端上报的逻辑高度)
|
// 保存布局参数(全部物理坐标 + scale,供 tray_menu_ready 换算前端上报的逻辑高度)
|
||||||
{
|
{
|
||||||
let mut layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
let mut layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
*layout = Some((x, tray_top, wa_top as f64, wa_bottom as f64, scale));
|
*layout = Some((x, my, scr_top as f64, scr_bottom as f64, scale));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 记录显示时间,用于失焦防抖
|
// 记录显示时间,用于失焦防抖
|
||||||
@@ -281,11 +308,26 @@ pub fn show_tray_menu(app: &AppHandle, cursor_pos: (f64, f64), tray_rect: (f64,
|
|||||||
precreate_tray_menu_window(app);
|
precreate_tray_menu_window(app);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发送状态给前端(前端测量内容高度后调用 tray_menu_ready 显示窗口)
|
// 1) 立即发送基础状态(不含代理节点,纯本地查询),菜单秒开——
|
||||||
|
// 前端测量内容高度后调用 tray_menu_ready 显示窗口。
|
||||||
|
let base = get_base_tray_state(app);
|
||||||
|
let _ = app.emit(crate::constants::events::TRAY_MENU_SHOW, base);
|
||||||
|
|
||||||
|
// 2) 异步拉取完整状态(含 mihomo /proxies 节点),到达后经 TRAY_MENU_STATE_UPDATED
|
||||||
|
// 补充给前端(前端在窗口可见时重新测量调整尺寸)。
|
||||||
|
// mihomo API 慢/挂起时不再阻塞菜单显示;超时 5s 放弃(保持基础状态)。
|
||||||
let app_clone = app.clone();
|
let app_clone = app.clone();
|
||||||
tauri::async_runtime::spawn(async move {
|
tauri::async_runtime::spawn(async move {
|
||||||
let state = get_tray_menu_state(&app_clone).await;
|
let state = match tokio::time::timeout(
|
||||||
let _ = app_clone.emit(crate::constants::events::TRAY_MENU_SHOW, state);
|
Duration::from_millis(5000),
|
||||||
|
get_full_tray_state(&app_clone),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(s) => s,
|
||||||
|
Err(_) => return,
|
||||||
|
};
|
||||||
|
let _ = app_clone.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -302,6 +344,22 @@ async fn refresh_and_emit_state(app: &AppHandle) {
|
|||||||
let _ = app.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
|
let _ = app.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 显示主窗口并强制置为前台。
|
||||||
|
/// Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||||
|
/// 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||||
|
pub fn focus_main_window(app: &AppHandle) {
|
||||||
|
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
||||||
|
let _ = window.show();
|
||||||
|
let _ = window.unminimize();
|
||||||
|
match window.hwnd() {
|
||||||
|
Ok(hwnd) => crate::win32_util::force_foreground(hwnd.0 as isize),
|
||||||
|
Err(_) => {
|
||||||
|
window.set_focus().ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ===== Tauri 命令 =====
|
// ===== Tauri 命令 =====
|
||||||
|
|
||||||
/// 执行菜单项动作(统一入口)
|
/// 执行菜单项动作(统一入口)
|
||||||
@@ -338,6 +396,21 @@ pub async fn tray_menu_action(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
"system_proxy_toggle" => {
|
||||||
|
// 根据注册表当前真实状态切换(不依赖 settings.json 缓存,避免与主界面不同步)
|
||||||
|
let mihomo = app.state::<MihomoManager>();
|
||||||
|
if crate::mihomo_manager::get_system_proxy_windows() {
|
||||||
|
if let Err(e) = mihomo.disable_system_proxy() {
|
||||||
|
crate::logger::log_error("tray", &format!("关闭系统代理失败: {}", e));
|
||||||
|
send_notification(&app, "系统代理关闭失败", &e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if let Err(e) = mihomo.enable_system_proxy() {
|
||||||
|
crate::logger::log_error("tray", &format!("开启系统代理失败: {}", e));
|
||||||
|
send_notification(&app, "系统代理开启失败", &e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
"osd_toggle" => {
|
"osd_toggle" => {
|
||||||
let _ = app.emit(crate::constants::events::TRAY_TOGGLE_OSD, ());
|
let _ = app.emit(crate::constants::events::TRAY_TOGGLE_OSD, ());
|
||||||
}
|
}
|
||||||
@@ -348,18 +421,12 @@ pub async fn tray_menu_action(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"download_new" => {
|
"download_new" => {
|
||||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
focus_main_window(&app);
|
||||||
window.show().ok();
|
|
||||||
window.set_focus().ok();
|
|
||||||
}
|
|
||||||
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
|
let _ = app.emit(crate::constants::events::TRAY_NEW_DOWNLOAD, ());
|
||||||
hide_tray_menu(&app);
|
hide_tray_menu(&app);
|
||||||
}
|
}
|
||||||
"settings" => {
|
"settings" => {
|
||||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
focus_main_window(&app);
|
||||||
window.show().ok();
|
|
||||||
window.set_focus().ok();
|
|
||||||
}
|
|
||||||
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
|
let _ = app.emit(crate::constants::events::TRAY_OPEN_SETTINGS, ());
|
||||||
hide_tray_menu(&app);
|
hide_tray_menu(&app);
|
||||||
}
|
}
|
||||||
@@ -370,10 +437,21 @@ pub async fn tray_menu_action(
|
|||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 刷新状态并发送给前端(quit 除外,quit 后进程已退出)
|
// 按动作类型选择性刷新,避免无关动作(OSD 开关/跳转设置)也全量请求 mihomo API:
|
||||||
if action != "quit" {
|
// - 代理相关动作:全量刷新(节点列表/延迟可能已变化)
|
||||||
|
// - Kernel/OSD:仅刷新本地基础状态(monitor 运行状态)
|
||||||
|
// - 跳转/退出:不刷新(quit 后进程已退出)
|
||||||
|
match action.as_str() {
|
||||||
|
"proxy_enable" | "proxy_disable" | "proxy_refresh" | "proxy_select_node"
|
||||||
|
| "system_proxy_toggle" => {
|
||||||
refresh_and_emit_state(&app).await;
|
refresh_and_emit_state(&app).await;
|
||||||
}
|
}
|
||||||
|
"kernel_restart" | "osd_toggle" => {
|
||||||
|
let state = get_base_tray_state(&app);
|
||||||
|
let _ = app.emit(crate::constants::events::TRAY_MENU_STATE_UPDATED, state);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -392,9 +470,9 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
|||||||
let win = app.get_webview_window(TRAY_MENU_LABEL)
|
let win = app.get_webview_window(TRAY_MENU_LABEL)
|
||||||
.ok_or("tray-menu window not found")?;
|
.ok_or("tray-menu window not found")?;
|
||||||
|
|
||||||
let (x, tray_top, wa_top, wa_bottom, scale) = {
|
let (x, cursor_y, scr_top, scr_bottom, scale) = {
|
||||||
let layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
let layout = LAST_MENU_LAYOUT.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
layout.unwrap_or((0.0, 1040.0, 0.0, 1040.0, 1.0))
|
layout.unwrap_or((0.0, 1040.0, 0.0, 1080.0, 1.0))
|
||||||
};
|
};
|
||||||
|
|
||||||
// 将内容高度限制在合理范围内(前端上报为逻辑像素)
|
// 将内容高度限制在合理范围内(前端上报为逻辑像素)
|
||||||
@@ -408,14 +486,22 @@ pub async fn tray_menu_ready(content_height: f64, app: AppHandle) -> Result<(),
|
|||||||
height: win_h_px as u32,
|
height: win_h_px as u32,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// 垂直:菜单下边缘紧贴托盘图标顶部(向上弹出,物理坐标)
|
// 垂直:菜单底部对齐鼠标点击位置(向上弹出,物理坐标)。
|
||||||
let y = (tray_top - win_h_px).max(wa_top).min(wa_bottom - win_h_px);
|
// 用屏幕边界而非工作区 clamp,使菜单贴近/覆盖任务栏上的鼠标位置,
|
||||||
|
// 而不是被工作区底部(任务栏顶部)截断后整体出现在任务栏上方。
|
||||||
|
let y = (cursor_y - win_h_px).max(scr_top).min(scr_bottom - win_h_px);
|
||||||
|
|
||||||
let pos = tauri::Position::Physical(tauri::PhysicalPosition {
|
let pos = tauri::Position::Physical(tauri::PhysicalPosition {
|
||||||
x: x as i32,
|
x: x as i32,
|
||||||
y: y as i32,
|
y: y as i32,
|
||||||
});
|
});
|
||||||
let _ = win.set_position(pos);
|
let _ = win.set_position(pos);
|
||||||
|
// 以实际显示时刻重置失焦防抖起点:右键到此处可能间隔较久(前端测量 + 基础状态),
|
||||||
|
// 若沿用右键时刻,WebView2 显示瞬间的焦点抖动会被误判为失焦而立即隐藏菜单。
|
||||||
|
{
|
||||||
|
let mut t = LAST_SHOW_TIME.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
*t = Some(Instant::now());
|
||||||
|
}
|
||||||
let _ = win.show();
|
let _ = win.show();
|
||||||
let _ = win.set_focus();
|
let _ = win.set_focus();
|
||||||
|
|
||||||
@@ -446,33 +532,57 @@ async fn enable_proxy(app: &AppHandle) -> Result<(), String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 获取节点列表
|
// 2. 获取节点并择优:遵循自动切换的目标组与地区筛选(关闭自动切换时退化为主组 + 全量节点)
|
||||||
let proxies = mihomo.get_proxies().await?;
|
let settings = mihomo.load_settings();
|
||||||
let (group, nodes, _now) = parse_main_group(&proxies)
|
|
||||||
.ok_or_else(|| "无法解析代理组".to_string())?;
|
|
||||||
|
|
||||||
if !nodes.is_empty() {
|
match crate::mihomo_manager::pick_best(&mihomo, &settings).await {
|
||||||
// 3. 并行测试所有节点延迟
|
Ok(Some((group, name, delay, now))) => {
|
||||||
let best = test_and_select_best(&mihomo, &group, &nodes).await;
|
// 与自动切换一样,仅当当前节点不是最优时才切换
|
||||||
|
if name != now {
|
||||||
// 4. 发送通知
|
let _ = mihomo.select_proxy(&group, &name).await;
|
||||||
match &best {
|
|
||||||
Some((name, delay)) => {
|
|
||||||
send_notification(
|
|
||||||
app,
|
|
||||||
"代理已开启",
|
|
||||||
&format!("当前节点: {} ({}ms)", name, delay),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
send_notification(app, "代理已开启", "所有节点均超时,未自动选择");
|
|
||||||
}
|
}
|
||||||
|
send_notification(app, "代理已开启", &format!("当前节点: {} ({}ms)", name, delay));
|
||||||
}
|
}
|
||||||
|
Ok(None) | Err(_) => {
|
||||||
|
// 区分「无可用节点」与「全部超时」两种情况
|
||||||
|
let unavailable = {
|
||||||
|
let proxies = mihomo.get_proxies().await.ok();
|
||||||
|
let group_name: Option<String> = if !settings.auto_switch_group.is_empty() {
|
||||||
|
Some(settings.auto_switch_group.clone())
|
||||||
} else {
|
} else {
|
||||||
|
proxies
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|p| p.get("proxies"))
|
||||||
|
.and_then(|m| m.as_object())
|
||||||
|
.and_then(|map| {
|
||||||
|
let mut names = map.iter().filter(|(_, v)| {
|
||||||
|
v.get("type").and_then(|t| t.as_str()) == Some("Selector")
|
||||||
|
});
|
||||||
|
names.next().map(|(n, _)| n.clone())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let empty = group_name.map(|g| {
|
||||||
|
proxies
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|p| p.get("proxies"))
|
||||||
|
.and_then(|m| m.as_object())
|
||||||
|
.and_then(|map| map.get(&g))
|
||||||
|
.and_then(|v| v.get("all"))
|
||||||
|
.and_then(|v| v.as_array())
|
||||||
|
.map(|a| a.is_empty())
|
||||||
|
.unwrap_or(true)
|
||||||
|
}).unwrap_or(true);
|
||||||
|
empty
|
||||||
|
};
|
||||||
|
if unavailable {
|
||||||
send_notification(app, "代理已开启", "无可用节点");
|
send_notification(app, "代理已开启", "无可用节点");
|
||||||
|
} else {
|
||||||
|
send_notification(app, "代理已开启", "所有候选节点均超时,未自动选择");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 开启系统代理
|
// 3. 开启系统代理
|
||||||
mihomo.enable_system_proxy()?;
|
mihomo.enable_system_proxy()?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -495,40 +605,6 @@ async fn disable_proxy(app: &AppHandle) -> Result<(), String> {
|
|||||||
|
|
||||||
// ===== 择优选择节点 =====
|
// ===== 择优选择节点 =====
|
||||||
|
|
||||||
/// 并行测试所有节点延迟,选择最低延迟节点
|
|
||||||
async fn test_and_select_best(
|
|
||||||
mihomo: &MihomoManager,
|
|
||||||
group: &str,
|
|
||||||
nodes: &[String],
|
|
||||||
) -> Option<(String, u32)> {
|
|
||||||
use futures_util::future::join_all;
|
|
||||||
|
|
||||||
let futures: Vec<_> = nodes
|
|
||||||
.iter()
|
|
||||||
.map(|name| async move {
|
|
||||||
let delay = mihomo
|
|
||||||
.test_delay(name, "https://www.gstatic.com/generate_204", 5000)
|
|
||||||
.await
|
|
||||||
.ok();
|
|
||||||
(name.clone(), delay)
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let results = join_all(futures).await;
|
|
||||||
|
|
||||||
let best = results
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|(name, delay)| delay.map(|d| (name, d)))
|
|
||||||
.filter(|(_, d)| *d > 0)
|
|
||||||
.min_by_key(|(_, d)| *d);
|
|
||||||
|
|
||||||
if let Some((ref name, _)) = best {
|
|
||||||
let _ = mihomo.select_proxy(group, name).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
best
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 并行测试所有节点延迟(更新 mihomo 内部 history)
|
/// 并行测试所有节点延迟(更新 mihomo 内部 history)
|
||||||
async fn test_all_delays(app: &AppHandle) {
|
async fn test_all_delays(app: &AppHandle) {
|
||||||
let mihomo = app.state::<MihomoManager>();
|
let mihomo = app.state::<MihomoManager>();
|
||||||
@@ -647,31 +723,17 @@ pub fn create_tray_menu(app: &AppHandle) -> Result<(), tauri::Error> {
|
|||||||
button: MouseButton::Left,
|
button: MouseButton::Left,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
// 左键:显示主窗口
|
// 左键:显示主窗口(强制置前,绕过前台锁定)
|
||||||
if let Some(window) = app.get_webview_window(crate::constants::windows::MAIN) {
|
focus_main_window(&app);
|
||||||
window.show().ok();
|
|
||||||
window.set_focus().ok();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
TrayIconEvent::Click {
|
TrayIconEvent::Click {
|
||||||
button: MouseButton::Right,
|
button: MouseButton::Right,
|
||||||
position,
|
position,
|
||||||
rect,
|
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
// 右键:显示自定义菜单窗口(使用事件中的精确坐标)
|
// 右键:显示自定义菜单窗口(使用事件中的鼠标坐标)
|
||||||
let cursor = (position.x, position.y);
|
let cursor = (position.x, position.y);
|
||||||
// 从 Rect 的 Position/Size 枚举中提取物理像素值
|
show_tray_menu(&app, cursor);
|
||||||
let (rx, ry) = match rect.position {
|
|
||||||
tauri::Position::Physical(p) => (p.x as f64, p.y as f64),
|
|
||||||
tauri::Position::Logical(p) => (p.x, p.y),
|
|
||||||
};
|
|
||||||
let (_rw, rh) = match rect.size {
|
|
||||||
tauri::Size::Physical(s) => (s.width as f64, s.height as f64),
|
|
||||||
tauri::Size::Logical(s) => (s.width, s.height),
|
|
||||||
};
|
|
||||||
let tray_r = (rx, ry, _rw, rh);
|
|
||||||
show_tray_menu(&app, cursor, tray_r);
|
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,506 @@
|
|||||||
|
//! 应用自更新模块。
|
||||||
|
//! 更新源为自建 Gitea:`https://gitea.atie.fun/LFeng/Thing` 的 release 资产。
|
||||||
|
//! - 便携版(无 unins000.exe 且不在 Program Files):下载新 thing.exe → update.bat 覆盖重启
|
||||||
|
//! - 安装版(NSIS):下载新 setup.exe → 提权静默安装 /S
|
||||||
|
//! - ThingHK 内核:下载由前端下载模块完成 → apply 命令 need_stop 等待确认 → 解压覆盖
|
||||||
|
//! {app_data}/monitor/cores/ThingHK.exe(与代理模块 mihomo 内核更新同模式)
|
||||||
|
use serde::Serialize;
|
||||||
|
use specta::Type;
|
||||||
|
use std::fs;
|
||||||
|
use std::io::{Read, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::{atomic::{AtomicBool, Ordering}, Mutex};
|
||||||
|
use tauri::{AppHandle, Emitter, Manager};
|
||||||
|
use tokio::sync::{oneshot, watch};
|
||||||
|
|
||||||
|
use crate::constants::events::UPDATE_PROGRESS;
|
||||||
|
|
||||||
|
/// 用户主动取消 ThingHK 更新的标记错误信息(前端据此静默处理,不弹错误 toast)
|
||||||
|
const THINGHK_UPDATE_CANCELLED: &str = "更新已取消";
|
||||||
|
|
||||||
|
/// ThingHK 内核更新的跨命令状态:apply 过程中 need_stop 阶段等待前端确认。
|
||||||
|
/// 与 MihomoManager 的 install_confirm/kernel_cancel 同构。
|
||||||
|
pub struct ThinghkUpdateState {
|
||||||
|
/// need_stop 等待阶段的确认通道(前端调 confirm 命令时唤醒 apply 继续)
|
||||||
|
confirm_tx: Mutex<Option<oneshot::Sender<()>>>,
|
||||||
|
/// 取消标志 + 唤醒通道(前端调 cancel 命令时置位,apply 等待循环立即返回)
|
||||||
|
cancel_flag: AtomicBool,
|
||||||
|
cancel_tx: watch::Sender<bool>,
|
||||||
|
cancel_rx: watch::Receiver<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThinghkUpdateState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let (tx, rx) = watch::channel(false);
|
||||||
|
Self {
|
||||||
|
confirm_tx: Mutex::new(None),
|
||||||
|
cancel_flag: AtomicBool::new(false),
|
||||||
|
cancel_tx: tx,
|
||||||
|
cancel_rx: rx,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 前端已停止监控内核,唤醒 apply 继续解压替换
|
||||||
|
fn confirm(&self) {
|
||||||
|
if let Some(tx) = self.confirm_tx.lock().unwrap_or_else(|e| e.into_inner()).take() {
|
||||||
|
let _ = tx.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取消更新:置位取消标志并唤醒 apply 等待循环
|
||||||
|
fn cancel(&self) {
|
||||||
|
self.cancel_flag.store(true, Ordering::SeqCst);
|
||||||
|
let _ = self.cancel_tx.send(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 进入新的 apply 流程前复位取消标志
|
||||||
|
fn reset(&self) {
|
||||||
|
self.cancel_flag.store(false, Ordering::SeqCst);
|
||||||
|
let _ = self.cancel_tx.send(false);
|
||||||
|
*self.confirm_tx.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 发布仓库(Gitea)
|
||||||
|
const GITEA_REPO: &str = "LFeng/Thing";
|
||||||
|
const GITEA_BASE: &str = "https://gitea.atie.fun";
|
||||||
|
|
||||||
|
/// release 中的一个资产
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateAsset {
|
||||||
|
pub name: String,
|
||||||
|
pub size: u64,
|
||||||
|
pub browser_download_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查更新的结果
|
||||||
|
#[derive(Debug, Clone, Serialize, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateCheckResult {
|
||||||
|
pub current_version: String,
|
||||||
|
pub latest_version: String,
|
||||||
|
pub has_update: bool,
|
||||||
|
/// portable | installed
|
||||||
|
pub install_type: String,
|
||||||
|
pub release_name: String,
|
||||||
|
pub release_body: String,
|
||||||
|
pub assets: Vec<UpdateAsset>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新进度事件载荷(与内核安装进度同构,独立事件便于 UI 区分)
|
||||||
|
#[derive(Serialize, Clone, Type)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct UpdateProgress {
|
||||||
|
pub stage: String,
|
||||||
|
pub percent: u8,
|
||||||
|
#[specta(type = f64)]
|
||||||
|
pub downloaded_bytes: u64,
|
||||||
|
#[specta(type = Option<f64>)]
|
||||||
|
pub total_bytes: Option<u64>,
|
||||||
|
pub message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 版本比较 ----------
|
||||||
|
|
||||||
|
/// 解析 vX.Y.Z 为数字元组用于比较;解析失败返回 (0,0,0)
|
||||||
|
fn parse_version(v: &str) -> (u32, u32, u32) {
|
||||||
|
let s = v.trim().trim_start_matches('v');
|
||||||
|
let mut parts = s.split('.');
|
||||||
|
let major = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
|
||||||
|
let minor = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0);
|
||||||
|
let patch = parts
|
||||||
|
.next()
|
||||||
|
.map(|p| p.chars().take_while(|c| c.is_ascii_digit()).collect::<String>())
|
||||||
|
.and_then(|p| p.parse().ok())
|
||||||
|
.unwrap_or(0);
|
||||||
|
(major, minor, patch)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn version_gt(a: &str, b: &str) -> bool {
|
||||||
|
parse_version(a) > parse_version(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Gitea API ----------
|
||||||
|
|
||||||
|
struct LatestRelease {
|
||||||
|
tag_name: String,
|
||||||
|
name: String,
|
||||||
|
body: String,
|
||||||
|
assets: Vec<UpdateAsset>,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_latest_release() -> Result<LatestRelease, String> {
|
||||||
|
let url = format!("{}/api/v1/repos/{}/releases/latest", GITEA_BASE, GITEA_REPO);
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.timeout(std::time::Duration::from_secs(15))
|
||||||
|
.build()
|
||||||
|
.map_err(|e| format!("创建 HTTP 客户端失败: {}", e))?;
|
||||||
|
let resp = client
|
||||||
|
.get(&url)
|
||||||
|
.header("User-Agent", "thing-app")
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("请求 Gitea API 失败: {}", e))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(format!("Gitea API 返回 HTTP {}", resp.status()));
|
||||||
|
}
|
||||||
|
let json: serde_json::Value = resp
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.map_err(|e| format!("解析 Gitea 响应失败: {}", e))?;
|
||||||
|
let mut assets = Vec::new();
|
||||||
|
if let Some(list) = json.get("assets").and_then(|v| v.as_array()) {
|
||||||
|
for a in list {
|
||||||
|
if let (Some(name), Some(url)) = (
|
||||||
|
a.get("name").and_then(|v| v.as_str()),
|
||||||
|
a.get("browser_download_url").and_then(|v| v.as_str()),
|
||||||
|
) {
|
||||||
|
assets.push(UpdateAsset {
|
||||||
|
name: name.to_string(),
|
||||||
|
size: a.get("size").and_then(|v| v.as_u64()).unwrap_or(0),
|
||||||
|
browser_download_url: url.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(LatestRelease {
|
||||||
|
tag_name: json.get("tag_name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||||
|
name: json.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||||
|
body: json.get("body").and_then(|v| v.as_str()).unwrap_or("").to_string(),
|
||||||
|
assets,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 解压 ----------
|
||||||
|
// ThingHK 内核更新包由前端下载模块负责下载(同 mihomo),此处仅解压替换。
|
||||||
|
|
||||||
|
/// 用 zip crate 解压(纯 Rust,避免 PowerShell 执行策略问题)
|
||||||
|
fn extract_zip(zip_path: &Path, dest: &Path) -> Result<(), String> {
|
||||||
|
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {}", e))?;
|
||||||
|
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {}", e))?;
|
||||||
|
for i in 0..archive.len() {
|
||||||
|
let mut entry = archive
|
||||||
|
.by_index(i)
|
||||||
|
.map_err(|e| format!("读取条目失败: {}", e))?;
|
||||||
|
let outpath = match entry.enclosed_name() {
|
||||||
|
Some(p) => dest.join(p),
|
||||||
|
None => continue,
|
||||||
|
};
|
||||||
|
if entry.is_dir() {
|
||||||
|
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||||
|
} else {
|
||||||
|
if let Some(parent) = outpath.parent() {
|
||||||
|
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||||
|
let mut buf = [0u8; 8192];
|
||||||
|
loop {
|
||||||
|
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||||
|
if n == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 安装类型 / ShellExecute ----------
|
||||||
|
|
||||||
|
/// 判断当前是便携版还是安装版。
|
||||||
|
/// NSIS 安装会在程序目录生成 unins000.exe;MSI 通常安装到 Program Files。
|
||||||
|
fn is_installed_version() -> bool {
|
||||||
|
if let Ok(exe) = std::env::current_exe() {
|
||||||
|
if let Some(dir) = exe.parent() {
|
||||||
|
if dir.join("unins000.exe").exists() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let p = dir.to_string_lossy().to_lowercase();
|
||||||
|
if p.contains("program files") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 通过 ShellExecuteW 启动程序/文档(绕过 Job Object,脱离主进程生命周期)
|
||||||
|
fn shell_execute(verb: &str, file: &Path, params: &str, show: i32) -> Result<(), String> {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
use std::os::windows::ffi::OsStrExt;
|
||||||
|
use windows_sys::Win32::UI::Shell::ShellExecuteW;
|
||||||
|
let file_w: Vec<u16> = file.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
|
||||||
|
let verb_w: Vec<u16> = verb.encode_utf16().chain(std::iter::once(0)).collect();
|
||||||
|
let params_w: Vec<u16> = params.encode_utf16().chain(std::iter::once(0)).collect();
|
||||||
|
let res = unsafe {
|
||||||
|
ShellExecuteW(
|
||||||
|
0 as isize,
|
||||||
|
verb_w.as_ptr(),
|
||||||
|
file_w.as_ptr(),
|
||||||
|
params_w.as_ptr(),
|
||||||
|
std::ptr::null(),
|
||||||
|
show,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
if (res as isize) <= 32 {
|
||||||
|
return Err(format!("ShellExecuteW 失败 (code={})", res));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
let _ = (verb, file, params, show);
|
||||||
|
Err("仅支持 Windows".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 便携版:写 update.bat 等待主进程退出 → 覆盖 exe → 重新启动
|
||||||
|
fn apply_portable_update(new_exe: &Path) -> Result<(), String> {
|
||||||
|
let cur_exe = std::env::current_exe().map_err(|e| format!("获取当前程序路径失败: {}", e))?;
|
||||||
|
let cur_dir = cur_exe.parent().ok_or("无法确定程序目录".to_string())?;
|
||||||
|
let bat_path = cur_dir.join("update.bat");
|
||||||
|
let script = format!(
|
||||||
|
"@echo off\r\n\
|
||||||
|
:wait\r\n\
|
||||||
|
tasklist /FI \"IMAGENAME eq thing.exe\" 2>nul | findstr /i \"thing.exe\" >nul\r\n\
|
||||||
|
if not errorlevel 1 (\r\n\
|
||||||
|
ping -n 2 127.0.0.1 >nul\r\n\
|
||||||
|
goto wait\r\n\
|
||||||
|
)\r\n\
|
||||||
|
copy /y \"{new}\" \"{cur}\" >nul\r\n\
|
||||||
|
if errorlevel 1 exit /b 1\r\n\
|
||||||
|
start \"\" \"{cur}\"\r\n\
|
||||||
|
del \"{new}\" >nul 2>nul\r\n\
|
||||||
|
del \"%~f0\" >nul 2>nul\r\n",
|
||||||
|
new = new_exe.display(),
|
||||||
|
cur = cur_exe.display()
|
||||||
|
);
|
||||||
|
fs::write(&bat_path, script).map_err(|e| format!("写入更新脚本失败: {}", e))?;
|
||||||
|
// 用 cmd /c 启动 bat 并隐藏窗口;ShellExecute 启动的进程不属于本进程 Job,
|
||||||
|
// 主进程退出后 update.bat 仍能继续执行
|
||||||
|
let windir = std::env::var("WINDIR").unwrap_or_else(|_| "C:\\Windows".into());
|
||||||
|
let cmd_exe = Path::new(&windir).join("System32").join("cmd.exe");
|
||||||
|
shell_execute("open", &cmd_exe, &format!("/c \"{}\"", bat_path.display()), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 命令 ----------
|
||||||
|
|
||||||
|
/// 获取当前应用版本
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn app_version(app: AppHandle) -> String {
|
||||||
|
app.package_info().version.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 检查 Gitea 最新 release,返回版本对比与可用资产
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn update_check(app: AppHandle) -> Result<UpdateCheckResult, String> {
|
||||||
|
let latest = fetch_latest_release().await?;
|
||||||
|
let latest_version = latest.tag_name.trim_start_matches('v').to_string();
|
||||||
|
let current_version = app.package_info().version.to_string();
|
||||||
|
let has_update = version_gt(&latest_version, ¤t_version);
|
||||||
|
Ok(UpdateCheckResult {
|
||||||
|
current_version,
|
||||||
|
latest_version,
|
||||||
|
has_update,
|
||||||
|
install_type: if is_installed_version() { "installed".into() } else { "portable".into() },
|
||||||
|
release_name: latest.name,
|
||||||
|
release_body: latest.body,
|
||||||
|
assets: latest.assets,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 更新应用本体(安装阶段)。下载由前端下载模块完成,本命令接收已下载的
|
||||||
|
/// 安装包路径(便携版 thing_{v}_x64.exe / 安装版 thing_{v}_x64-setup.exe)。
|
||||||
|
/// 便携版:copy 到临时目录 → update.bat 覆盖重启;
|
||||||
|
/// 安装版:copy 到临时目录 → 提权静默安装 /S。
|
||||||
|
/// 调用返回前会触发应用退出。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn update_install(app: AppHandle, downloaded_path: String) -> Result<(), String> {
|
||||||
|
let src = PathBuf::from(&downloaded_path);
|
||||||
|
if !src.exists() {
|
||||||
|
return Err(format!("下载文件不存在: {}", downloaded_path));
|
||||||
|
}
|
||||||
|
let installed = is_installed_version();
|
||||||
|
// copy 到临时目录:与 update.bat / 安装器解耦,随后即可删除下载目录中的源文件
|
||||||
|
let temp_dir = std::env::temp_dir().join("thing-update");
|
||||||
|
fs::create_dir_all(&temp_dir).map_err(|e| format!("创建临时目录失败: {}", e))?;
|
||||||
|
let file_name = src
|
||||||
|
.file_name()
|
||||||
|
.map(|n| n.to_string_lossy().to_string())
|
||||||
|
.unwrap_or_else(|| "thing_update.exe".into());
|
||||||
|
let dest = temp_dir.join(&file_name);
|
||||||
|
fs::copy(&src, &dest).map_err(|e| format!("复制安装包到临时目录失败: {}", e))?;
|
||||||
|
// 临时副本就绪后清理下载目录中的源文件(失败不影响更新流程)
|
||||||
|
let _ = fs::remove_file(&src);
|
||||||
|
|
||||||
|
let _ = app.emit(
|
||||||
|
UPDATE_PROGRESS,
|
||||||
|
UpdateProgress {
|
||||||
|
stage: "applying".into(),
|
||||||
|
percent: 100,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: if installed { "正在启动安装程序...".into() } else { "正在替换程序文件...".into() },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if installed {
|
||||||
|
// 提权静默安装 /S;UAC 确认期间主进程已退出,安装器可正常覆盖
|
||||||
|
shell_execute("runas", &dest, "/S", 0)?;
|
||||||
|
} else {
|
||||||
|
apply_portable_update(&dest)?;
|
||||||
|
}
|
||||||
|
// 延迟退出,确保 ShellExecute 已拉起子进程
|
||||||
|
app.exit(0);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用 ThingHK 内核更新:下载阶段已由下载模块完成,本命令仅做
|
||||||
|
/// need_stop(等待前端停止监控内核并确认)→ 解压 → 替换。
|
||||||
|
/// 进度通过 UPDATE_PROGRESS 事件上报,前端据 need_stop 弹出确认对话框。
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub async fn update_thinghk_apply(
|
||||||
|
app: AppHandle,
|
||||||
|
state: tauri::State<'_, ThinghkUpdateState>,
|
||||||
|
zip_path: String,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
state.reset();
|
||||||
|
let result = update_thinghk_apply_inner(&app, &state, PathBuf::from(&zip_path)).await;
|
||||||
|
if let Err(ref e) = result {
|
||||||
|
// 取消是用户主动行为,静默返回即可;其余失败 emit error 阶段避免前端进度卡死
|
||||||
|
if e != THINGHK_UPDATE_CANCELLED {
|
||||||
|
let _ = app.emit(
|
||||||
|
UPDATE_PROGRESS,
|
||||||
|
UpdateProgress {
|
||||||
|
stage: "error".into(),
|
||||||
|
percent: 0,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: e.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_thinghk_apply_inner(
|
||||||
|
app: &AppHandle,
|
||||||
|
state: &ThinghkUpdateState,
|
||||||
|
zip_path: PathBuf,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if !zip_path.exists() {
|
||||||
|
return Err(format!("下载文件不存在: {}", zip_path.display()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// need_stop:等待前端停止监控内核并确认(exe 被占用会导致覆盖失败)。
|
||||||
|
// 确认/取消由 confirm/cancel 命令跨命令唤醒(与 mihomo need_stop 同构)。
|
||||||
|
let _ = app.emit(
|
||||||
|
UPDATE_PROGRESS,
|
||||||
|
UpdateProgress {
|
||||||
|
stage: "need_stop".into(),
|
||||||
|
percent: 90,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: "需要停止监控内核才能继续安装".into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let (tx, mut rx) = oneshot::channel::<()>();
|
||||||
|
*state.confirm_tx.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
|
||||||
|
let mut cancel_rx = state.cancel_rx.clone();
|
||||||
|
loop {
|
||||||
|
if state.cancel_flag.load(Ordering::SeqCst) {
|
||||||
|
*state.confirm_tx.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||||
|
return Err(THINGHK_UPDATE_CANCELLED.to_string());
|
||||||
|
}
|
||||||
|
tokio::select! {
|
||||||
|
_ = &mut rx => break,
|
||||||
|
_ = cancel_rx.changed() => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解压阶段
|
||||||
|
let _ = app.emit(
|
||||||
|
UPDATE_PROGRESS,
|
||||||
|
UpdateProgress {
|
||||||
|
stage: "extracting".into(),
|
||||||
|
percent: 95,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: "正在解压内核...".into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let temp_dir = std::env::temp_dir().join("thing-update");
|
||||||
|
let extract_dir = temp_dir.join("thinghk_extract");
|
||||||
|
let _ = fs::remove_dir_all(&extract_dir);
|
||||||
|
extract_zip(&zip_path, &extract_dir)?;
|
||||||
|
|
||||||
|
// 在解压目录中查找 ThingHK.exe
|
||||||
|
let exe_path = find_thinghk_exe(&extract_dir).ok_or("内核包中未找到 ThingHK.exe".to_string())?;
|
||||||
|
let app_data = app
|
||||||
|
.path()
|
||||||
|
.app_data_dir()
|
||||||
|
.map_err(|e| format!("获取数据目录失败: {}", e))?;
|
||||||
|
let cores_dir = app_data.join("monitor").join("cores");
|
||||||
|
fs::create_dir_all(&cores_dir).map_err(|e| format!("创建内核目录失败: {}", e))?;
|
||||||
|
fs::copy(&exe_path, cores_dir.join("ThingHK.exe"))
|
||||||
|
.map_err(|e| format!("覆盖内核文件失败(请确认监控模块已停止): {}", e))?;
|
||||||
|
|
||||||
|
// 清理临时文件
|
||||||
|
let _ = fs::remove_file(&zip_path);
|
||||||
|
let _ = fs::remove_dir_all(&extract_dir);
|
||||||
|
let _ = app.emit(
|
||||||
|
UPDATE_PROGRESS,
|
||||||
|
UpdateProgress {
|
||||||
|
stage: "done".into(),
|
||||||
|
percent: 100,
|
||||||
|
downloaded_bytes: 0,
|
||||||
|
total_bytes: None,
|
||||||
|
message: "ThingHK 内核更新完成".into(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 前端已停止监控内核,确认继续解压替换(唤醒 need_stop 等待)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn update_thinghk_confirm(state: tauri::State<'_, ThinghkUpdateState>) -> Result<(), String> {
|
||||||
|
state.confirm();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 取消 ThingHK 内核更新(need_stop 等待阶段有效:唤醒 apply 以「已取消」返回,zip 保留便于重试)
|
||||||
|
#[tauri::command]
|
||||||
|
#[specta::specta]
|
||||||
|
pub fn update_thinghk_cancel(state: tauri::State<'_, ThinghkUpdateState>) -> Result<(), String> {
|
||||||
|
state.cancel();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_thinghk_exe(dir: &Path) -> Option<PathBuf> {
|
||||||
|
if let Ok(entries) = fs::read_dir(dir) {
|
||||||
|
for entry in entries.flatten() {
|
||||||
|
let path = entry.path();
|
||||||
|
if path.is_dir() {
|
||||||
|
if let Some(found) = find_thinghk_exe(&path) {
|
||||||
|
return Some(found);
|
||||||
|
}
|
||||||
|
} else if path
|
||||||
|
.file_name()
|
||||||
|
.and_then(|n| n.to_str())
|
||||||
|
.map(|s| s.eq_ignore_ascii_case("ThingHK.exe"))
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
return Some(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
@@ -60,6 +60,30 @@ pub fn get_work_area_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 获取指定点所在显示器的完整边界(含任务栏),返回 (left, top, right, bottom) 物理像素。
|
||||||
|
/// 与 get_work_area_at_point 不同,这里用 rcMonitor 而非 rcWork,
|
||||||
|
/// 用于需要在鼠标位置弹出、允许贴近/覆盖任务栏的场景(如托盘菜单)。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn get_monitor_bounds_at_point(x: i32, y: i32) -> Option<(i32, i32, i32, i32)> {
|
||||||
|
use windows_sys::Win32::Foundation::POINT;
|
||||||
|
use windows_sys::Win32::Graphics::Gdi::{
|
||||||
|
GetMonitorInfoW, MonitorFromPoint, MONITORINFO, MONITOR_DEFAULTTONEAREST,
|
||||||
|
};
|
||||||
|
|
||||||
|
let pt = POINT { x, y };
|
||||||
|
let hmon = unsafe { MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST) };
|
||||||
|
let mut mi: MONITORINFO = unsafe { std::mem::zeroed() };
|
||||||
|
mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;
|
||||||
|
unsafe {
|
||||||
|
if GetMonitorInfoW(hmon, &mut mi) != 0 {
|
||||||
|
let rc = mi.rcMonitor;
|
||||||
|
Some((rc.left, rc.top, rc.right, rc.bottom))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// 获取指定点所在显示器的有效 DPI。
|
/// 获取指定点所在显示器的有效 DPI。
|
||||||
/// scale factor = dpi / 96。
|
/// scale factor = dpi / 96。
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
@@ -81,6 +105,115 @@ pub fn get_dpi_for_point(x: i32, y: i32) -> Option<u32> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 强制将窗口置为前台(绕过 Windows 前台锁定限制)。
|
||||||
|
/// Tauri 的 set_focus 内部调用 SetForegroundWindow,受前台锁定(foreground lock)限制:
|
||||||
|
/// 本进程不拥有前台时调用会被系统忽略,导致已打开但被遮挡的窗口无法到前台。
|
||||||
|
/// 先模拟 Alt 键释放以重置前台锁定,再 SetForegroundWindow + BringWindowToTop。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn force_foreground(hwnd: isize) {
|
||||||
|
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
|
||||||
|
keybd_event, KEYEVENTF_KEYUP, VK_MENU,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::{BringWindowToTop, SetForegroundWindow};
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
keybd_event(VK_MENU as u8, 0, KEYEVENTF_KEYUP, 0);
|
||||||
|
let _ = SetForegroundWindow(hwnd);
|
||||||
|
let _ = BringWindowToTop(hwnd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 应用 WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW 扩展样式到指定窗口。
|
||||||
|
/// 用于预览窗等不抢焦点的悬浮窗:窗口可接收鼠标交互但不激活、不进 Alt-Tab。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn apply_no_activate(hwnd: isize) {
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::{
|
||||||
|
GetWindowLongPtrW, SetWindowLongPtrW, GWL_EXSTYLE, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
|
||||||
|
let new_ex = ex | (WS_EX_NOACTIVATE as isize) | (WS_EX_TOOLWINDOW as isize);
|
||||||
|
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, new_ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 鼠标左键当前是否按下(GetAsyncKeyState,全局异步状态,无需窗口焦点)。
|
||||||
|
/// 供看护线程轮询检测"点击外部"(配合按下沿判定)。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn is_left_button_down() -> bool {
|
||||||
|
use windows_sys::Win32::UI::Input::KeyboardAndMouse::GetAsyncKeyState;
|
||||||
|
|
||||||
|
const VK_LBUTTON: i32 = 0x01;
|
||||||
|
((unsafe { GetAsyncKeyState(VK_LBUTTON) } as u32) & 0x8000) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn is_left_button_down() -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 强制窗口应用系统圆角(DWMWCP_ROUND,Win11 约 8px)。
|
||||||
|
/// 带 WS_EX_NOACTIVATE 等扩展样式的悬浮窗系统不会自动圆角(呈现直角),
|
||||||
|
/// 与常规弹窗外观不一致;通过 DWMWA_WINDOW_CORNER_PREFERENCE 显式指定圆角偏好。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn apply_rounded_corners(hwnd: isize) {
|
||||||
|
use windows_sys::Win32::Graphics::Dwm::{
|
||||||
|
DwmSetWindowAttribute, DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_ROUND,
|
||||||
|
};
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let pref: i32 = DWMWCP_ROUND;
|
||||||
|
let _ = DwmSetWindowAttribute(
|
||||||
|
hwnd,
|
||||||
|
DWMWA_WINDOW_CORNER_PREFERENCE as u32,
|
||||||
|
&pref as *const i32 as *const core::ffi::c_void,
|
||||||
|
std::mem::size_of::<i32>() as u32,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 以不激活方式显示窗口(SW_SHOWNOACTIVATE),避免抢走弹窗等前台窗口的焦点。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn show_no_activate(hwnd: isize) {
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_SHOWNOACTIVATE};
|
||||||
|
unsafe {
|
||||||
|
ShowWindow(hwnd, SW_SHOWNOACTIVATE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 隐藏窗口(SW_HIDE)。供以原生方式显示(SW_SHOWNOACTIVATE)的悬浮窗兜底隐藏,
|
||||||
|
/// 与 Tauri 的 hide() 并存以确保任何路径下都被可靠隐藏。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn hide_window(hwnd: isize) {
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::{ShowWindow, SW_HIDE};
|
||||||
|
unsafe {
|
||||||
|
ShowWindow(hwnd, SW_HIDE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 系统自上次用户输入(鼠标/键盘)以来的空闲时长(毫秒)。
|
||||||
|
/// 用于闲时执行耗时后台任务(如文件索引构建),避免与应用运行/用户操作抢 IO。
|
||||||
|
/// GetLastInputInfo 的 dwTime 与 GetTickCount 同为系统启动后毫秒数,用 wrapping 减法防回绕。
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub fn get_idle_time_ms() -> u64 {
|
||||||
|
use windows_sys::Win32::System::SystemInformation::GetTickCount;
|
||||||
|
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
|
||||||
|
GetLastInputInfo, LASTINPUTINFO,
|
||||||
|
};
|
||||||
|
use std::mem::size_of;
|
||||||
|
|
||||||
|
let mut lii = LASTINPUTINFO {
|
||||||
|
cbSize: size_of::<LASTINPUTINFO>() as u32,
|
||||||
|
dwTime: 0,
|
||||||
|
};
|
||||||
|
unsafe {
|
||||||
|
if GetLastInputInfo(&mut lii) != 0 {
|
||||||
|
return GetTickCount().wrapping_sub(lii.dwTime) as u64;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
// ===== 非 Windows 平台空实现 =====
|
// ===== 非 Windows 平台空实现 =====
|
||||||
|
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
@@ -94,3 +227,24 @@ pub fn get_work_area_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)>
|
|||||||
|
|
||||||
#[cfg(not(windows))]
|
#[cfg(not(windows))]
|
||||||
pub fn get_dpi_for_point(_x: i32, _y: i32) -> Option<u32> { None }
|
pub fn get_dpi_for_point(_x: i32, _y: i32) -> Option<u32> { None }
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn get_monitor_bounds_at_point(_x: i32, _y: i32) -> Option<(i32, i32, i32, i32)> { None }
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn force_foreground(_hwnd: isize) {}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn apply_no_activate(_hwnd: isize) {}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn apply_rounded_corners(_hwnd: isize) {}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn show_no_activate(_hwnd: isize) {}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn hide_window(_hwnd: isize) {}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn get_idle_time_ms() -> u64 { 0 }
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://schema.tauri.app/config/2",
|
"$schema": "https://schema.tauri.app/config/2",
|
||||||
"productName": "thing",
|
"productName": "thing",
|
||||||
"version": "0.1.0",
|
"version": "26.8.4",
|
||||||
"identifier": "thing.lfeng.me",
|
"identifier": "thing.lfeng.me",
|
||||||
"build": {
|
"build": {
|
||||||
"beforeDevCommand": "bun run dev",
|
"beforeDevCommand": "bun run dev",
|
||||||
"devUrl": "http://localhost:1420",
|
"devUrl": "http://localhost:14210",
|
||||||
"beforeBuildCommand": "bun run build",
|
"beforeBuildCommand": "bun run build",
|
||||||
"frontendDist": "../dist"
|
"frontendDist": "../dist"
|
||||||
},
|
},
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
"transparent": true,
|
"transparent": true,
|
||||||
"visible": false,
|
"visible": false,
|
||||||
"windowEffects": {
|
"windowEffects": {
|
||||||
"effects": ["acrylic", "mica"]
|
"effects": ["mica", "acrylic"]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -37,6 +37,11 @@
|
|||||||
"icons/icon.icns",
|
"icons/icon.icns",
|
||||||
"icons/icon.ico"
|
"icons/icon.ico"
|
||||||
],
|
],
|
||||||
"resources": ["binaries/*", "resources/thing-extension/**/*"]
|
"resources": ["binaries/*", "resources/thing-extension/**/*"],
|
||||||
|
"windows": {
|
||||||
|
"nsis": {
|
||||||
|
"compression": "lzma"
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+89
-8
@@ -10,16 +10,19 @@ import { useAppStore } from '@/stores/appStore'
|
|||||||
import { useScreenshotStore } from '@/stores/screenshotStore'
|
import { useScreenshotStore } from '@/stores/screenshotStore'
|
||||||
import { useQuickPanelStore } from '@/stores/quickpanelStore'
|
import { useQuickPanelStore } from '@/stores/quickpanelStore'
|
||||||
import { useMonitorStore } from '@/stores/monitorStore'
|
import { useMonitorStore } from '@/stores/monitorStore'
|
||||||
|
import { useProcessStore } from '@/stores/processStore'
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||||
import { moduleRegistry } from '@/modules/registry'
|
import { moduleRegistry } from '@/modules/registry'
|
||||||
import type { ModuleMeta } from '@/types/module'
|
import type { ModuleMeta } from '@/types/module'
|
||||||
import { pendingNewDownload } from '@/lib/trayEvents'
|
import { pendingNewDownload } from '@/lib/trayEvents'
|
||||||
import { EVENTS, STORAGE_KEYS } from '@/lib/constants'
|
import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||||
|
import { commands } from '@/lib/bindings'
|
||||||
|
|
||||||
const appStore = useAppStore()
|
const appStore = useAppStore()
|
||||||
const screenshotStore = useScreenshotStore()
|
const screenshotStore = useScreenshotStore()
|
||||||
const quickpanelStore = useQuickPanelStore()
|
const quickpanelStore = useQuickPanelStore()
|
||||||
const monitorStore = useMonitorStore()
|
const monitorStore = useMonitorStore()
|
||||||
|
const processStore = useProcessStore()
|
||||||
|
|
||||||
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
|
/** 侧边栏 / 标题栏需要的模块信息(id + name + icon) */
|
||||||
interface NavModule {
|
interface NavModule {
|
||||||
@@ -41,6 +44,9 @@ const activeModule = ref('')
|
|||||||
|
|
||||||
const activeComponent = shallowRef<Component | null>(null)
|
const activeComponent = shallowRef<Component | null>(null)
|
||||||
|
|
||||||
|
/** 模块组件加载中(异步 import 未完成)标志,避免切换期间仍显示上一个模块内容 */
|
||||||
|
const moduleLoading = ref(false)
|
||||||
|
|
||||||
/** 当前可显示的模块(内置模块 + 已启用的用户模块),按用户排序显示 */
|
/** 当前可显示的模块(内置模块 + 已启用的用户模块),按用户排序显示 */
|
||||||
const availableModules = computed<NavModule[]>(() => {
|
const availableModules = computed<NavModule[]>(() => {
|
||||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||||
@@ -65,10 +71,15 @@ const availableModules = computed<NavModule[]>(() => {
|
|||||||
let moduleLoadSeq = 0
|
let moduleLoadSeq = 0
|
||||||
const loadModule = async (moduleId: string) => {
|
const loadModule = async (moduleId: string) => {
|
||||||
const seq = ++moduleLoadSeq
|
const seq = ++moduleLoadSeq
|
||||||
|
// 立即清空旧组件并进入加载态,避免异步 import 期间仍渲染上一个模块内容
|
||||||
|
// (否则 ModuleContainer 以 :key="activeModule" 重挂载旧组件,用户误以为切换失败)
|
||||||
|
activeComponent.value = null
|
||||||
|
moduleLoading.value = true
|
||||||
const component = await moduleRegistry.loadComponent(moduleId)
|
const component = await moduleRegistry.loadComponent(moduleId)
|
||||||
// 过期请求(期间用户又切换了模块)直接丢弃,不覆盖 activeComponent 也不触发钩子
|
// 过期请求(期间用户又切换了模块)直接丢弃,不覆盖 activeComponent 也不触发钩子
|
||||||
if (seq !== moduleLoadSeq) return
|
if (seq !== moduleLoadSeq) return
|
||||||
activeComponent.value = component
|
activeComponent.value = component
|
||||||
|
moduleLoading.value = false
|
||||||
|
|
||||||
// 调用模块的 onActivate 生命周期钩子
|
// 调用模块的 onActivate 生命周期钩子
|
||||||
const config = moduleRegistry.getConfig(moduleId)
|
const config = moduleRegistry.getConfig(moduleId)
|
||||||
@@ -76,6 +87,9 @@ const loadModule = async (moduleId: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleModuleChange = (moduleId: string) => {
|
const handleModuleChange = (moduleId: string) => {
|
||||||
|
// 同模块不重新加载(保留组件状态);搜索/托盘跳转到当前模块时仅触发 tab 导航
|
||||||
|
if (activeModule.value === moduleId) return
|
||||||
|
|
||||||
// 调用上一个模块的 onDeactivate 钩子
|
// 调用上一个模块的 onDeactivate 钩子
|
||||||
const prevConfig = moduleRegistry.getConfig(activeModule.value)
|
const prevConfig = moduleRegistry.getConfig(activeModule.value)
|
||||||
prevConfig?.lifecycle?.onDeactivate?.()
|
prevConfig?.lifecycle?.onDeactivate?.()
|
||||||
@@ -85,10 +99,59 @@ const handleModuleChange = (moduleId: string) => {
|
|||||||
loadModule(moduleId)
|
loadModule(moduleId)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 搜索跳转与普通切换同路径:补齐 onDeactivate 钩子,避免旧模块资源泄漏
|
||||||
const handleSearch = (moduleId: string) => {
|
const handleSearch = (moduleId: string) => {
|
||||||
activeModule.value = moduleId
|
handleModuleChange(moduleId)
|
||||||
localStorage.setItem(LAST_MODULE_KEY, moduleId)
|
}
|
||||||
loadModule(moduleId)
|
|
||||||
|
// 为单个下载任务创建专属的一次性下载窗口(浏览器扩展发起)。
|
||||||
|
// label 带 task id 保证同时多个下载时各占一个窗口;对应 capabilities/download-window.json 的 glob "download-window-*"
|
||||||
|
async function openDownloadWindow(taskId: string) {
|
||||||
|
const { WebviewWindow } = await import('@tauri-apps/api/webviewWindow')
|
||||||
|
const { currentMonitor } = await import('@tauri-apps/api/window')
|
||||||
|
const label = `${WINDOWS.downloadWindow}-${taskId}`
|
||||||
|
try {
|
||||||
|
const existing = await WebviewWindow.getByLabel(label)
|
||||||
|
if (existing) {
|
||||||
|
// 已存在:用 Rust 端强制置前(绕过前台锁定,双屏/后台创建也能到前台)
|
||||||
|
await commands.downloaderFocusWindow(label)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 定位到主窗口当前所在显示器的中央偏上
|
||||||
|
const monitor = await currentMonitor()
|
||||||
|
const scale = monitor?.scaleFactor ?? 1
|
||||||
|
const w = 420
|
||||||
|
const h = 176
|
||||||
|
const x = Math.round(((monitor?.size.width ?? 1920) / scale - w) / 2)
|
||||||
|
const y = Math.round(((monitor?.size.height ?? 1080) / scale - h) / 2 * 0.8)
|
||||||
|
const win = new WebviewWindow(label, {
|
||||||
|
url: `index.html#download-window?task=${encodeURIComponent(taskId)}`,
|
||||||
|
title: '下载',
|
||||||
|
width: w,
|
||||||
|
height: h,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
decorations: false,
|
||||||
|
transparent: true,
|
||||||
|
resizable: false,
|
||||||
|
maximizable: false,
|
||||||
|
minimizable: true,
|
||||||
|
shadow: true,
|
||||||
|
visible: false,
|
||||||
|
focus: false,
|
||||||
|
// 默认不置顶、放入任务栏(可最小化,任务栏图标唤出);下载完成时窗口置前提醒。
|
||||||
|
// 隐藏创建:由 DownloadWindow 贴合内容高度后一次性 show,避免显示后再 resize 闪烁
|
||||||
|
})
|
||||||
|
win.once('tauri://error', (e) => console.error('创建下载窗口失败:', e))
|
||||||
|
// 窗口改为隐藏创建:由 DownloadWindow 在 onMounted 贴合内容高度后一次性 show,
|
||||||
|
// 避免"先以 176 高度显示、再 resize 到内容高度"造成的闪烁。
|
||||||
|
// 此处仅保留异常兜底:WebView 加载异常导致 DownloadWindow 未 reveal 时,强制显示。
|
||||||
|
win.once('tauri://created', () => {
|
||||||
|
window.setTimeout(() => { void commands.downloaderFocusWindow(label) }, 2500)
|
||||||
|
})
|
||||||
|
} catch (e) {
|
||||||
|
console.error('创建下载窗口失败:', e)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getFallbackModule = () => {
|
const getFallbackModule = () => {
|
||||||
@@ -99,14 +162,14 @@ const getFallbackModule = () => {
|
|||||||
return fallback?.id || 'settings'
|
return fallback?.id || 'settings'
|
||||||
}
|
}
|
||||||
|
|
||||||
watch(() => appStore.enabledModules.length, () => {
|
// 按 id 列表监听(而非 length):同时禁用一个 + 启用另一个时 length 不变,会漏检回退
|
||||||
|
watch(() => appStore.enabledModules.map(m => m.id).join(','), () => {
|
||||||
// 启动期间 activeModule 尚未确定,跳过
|
// 启动期间 activeModule 尚未确定,跳过
|
||||||
if (!activeModule.value) return
|
if (!activeModule.value) return
|
||||||
const enabledIds = appStore.enabledModules.map(m => m.id)
|
const enabledIds = appStore.enabledModules.map(m => m.id)
|
||||||
if (activeModule.value !== 'settings' && !enabledIds.includes(activeModule.value)) {
|
if (activeModule.value !== 'settings' && !enabledIds.includes(activeModule.value)) {
|
||||||
const fallback = getFallbackModule()
|
const fallback = getFallbackModule()
|
||||||
activeModule.value = fallback
|
handleModuleChange(fallback)
|
||||||
loadModule(fallback)
|
|
||||||
}
|
}
|
||||||
// 模块启用/禁用变化时重新同步快速面板命令缓存
|
// 模块启用/禁用变化时重新同步快速面板命令缓存
|
||||||
quickpanelStore.syncCommands()
|
quickpanelStore.syncCommands()
|
||||||
@@ -149,9 +212,16 @@ onMounted(async () => {
|
|||||||
// 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取
|
// 快速面板:同步命令缓存与设置到 localStorage,供独立窗口读取
|
||||||
quickpanelStore.syncCommands()
|
quickpanelStore.syncCommands()
|
||||||
quickpanelStore.syncSettings()
|
quickpanelStore.syncSettings()
|
||||||
|
// 初始化文件索引 DB 并恢复增量监听(上次构建过索引时自动恢复,不重建)
|
||||||
|
commands.quickpanelInitFileIndex().catch(e => console.error('文件索引初始化失败:', e))
|
||||||
// 监听快速面板执行命令事件:显示主窗口 + 切换模块
|
// 监听快速面板执行命令事件:显示主窗口 + 切换模块
|
||||||
trayUnlisteners.push(
|
trayUnlisteners.push(
|
||||||
await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => {
|
await listen<{ moduleId: string }>('quickpanel-execute-command', async (e) => {
|
||||||
|
// Rust 端强制置前(绕过 Windows 前台锁定,主窗口被遮挡时也能到前台)
|
||||||
|
try {
|
||||||
|
await commands.quickpanelFocusMainWindow()
|
||||||
|
} catch {
|
||||||
|
// 回退:前端 show + setFocus
|
||||||
const win = getCurrentWindow()
|
const win = getCurrentWindow()
|
||||||
try {
|
try {
|
||||||
await win.show()
|
await win.show()
|
||||||
@@ -160,6 +230,7 @@ onMounted(async () => {
|
|||||||
} catch {
|
} catch {
|
||||||
/* 忽略窗口操作失败 */
|
/* 忽略窗口操作失败 */
|
||||||
}
|
}
|
||||||
|
}
|
||||||
handleSearch(e.payload.moduleId)
|
handleSearch(e.payload.moduleId)
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@@ -177,6 +248,14 @@ onMounted(async () => {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
// 浏览器扩展新增下载:为该任务创建一个专属的一次性下载窗口(不打断主界面)。
|
||||||
|
// 主窗口本身无需置前,下载进度/完成事件由独立窗口自行监听。
|
||||||
|
trayUnlisteners.push(
|
||||||
|
await listen<{ id: string }>(EVENTS.downloadExtensionAdded, (e) => {
|
||||||
|
if (!e.payload?.id) return
|
||||||
|
void openDownloadWindow(e.payload.id)
|
||||||
|
})
|
||||||
|
)
|
||||||
trayUnlisteners.push(
|
trayUnlisteners.push(
|
||||||
await listen(EVENTS.trayOpenSettings, () => {
|
await listen(EVENTS.trayOpenSettings, () => {
|
||||||
handleModuleChange('settings')
|
handleModuleChange('settings')
|
||||||
@@ -193,6 +272,8 @@ onUnmounted(() => {
|
|||||||
screenshotStore.destroyExportListener()
|
screenshotStore.destroyExportListener()
|
||||||
// 释放 OSD 事件监听与配置 watcher
|
// 释放 OSD 事件监听与配置 watcher
|
||||||
monitorStore.disposeOsd()
|
monitorStore.disposeOsd()
|
||||||
|
// 释放进程状态事件监听
|
||||||
|
processStore.destroyListener()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -206,7 +287,7 @@ onUnmounted(() => {
|
|||||||
:active-module="activeModule"
|
:active-module="activeModule"
|
||||||
@change="handleModuleChange"
|
@change="handleModuleChange"
|
||||||
/>
|
/>
|
||||||
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" />
|
<ModuleContainer :active-component="activeComponent" :active-module="activeModule" :loading="moduleLoading" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" />
|
<Toaster position="bottom-right" rich-colors close-button :style="{ zIndex: 99999 }" />
|
||||||
|
|||||||
@@ -1,16 +1,33 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { Component } from 'vue'
|
import type { Component } from 'vue'
|
||||||
|
import { ref, watch } from 'vue'
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
|
||||||
defineProps<{
|
const props = defineProps<{
|
||||||
activeComponent: Component | null
|
activeComponent: Component | null
|
||||||
activeModule: string
|
activeModule: string
|
||||||
|
loading: boolean
|
||||||
}>()
|
}>()
|
||||||
|
|
||||||
|
const containerRef = ref<HTMLElement | null>(null)
|
||||||
|
|
||||||
|
// 切换模块时重置主滚动区位置,避免新模块沿用上一个模块的滚动距离
|
||||||
|
watch(
|
||||||
|
() => props.activeModule,
|
||||||
|
() => {
|
||||||
|
const viewport = containerRef.value?.querySelector<HTMLElement>(
|
||||||
|
'[data-slot="scroll-area-viewport"]'
|
||||||
|
)
|
||||||
|
if (viewport) viewport.scrollTop = 0
|
||||||
|
}
|
||||||
|
)
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<main
|
<main
|
||||||
class="flex-1"
|
ref="containerRef"
|
||||||
|
class="flex-1 min-w-0"
|
||||||
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
:style="{ backgroundColor: 'var(--effect-bg)', backdropFilter: 'var(--effect-blur)' }"
|
||||||
>
|
>
|
||||||
<ScrollArea data-main-scroll class="h-full w-full">
|
<ScrollArea data-main-scroll class="h-full w-full">
|
||||||
@@ -22,6 +39,30 @@ defineProps<{
|
|||||||
>
|
>
|
||||||
<component :is="activeComponent" />
|
<component :is="activeComponent" />
|
||||||
</div>
|
</div>
|
||||||
|
<div
|
||||||
|
v-else-if="loading"
|
||||||
|
key="loading"
|
||||||
|
class="h-full w-full p-6"
|
||||||
|
>
|
||||||
|
<!-- 模块加载骨架:撑起画面,避免空白闪屏 -->
|
||||||
|
<div class="h-full max-w-5xl mx-auto space-y-5">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<Skeleton class="h-8 w-40" />
|
||||||
|
<Skeleton class="h-6 w-24 ml-auto" />
|
||||||
|
</div>
|
||||||
|
<div class="grid gap-4 md:grid-cols-2">
|
||||||
|
<div v-for="n in 4" :key="n" class="rounded-lg border p-5 space-y-4">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<Skeleton class="h-5 w-32" />
|
||||||
|
<Skeleton class="h-5 w-16" />
|
||||||
|
</div>
|
||||||
|
<Skeleton class="h-4 w-full" />
|
||||||
|
<Skeleton class="h-4 w-5/6" />
|
||||||
|
<Skeleton class="h-4 w-2/3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
v-else
|
v-else
|
||||||
key="empty"
|
key="empty"
|
||||||
|
|||||||
@@ -31,14 +31,14 @@ const displayModules = computed(() => {
|
|||||||
<Button
|
<Button
|
||||||
:variant="activeModule === module.id ? 'default' : 'ghost'"
|
:variant="activeModule === module.id ? 'default' : 'ghost'"
|
||||||
size="icon"
|
size="icon"
|
||||||
class="h-10 w-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||||
:class="{
|
:class="{
|
||||||
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
|
'bg-primary text-primary-foreground shadow-md': activeModule === module.id,
|
||||||
'hover:bg-secondary/50': activeModule !== module.id
|
'hover:bg-secondary/50': activeModule !== module.id
|
||||||
}"
|
}"
|
||||||
@click="emit('change', module.id)"
|
@click="activeModule !== module.id && emit('change', module.id)"
|
||||||
>
|
>
|
||||||
<component :is="getModuleIcon(module.icon)" class="h-5 w-5" />
|
<component :is="getModuleIcon(module.icon)" class="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="right" class="w-fit">
|
<TooltipContent side="right" class="w-fit">
|
||||||
@@ -55,14 +55,14 @@ const displayModules = computed(() => {
|
|||||||
<Button
|
<Button
|
||||||
:variant="activeModule === 'settings' ? 'default' : 'ghost'"
|
:variant="activeModule === 'settings' ? 'default' : 'ghost'"
|
||||||
size="icon"
|
size="icon"
|
||||||
class="h-10 w-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
class="size-10 rounded-lg transition-[background-color,color,box-shadow] duration-300"
|
||||||
:class="{
|
:class="{
|
||||||
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
|
'bg-primary text-primary-foreground shadow-md': activeModule === 'settings',
|
||||||
'hover:bg-secondary/50': activeModule !== 'settings'
|
'hover:bg-secondary/50': activeModule !== 'settings'
|
||||||
}"
|
}"
|
||||||
@click="emit('change', 'settings')"
|
@click="activeModule !== 'settings' && emit('change', 'settings')"
|
||||||
>
|
>
|
||||||
<Settings class="h-5 w-5" />
|
<Settings class="size-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent side="right" class="w-fit">
|
<TooltipContent side="right" class="w-fit">
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script setup lang="ts">
|
<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 { Search, Settings, ChevronRight, ArrowUp, Check, Loader2 } from '@lucide/vue'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
import { invoke } from '@tauri-apps/api/core'
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
@@ -42,6 +42,11 @@ const hasSearchContent = computed(() => {
|
|||||||
return searchQuery.value.trim().length > 0
|
return searchQuery.value.trim().length > 0
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** 模块 id → 名称 查找表(用于搜索结果中标注所属模块) */
|
||||||
|
const moduleNameById = computed(() => {
|
||||||
|
return new Map(props.modules.map(m => [m.id, m.name]))
|
||||||
|
})
|
||||||
|
|
||||||
const handleSearchSelect = (moduleId: string) => {
|
const handleSearchSelect = (moduleId: string) => {
|
||||||
emit('search', moduleId)
|
emit('search', moduleId)
|
||||||
searchQuery.value = ''
|
searchQuery.value = ''
|
||||||
@@ -50,6 +55,10 @@ const handleSearchSelect = (moduleId: string) => {
|
|||||||
|
|
||||||
const handleSettingSelect = (item: SearchItem) => {
|
const handleSettingSelect = (item: SearchItem) => {
|
||||||
emit('search', item.moduleId)
|
emit('search', item.moduleId)
|
||||||
|
// 记录待跳转 tab:模块挂载后由 useModuleTabs 自动切换(模块已挂载时同样生效)
|
||||||
|
if (item.tab) {
|
||||||
|
tabsStore.setPendingTab(item.moduleId, item.tab)
|
||||||
|
}
|
||||||
if (item.action) {
|
if (item.action) {
|
||||||
item.action()
|
item.action()
|
||||||
}
|
}
|
||||||
@@ -57,6 +66,65 @@ const handleSettingSelect = (item: SearchItem) => {
|
|||||||
isSearchFocused.value = false
|
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
|
let tauriWindow: ReturnType<typeof getCurrentWindow> | null = null
|
||||||
try {
|
try {
|
||||||
tauriWindow = getCurrentWindow()
|
tauriWindow = getCurrentWindow()
|
||||||
@@ -187,12 +255,23 @@ const initScrollListener = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// resize 节流定时器:拖拽调整大小时 onResized 高频触发,避免每次都发 isMaximized IPC
|
||||||
|
let resizeDebounce: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
if (tauriWindow) {
|
if (tauriWindow) {
|
||||||
try {
|
try {
|
||||||
isMaximized.value = await tauriWindow.isMaximized()
|
isMaximized.value = await tauriWindow.isMaximized()
|
||||||
unlistenMaximize = await tauriWindow.onResized(async () => {
|
unlistenMaximize = await tauriWindow.onResized(() => {
|
||||||
|
if (resizeDebounce) return
|
||||||
|
resizeDebounce = setTimeout(async () => {
|
||||||
|
resizeDebounce = null
|
||||||
|
try {
|
||||||
isMaximized.value = await tauriWindow!.isMaximized()
|
isMaximized.value = await tauriWindow!.isMaximized()
|
||||||
|
} catch {
|
||||||
|
/* 窗口已销毁等异常忽略 */
|
||||||
|
}
|
||||||
|
}, 150)
|
||||||
})
|
})
|
||||||
} catch {
|
} catch {
|
||||||
// 非 Tauri 环境忽略
|
// 非 Tauri 环境忽略
|
||||||
@@ -209,6 +288,7 @@ onMounted(async () => {
|
|||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener('mousemove', handleFirstMouseMove)
|
window.removeEventListener('mousemove', handleFirstMouseMove)
|
||||||
if (restoreHoverTimer) clearTimeout(restoreHoverTimer)
|
if (restoreHoverTimer) clearTimeout(restoreHoverTimer)
|
||||||
|
if (resizeDebounce) clearTimeout(resizeDebounce)
|
||||||
if (unlistenMaximize) unlistenMaximize()
|
if (unlistenMaximize) unlistenMaximize()
|
||||||
if (unlistenFocus) unlistenFocus()
|
if (unlistenFocus) unlistenFocus()
|
||||||
if (scrollViewport) scrollViewport.removeEventListener('scroll', handleMainScroll)
|
if (scrollViewport) scrollViewport.removeEventListener('scroll', handleMainScroll)
|
||||||
@@ -259,8 +339,7 @@ const handleBlur = () => {
|
|||||||
<Transition name="floating-tabs">
|
<Transition name="floating-tabs">
|
||||||
<button
|
<button
|
||||||
v-if="showScrollTop"
|
v-if="showScrollTop"
|
||||||
class="flex items-center justify-center h-6 w-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
class="flex items-center justify-center size-6 rounded-md text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
|
||||||
title="回到顶部"
|
|
||||||
@click="scrollToTop"
|
@click="scrollToTop"
|
||||||
@mousedown.stop
|
@mousedown.stop
|
||||||
>
|
>
|
||||||
@@ -276,7 +355,6 @@ const handleBlur = () => {
|
|||||||
v-if="tabsStore.saveVisible"
|
v-if="tabsStore.saveVisible"
|
||||||
class="flex items-center gap-1.5 h-7 px-3 mr-1 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-60 disabled:pointer-events-none transition-colors pointer-events-auto"
|
class="flex items-center gap-1.5 h-7 px-3 mr-1 text-xs font-medium rounded-md bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-60 disabled:pointer-events-none transition-colors pointer-events-auto"
|
||||||
:disabled="tabsStore.saving"
|
:disabled="tabsStore.saving"
|
||||||
title="保存当前模块设置"
|
|
||||||
@click="tabsStore.runSave"
|
@click="tabsStore.runSave"
|
||||||
@mousedown.stop
|
@mousedown.stop
|
||||||
>
|
>
|
||||||
@@ -287,7 +365,7 @@ const handleBlur = () => {
|
|||||||
</Transition>
|
</Transition>
|
||||||
<div class="relative max-w-xs mr-3 pointer-events-auto">
|
<div class="relative max-w-xs mr-3 pointer-events-auto">
|
||||||
<Search
|
<Search
|
||||||
class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"
|
class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground"
|
||||||
/>
|
/>
|
||||||
<Input
|
<Input
|
||||||
v-model="searchQuery"
|
v-model="searchQuery"
|
||||||
@@ -295,9 +373,10 @@ const handleBlur = () => {
|
|||||||
class="h-7 pl-8 text-sm bg-secondary/50 border-0 focus-visible:ring-1"
|
class="h-7 pl-8 text-sm bg-secondary/50 border-0 focus-visible:ring-1"
|
||||||
@focus="isSearchFocused = true"
|
@focus="isSearchFocused = true"
|
||||||
@blur="handleBlur"
|
@blur="handleBlur"
|
||||||
|
@keydown="handleSearchKeydown"
|
||||||
/>
|
/>
|
||||||
<div
|
<div
|
||||||
v-if="isSearchFocused && hasSearchContent"
|
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"
|
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">
|
<template v-if="filteredModules.length > 0">
|
||||||
@@ -305,10 +384,13 @@ const handleBlur = () => {
|
|||||||
模块
|
模块
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
v-for="module in filteredModules"
|
v-for="(module, mi) in filteredModules"
|
||||||
:key="module.id"
|
: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="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)"
|
@click="handleSearchSelect(module.id)"
|
||||||
|
@mouseenter="highlightIndex = mi"
|
||||||
>
|
>
|
||||||
<span>{{ module.name }}</span>
|
<span>{{ module.name }}</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -320,19 +402,27 @@ const handleBlur = () => {
|
|||||||
设置项
|
设置项
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
v-for="item in searchResults"
|
v-for="(item, si) in searchResults"
|
||||||
:key="item.id"
|
: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="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)"
|
@click="handleSettingSelect(item)"
|
||||||
|
@mouseenter="highlightIndex = filteredModules.length + si"
|
||||||
>
|
>
|
||||||
<Settings class="h-4 w-4 text-muted-foreground" />
|
<Settings class="size-4 text-muted-foreground shrink-0" />
|
||||||
<div class="flex-1 min-w-0">
|
<div class="flex-1 min-w-0">
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
<span class="truncate">{{ item.title }}</span>
|
<span class="truncate">{{ item.title }}</span>
|
||||||
|
<span class="shrink-0 text-[10px] text-muted-foreground/70 px-1 py-px rounded bg-muted">
|
||||||
|
{{ moduleNameById.get(item.moduleId) || item.moduleId }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
<span v-if="item.description" class="block text-xs text-muted-foreground truncate">
|
<span v-if="item.description" class="block text-xs text-muted-foreground truncate">
|
||||||
{{ item.description }}
|
{{ item.description }}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<ChevronRight class="h-4 w-4 text-muted-foreground" />
|
<ChevronRight class="size-4 text-muted-foreground shrink-0" />
|
||||||
</button>
|
</button>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
@@ -347,7 +437,7 @@ const handleBlur = () => {
|
|||||||
|
|
||||||
<div class="flex items-center pointer-events-auto" :class="{ 'hover-suppressed': hoverSuppressed }">
|
<div class="flex items-center pointer-events-auto" :class="{ 'hover-suppressed': hoverSuppressed }">
|
||||||
<button
|
<button
|
||||||
class="h-10 w-10 flex items-center justify-center hover:bg-foreground/5 transition-colors rounded-sm"
|
class="size-10 flex items-center justify-center hover:bg-foreground/5 transition-colors rounded-sm"
|
||||||
@click="minimize"
|
@click="minimize"
|
||||||
@mousedown.stop
|
@mousedown.stop
|
||||||
>
|
>
|
||||||
@@ -358,7 +448,7 @@ const handleBlur = () => {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
id="titlebar-maximize"
|
id="titlebar-maximize"
|
||||||
class="h-10 w-10 flex items-center justify-center transition-colors rounded-sm titlebar-maximize-btn"
|
class="size-10 flex items-center justify-center transition-colors rounded-sm titlebar-maximize-btn"
|
||||||
@click="maximize"
|
@click="maximize"
|
||||||
@mousedown.stop
|
@mousedown.stop
|
||||||
>
|
>
|
||||||
@@ -375,7 +465,7 @@ const handleBlur = () => {
|
|||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
class="h-10 w-10 flex items-center justify-center hover:bg-red-500 hover:text-white text-foreground transition-colors rounded-sm"
|
class="size-10 flex items-center justify-center hover:bg-red-500 hover:text-white text-foreground transition-colors rounded-sm"
|
||||||
@click="close"
|
@click="close"
|
||||||
@mousedown.stop
|
@mousedown.stop
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="empty"
|
||||||
|
:class="cn(
|
||||||
|
'flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance rounded-lg border-dashed p-6 text-center md:p-12',
|
||||||
|
props.class,
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="empty-content"
|
||||||
|
:class="cn(
|
||||||
|
'flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm',
|
||||||
|
props.class,
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<p
|
||||||
|
data-slot="empty-description"
|
||||||
|
:class="cn(
|
||||||
|
'text-muted-foreground [&>a:hover]:text-primary text-sm/relaxed [&>a]:underline [&>a]:underline-offset-4',
|
||||||
|
$attrs.class ?? '',
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</p>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="empty-header"
|
||||||
|
:class="cn(
|
||||||
|
'flex max-w-sm flex-col items-center gap-2 text-center',
|
||||||
|
props.class,
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import type { EmptyMediaVariants } from "."
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { emptyMediaVariants } from "."
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
variant?: EmptyMediaVariants["variant"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="empty-icon"
|
||||||
|
:data-variant="variant"
|
||||||
|
:class="cn(emptyMediaVariants({ variant }), props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="empty-title"
|
||||||
|
:class="cn('text-lg font-medium tracking-tight', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { VariantProps } from "class-variance-authority"
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
|
||||||
|
export { default as Empty } from "./Empty.vue"
|
||||||
|
export { default as EmptyContent } from "./EmptyContent.vue"
|
||||||
|
export { default as EmptyDescription } from "./EmptyDescription.vue"
|
||||||
|
export { default as EmptyHeader } from "./EmptyHeader.vue"
|
||||||
|
export { default as EmptyMedia } from "./EmptyMedia.vue"
|
||||||
|
export { default as EmptyTitle } from "./EmptyTitle.vue"
|
||||||
|
|
||||||
|
export const emptyMediaVariants = cva(
|
||||||
|
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-transparent",
|
||||||
|
icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
export type EmptyMediaVariants = VariantProps<typeof emptyMediaVariants>
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { HTMLAttributes } from "vue"
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { ref } from "vue"
|
||||||
import { useVModel } from "@vueuse/core"
|
import { useVModel } from "@vueuse/core"
|
||||||
import { cn } from "@/lib/utils"
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
@@ -17,10 +18,19 @@ const modelValue = useVModel(props, "modelValue", emits, {
|
|||||||
passive: true,
|
passive: true,
|
||||||
defaultValue: props.defaultValue,
|
defaultValue: props.defaultValue,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 暴露原生 input 元素与 focus,供父级 `ref="xx"` 后调用 xx.focus()
|
||||||
|
// (组件默认不转发,ref 拿到的是组件实例,调用 .focus() 会报 "focus is not a function")
|
||||||
|
const inputEl = ref<HTMLInputElement | null>(null)
|
||||||
|
defineExpose({
|
||||||
|
focus: () => inputEl.value?.focus(),
|
||||||
|
element: () => inputEl.value,
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<input
|
<input
|
||||||
|
ref="inputEl"
|
||||||
v-model="modelValue"
|
v-model="modelValue"
|
||||||
data-slot="input"
|
data-slot="input"
|
||||||
:class="cn(
|
:class="cn(
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="skeleton"
|
||||||
|
:class="cn('animate-pulse rounded-md bg-muted', props.class)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export { default as Skeleton } from "./Skeleton.vue"
|
||||||
@@ -24,7 +24,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
|||||||
data-slot="switch"
|
data-slot="switch"
|
||||||
v-bind="forwarded"
|
v-bind="forwarded"
|
||||||
:class="cn(
|
:class="cn(
|
||||||
'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50',
|
'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-3 disabled:cursor-not-allowed disabled:opacity-50 cursor-pointer hover:data-[state=checked]:bg-primary/90 hover:data-[state=unchecked]:bg-input/70 active:scale-95',
|
||||||
props.class,
|
props.class,
|
||||||
)"
|
)"
|
||||||
>
|
>
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
|||||||
<TooltipContent
|
<TooltipContent
|
||||||
data-slot="tooltip-content"
|
data-slot="tooltip-content"
|
||||||
v-bind="{ ...forwarded, ...$attrs }"
|
v-bind="{ ...forwarded, ...$attrs }"
|
||||||
:class="cn('bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit rounded-md px-3 py-1.5 text-xs text-balance', props.class)"
|
:class="cn('bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit max-w-[calc(100vw-2rem)] rounded-md px-3 py-1.5 text-xs', props.class)"
|
||||||
>
|
>
|
||||||
<slot />
|
<slot />
|
||||||
|
|
||||||
|
|||||||
+272
-20
@@ -4,16 +4,45 @@ import { invoke as __TAURI_INVOKE } from "@tauri-apps/api/core";
|
|||||||
|
|
||||||
/** Commands */
|
/** Commands */
|
||||||
export const commands = {
|
export const commands = {
|
||||||
|
/** 获取当前应用版本 */
|
||||||
|
appVersion: () => __TAURI_INVOKE<string>("app_version"),
|
||||||
|
/** 检查 Gitea 最新 release,返回版本对比与可用资产 */
|
||||||
|
updateCheck: () => __TAURI_INVOKE<UpdateCheckResult>("update_check"),
|
||||||
|
/**
|
||||||
|
* 更新应用本体(安装阶段)。下载由前端下载模块完成,本命令接收已下载的
|
||||||
|
* 安装包路径(便携版 thing_{v}_x64.exe / 安装版 thing_{v}_x64-setup.exe)。
|
||||||
|
* 便携版:copy 到临时目录 → update.bat 覆盖重启;
|
||||||
|
* 安装版:copy 到临时目录 → 提权静默安装 /S。
|
||||||
|
* 调用返回前会触发应用退出。
|
||||||
|
*/
|
||||||
|
updateInstall: (downloadedPath: string) => __TAURI_INVOKE<null>("update_install", { downloadedPath }),
|
||||||
|
/**
|
||||||
|
* 应用 ThingHK 内核更新:下载阶段已由下载模块完成,本命令仅做
|
||||||
|
* need_stop(等待前端停止监控内核并确认)→ 解压 → 替换。
|
||||||
|
* 进度通过 UPDATE_PROGRESS 事件上报,前端据 need_stop 弹出确认对话框。
|
||||||
|
*/
|
||||||
|
updateThinghkApply: (zipPath: string) => __TAURI_INVOKE<null>("update_thinghk_apply", { zipPath }),
|
||||||
|
/** 前端已停止监控内核,确认继续解压替换(唤醒 need_stop 等待) */
|
||||||
|
updateThinghkConfirm: () => __TAURI_INVOKE<null>("update_thinghk_confirm"),
|
||||||
|
/** 取消 ThingHK 内核更新(need_stop 等待阶段有效:唤醒 apply 以「已取消」返回,zip 保留便于重试) */
|
||||||
|
updateThinghkCancel: () => __TAURI_INVOKE<null>("update_thinghk_cancel"),
|
||||||
proxyActivateProfile: (id: string) => __TAURI_INVOKE<null>("proxy_activate_profile", { id }),
|
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"),
|
proxyCheckKernelUpdate: () => __TAURI_INVOKE<KernelUpdateInfo>("proxy_check_kernel_update"),
|
||||||
proxyClearSystemProxy: () => __TAURI_INVOKE<null>("proxy_clear_system_proxy"),
|
proxyClearSystemProxy: () => __TAURI_INVOKE<null>("proxy_clear_system_proxy"),
|
||||||
proxyCloseConnection: (id: string) => __TAURI_INVOKE<null>("proxy_close_connection", { id }),
|
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 }),
|
proxyDeleteProfile: (id: string) => __TAURI_INVOKE<null>("proxy_delete_profile", { id }),
|
||||||
proxyGetSettings: () => __TAURI_INVOKE<ProxySettings>("proxy_get_settings"),
|
proxyGetSettings: () => __TAURI_INVOKE<ProxySettings>("proxy_get_settings"),
|
||||||
proxyGetSystemProxy: () => __TAURI_INVOKE<boolean>("proxy_get_system_proxy"),
|
proxyGetSystemProxy: () => __TAURI_INVOKE<boolean>("proxy_get_system_proxy"),
|
||||||
proxyImportProfile: (url: string, name: string) => __TAURI_INVOKE<ProfileMeta>("proxy_import_profile", { url, name }),
|
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"),
|
proxyKernelInfo: () => __TAURI_INVOKE<KernelInfo>("proxy_kernel_info"),
|
||||||
proxyRestart: () => __TAURI_INVOKE<ProcessInfo>("proxy_restart"),
|
proxyRestart: () => __TAURI_INVOKE<ProcessInfo>("proxy_restart"),
|
||||||
proxySaveSettings: (settings: ProxySettings) => __TAURI_INVOKE<null>("proxy_save_settings", { settings }),
|
proxySaveSettings: (settings: ProxySettings) => __TAURI_INVOKE<null>("proxy_save_settings", { settings }),
|
||||||
@@ -22,12 +51,15 @@ export const commands = {
|
|||||||
proxyStart: () => __TAURI_INVOKE<ProcessInfo>("proxy_start"),
|
proxyStart: () => __TAURI_INVOKE<ProcessInfo>("proxy_start"),
|
||||||
proxyStatus: () => __TAURI_INVOKE<ProxyStatus>("proxy_status"),
|
proxyStatus: () => __TAURI_INVOKE<ProxyStatus>("proxy_status"),
|
||||||
proxyStop: () => __TAURI_INVOKE<null>("proxy_stop"),
|
proxyStop: () => __TAURI_INVOKE<null>("proxy_stop"),
|
||||||
|
proxyTraffic: () => __TAURI_INVOKE<TrafficSnapshot>("proxy_traffic"),
|
||||||
proxyTestDelay: (name: string, url: string | null, timeout: number | null) => __TAURI_INVOKE<number>("proxy_test_delay", { name, url, timeout }),
|
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 }),
|
proxyUpdateProfile: (id: string) => __TAURI_INVOKE<ProfileMeta>("proxy_update_profile", { id }),
|
||||||
/** 读取快速面板设置(快捷键等) */
|
/** 读取快速面板设置(快捷键等) */
|
||||||
quickpanelGetSettings: () => __TAURI_INVOKE<QuickPanelSettings>("quickpanel_get_settings"),
|
quickpanelGetSettings: () => __TAURI_INVOKE<QuickPanelSettings>("quickpanel_get_settings"),
|
||||||
/** 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口 */
|
/**
|
||||||
|
* 保存快速面板设置;快捷键变化时自动重新注册 + 预创建窗口,
|
||||||
|
* 索引目录变化时闲时自动重建索引。
|
||||||
|
*/
|
||||||
quickpanelSaveSettings: (settings: QuickPanelSettings) => __TAURI_INVOKE<null>("quickpanel_save_settings", { settings }),
|
quickpanelSaveSettings: (settings: QuickPanelSettings) => __TAURI_INVOKE<null>("quickpanel_save_settings", { settings }),
|
||||||
/** 注册(或切换)快速面板全局快捷键 */
|
/** 注册(或切换)快速面板全局快捷键 */
|
||||||
quickpanelRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("quickpanel_register_shortcut", { shortcut }),
|
quickpanelRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("quickpanel_register_shortcut", { shortcut }),
|
||||||
@@ -41,7 +73,12 @@ export const commands = {
|
|||||||
quickpanelShowWindow: () => __TAURI_INVOKE<null>("quickpanel_show_window"),
|
quickpanelShowWindow: () => __TAURI_INVOKE<null>("quickpanel_show_window"),
|
||||||
/** 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗) */
|
/** 锁定屏幕(Windows: rundll32 user32.dll,LockWorkStation,CREATE_NO_WINDOW 避免黑窗) */
|
||||||
quickpanelLockScreen: () => __TAURI_INVOKE<null>("quickpanel_lock_screen"),
|
quickpanelLockScreen: () => __TAURI_INVOKE<null>("quickpanel_lock_screen"),
|
||||||
/** 初始化文件索引数据库(应用启动时调用) */
|
/**
|
||||||
|
* 初始化文件索引数据库(应用启动时调用)。
|
||||||
|
* 若存在上次构建的索引(last_built_dirs 非空),自动恢复 notify 增量监听,
|
||||||
|
* 无需重建即可继续自动同步文件变更。
|
||||||
|
* 若从未构建过(首次运行),闲时自动建立索引,无需用户手动点"构建索引"。
|
||||||
|
*/
|
||||||
quickpanelInitFileIndex: () => __TAURI_INVOKE<null>("quickpanel_init_file_index"),
|
quickpanelInitFileIndex: () => __TAURI_INVOKE<null>("quickpanel_init_file_index"),
|
||||||
/** 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用) */
|
/** 构建文件索引(全量重建,阻塞操作建议在 spawn_blocking 调用) */
|
||||||
quickpanelBuildFileIndex: () => __TAURI_INVOKE<number>("quickpanel_build_file_index"),
|
quickpanelBuildFileIndex: () => __TAURI_INVOKE<number>("quickpanel_build_file_index"),
|
||||||
@@ -81,8 +118,41 @@ export const commands = {
|
|||||||
/**
|
/**
|
||||||
* 运行系统命令(不设置 CREATE_NO_WINDOW,使 cmd/powershell/regedit 等显示自身窗口)
|
* 运行系统命令(不设置 CREATE_NO_WINDOW,使 cmd/powershell/regedit 等显示自身窗口)
|
||||||
* 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
* 适用于内置系统工具:regedit、shutdown、cmd、powershell、taskmgr 等。
|
||||||
|
* - 控制台类交互程序(cmd/powershell/pwsh)额外设置 CREATE_NEW_CONSOLE,
|
||||||
|
* 否则从 GUI 宿主启动时无可见控制台窗口(表现为"点击没反应")。
|
||||||
|
* - .msc 控制台文件(如 devmgmt.msc)不可被 CreateProcess 直接执行,
|
||||||
|
* 改由 mmc 打开(路径解析到 System32,不受当前工作目录影响)。
|
||||||
*/
|
*/
|
||||||
quickpanelRunSystemCommand: (command: string, args: string[]) => __TAURI_INVOKE<null>("quickpanel_run_system_command", { command, args }),
|
quickpanelRunSystemCommand: (command: string, args: string[]) => __TAURI_INVOKE<null>("quickpanel_run_system_command", { command, args }),
|
||||||
|
/** 列出目录下的压缩包文件(供批量解压面板使用)。 */
|
||||||
|
quickpanelListArchives: (dir: string) => __TAURI_INVOKE<ArchiveInfo[]>("quickpanel_list_archives", { dir }),
|
||||||
|
/** 列出目录下的全部条目(供批量重命名/删除面板使用,不含子目录递归)。 */
|
||||||
|
quickpanelListDir: (dir: string) => __TAURI_INVOKE<FileEntry[]>("quickpanel_list_dir", { dir }),
|
||||||
|
/**
|
||||||
|
* 批量解压。`files` 为压缩包路径列表,`dest_dir` 为目标目录,
|
||||||
|
* `password` 为统一解压密码(可空),`into_subfolder` 是否解压到同名子文件夹。
|
||||||
|
* 每完成一个文件通过 `quickpanel-extract-progress` 事件推送进度。
|
||||||
|
*/
|
||||||
|
quickpanelBatchExtract: (files: string[], destDir: string, password: string | null, intoSubfolder: boolean) => __TAURI_INVOKE<ExtractResult[]>("quickpanel_batch_extract", { files, destDir, password, intoSubfolder }),
|
||||||
|
/**
|
||||||
|
* 正则批量重命名预览:对每个文件名应用 `pattern → replacement`,
|
||||||
|
* 仅返回有匹配的文件,`newName` 为替换结果。
|
||||||
|
*/
|
||||||
|
quickpanelPreviewRename: (files: string[], pattern: string, replacement: string) => __TAURI_INVOKE<RenamePreview[]>("quickpanel_preview_rename", { files, pattern, replacement }),
|
||||||
|
/** 执行重命名。同一目录下若目标已存在则跳过该项。 */
|
||||||
|
quickpanelApplyRename: (items: RenameItem[]) => __TAURI_INVOKE<RenameResult[]>("quickpanel_apply_rename", { items }),
|
||||||
|
/**
|
||||||
|
* 批量删除文件/目录。`force=false` 时移动至回收站;`force=true` 时先递归清除
|
||||||
|
* 只读属性再永久删除(可绕过只读/部分占用导致的删除失败,但被其他进程真正
|
||||||
|
* 锁定的文件仍会失败并返回原因)。
|
||||||
|
*/
|
||||||
|
quickpanelDeleteFiles: (paths: string[], force: boolean) => __TAURI_INVOKE<DeleteResult[]>("quickpanel_delete_files", { paths, force }),
|
||||||
|
/**
|
||||||
|
* 显示主窗口并强制置为前台。
|
||||||
|
* Tauri 的 set_focus 在 Windows 上受前台锁定限制,主窗口被其他应用遮挡时无法到前台;
|
||||||
|
* 改用原生 SetForegroundWindow + BringWindowToTop(模拟 Alt 键重置前台锁定)。
|
||||||
|
*/
|
||||||
|
quickpanelFocusMainWindow: () => __TAURI_INVOKE<null>("quickpanel_focus_main_window"),
|
||||||
clipboardGetHistory: (limit: number | null, offset: number | null, kind: string | null) => __TAURI_INVOKE<HistoryPage>("clipboard_get_history", { limit, offset, kind }),
|
clipboardGetHistory: (limit: number | null, offset: number | null, kind: string | null) => __TAURI_INVOKE<HistoryPage>("clipboard_get_history", { limit, offset, kind }),
|
||||||
clipboardGetPinned: () => __TAURI_INVOKE<ClipboardItem[]>("clipboard_get_pinned"),
|
clipboardGetPinned: () => __TAURI_INVOKE<ClipboardItem[]>("clipboard_get_pinned"),
|
||||||
clipboardSearch: (query: string, limit: number | null, offset: number | null) => __TAURI_INVOKE<HistoryPage>("clipboard_search", { query, limit, offset }),
|
clipboardSearch: (query: string, limit: number | null, offset: number | null) => __TAURI_INVOKE<HistoryPage>("clipboard_search", { query, limit, offset }),
|
||||||
@@ -92,6 +162,8 @@ export const commands = {
|
|||||||
/** 图片 PNG base64(仅 image 类型) */
|
/** 图片 PNG base64(仅 image 类型) */
|
||||||
imageBase64: string | null,
|
imageBase64: string | null,
|
||||||
}) & (ClipboardItem) | null>("clipboard_get_item", { id }),
|
}) & (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 }),
|
clipboardSetPinned: (id: number, pinned: boolean) => __TAURI_INVOKE<boolean>("clipboard_set_pinned", { id, pinned }),
|
||||||
clipboardDelete: (id: number) => __TAURI_INVOKE<boolean>("clipboard_delete", { id }),
|
clipboardDelete: (id: number) => __TAURI_INVOKE<boolean>("clipboard_delete", { id }),
|
||||||
clipboardClear: () => __TAURI_INVOKE<boolean>("clipboard_clear"),
|
clipboardClear: () => __TAURI_INVOKE<boolean>("clipboard_clear"),
|
||||||
@@ -114,16 +186,40 @@ export const commands = {
|
|||||||
clipboardShowWindow: () => __TAURI_INVOKE<null>("clipboard_show_window"),
|
clipboardShowWindow: () => __TAURI_INVOKE<null>("clipboard_show_window"),
|
||||||
/** 隐藏弹窗并模拟 Ctrl+V 粘贴到原窗口 */
|
/** 隐藏弹窗并模拟 Ctrl+V 粘贴到原窗口 */
|
||||||
clipboardPasteToTarget: () => __TAURI_INVOKE<null>("clipboard_paste_to_target"),
|
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"),
|
downloaderGetTasks: () => __TAURI_INVOKE<DownloadTask[]>("downloader_get_tasks"),
|
||||||
/** 检查 URL 重复性并探测文件信息(添加下载前调用) */
|
/** 检查 URL 重复性并探测文件信息(添加下载前调用) */
|
||||||
downloaderCheckUrl: (url: string, dir: string | null, headers: { [key in string]: string } | null) => __TAURI_INVOKE<CheckUrlResult>("downloader_check_url", { url, dir, headers }),
|
downloaderCheckUrl: (url: string, dir: string | null, headers: { [key in string]: string } | null) => __TAURI_INVOKE<CheckUrlResult>("downloader_check_url", { url, dir, headers }),
|
||||||
/** 添加下载任务 */
|
/** 添加下载任务 */
|
||||||
downloaderAddTask: (url: string, filename: string | null, dir: string | null, headers: { [key in string]: string } | null, autoRename: boolean | null) => __TAURI_INVOKE<string>("downloader_add_task", { url, filename, dir, headers, autoRename }),
|
downloaderAddTask: (url: string, filename: string | null, dir: string | null, headers: { [key in string]: string } | null, autoRename: boolean | null, onlyFiles: number[] | null) => __TAURI_INVOKE<string>("downloader_add_task", { url, filename, dir, headers, autoRename, onlyFiles }),
|
||||||
/** 暂停任务 */
|
/** 暂停任务 */
|
||||||
downloaderPauseTask: (id: string) => __TAURI_INVOKE<null>("downloader_pause_task", { id }),
|
downloaderPauseTask: (id: string) => __TAURI_INVOKE<null>("downloader_pause_task", { id }),
|
||||||
/** 恢复任务 */
|
/** 恢复任务 */
|
||||||
downloaderResumeTask: (id: string) => __TAURI_INVOKE<null>("downloader_resume_task", { id }),
|
downloaderResumeTask: (id: string) => __TAURI_INVOKE<null>("downloader_resume_task", { id }),
|
||||||
|
/** 取消任务(置为已取消,清空进度并删除下载文件,但保留记录) */
|
||||||
|
downloaderCancelTask: (id: string) => __TAURI_INVOKE<null>("downloader_cancel_task", { id }),
|
||||||
|
/** 重新下载已取消/出错的任务 */
|
||||||
|
downloaderRedownload: (id: string) => __TAURI_INVOKE<null>("downloader_redownload", { id }),
|
||||||
/** 移除任务 */
|
/** 移除任务 */
|
||||||
downloaderRemoveTask: (id: string, deleteFiles: boolean | null) => __TAURI_INVOKE<null>("downloader_remove_task", { id, deleteFiles }),
|
downloaderRemoveTask: (id: string, deleteFiles: boolean | null) => __TAURI_INVOKE<null>("downloader_remove_task", { id, deleteFiles }),
|
||||||
/** 获取设置 */
|
/** 获取设置 */
|
||||||
@@ -134,14 +230,37 @@ export const commands = {
|
|||||||
downloaderOpenDir: (path: string) => __TAURI_INVOKE<null>("downloader_open_dir", { path }),
|
downloaderOpenDir: (path: string) => __TAURI_INVOKE<null>("downloader_open_dir", { path }),
|
||||||
/** 用系统默认浏览器打开 URL */
|
/** 用系统默认浏览器打开 URL */
|
||||||
downloaderOpenUrl: (url: string) => __TAURI_INVOKE<null>("downloader_open_url", { url }),
|
downloaderOpenUrl: (url: string) => __TAURI_INVOKE<null>("downloader_open_url", { url }),
|
||||||
|
/**
|
||||||
|
* 将指定 label 的下载窗口显示并强制置为前台。
|
||||||
|
* Tauri 的 set_focus 在 Windows 上受前台锁定限制(尤其下载窗口由后台进程创建、
|
||||||
|
* 或创建到非主显示器时更明显),改用原生 SetForegroundWindow + BringWindowToTop
|
||||||
|
* (模拟 Alt 键重置前台锁定),保证开始/完成下载时窗口能正确定位到前台。
|
||||||
|
*/
|
||||||
|
downloaderFocusWindow: (label: string) => __TAURI_INVOKE<null>("downloader_focus_window", { label }),
|
||||||
|
/** 解析磁力链 / .torrent 文件,返回种子信息(名称 / infohash / 文件列表),供前端做文件勾选 */
|
||||||
|
downloaderInspect: (input: string) => __TAURI_INVOKE<TorrentInfo>("downloader_inspect", { input }),
|
||||||
|
/** 磁力任务:元数据解析成功后,用户勾选文件并确认开始下载 */
|
||||||
|
downloaderSelectBtFiles: (id: string, onlyFiles: number[]) => __TAURI_INVOKE<null>("downloader_select_bt_files", { id, onlyFiles }),
|
||||||
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
|
/** 禁用指定窗口(按 label 查找)的显示/隐藏过渡动画,消除覆盖层出现/消失时的缩放动画 */
|
||||||
screenshotDisableTransitions: (label: string) => __TAURI_INVOKE<null>("screenshot_disable_transitions", { 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 }),
|
screenshotRegisterShortcut: (shortcut: string) => __TAURI_INVOKE<null>("screenshot_register_shortcut", { shortcut }),
|
||||||
/** 注销截图全局快捷键 */
|
/** 注销截图全局快捷键 */
|
||||||
screenshotUnregisterShortcut: () => __TAURI_INVOKE<null>("screenshot_unregister_shortcut"),
|
screenshotUnregisterShortcut: () => __TAURI_INVOKE<null>("screenshot_unregister_shortcut"),
|
||||||
/** 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码 */
|
/**
|
||||||
screenshotCaptureFullscreen: () => __TAURI_INVOKE<null>("screenshot_capture_fullscreen"),
|
* 注册(或切换)贴图全局快捷键。传入空字符串则禁用快捷键。
|
||||||
|
* 按下时 emit 'screenshot-pin-shortcut',由前端切换贴图窗口显示/隐藏。
|
||||||
|
*/
|
||||||
|
screenshotRegisterPinShortcut: (shortcut: string) => __TAURI_INVOKE<null>("screenshot_register_pin_shortcut", { shortcut }),
|
||||||
|
/** 注销贴图全局快捷键 */
|
||||||
|
screenshotUnregisterPinShortcut: () => __TAURI_INVOKE<null>("screenshot_unregister_pin_shortcut"),
|
||||||
|
/**
|
||||||
|
* 捕获整个虚拟屏(多显示器拼接)存入静态,不做 PNG 编码。
|
||||||
|
* 同时返回捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返)。
|
||||||
|
*/
|
||||||
|
screenshotCaptureFullscreen: () => __TAURI_INVOKE<CaptureStart>("screenshot_capture_fullscreen"),
|
||||||
/** 全屏捕获编码为 PNG base64 并清除(全屏截图直接进编辑器) */
|
/** 全屏捕获编码为 PNG base64 并清除(全屏截图直接进编辑器) */
|
||||||
screenshotFullscreenPng: () => __TAURI_INVOKE<CaptureData>("screenshot_fullscreen_png"),
|
screenshotFullscreenPng: () => __TAURI_INVOKE<CaptureData>("screenshot_fullscreen_png"),
|
||||||
/** 清除静态全屏捕获(覆盖层关闭/取消时释放内存) */
|
/** 清除静态全屏捕获(覆盖层关闭/取消时释放内存) */
|
||||||
@@ -150,15 +269,12 @@ export const commands = {
|
|||||||
screenshotCropStored: (x: number, y: number, w: number, h: number) => __TAURI_INVOKE<CaptureData>("screenshot_crop_stored", { x, y, w, h }),
|
screenshotCropStored: (x: number, y: number, w: number, h: number) => __TAURI_INVOKE<CaptureData>("screenshot_crop_stored", { x, y, w, h }),
|
||||||
/** 裁剪已存储的全屏捕获并直接写入剪贴板(一次 IPC 完成"裁剪+复制") */
|
/** 裁剪已存储的全屏捕获并直接写入剪贴板(一次 IPC 完成"裁剪+复制") */
|
||||||
screenshotCropCopyStored: (x: number, y: number, w: number, h: number) => __TAURI_INVOKE<CaptureData>("screenshot_crop_copy_stored", { x, y, w, h }),
|
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<{
|
* 枚举可拾取的顶层窗口(Z 序顶→底,排除本进程/不可见/工具窗口)。
|
||||||
hwnd: number,
|
* 前端在截图开始时缓存列表,鼠标移动时在 JS 侧本地命中测试,消除逐帧 IPC 往返。
|
||||||
title: string,
|
*/
|
||||||
rect: ScreenRect,
|
screenshotPickList: () => __TAURI_INVOKE<WindowInfo[]>("screenshot_pick_list"),
|
||||||
/** DWM 扩展边框矩形(视觉边界,去掉最大化窗口的隐形缩放边框),命中测试用 rect,高亮用 visual_rect */
|
/** 获取当前鼠标物理屏幕坐标(贴图窗口拖动跟随等场景使用) */
|
||||||
visualRect: ScreenRect | null,
|
|
||||||
} | null>("screenshot_window_from_point", { x, y }),
|
|
||||||
/** 获取当前鼠标物理屏幕坐标(覆盖层打开时定位初始悬停窗口) */
|
|
||||||
screenshotCursorPos: () => __TAURI_INVOKE<[number, number]>("screenshot_cursor_pos"),
|
screenshotCursorPos: () => __TAURI_INVOKE<[number, number]>("screenshot_cursor_pos"),
|
||||||
/** 枚举所有可见顶层窗口 */
|
/** 枚举所有可见顶层窗口 */
|
||||||
screenshotEnumWindows: () => __TAURI_INVOKE<WindowInfo[]>("screenshot_enum_windows"),
|
screenshotEnumWindows: () => __TAURI_INVOKE<WindowInfo[]>("screenshot_enum_windows"),
|
||||||
@@ -186,6 +302,22 @@ export type AppRecord = {
|
|||||||
path: string,
|
path: string,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ArchiveInfo = {
|
||||||
|
name: string,
|
||||||
|
path: string,
|
||||||
|
size: number,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** BT 种子内文件条目(多文件任务用;阶段1下载全部文件,但保留列表供 UI 展示) */
|
||||||
|
export type BtFileInfo = {
|
||||||
|
/** 文件在种子内的索引 */
|
||||||
|
index: number,
|
||||||
|
/** 相对种子根目录的路径(如 "sub/file.mkv") */
|
||||||
|
path: string,
|
||||||
|
/** 文件大小(字节) */
|
||||||
|
size: number,
|
||||||
|
};
|
||||||
|
|
||||||
/** 前端可见的捕获数据 */
|
/** 前端可见的捕获数据 */
|
||||||
export type CaptureData = {
|
export type CaptureData = {
|
||||||
pngBase64: string,
|
pngBase64: string,
|
||||||
@@ -193,6 +325,12 @@ export type CaptureData = {
|
|||||||
height: number,
|
height: number,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 截图启动信息:捕获时刻的光标物理坐标(覆盖层据此做初始窗口拾取,省一次 IPC 往返) */
|
||||||
|
export type CaptureStart = {
|
||||||
|
cursorX: number,
|
||||||
|
cursorY: number,
|
||||||
|
};
|
||||||
|
|
||||||
/** check_url 命令返回的结果 */
|
/** check_url 命令返回的结果 */
|
||||||
export type CheckUrlResult = {
|
export type CheckUrlResult = {
|
||||||
/** 探测是否成功 */
|
/** 探测是否成功 */
|
||||||
@@ -260,16 +398,32 @@ export type CustomCommand = {
|
|||||||
args?: string[],
|
args?: string[],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 批量删除单个条目的结果。 */
|
||||||
|
export type DeleteResult = {
|
||||||
|
name: string,
|
||||||
|
path: string,
|
||||||
|
ok: boolean,
|
||||||
|
error: string,
|
||||||
|
};
|
||||||
|
|
||||||
/** 下载任务 */
|
/** 下载任务 */
|
||||||
export type DownloadTask = {
|
export type DownloadTask = {
|
||||||
/** 任务 ID(自增 hex 字符串) */
|
/** 任务 ID(自增 hex 字符串) */
|
||||||
id: string,
|
id: string,
|
||||||
/** 下载地址 */
|
/** 下载地址(HTTP URL 或磁力链接) */
|
||||||
url: string,
|
url: string,
|
||||||
/** 文件名 */
|
/** 文件名(HTTP:目标文件名;BT:种子名称) */
|
||||||
filename: string,
|
filename: string,
|
||||||
/** 保存目录(绝对路径) */
|
/** 保存目录(绝对路径) */
|
||||||
dir: string,
|
dir: string,
|
||||||
|
/** 协议类型 */
|
||||||
|
protocol?: TaskProtocol,
|
||||||
|
/** BT 种子 infohash(协议=BitTorrent 时存在) */
|
||||||
|
infoHash?: string | null,
|
||||||
|
/** BT 种子内文件列表(协议=BitTorrent 时存在) */
|
||||||
|
btFiles?: BtFileInfo[],
|
||||||
|
/** BT 元数据是否已解析就绪(异步添加时:后台解析完成前为 false,调度器跳过) */
|
||||||
|
btMetadataReady?: boolean,
|
||||||
/** 状态 */
|
/** 状态 */
|
||||||
status: TaskStatus,
|
status: TaskStatus,
|
||||||
/** 文件总大小(字节),0=未知 */
|
/** 文件总大小(字节),0=未知 */
|
||||||
@@ -310,6 +464,16 @@ export type DownloaderSettings = {
|
|||||||
deleteFilesOnRemove?: boolean,
|
deleteFilesOnRemove?: boolean,
|
||||||
/** 添加下载前检查重复(URL 或文件名重复时询问) */
|
/** 添加下载前检查重复(URL 或文件名重复时询问) */
|
||||||
checkDuplicate?: boolean,
|
checkDuplicate?: boolean,
|
||||||
|
/** 下载是否使用代理:true=尊重系统代理(mihomo 开启系统代理时经其转发),false=强制直连 */
|
||||||
|
useProxy?: boolean,
|
||||||
|
/** BitTorrent 上传限速 KB/s(0=不限) */
|
||||||
|
btUploadLimitKb?: number,
|
||||||
|
/** BitTorrent 下载完成后是否继续做种上传(false=下载完即停止上传) */
|
||||||
|
btSeedAfterDownload?: boolean,
|
||||||
|
/** BitTorrent 监听端口(0=自动选择) */
|
||||||
|
btListenPort?: number,
|
||||||
|
/** BitTorrent 使用代理下载:开启后自动使用代理模块(mihomo)的 SOCKS5 端口;代理不可用时降级直连 */
|
||||||
|
btUseProxy?: boolean,
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 重复类型 */
|
/** 重复类型 */
|
||||||
@@ -330,6 +494,20 @@ export type ExistingTaskInfo = {
|
|||||||
status: TaskStatus,
|
status: TaskStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ExtractResult = {
|
||||||
|
name: string,
|
||||||
|
path: string,
|
||||||
|
ok: boolean,
|
||||||
|
error: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FileEntry = {
|
||||||
|
name: string,
|
||||||
|
path: string,
|
||||||
|
isDir: boolean,
|
||||||
|
size: number,
|
||||||
|
};
|
||||||
|
|
||||||
/** 单个文件记录(返回给前端) */
|
/** 单个文件记录(返回给前端) */
|
||||||
export type FileRecord = {
|
export type FileRecord = {
|
||||||
path: string,
|
path: string,
|
||||||
@@ -429,6 +607,26 @@ export type QuickPanelSettings = {
|
|||||||
customCommands?: CustomCommand[],
|
customCommands?: CustomCommand[],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type RenameItem = {
|
||||||
|
path: string,
|
||||||
|
oldName: string,
|
||||||
|
newName: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RenamePreview = {
|
||||||
|
path: string,
|
||||||
|
oldName: string,
|
||||||
|
newName: string,
|
||||||
|
error: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type RenameResult = {
|
||||||
|
oldName: string,
|
||||||
|
newName: string,
|
||||||
|
ok: boolean,
|
||||||
|
error: string,
|
||||||
|
};
|
||||||
|
|
||||||
export type ScreenRect = {
|
export type ScreenRect = {
|
||||||
x: number,
|
x: number,
|
||||||
y: number,
|
y: number,
|
||||||
@@ -460,6 +658,13 @@ export type SpecialLocation = {
|
|||||||
args: string[],
|
args: string[],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** 任务下载协议类型 */
|
||||||
|
export type TaskProtocol =
|
||||||
|
/** HTTP/HTTPS 直链 */
|
||||||
|
"http" |
|
||||||
|
/** BitTorrent(磁力链 / .torrent 文件) */
|
||||||
|
"bittorrent";
|
||||||
|
|
||||||
/** 任务状态 */
|
/** 任务状态 */
|
||||||
export type TaskStatus =
|
export type TaskStatus =
|
||||||
/** 排队等待(并发数已满) */
|
/** 排队等待(并发数已满) */
|
||||||
@@ -471,7 +676,54 @@ export type TaskStatus =
|
|||||||
/** 已完成 */
|
/** 已完成 */
|
||||||
"complete" |
|
"complete" |
|
||||||
/** 错误 */
|
/** 错误 */
|
||||||
"error";
|
"error" |
|
||||||
|
/** 已取消(用户取消:进度与文件已清除,仅保留记录,只能再次下载) */
|
||||||
|
"cancelled";
|
||||||
|
|
||||||
|
/** 种子信息(inspect 解析结果,供命令返回给前端做文件勾选) */
|
||||||
|
export type TorrentInfo = {
|
||||||
|
/** 种子名称 */
|
||||||
|
name: string,
|
||||||
|
/** infohash(hex 小写字符串) */
|
||||||
|
infoHash: string,
|
||||||
|
/** 种子内全部文件总大小(字节) */
|
||||||
|
totalSize: number,
|
||||||
|
/** 种子内文件列表 */
|
||||||
|
files: BtFileInfo[],
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 实时流量快照(由 /connections 的会话总量差分得出实时速率) */
|
||||||
|
export type TrafficSnapshot = {
|
||||||
|
/** 本次会话累计下载字节数 */
|
||||||
|
downloadTotal: number,
|
||||||
|
/** 本次会话累计上传字节数 */
|
||||||
|
uploadTotal: number,
|
||||||
|
/** 实时下载速率(字节/秒) */
|
||||||
|
downloadSpeed: number,
|
||||||
|
/** 实时上传速率(字节/秒) */
|
||||||
|
uploadSpeed: number,
|
||||||
|
/** 当前活跃连接数 */
|
||||||
|
activeConnections: number,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** release 中的一个资产 */
|
||||||
|
export type UpdateAsset = {
|
||||||
|
name: string,
|
||||||
|
size: number,
|
||||||
|
browserDownloadUrl: string,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 检查更新的结果 */
|
||||||
|
export type UpdateCheckResult = {
|
||||||
|
currentVersion: string,
|
||||||
|
latestVersion: string,
|
||||||
|
hasUpdate: boolean,
|
||||||
|
/** portable | installed */
|
||||||
|
installType: string,
|
||||||
|
releaseName: string,
|
||||||
|
releaseBody: string,
|
||||||
|
assets: UpdateAsset[],
|
||||||
|
};
|
||||||
|
|
||||||
/** 窗口信息(窗口拾取 / 枚举) */
|
/** 窗口信息(窗口拾取 / 枚举) */
|
||||||
export type WindowInfo = {
|
export type WindowInfo = {
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ export const WINDOWS = {
|
|||||||
main: 'main',
|
main: 'main',
|
||||||
osdOverlay: 'osd-overlay',
|
osdOverlay: 'osd-overlay',
|
||||||
screenshotOverlay: 'screenshot-overlay',
|
screenshotOverlay: 'screenshot-overlay',
|
||||||
|
screenshotPin: 'screenshot-pin',
|
||||||
|
/** 单文件一次性下载窗口前缀,实际 label = `${downloadWindow}-<taskId>` */
|
||||||
|
downloadWindow: 'download-window',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
|
/** Tauri 事件名(前端 emit / listen 与 Rust constants::events 对应) */
|
||||||
@@ -23,22 +26,45 @@ export const EVENTS = {
|
|||||||
clipboardChanged: 'clipboard-changed',
|
clipboardChanged: 'clipboard-changed',
|
||||||
clipboardPopupShow: 'clipboard-popup-show',
|
clipboardPopupShow: 'clipboard-popup-show',
|
||||||
clipboardPopupHide: 'clipboard-popup-hide',
|
clipboardPopupHide: 'clipboard-popup-hide',
|
||||||
|
clipboardPreviewShow: 'clipboard-preview-show',
|
||||||
|
clipboardPreviewHide: 'clipboard-preview-hide',
|
||||||
|
// 鼠标进入/离开独立预览窗(弹窗据此决定是否延迟隐藏预览,便于点击复制/放大)
|
||||||
|
clipboardPreviewEnter: 'clipboard-preview-enter',
|
||||||
|
clipboardPreviewLeave: 'clipboard-preview-leave',
|
||||||
// 快速面板
|
// 快速面板
|
||||||
quickpanelShow: 'quickpanel-show',
|
quickpanelShow: 'quickpanel-show',
|
||||||
quickpanelHide: 'quickpanel-hide',
|
quickpanelHide: 'quickpanel-hide',
|
||||||
quickpanelExecuteCommand: 'quickpanel-execute-command',
|
quickpanelExecuteCommand: 'quickpanel-execute-command',
|
||||||
|
quickpanelExtractProgress: 'quickpanel-extract-progress',
|
||||||
|
// 文件索引构建完成(闲时自动建立/重建、手动构建)
|
||||||
|
quickpanelIndexUpdated: 'quickpanel-index-updated',
|
||||||
// 截图
|
// 截图
|
||||||
screenshotBegin: 'screenshot-begin',
|
screenshotBegin: 'screenshot-begin',
|
||||||
screenshotOverlayReady: 'screenshot-overlay-ready',
|
screenshotOverlayReady: 'screenshot-overlay-ready',
|
||||||
screenshotShortcut: 'screenshot-shortcut',
|
screenshotShortcut: 'screenshot-shortcut',
|
||||||
|
screenshotPinShortcut: 'screenshot-pin-shortcut',
|
||||||
|
screenshotPinReady: 'screenshot-pin-ready',
|
||||||
|
screenshotPinShow: 'screenshot-pin-show',
|
||||||
screenshotExported: 'screenshot-exported',
|
screenshotExported: 'screenshot-exported',
|
||||||
// 内核安装进度
|
// 内核安装进度
|
||||||
kernelInstallProgress: 'kernel-install-progress',
|
kernelInstallProgress: 'kernel-install-progress',
|
||||||
|
// 后端自动切换节点完成(后台执行,刷新节点列表并提示)
|
||||||
|
proxyAutoSwitch: 'proxy-auto-switch',
|
||||||
|
// 应用更新进度
|
||||||
|
updateProgress: 'update-progress',
|
||||||
// 监控 OSD
|
// 监控 OSD
|
||||||
osdStateUpdate: 'osd-state-update',
|
osdStateUpdate: 'osd-state-update',
|
||||||
|
/** OSD 数据通道:仅推送显示项 key→value 映射 + 网速(高频,每秒) */
|
||||||
|
osdDataUpdate: 'osd-data-update',
|
||||||
|
/** OSD 窗口挂载后请求主窗口补发配置+数据(防止错过创建时的首推) */
|
||||||
|
osdConfigRequest: 'osd-config-request',
|
||||||
osdContentSize: 'osd-content-size',
|
osdContentSize: 'osd-content-size',
|
||||||
osdSystemUiActive: 'osd-system-ui-active',
|
osdSystemUiActive: 'osd-system-ui-active',
|
||||||
osdSystemUiInactive: 'osd-system-ui-inactive',
|
osdSystemUiInactive: 'osd-system-ui-inactive',
|
||||||
|
/** 前台出现全屏应用(游戏):OSD 应隐藏以避免游戏掉帧 */
|
||||||
|
osdGameActive: 'osd-game-active',
|
||||||
|
/** 全屏应用退出前台:OSD 可恢复显示 */
|
||||||
|
osdGameInactive: 'osd-game-inactive',
|
||||||
osdStartDrag: 'osd-start-drag',
|
osdStartDrag: 'osd-start-drag',
|
||||||
osdEndDrag: 'osd-end-drag',
|
osdEndDrag: 'osd-end-drag',
|
||||||
monitorReady: 'monitor-ready',
|
monitorReady: 'monitor-ready',
|
||||||
@@ -50,6 +76,10 @@ export const EVENTS = {
|
|||||||
// 其他
|
// 其他
|
||||||
processStatusChanged: 'process-status-changed',
|
processStatusChanged: 'process-status-changed',
|
||||||
downloadAdded: 'download-added',
|
downloadAdded: 'download-added',
|
||||||
|
/** 任务被删除(浏览器扩展通过 HTTP API 删除任务时发出,前端据此刷新任务列表) */
|
||||||
|
downloadRemoved: 'download-removed',
|
||||||
|
/** 浏览器扩展通过 HTTP API 新增下载(负载 { id },前端据以为该任务创建专属下载窗口) */
|
||||||
|
downloadExtensionAdded: 'download-extension-added',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
/** localStorage 存储键 */
|
/** localStorage 存储键 */
|
||||||
@@ -60,6 +90,19 @@ export const STORAGE_KEYS = {
|
|||||||
quickpanelSettings: 'thing_quickpanel_settings',
|
quickpanelSettings: 'thing_quickpanel_settings',
|
||||||
quickpanelHistory: 'thing_quickpanel_history',
|
quickpanelHistory: 'thing_quickpanel_history',
|
||||||
quickpanelHistoryItems: 'thing_quickpanel_history_items',
|
quickpanelHistoryItems: 'thing_quickpanel_history_items',
|
||||||
|
quickpanelPwdHistory: 'thing_quickpanel_pwd_history',
|
||||||
|
quickpanelPwdFavs: 'thing_quickpanel_pwd_favs',
|
||||||
|
quickpanelRenameMatchHistory: 'thing_quickpanel_rename_match_history',
|
||||||
|
quickpanelRenameMatchFavs: 'thing_quickpanel_rename_match_favs',
|
||||||
|
quickpanelRenameReplaceHistory: 'thing_quickpanel_rename_replace_history',
|
||||||
|
quickpanelRenameReplaceFavs: 'thing_quickpanel_rename_replace_favs',
|
||||||
|
quickpanelDeleteFilterHistory: 'thing_quickpanel_delete_filter_history',
|
||||||
|
quickpanelDeleteFilterFavs: 'thing_quickpanel_delete_filter_favs',
|
||||||
currencyRates: 'thing_quickpanel_currency_rates',
|
currencyRates: 'thing_quickpanel_currency_rates',
|
||||||
monitorOsdConfig: 'thing_monitor_osd_config',
|
monitorOsdConfig: 'thing_monitor_osd_config',
|
||||||
|
/** 关闭"自动启动监控内核"时暂存的 OSD 开关状态(开启自动启动时据此恢复) */
|
||||||
|
monitorOsdPending: 'thing_monitor_osd_pending',
|
||||||
|
monitorOverviewCards: 'thing_monitor_overview_cards',
|
||||||
|
screenshotHistory: 'thing_screenshot_history',
|
||||||
|
screenshotPinIndex: 'thing_screenshot_pin_index',
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
@@ -10,3 +10,6 @@ import { ref } from 'vue'
|
|||||||
|
|
||||||
/** 待打开新建下载对话框(由托盘"新建下载"触发) */
|
/** 待打开新建下载对话框(由托盘"新建下载"触发) */
|
||||||
export const pendingNewDownload = ref(false)
|
export const pendingNewDownload = ref(false)
|
||||||
|
|
||||||
|
/** 待切换到下载任务列表页(由浏览器扩展新增下载触发,不弹对话框直接看任务) */
|
||||||
|
export const pendingShowDownloadTasks = ref(false)
|
||||||
|
|||||||
@@ -12,12 +12,15 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
|||||||
* ```ts
|
* ```ts
|
||||||
* // 模块 <script setup> 顶部
|
* // 模块 <script setup> 顶部
|
||||||
* const activeTab = ref('overview')
|
* const activeTab = ref('overview')
|
||||||
* const tabsListRef = useModuleTabs(activeTab, [
|
* const tabsListRef = useModuleTabs('proxy', activeTab, [
|
||||||
* { value: 'overview', label: '概览' },
|
* { value: 'overview', label: '概览' },
|
||||||
* { value: 'settings', label: '设置' }
|
* { value: 'settings', label: '设置' }
|
||||||
* ])
|
* ])
|
||||||
* ```
|
* ```
|
||||||
*
|
*
|
||||||
|
* 第一个参数为模块 id:搜索导航跳转时,模块挂载后会自动
|
||||||
|
* 消费 moduleTabsStore 中对应的待跳转 tab(pendingTab)。
|
||||||
|
*
|
||||||
* ```vue
|
* ```vue
|
||||||
* <!-- 模板中给 TabsList 包一层带 ref 的 div -->
|
* <!-- 模板中给 TabsList 包一层带 ref 的 div -->
|
||||||
* <div ref="tabsListRef">
|
* <div ref="tabsListRef">
|
||||||
@@ -29,7 +32,8 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
|||||||
* 1. onMounted 时注册标签到 moduleTabsStore,TitleBar 据此渲染浮动切换器
|
* 1. onMounted 时注册标签到 moduleTabsStore,TitleBar 据此渲染浮动切换器
|
||||||
* 2. 用 IntersectionObserver 监听 TabsList 可见性(rootMargin 裁剪 TitleBar 高度)
|
* 2. 用 IntersectionObserver 监听 TabsList 可见性(rootMargin 裁剪 TitleBar 高度)
|
||||||
* 3. 双向 watch 同步本地 activeTab 与 store.activeTab
|
* 3. 双向 watch 同步本地 activeTab 与 store.activeTab
|
||||||
* 4. onUnmounted 时清理 observer 并注销标签
|
* 4. 消费搜索导航的待跳转 tab(模块尚未挂载的场景)
|
||||||
|
* 5. onUnmounted 时清理 observer 并注销标签
|
||||||
*
|
*
|
||||||
* ## 约束
|
* ## 约束
|
||||||
* - TitleBar 高度固定为 40px (h-10),composable 内部已用 44px 裁剪(含缓冲)
|
* - TitleBar 高度固定为 40px (h-10),composable 内部已用 44px 裁剪(含缓冲)
|
||||||
@@ -37,6 +41,7 @@ import { useModuleTabsStore, type ModuleTab } from '@/stores/moduleTabsStore'
|
|||||||
* - 模块卸载时务必让 composable 的 onUnmounted 执行(已自动处理,无需手动调用)
|
* - 模块卸载时务必让 composable 的 onUnmounted 执行(已自动处理,无需手动调用)
|
||||||
*/
|
*/
|
||||||
export function useModuleTabs(
|
export function useModuleTabs(
|
||||||
|
moduleId: string,
|
||||||
activeTab: Ref<string>,
|
activeTab: Ref<string>,
|
||||||
tabs: ModuleTab[]
|
tabs: ModuleTab[]
|
||||||
): Ref<HTMLElement | null> {
|
): Ref<HTMLElement | null> {
|
||||||
@@ -45,6 +50,15 @@ export function useModuleTabs(
|
|||||||
|
|
||||||
let observer: IntersectionObserver | null = null
|
let observer: IntersectionObserver | null = null
|
||||||
|
|
||||||
|
/** 应用待跳转 tab(若属于当前模块的 tab 列表) */
|
||||||
|
const applyPendingTab = () => {
|
||||||
|
const pending = tabsStore.consumePendingTab(moduleId)
|
||||||
|
if (pending && tabs.some(t => t.value === pending)) {
|
||||||
|
activeTab.value = pending
|
||||||
|
tabsStore.setActiveTab(pending)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const setupObserver = () => {
|
const setupObserver = () => {
|
||||||
const el = tabsListRef.value
|
const el = tabsListRef.value
|
||||||
if (!el || observer) return
|
if (!el || observer) return
|
||||||
@@ -75,10 +89,19 @@ export function useModuleTabs(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 模块已挂载时(搜索结果选中同一模块),pendingTab 变化 → 直接切换 tab
|
||||||
|
watch(() => tabsStore.pendingTab, (p) => {
|
||||||
|
if (p?.moduleId === moduleId) {
|
||||||
|
applyPendingTab()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
tabsStore.registerTabs(tabs, activeTab.value)
|
tabsStore.registerTabs(tabs, activeTab.value)
|
||||||
await nextTick()
|
await nextTick()
|
||||||
setupObserver()
|
setupObserver()
|
||||||
|
// 搜索导航跳转:模块刚挂载,消费待跳转 tab
|
||||||
|
applyPendingTab()
|
||||||
})
|
})
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
|
|||||||
+21
-5
@@ -6,8 +6,17 @@ import 'vue-sonner/style.css'
|
|||||||
import { createLogger } from './lib/logger'
|
import { createLogger } from './lib/logger'
|
||||||
const logger = createLogger('main')
|
const logger = createLogger('main')
|
||||||
|
|
||||||
|
// 禁用 WebView 默认右键菜单(桌面应用体验,主窗口与独立窗口共用)
|
||||||
|
document.addEventListener('contextmenu', (e) => e.preventDefault())
|
||||||
|
|
||||||
|
// 良性通知过滤:ResizeObserver 回调引发的布局变化在同一帧内级联时,
|
||||||
|
// 浏览器会派发此 ErrorEvent(规范定义为"通知"而非异常,无可操作信息)。
|
||||||
|
// 监控数据每秒刷新、reka-ui 组件挂载时高发,直接忽略避免污染日志。
|
||||||
|
const BENIGN_RESIZE_OBSERVER_RE = /^ResizeObserver loop (completed with undelivered notifications|limit exceeded)/i
|
||||||
|
|
||||||
// 全局未捕获异常日志
|
// 全局未捕获异常日志
|
||||||
window.addEventListener('error', (event) => {
|
window.addEventListener('error', (event) => {
|
||||||
|
if (event.message && BENIGN_RESIZE_OBSERVER_RE.test(event.message)) return
|
||||||
logger.error(`全局JS错误: ${event.message} @ ${event.filename}:${event.lineno}`)
|
logger.error(`全局JS错误: ${event.message} @ ${event.filename}:${event.lineno}`)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -22,18 +31,22 @@ window.addEventListener('unhandledrejection', (event) => {
|
|||||||
const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Promise<{ default: Component }>]> = [
|
const standaloneWindowApps: Array<[hash: string, label: string, loader: () => Promise<{ default: Component }>]> = [
|
||||||
['#osd-overlay', 'OSD', () => import('./modules/monitor/OsdWindow.vue')],
|
['#osd-overlay', 'OSD', () => import('./modules/monitor/OsdWindow.vue')],
|
||||||
['#clipboard-popup', '剪贴板弹窗', () => import('./modules/clipboard/ClipboardPopup.vue')],
|
['#clipboard-popup', '剪贴板弹窗', () => import('./modules/clipboard/ClipboardPopup.vue')],
|
||||||
|
['#clipboard-preview', '剪贴板预览', () => import('./modules/clipboard/ClipboardPreview.vue')],
|
||||||
['#quick-panel', '快速面板弹窗', () => import('./modules/quickpanel/QuickPanel.vue')],
|
['#quick-panel', '快速面板弹窗', () => import('./modules/quickpanel/QuickPanel.vue')],
|
||||||
['#tray-menu', '托盘菜单', () => import('./modules/tray/TrayMenu.vue')],
|
['#tray-menu', '托盘菜单', () => import('./modules/tray/TrayMenu.vue')],
|
||||||
['#screenshot-overlay', '截图覆盖层', () => import('./modules/screenshot/ScreenshotOverlay.vue')],
|
['#screenshot-overlay', '截图覆盖层', () => import('./modules/screenshot/ScreenshotOverlay.vue')],
|
||||||
['#screenshot-editor', '截图编辑器', () => import('./modules/screenshot/ScreenshotEditor.vue')],
|
['#screenshot-editor', '截图编辑器', () => import('./modules/screenshot/ScreenshotEditor.vue')],
|
||||||
|
['#screenshot-pin', '贴图窗口', () => import('./modules/screenshot/ScreenshotPin.vue')],
|
||||||
|
['#download-window', '下载窗口', () => import('./modules/downloader/DownloadWindow.vue')],
|
||||||
]
|
]
|
||||||
|
|
||||||
const winHash = window.location.hash
|
const winHash = window.location.hash
|
||||||
|
|
||||||
// #screenshot-overlay 带窗口号参数(多屏),按前缀匹配;其余精确匹配
|
// #screenshot-overlay 带窗口号参数(多屏)、#download-window 带 ?task= 参数,按前缀匹配;其余精确匹配
|
||||||
const matched = standaloneWindowApps.find(([hash]) =>
|
const matched = standaloneWindowApps.find(([hash]) => {
|
||||||
hash === '#screenshot-overlay' ? winHash.startsWith(hash) : winHash === hash
|
if (hash === '#screenshot-overlay' || hash === '#download-window') return winHash.startsWith(hash)
|
||||||
)
|
return winHash === hash
|
||||||
|
})
|
||||||
|
|
||||||
if (matched) {
|
if (matched) {
|
||||||
const [, label, loader] = matched
|
const [, label, loader] = matched
|
||||||
@@ -77,14 +90,17 @@ if (matched) {
|
|||||||
useProcessStore().initListener().catch(e => console.error('Process listener init error:', e))
|
useProcessStore().initListener().catch(e => console.error('Process listener init error:', e))
|
||||||
})
|
})
|
||||||
|
|
||||||
// 截图模块:加载设置 + 预创建常驻覆盖层窗口 + 监听导出事件(历史/自动保存)+ 注册并监听全局快捷键
|
// 截图模块:加载设置 + 恢复持久化历史 + 预创建常驻覆盖层窗口 + 监听导出事件(历史/自动保存)+ 注册并监听全局快捷键(截图/贴图)
|
||||||
void import('./stores/screenshotStore').then(({ useScreenshotStore }) => {
|
void import('./stores/screenshotStore').then(({ useScreenshotStore }) => {
|
||||||
const screenshotStore = useScreenshotStore()
|
const screenshotStore = useScreenshotStore()
|
||||||
screenshotStore.loadSettings()
|
screenshotStore.loadSettings()
|
||||||
|
screenshotStore.loadHistory()
|
||||||
screenshotStore.initOverlay().catch(e => console.error('Screenshot overlay init error:', e))
|
screenshotStore.initOverlay().catch(e => console.error('Screenshot overlay init error:', e))
|
||||||
screenshotStore.initExportListener().catch(e => console.error('Screenshot export listener init error:', e))
|
screenshotStore.initExportListener().catch(e => console.error('Screenshot export listener init error:', e))
|
||||||
screenshotStore.initShortcutListener().catch(e => console.error('Screenshot shortcut listener init error:', e))
|
screenshotStore.initShortcutListener().catch(e => console.error('Screenshot shortcut listener init error:', e))
|
||||||
screenshotStore.initShortcutRegistration().catch(e => console.error('Screenshot shortcut registration init error:', e))
|
screenshotStore.initShortcutRegistration().catch(e => console.error('Screenshot shortcut registration init error:', e))
|
||||||
|
screenshotStore.initPinShortcutListener().catch(e => console.error('Screenshot pin shortcut listener init error:', e))
|
||||||
|
screenshotStore.initPinShortcutRegistration().catch(e => console.error('Screenshot pin shortcut registration init error:', e))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,12 +26,16 @@ import {
|
|||||||
import {
|
import {
|
||||||
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
||||||
} from '@/components/ui/pagination'
|
} from '@/components/ui/pagination'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
import {
|
||||||
|
Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle,
|
||||||
|
} from '@/components/ui/empty'
|
||||||
|
|
||||||
const store = useClipboardStore()
|
const store = useClipboardStore()
|
||||||
|
|
||||||
const activeTab = ref('history')
|
const activeTab = ref('history')
|
||||||
const tabsStore = useModuleTabsStore()
|
const tabsStore = useModuleTabsStore()
|
||||||
const tabsListRef = useModuleTabs(activeTab, [
|
const tabsListRef = useModuleTabs('clipboard', activeTab, [
|
||||||
{ value: 'history', label: '历史' },
|
{ value: 'history', label: '历史' },
|
||||||
{ value: 'pinned', label: '固定' },
|
{ value: 'pinned', label: '固定' },
|
||||||
{ value: 'settings', label: '设置' },
|
{ value: 'settings', label: '设置' },
|
||||||
@@ -72,11 +76,21 @@ const gotoPage = async (p: number) => {
|
|||||||
const detailOpen = ref(false)
|
const detailOpen = ref(false)
|
||||||
const detailLoading = ref(false)
|
const detailLoading = ref(false)
|
||||||
const detail = ref<ClipboardItemDetail | null>(null)
|
const detail = ref<ClipboardItemDetail | null>(null)
|
||||||
|
/** 详情加载序号:快速点击多个条目时丢弃过期请求结果,避免旧请求覆盖新详情 */
|
||||||
|
let detailSeq = 0
|
||||||
const openDetail = async (item: ClipboardItem) => {
|
const openDetail = async (item: ClipboardItem) => {
|
||||||
|
// reka-ui Dialog 打开时会把当前活动元素记为 triggerElement,关闭时对其无 preventScroll 地 focus,
|
||||||
|
// 导致历史列表的 ScrollAreaViewport(tabindex=0) 被聚焦并滚回顶部。打开前 blur,避免记录滚动容器。
|
||||||
|
const active = document.activeElement
|
||||||
|
if (active instanceof HTMLElement) {
|
||||||
|
active.blur()
|
||||||
|
}
|
||||||
detailOpen.value = true
|
detailOpen.value = true
|
||||||
detailLoading.value = true
|
detailLoading.value = true
|
||||||
detail.value = null
|
detail.value = null
|
||||||
|
const seq = ++detailSeq
|
||||||
const d = await store.getItem(item.id)
|
const d = await store.getItem(item.id)
|
||||||
|
if (seq !== detailSeq) return // 过期请求丢弃
|
||||||
detail.value = d
|
detail.value = d
|
||||||
detailLoading.value = false
|
detailLoading.value = false
|
||||||
}
|
}
|
||||||
@@ -282,9 +296,17 @@ const historyList = computed(() => store.history)
|
|||||||
const pinnedList = computed(() => store.pinned)
|
const pinnedList = computed(() => store.pinned)
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await store.init()
|
// 首次进入:异步加载并显示骨架屏。再次进入时 store 已缓存历史/固定/设置,
|
||||||
await Promise.all([loadPage(), store.refreshPinned()])
|
// 直接即时渲染缓存数据,后台并行静默刷新,避免每次切换都出现骨架屏/空态闪烁。
|
||||||
|
const isFirst = !store.initialized
|
||||||
|
if (isFirst) store.loading = true
|
||||||
|
try {
|
||||||
|
await Promise.all([store.init(), loadPage(), store.refreshPinned()])
|
||||||
|
store.initialized = true
|
||||||
form.value = { ...store.settings }
|
form.value = { ...store.settings }
|
||||||
|
} finally {
|
||||||
|
store.loading = false
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
@@ -308,7 +330,7 @@ onUnmounted(() => {
|
|||||||
<TabsContent value="history" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
<TabsContent value="history" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||||
<div class="flex items-center gap-2 mb-3 shrink-0">
|
<div class="flex items-center gap-2 mb-3 shrink-0">
|
||||||
<div class="relative flex-1 max-w-sm">
|
<div class="relative flex-1 max-w-sm">
|
||||||
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||||
<Input v-model="searchQuery" placeholder="搜索历史..." class="pl-8" />
|
<Input v-model="searchQuery" placeholder="搜索历史..." class="pl-8" />
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-1">
|
<div class="flex items-center gap-1">
|
||||||
@@ -327,7 +349,7 @@ onUnmounted(() => {
|
|||||||
{{ store.historyTotal }} 条
|
{{ store.historyTotal }} 条
|
||||||
</Badge>
|
</Badge>
|
||||||
<Button variant="outline" size="sm" @click="clearOpen = true" :disabled="!historyList.length">
|
<Button variant="outline" size="sm" @click="clearOpen = true" :disabled="!historyList.length">
|
||||||
<Eraser class="h-4 w-4 mr-1" />清空
|
<Eraser class="size-4 mr-1" />清空
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -368,22 +390,42 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<ScrollArea class="flex-1 min-h-0">
|
<ScrollArea class="flex-1 min-h-0">
|
||||||
<div class="space-y-1.5 pr-2">
|
<div class="space-y-1.5 pr-2">
|
||||||
|
<!-- 加载骨架:数据异步返回前撑起画面,避免误显示"暂无历史" -->
|
||||||
|
<div v-if="store.loading" class="space-y-1.5">
|
||||||
<div
|
<div
|
||||||
v-if="!historyList.length"
|
v-for="n in 8" :key="n"
|
||||||
class="flex flex-col items-center justify-center text-muted-foreground py-12"
|
class="flex items-center gap-3 rounded-lg border p-3"
|
||||||
>
|
>
|
||||||
<ClipboardList class="h-12 w-12 mb-3 opacity-40" />
|
<Skeleton class="size-4 shrink-0" />
|
||||||
<p class="text-sm">暂无历史记录,复制内容后将自动收录</p>
|
<div class="flex-1 space-y-2">
|
||||||
|
<Skeleton class="h-3.5 w-3/4" />
|
||||||
|
<Skeleton class="h-2.5 w-1/4" />
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Empty
|
||||||
|
v-else-if="!historyList.length"
|
||||||
|
class="py-12"
|
||||||
|
>
|
||||||
|
<EmptyHeader>
|
||||||
|
<EmptyMedia variant="icon">
|
||||||
|
<ClipboardList class="size-6" />
|
||||||
|
</EmptyMedia>
|
||||||
|
<EmptyTitle>暂无历史记录</EmptyTitle>
|
||||||
|
</EmptyHeader>
|
||||||
|
<EmptyContent>
|
||||||
|
<EmptyDescription>复制内容后将自动收录,图片与文件也会被记录</EmptyDescription>
|
||||||
|
</EmptyContent>
|
||||||
|
</Empty>
|
||||||
<Card
|
<Card
|
||||||
v-for="item in historyList"
|
v-for="item in historyList"
|
||||||
:key="item.id"
|
:key="item.id"
|
||||||
class="group hover:shadow-md transition-shadow py-0"
|
class="group hover:shadow-md transition-shadow py-0"
|
||||||
>
|
>
|
||||||
<CardContent class="flex items-center gap-3 px-3 py-2">
|
<CardContent class="flex items-center gap-3 px-3 py-2">
|
||||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-muted-foreground shrink-0" />
|
<component :is="kindIcon(item.kind)" class="size-4 text-muted-foreground shrink-0" />
|
||||||
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
||||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
<p class="text-sm break-all line-clamp-1">{{ item.preview }}</p>
|
||||||
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
||||||
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
||||||
<span>{{ formatTime(item.createdAt) }}</span>
|
<span>{{ formatTime(item.createdAt) }}</span>
|
||||||
@@ -391,13 +433,13 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="复制" @click.stop="handleCopy(item)">
|
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
|
||||||
<Copy class="h-3.5 w-3.5" />
|
<Copy class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" :title="item.pinned ? '取消固定' : '固定'" @click.stop="handlePin(item)">
|
<Button variant="ghost" size="icon" class="size-7" :title="item.pinned ? '取消固定' : '固定'" @click.stop="handlePin(item)">
|
||||||
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -410,19 +452,22 @@ onUnmounted(() => {
|
|||||||
<!-- 固定 -->
|
<!-- 固定 -->
|
||||||
<TabsContent value="pinned" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
<TabsContent value="pinned" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||||
<div class="flex-1 min-h-0 overflow-y-auto space-y-1.5 pr-1">
|
<div class="flex-1 min-h-0 overflow-y-auto space-y-1.5 pr-1">
|
||||||
<div
|
<Empty v-if="!pinnedList.length" class="h-full py-8">
|
||||||
v-if="!pinnedList.length"
|
<EmptyHeader>
|
||||||
class="flex flex-col items-center justify-center h-full text-muted-foreground"
|
<EmptyMedia variant="icon">
|
||||||
>
|
<Pin class="size-6" />
|
||||||
<Pin class="h-12 w-12 mb-3 opacity-40" />
|
</EmptyMedia>
|
||||||
<p class="text-sm">暂无固定条目</p>
|
<EmptyTitle>暂无固定条目</EmptyTitle>
|
||||||
<p class="text-xs mt-1">鼠标悬停历史条目,点击图钉按钮即可固定</p>
|
</EmptyHeader>
|
||||||
</div>
|
<EmptyContent>
|
||||||
|
<EmptyDescription>鼠标悬停历史条目,点击图钉按钮即可固定</EmptyDescription>
|
||||||
|
</EmptyContent>
|
||||||
|
</Empty>
|
||||||
<Card v-for="item in pinnedList" :key="item.id" class="group hover:shadow-md transition-shadow py-0">
|
<Card v-for="item in pinnedList" :key="item.id" class="group hover:shadow-md transition-shadow py-0">
|
||||||
<CardContent class="flex items-center gap-3 px-3 py-2">
|
<CardContent class="flex items-center gap-3 px-3 py-2">
|
||||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-primary shrink-0" />
|
<component :is="kindIcon(item.kind)" class="size-4 text-primary shrink-0" />
|
||||||
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
<div class="flex-1 min-w-0 cursor-pointer" @click="openDetail(item)">
|
||||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
<p class="text-sm break-all line-clamp-1">{{ item.preview }}</p>
|
||||||
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
<div class="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground flex-wrap">
|
||||||
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
<Badge variant="outline" :class="['px-1.5 py-0 text-[10px] border', kindBadgeClass(item.kind)]">{{ kindLabel(item.kind) }}</Badge>
|
||||||
<span>{{ formatTime(item.createdAt) }}</span>
|
<span>{{ formatTime(item.createdAt) }}</span>
|
||||||
@@ -430,13 +475,13 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
<div class="flex items-center gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition">
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="复制" @click.stop="handleCopy(item)">
|
<Button variant="ghost" size="icon" class="size-7" title="复制" @click.stop="handleCopy(item)">
|
||||||
<Copy class="h-3.5 w-3.5" />
|
<Copy class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7" title="取消固定" @click.stop="handlePin(item)">
|
<Button variant="ghost" size="icon" class="size-7" title="取消固定" @click.stop="handlePin(item)">
|
||||||
<PinOff class="h-3.5 w-3.5" />
|
<PinOff class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
<Button variant="ghost" size="icon" class="h-7 w-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
<Button variant="ghost" size="icon" class="size-7 hover:text-destructive" title="删除" @click.stop="handleDelete(item)">
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -450,7 +495,7 @@ onUnmounted(() => {
|
|||||||
<div class="max-w-xl space-y-4">
|
<div class="max-w-xl space-y-4">
|
||||||
<div class="flex items-center">
|
<div class="flex items-center">
|
||||||
<h3 class="text-base font-medium flex items-center gap-2">
|
<h3 class="text-base font-medium flex items-center gap-2">
|
||||||
<SettingsIcon class="h-4 w-4" />基本设置
|
<SettingsIcon class="size-4" />基本设置
|
||||||
</h3>
|
</h3>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -519,7 +564,7 @@ onUnmounted(() => {
|
|||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<div>
|
<div>
|
||||||
<Label class="flex items-center gap-2">
|
<Label class="flex items-center gap-2">
|
||||||
<Keyboard class="h-4 w-4" />快捷弹窗快捷键
|
<Keyboard class="size-4" />快捷弹窗快捷键
|
||||||
</Label>
|
</Label>
|
||||||
<p class="text-xs text-muted-foreground mt-1">全局快捷键触发鼠标位置历史弹窗,留空禁用</p>
|
<p class="text-xs text-muted-foreground mt-1">全局快捷键触发鼠标位置历史弹窗,留空禁用</p>
|
||||||
</div>
|
</div>
|
||||||
@@ -563,7 +608,7 @@ onUnmounted(() => {
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
<div class="flex-1 min-h-0 overflow-auto">
|
<div class="flex-1 min-h-0 overflow-auto">
|
||||||
<div v-if="detailLoading" class="flex items-center justify-center py-12">
|
<div v-if="detailLoading" class="flex items-center justify-center py-12">
|
||||||
<Loader2 class="h-6 w-6 animate-spin text-muted-foreground" />
|
<Loader2 class="size-6 animate-spin text-muted-foreground" />
|
||||||
</div>
|
</div>
|
||||||
<template v-else-if="detail">
|
<template v-else-if="detail">
|
||||||
<img
|
<img
|
||||||
@@ -575,7 +620,7 @@ onUnmounted(() => {
|
|||||||
<p v-else-if="detail.kind === 'image'" class="text-sm text-muted-foreground text-center py-8">
|
<p v-else-if="detail.kind === 'image'" class="text-sm text-muted-foreground text-center py-8">
|
||||||
图片预览不可用
|
图片预览不可用
|
||||||
</p>
|
</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">
|
<ul v-else-if="detail.kind === 'files'" class="space-y-1 text-sm">
|
||||||
<li
|
<li
|
||||||
v-for="(p, i) in (parseFiles(detail.content))"
|
v-for="(p, i) in (parseFiles(detail.content))"
|
||||||
|
|||||||
@@ -8,13 +8,18 @@ import { Effect, EffectState } from '@tauri-apps/api/window'
|
|||||||
import { commands } from '@/lib/bindings'
|
import { commands } from '@/lib/bindings'
|
||||||
import {
|
import {
|
||||||
ClipboardList, Pin, PinOff, Trash2, Search, Image as ImageIcon,
|
ClipboardList, Pin, PinOff, Trash2, Search, Image as ImageIcon,
|
||||||
FileText, Files, Loader2,
|
FileText, Files,
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||||
import { Input } from '@/components/ui/input'
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import {
|
||||||
|
Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
|
||||||
|
} from '@/components/ui/select'
|
||||||
import {
|
import {
|
||||||
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
Pagination, PaginationContent, PaginationItem, PaginationEllipsis,
|
||||||
} from '@/components/ui/pagination'
|
} from '@/components/ui/pagination'
|
||||||
|
import { Skeleton } from '@/components/ui/skeleton'
|
||||||
|
|
||||||
// ===== 与 Rust 端对应的数据结构(bindings 提供,camelCase) =====
|
// ===== 与 Rust 端对应的数据结构(bindings 提供,camelCase) =====
|
||||||
// kind 为 bindings 生成的 string,前端按字符串比较即可
|
// kind 为 bindings 生成的 string,前端按字符串比较即可
|
||||||
@@ -26,6 +31,8 @@ const total = ref(0)
|
|||||||
const currentPage = ref(1)
|
const currentPage = ref(1)
|
||||||
const PAGE_SIZE = 50
|
const PAGE_SIZE = 50
|
||||||
const searchQuery = ref('')
|
const searchQuery = ref('')
|
||||||
|
/** 类型筛选:全部/文本/图片/文件 */
|
||||||
|
const kindFilter = ref<'all' | 'text' | 'image' | 'files'>('all')
|
||||||
const selectedIndex = ref(0)
|
const selectedIndex = ref(0)
|
||||||
const loading = ref(false)
|
const loading = ref(false)
|
||||||
const searchInputRef = ref<HTMLInputElement | null>(null)
|
const searchInputRef = ref<HTMLInputElement | null>(null)
|
||||||
@@ -37,21 +44,37 @@ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)
|
|||||||
// ===== 数据加载 =====
|
// ===== 数据加载 =====
|
||||||
/** 加载请求序号:翻页/搜索快速操作时丢弃过期请求结果,避免旧请求覆盖新结果 */
|
/** 加载请求序号:翻页/搜索快速操作时丢弃过期请求结果,避免旧请求覆盖新结果 */
|
||||||
let loadSeq = 0
|
let loadSeq = 0
|
||||||
|
/** 列表视图:history = 全部历史(后端分页);pinned = 仅钉住条目(前端筛选+分页) */
|
||||||
|
const viewMode = ref<'history' | 'pinned'>('history')
|
||||||
async function loadData() {
|
async function loadData() {
|
||||||
const seq = ++loadSeq
|
const seq = ++loadSeq
|
||||||
loading.value = true
|
loading.value = true
|
||||||
try {
|
try {
|
||||||
|
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 {
|
||||||
const q = searchQuery.value.trim()
|
const q = searchQuery.value.trim()
|
||||||
const offset = (currentPage.value - 1) * PAGE_SIZE
|
const offset = (currentPage.value - 1) * PAGE_SIZE
|
||||||
let res: HistoryPage
|
let res: HistoryPage
|
||||||
if (q) {
|
if (q) {
|
||||||
res = await commands.clipboardSearch(q, PAGE_SIZE, offset)
|
res = await commands.clipboardSearch(q, PAGE_SIZE, offset)
|
||||||
} else {
|
} else {
|
||||||
res = await commands.clipboardGetHistory(PAGE_SIZE, offset, 'all')
|
res = await commands.clipboardGetHistory(PAGE_SIZE, offset, kindFilter.value)
|
||||||
}
|
}
|
||||||
if (seq !== loadSeq) return // 过期请求丢弃
|
if (seq !== loadSeq) return // 过期请求丢弃
|
||||||
items.value = res.items
|
items.value = res.items
|
||||||
total.value = res.total
|
total.value = res.total
|
||||||
|
}
|
||||||
selectedIndex.value = 0
|
selectedIndex.value = 0
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (seq !== loadSeq) return
|
if (seq !== loadSeq) return
|
||||||
@@ -66,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) {
|
async function gotoPage(p: number) {
|
||||||
currentPage.value = Math.min(Math.max(1, p), totalPages.value)
|
currentPage.value = Math.min(Math.max(1, p), totalPages.value)
|
||||||
await loadData()
|
await loadData()
|
||||||
}
|
}
|
||||||
|
|
||||||
// 防抖搜索
|
// 防抖搜索/筛选
|
||||||
watch(searchQuery, () => {
|
watch([searchQuery, kindFilter], () => {
|
||||||
currentPage.value = 1
|
currentPage.value = 1
|
||||||
if (searchTimer) clearTimeout(searchTimer)
|
if (searchTimer) clearTimeout(searchTimer)
|
||||||
searchTimer = setTimeout(loadData, 200)
|
searchTimer = setTimeout(loadData, 200)
|
||||||
@@ -106,7 +136,14 @@ async function deleteItem(item: ClipboardItem, ev: Event) {
|
|||||||
ev.stopPropagation()
|
ev.stopPropagation()
|
||||||
try {
|
try {
|
||||||
await commands.clipboardDelete(item.id)
|
await commands.clipboardDelete(item.id)
|
||||||
|
// 本地先移除保持即时反馈,再整页刷新(total/分页数与后端保持一致;
|
||||||
|
// 钉住视图下数据源也需重建)
|
||||||
items.value = items.value.filter((i) => i.id !== item.id)
|
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) {
|
} catch (e) {
|
||||||
console.error('[clipboard-popup] 删除失败:', e)
|
console.error('[clipboard-popup] 删除失败:', e)
|
||||||
}
|
}
|
||||||
@@ -120,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) {
|
function onKeydown(e: KeyboardEvent) {
|
||||||
|
if (selectOpen.value) return
|
||||||
if (e.key === 'ArrowDown') {
|
if (e.key === 'ArrowDown') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
selectedIndex.value = Math.min(selectedIndex.value + 1, items.value.length - 1)
|
selectedIndex.value = Math.min(selectedIndex.value + 1, items.value.length - 1)
|
||||||
cancelHoverTimer()
|
showSelectedPreview()
|
||||||
previewVisible.value = false
|
|
||||||
scrollSelectedIntoView()
|
scrollSelectedIntoView()
|
||||||
} else if (e.key === 'ArrowUp') {
|
} else if (e.key === 'ArrowUp') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
|
selectedIndex.value = Math.max(selectedIndex.value - 1, 0)
|
||||||
cancelHoverTimer()
|
showSelectedPreview()
|
||||||
previewVisible.value = false
|
|
||||||
scrollSelectedIntoView()
|
scrollSelectedIntoView()
|
||||||
} else if (e.key === 'Enter') {
|
} else if (e.key === 'Enter') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -140,6 +267,8 @@ function onKeydown(e: KeyboardEvent) {
|
|||||||
if (item) selectAndPaste(item)
|
if (item) selectAndPaste(item)
|
||||||
} else if (e.key === 'Escape') {
|
} else if (e.key === 'Escape') {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
|
cancelHoverTimer()
|
||||||
|
void hidePreview()
|
||||||
hideWindow()
|
hideWindow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -175,62 +304,6 @@ const formatTime = (ms: number) => {
|
|||||||
|
|
||||||
const hasItems = computed(() => items.value.length > 0)
|
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 读取主应用的主题设置 */
|
/** 从 localStorage 读取主应用的主题设置 */
|
||||||
function readMainTheme(): { theme: string; effect: string } {
|
function readMainTheme(): { theme: string; effect: string } {
|
||||||
@@ -333,15 +406,37 @@ onMounted(async () => {
|
|||||||
await applyTheme()
|
await applyTheme()
|
||||||
searchQuery.value = ''
|
searchQuery.value = ''
|
||||||
currentPage.value = 1
|
currentPage.value = 1
|
||||||
// 重置预览状态,清空缓存避免历史图片占用内存
|
// 隐藏独立预览窗口(弹窗重新显示时清除上次预览)
|
||||||
cancelHoverTimer()
|
cancelHoverTimer()
|
||||||
previewVisible.value = false
|
mouseInPreview.value = false
|
||||||
imageCache.clear()
|
void hidePreview()
|
||||||
await loadData()
|
await loadData()
|
||||||
await nextTick()
|
await nextTick()
|
||||||
searchInputRef.value?.focus()
|
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 loadData()
|
||||||
await nextTick()
|
await nextTick()
|
||||||
@@ -363,10 +458,10 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="popup-root flex flex-col h-screen w-screen" @keydown="onKeydown">
|
<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="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 h-4 w-4 text-muted-foreground" />
|
<Search class="absolute left-2.5 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
|
||||||
<Input
|
<Input
|
||||||
ref="searchInputRef"
|
ref="searchInputRef"
|
||||||
v-model="searchQuery"
|
v-model="searchQuery"
|
||||||
@@ -375,24 +470,38 @@ onUnmounted(() => {
|
|||||||
spellcheck="false"
|
spellcheck="false"
|
||||||
/>
|
/>
|
||||||
</div>
|
</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>
|
</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">
|
<ScrollArea class="popup-list flex-1 min-h-0">
|
||||||
<div class="space-y-1.5 p-2">
|
<div class="space-y-1.5 p-2">
|
||||||
<div v-if="loading && !hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
<div v-if="loading && !hasItems" class="space-y-1.5">
|
||||||
<Loader2 class="h-6 w-6 animate-spin" />
|
<div
|
||||||
|
v-for="n in 8"
|
||||||
|
:key="n"
|
||||||
|
class="flex items-start gap-3 rounded-lg border px-3 py-2"
|
||||||
|
>
|
||||||
|
<Skeleton class="size-4 shrink-0 mt-0.5" />
|
||||||
|
<div class="flex-1 space-y-1.5">
|
||||||
|
<Skeleton class="h-3.5 w-3/4" />
|
||||||
|
<Skeleton class="h-2.5 w-1/4" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-else-if="!hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
<div v-else-if="!hasItems" class="flex flex-col items-center justify-center py-12 text-muted-foreground">
|
||||||
<ClipboardList class="h-10 w-10 mb-2 opacity-40" />
|
<ClipboardList class="size-10 mb-2 opacity-40" />
|
||||||
<p class="text-sm">
|
<p class="text-sm">
|
||||||
{{ searchQuery ? '无匹配结果' : '暂无历史记录' }}
|
{{ searchQuery ? '无匹配结果' : '暂无历史记录' }}
|
||||||
</p>
|
</p>
|
||||||
@@ -406,19 +515,22 @@ onUnmounted(() => {
|
|||||||
@mouseenter="onItemHover(idx, item)"
|
@mouseenter="onItemHover(idx, item)"
|
||||||
@mouseleave="onItemLeave"
|
@mouseleave="onItemLeave"
|
||||||
>
|
>
|
||||||
<component :is="kindIcon(item.kind)" class="h-4 w-4 text-muted-foreground shrink-0 mt-0.5" />
|
<component :is="kindIcon(item.kind)" class="size-4 text-muted-foreground shrink-0 mt-0.5" />
|
||||||
<div class="flex-1 min-w-0">
|
<div class="flex-1 min-w-0">
|
||||||
<p class="text-sm break-all line-clamp-1" :title="item.preview">{{ item.preview }}</p>
|
<p
|
||||||
|
class="text-sm break-all line-clamp-1"
|
||||||
|
: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">
|
<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 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>
|
<span>{{ formatTime(item.createdAt) }}</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="popup-item-actions shrink-0">
|
<div class="popup-item-actions shrink-0">
|
||||||
<button class="popup-action-btn h-7 w-7" title="固定" @click="togglePin(item, $event)">
|
<button class="popup-action-btn size-7" :title="item.pinned ? '取消固定' : '固定'" @click="togglePin(item, $event)">
|
||||||
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
<component :is="item.pinned ? PinOff : Pin" class="h-3.5 w-3.5" />
|
||||||
</button>
|
</button>
|
||||||
<button class="popup-action-btn h-7 w-7 hover:text-destructive" title="删除" @click="deleteItem(item, $event)">
|
<button class="popup-action-btn size-7 hover:text-destructive" title="删除" @click="deleteItem(item, $event)">
|
||||||
<Trash2 class="h-3.5 w-3.5" />
|
<Trash2 class="h-3.5 w-3.5" />
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -426,8 +538,10 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
|
|
||||||
<!-- 分页(与剪切板历史统一样式) -->
|
<!-- 底部:总数 + 分页 + 视图切换(grid 两侧 1fr 等宽,分页严格居中) -->
|
||||||
<div v-if="totalPages > 1" class="flex items-center justify-center gap-1 px-2 py-1 border-t border-border">
|
<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
|
<Pagination
|
||||||
v-slot="{ page }"
|
v-slot="{ page }"
|
||||||
:page="currentPage"
|
:page="currentPage"
|
||||||
@@ -453,11 +567,27 @@ onUnmounted(() => {
|
|||||||
</PaginationContent>
|
</PaginationContent>
|
||||||
</Pagination>
|
</Pagination>
|
||||||
</div>
|
</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">
|
<div class="popup-footer shrink-0">
|
||||||
<span><kbd>↑</kbd><kbd>↓</kbd> 导航</span>
|
<span><kbd>↑</kbd><kbd>↓</kbd> 导航</span>
|
||||||
<span><kbd>Enter</kbd> 粘贴</span>
|
<span><kbd>Enter</kbd>/<kbd>左键</kbd> 粘贴</span>
|
||||||
<span><kbd>Esc</kbd> 关闭</span>
|
<span><kbd>Esc</kbd> 关闭</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -577,39 +707,6 @@ onUnmounted(() => {
|
|||||||
color: var(--muted-foreground);
|
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 {
|
.popup-footer kbd {
|
||||||
background: var(--muted);
|
background: var(--muted);
|
||||||
color: var(--foreground);
|
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>
|
||||||
@@ -5,7 +5,44 @@ const searchItems: SearchIndexItem[] = [
|
|||||||
{
|
{
|
||||||
title: '剪贴板历史',
|
title: '剪贴板历史',
|
||||||
description: '查看和管理剪贴板记录',
|
description: '查看和管理剪贴板记录',
|
||||||
keywords: ['剪贴板', '复制', '粘贴', 'clipboard', 'copy', 'paste']
|
keywords: ['剪贴板', '复制', '粘贴', 'clipboard', 'copy', 'paste'],
|
||||||
|
tab: 'history'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '固定记录',
|
||||||
|
description: '查看固定的剪贴板条目',
|
||||||
|
keywords: ['固定', '收藏', 'pin', '置顶'],
|
||||||
|
tab: 'pinned'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '剪贴板设置',
|
||||||
|
description: '历史数量、图片收录与快捷弹窗快捷键',
|
||||||
|
keywords: ['设置', 'setting', '选项', '配置'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '快捷弹窗快捷键',
|
||||||
|
description: '配置全局快捷键唤起剪贴板弹窗',
|
||||||
|
keywords: ['快捷键', '热键', 'shortcut', 'hotkey', '弹窗', 'popup'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '最大历史条数',
|
||||||
|
description: '设置剪贴板历史记录数量上限',
|
||||||
|
keywords: ['历史', '数量', '上限', '条数', 'max', 'limit'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '图片大小上限',
|
||||||
|
description: '设置收录图片的大小上限 (KB)',
|
||||||
|
keywords: ['图片', '大小', '上限', 'image', 'kb', '体积'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '记录图片',
|
||||||
|
description: '是否收录复制/截图的图片',
|
||||||
|
keywords: ['图片', '截图', '收录', 'image', 'capture'],
|
||||||
|
tab: 'settings'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,495 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||||
|
import { getCurrentWindow, Effect, EffectState } from '@tauri-apps/api/window'
|
||||||
|
import { LogicalSize } from '@tauri-apps/api/dpi'
|
||||||
|
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
|
import { Pause, Play, X, Minus, FolderOpen, AlertCircle, Loader2, XCircle } from '@lucide/vue'
|
||||||
|
import { commands, type DownloadTask, type Segment, type TaskStatus } from '@/lib/bindings'
|
||||||
|
import { STORAGE_KEYS } from '@/lib/constants'
|
||||||
|
import { createLogger } from '@/lib/logger'
|
||||||
|
|
||||||
|
const logger = createLogger('download-window')
|
||||||
|
|
||||||
|
// ===== 从 URL hash 解析任务 id:#download-window?task=<id> =====
|
||||||
|
const hash = window.location.hash
|
||||||
|
const taskId = new URLSearchParams(hash.split('?')[1] ?? '').get('task') ?? ''
|
||||||
|
if (!taskId) logger.warn('下载窗口缺少 task 参数')
|
||||||
|
|
||||||
|
const win = getCurrentWindow()
|
||||||
|
const task = ref<DownloadTask | null>(null)
|
||||||
|
const loading = ref(true)
|
||||||
|
const actionError = ref('')
|
||||||
|
|
||||||
|
// ===== 进度事件载荷(与 Rust 端 ProgressPayload 对应) =====
|
||||||
|
interface ProgressPayload {
|
||||||
|
id: string
|
||||||
|
completedSize: number
|
||||||
|
totalSize: number
|
||||||
|
speed: number
|
||||||
|
status: TaskStatus
|
||||||
|
segments: number[]
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadTask = async () => {
|
||||||
|
try {
|
||||||
|
const all = await commands.downloaderGetTasks()
|
||||||
|
task.value = all.find(t => t.id === taskId) ?? null
|
||||||
|
} catch (e) {
|
||||||
|
logger.error('获取任务失败: ' + e)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
// 任务已不存在(被模块/扩展删除):本窗口无存在意义,直接关闭
|
||||||
|
if (!task.value) {
|
||||||
|
await win.close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 文件名显示到窗口标题(无边框窗口下仍影响任务栏悬浮标题)
|
||||||
|
try { await win.setTitle(task.value.filename) } catch { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 状态派生 =====
|
||||||
|
const totalSize = computed(() => task.value?.totalSize ?? 0)
|
||||||
|
const completedSize = computed(() => task.value?.completedSize ?? 0)
|
||||||
|
const speed = computed(() => task.value?.speed ?? 0)
|
||||||
|
const status = computed<TaskStatus>(() => task.value?.status ?? 'active')
|
||||||
|
const progress = computed(() => {
|
||||||
|
if (!totalSize.value || totalSize.value === 0) return 0
|
||||||
|
return Math.min(100, Math.round((completedSize.value / totalSize.value) * 100))
|
||||||
|
})
|
||||||
|
const segments = computed(() => task.value?.segments ?? [])
|
||||||
|
const showSegments = computed(() => segments.value.length > 1)
|
||||||
|
|
||||||
|
const statusText = computed(() => {
|
||||||
|
switch (status.value) {
|
||||||
|
case 'active': return '下载中'
|
||||||
|
case 'queued': return '等待中'
|
||||||
|
case 'paused': return '已暂停'
|
||||||
|
case 'complete': return '已完成'
|
||||||
|
case 'error': return '出错'
|
||||||
|
case 'cancelled': return '已取消'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
const statusTone = computed(() => {
|
||||||
|
if (status.value === 'complete') return 'success'
|
||||||
|
if (status.value === 'error') return 'destructive'
|
||||||
|
if (status.value === 'paused' || status.value === 'cancelled') return 'muted'
|
||||||
|
return 'active'
|
||||||
|
})
|
||||||
|
|
||||||
|
// ===== 格式化 =====
|
||||||
|
const formatByte = (b: number) => {
|
||||||
|
if (!b || isNaN(b)) return '0 B'
|
||||||
|
if (b < 1024) return `${b} B`
|
||||||
|
if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`
|
||||||
|
if (b < 1024 * 1024 * 1024) return `${(b / 1024 / 1024).toFixed(2)} MB`
|
||||||
|
return `${(b / 1024 / 1024 / 1024).toFixed(2)} GB`
|
||||||
|
}
|
||||||
|
const formatTotal = (b: number) => (!b || b === 0 ? '未知' : formatByte(b))
|
||||||
|
|
||||||
|
// ===== 分段进度(横向分段条:每段宽度按其长度占整个文件的比例) =====
|
||||||
|
const segLen = (s: Segment) => s.end - s.start + 1
|
||||||
|
const totalSpan = computed(() => segments.value.reduce((a, s) => a + segLen(s), 0))
|
||||||
|
const segPercent = (s: Segment) => {
|
||||||
|
if (segLen(s) <= 0) return 0
|
||||||
|
return Math.min(100, Math.round((s.completed / segLen(s)) * 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 操作 =====
|
||||||
|
const errorTip = (e: unknown) => {
|
||||||
|
actionError.value = typeof e === 'string' ? e : '操作失败'
|
||||||
|
}
|
||||||
|
const doPause = async () => {
|
||||||
|
try { await commands.downloaderPauseTask(taskId) } catch (e) { return errorTip(e) }
|
||||||
|
await loadTask().catch(() => {})
|
||||||
|
}
|
||||||
|
const doResume = async () => {
|
||||||
|
try { await commands.downloaderResumeTask(taskId) } catch (e) { return errorTip(e) }
|
||||||
|
await loadTask().catch(() => {})
|
||||||
|
}
|
||||||
|
// 取消:二次确认(3 秒内再点一次才真正删除)
|
||||||
|
const armedCancel = ref(false)
|
||||||
|
let cancelArmTimer = 0
|
||||||
|
const doCancel = async () => {
|
||||||
|
if (!armedCancel.value) {
|
||||||
|
armedCancel.value = true
|
||||||
|
window.clearTimeout(cancelArmTimer)
|
||||||
|
cancelArmTimer = window.setTimeout(() => (armedCancel.value = false), 3000)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
window.clearTimeout(cancelArmTimer)
|
||||||
|
armedCancel.value = false
|
||||||
|
try { await commands.downloaderCancelTask(taskId) } catch (e) { return errorTip(e) }
|
||||||
|
await win.close()
|
||||||
|
}
|
||||||
|
const doOpenFolder = async () => {
|
||||||
|
if (!task.value?.dir) return
|
||||||
|
try { await commands.downloaderOpenDir(task.value.dir) } catch (e) { errorTip(e) }
|
||||||
|
}
|
||||||
|
const doMinimize = () => win.minimize()
|
||||||
|
const doClose = () => win.close()
|
||||||
|
|
||||||
|
// 标题文字按下拖动窗口:data-tauri-drag-region 对文字子元素可能不生效
|
||||||
|
// (文字层拦截 pointer 事件),改用显式 startDragging(仅左键)
|
||||||
|
const startDrag = () => {
|
||||||
|
win.startDragging().catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只读提示:错误等瞬态信息 3 秒后清除
|
||||||
|
const clearErrorSoon = () => {
|
||||||
|
if (!actionError.value) return
|
||||||
|
window.setTimeout(() => { if (!actionError.value) return; actionError.value = '' }, 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 主题与窗口效果(与主应用同步:主题 + mica/acrylic 效果) =====
|
||||||
|
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' }
|
||||||
|
}
|
||||||
|
/** 判断当前是否应为深色主题(弹窗独立窗口,system 模式用 matchMedia 可靠) */
|
||||||
|
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()
|
||||||
|
|
||||||
|
// 1. 设置窗口原生主题(system → null 跟随系统)
|
||||||
|
try {
|
||||||
|
if (theme === 'system') await win.setTheme(null)
|
||||||
|
else await win.setTheme(theme as 'dark' | 'light')
|
||||||
|
} catch { /* 忽略 */ }
|
||||||
|
|
||||||
|
// 2. 用 matchMedia 判断深浅(不依赖主应用状态)
|
||||||
|
const isDark = resolveIsDark(theme)
|
||||||
|
|
||||||
|
// 3. 设置 DOM class(effect 类供 style.css 变量联动)
|
||||||
|
root.classList.remove('dark', 'effect-mica', 'effect-acrylic', 'effect-normal')
|
||||||
|
root.classList.add(`effect-${effect}`)
|
||||||
|
if (isDark) root.classList.add('dark')
|
||||||
|
|
||||||
|
// 4. 设置窗口效果:mica/acrylic 下卡片透明,普通模式用不透明背景
|
||||||
|
try {
|
||||||
|
await win.clearEffects()
|
||||||
|
if (effect === 'mica') {
|
||||||
|
await win.setEffects({
|
||||||
|
effects: [Effect.Mica],
|
||||||
|
state: EffectState.FollowsWindowActiveState,
|
||||||
|
color: isDark ? [30, 41, 59, 0] : [248, 250, 252, 0],
|
||||||
|
})
|
||||||
|
await win.setBackgroundColor('#00000000')
|
||||||
|
root.style.setProperty('--popup-bg', 'transparent')
|
||||||
|
} else if (effect === 'acrylic') {
|
||||||
|
await win.setEffects({
|
||||||
|
effects: [Effect.Acrylic],
|
||||||
|
state: EffectState.FollowsWindowActiveState,
|
||||||
|
color: isDark ? [30, 41, 59, 0] : [248, 250, 252, 0],
|
||||||
|
})
|
||||||
|
await win.setBackgroundColor('#00000000')
|
||||||
|
root.style.setProperty('--popup-bg', 'transparent')
|
||||||
|
} else {
|
||||||
|
await win.setBackgroundColor(isDark ? '#0f172a' : '#ffffff')
|
||||||
|
root.style.setProperty('--popup-bg', isDark ? '#0f172a' : '#ffffff')
|
||||||
|
}
|
||||||
|
} catch { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 自动贴合内容高度:消除卡片下方留白 =====
|
||||||
|
const rootRef = ref<HTMLElement | null>(null)
|
||||||
|
let lastHeight = 0
|
||||||
|
let autoResizeObserver: ResizeObserver | null = null
|
||||||
|
// 仅兜底防窗口过小;正常状态下窗口严格贴合内容高度(既不高出导致底部露白,
|
||||||
|
// 也不低于 titlebar/loading 所需),由 getBoundingClientRect().height 决定
|
||||||
|
const MIN_H = 52
|
||||||
|
const WINDOW_W = 420
|
||||||
|
const applyAutoHeight = async () => {
|
||||||
|
if (!rootRef.value) return
|
||||||
|
try {
|
||||||
|
if (await win.isMinimized()) return
|
||||||
|
} catch { /* 忽略 */ }
|
||||||
|
const h = Math.max(MIN_H, Math.ceil(rootRef.value.getBoundingClientRect().height))
|
||||||
|
if (Math.abs(h - lastHeight) > 4) {
|
||||||
|
lastHeight = h
|
||||||
|
win.setSize(new LogicalSize(WINDOW_W, h)).catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 事件监听 =====
|
||||||
|
let progressUnlisten: UnlistenFn | null = null
|
||||||
|
let completeUnlisten: UnlistenFn | null = null
|
||||||
|
let onThemeChange: (() => void) | null = null
|
||||||
|
|
||||||
|
// 完成时置前提醒:恢复最小化 + 显示 + 聚焦(窗口从任务栏/后台唤出到最前)。
|
||||||
|
// 用 Rust 端 downloaderFocusWindow 强制置前,绕过 Windows 前台锁定(纯 setFocus 会被忽略)
|
||||||
|
const handleComplete = async () => {
|
||||||
|
await loadTask().catch(() => {})
|
||||||
|
if (status.value === 'complete') {
|
||||||
|
try { await commands.downloaderFocusWindow(win.label) } catch { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await applyTheme()
|
||||||
|
await loadTask()
|
||||||
|
|
||||||
|
progressUnlisten = await listen<ProgressPayload>('download-progress', (e) => {
|
||||||
|
if (e.payload.id !== taskId || !task.value) return
|
||||||
|
const t = task.value
|
||||||
|
t.completedSize = e.payload.completedSize
|
||||||
|
t.totalSize = e.payload.totalSize
|
||||||
|
t.speed = e.payload.speed
|
||||||
|
t.status = e.payload.status
|
||||||
|
if (Array.isArray(e.payload.segments) && t.segments) {
|
||||||
|
t.segments.forEach((seg, i) => {
|
||||||
|
const v = e.payload.segments[i]
|
||||||
|
if (v !== undefined) seg.completed = v
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
completeUnlisten = await listen<{ id: string }>('download-complete', (e) => {
|
||||||
|
if (e.payload?.id !== taskId) return
|
||||||
|
handleComplete()
|
||||||
|
})
|
||||||
|
|
||||||
|
const mq = window.matchMedia('(prefers-color-scheme: dark)')
|
||||||
|
onThemeChange = () => applyTheme()
|
||||||
|
mq.addEventListener('change', onThemeChange)
|
||||||
|
|
||||||
|
// 内容变化时自动贴合窗口高度(始终保留,覆盖后续加载→数据等状态下的高度变化)
|
||||||
|
lastHeight = 0
|
||||||
|
autoResizeObserver = new ResizeObserver(applyAutoHeight)
|
||||||
|
if (rootRef.value) autoResizeObserver.observe(rootRef.value)
|
||||||
|
|
||||||
|
// 首次显示:窗口由 App.vue 隐藏创建,此处先在隐藏态贴合到内容高度,
|
||||||
|
// 再延迟一小段等待 setSize 生效后一次性 show + 置前,
|
||||||
|
// 避免"先以初始高度显示、再 resize"造成的尺寸跳变闪烁。
|
||||||
|
void applyAutoHeight()
|
||||||
|
window.setTimeout(async () => {
|
||||||
|
// 隐藏态下多贴合一次,确保尺寸已对内容就位
|
||||||
|
await applyAutoHeight()
|
||||||
|
try { await win.show() } catch { /* 忽略 */ }
|
||||||
|
try { await win.unminimize() } catch { /* 忽略 */ }
|
||||||
|
void commands.downloaderFocusWindow(win.label).catch(() => {})
|
||||||
|
}, 120)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
progressUnlisten?.()
|
||||||
|
completeUnlisten?.()
|
||||||
|
autoResizeObserver?.disconnect()
|
||||||
|
if (onThemeChange) window.matchMedia('(prefers-color-scheme: dark)').removeEventListener('change', onThemeChange)
|
||||||
|
window.clearTimeout(cancelArmTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div ref="rootRef" class="dlw-root">
|
||||||
|
<!-- 顶部标题栏(可拖动):文件名作为标题,右侧放操作按钮 + 最小化 + 关闭 -->
|
||||||
|
<div class="dlw-titlebar" data-tauri-drag-region>
|
||||||
|
<div class="dlw-title-left" data-tauri-drag-region>
|
||||||
|
<Loader2 v-if="status === 'active'" class="size-3 shrink-0 animate-spin text-primary" />
|
||||||
|
<XCircle v-else-if="status === 'error'" class="size-3 shrink-0 text-red-500" />
|
||||||
|
<Pause v-else class="size-3 shrink-0 text-muted-foreground" />
|
||||||
|
<span v-if="loading" class="text-xs font-medium text-muted-foreground">下载</span>
|
||||||
|
<span v-else-if="task" class="dlw-title-name" :title="task.filename"
|
||||||
|
@mousedown.left.prevent="startDrag">{{ task.filename }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="dlw-title-right">
|
||||||
|
<button v-if="status === 'active'" class="dlw-btn" @click="doPause">
|
||||||
|
<Pause class="size-3" /> 暂停
|
||||||
|
</button>
|
||||||
|
<button v-else-if="status === 'paused'" class="dlw-btn" @click="doResume">
|
||||||
|
<Play class="size-3" /> 继续
|
||||||
|
</button>
|
||||||
|
<button v-if="status !== 'complete' && status !== 'error'" class="dlw-btn dlw-btn-danger" @click="doCancel">
|
||||||
|
{{ armedCancel ? '再点一次取消' : '取消' }}
|
||||||
|
</button>
|
||||||
|
<button v-if="status === 'complete'" class="dlw-btn dlw-btn-primary" @click="doOpenFolder">
|
||||||
|
<FolderOpen class="size-3" /> 打开文件夹
|
||||||
|
</button>
|
||||||
|
<button v-else-if="status === 'error' && task?.dir" class="dlw-btn" @click="doOpenFolder">
|
||||||
|
<FolderOpen class="size-3" /> 打开目录
|
||||||
|
</button>
|
||||||
|
<button class="dlw-icon-btn" title="最小化" @click="doMinimize">
|
||||||
|
<Minus class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
<button class="dlw-icon-btn" title="关闭(下载在后台继续)" @click="doClose">
|
||||||
|
<X class="size-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 主体:状态 + 总进度 + 分段条 -->
|
||||||
|
<div class="dlw-body">
|
||||||
|
<div v-if="loading" class="dlw-loading">
|
||||||
|
<Loader2 class="size-5 animate-spin text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else-if="task">
|
||||||
|
<div class="flex items-center justify-between gap-2 text-xs">
|
||||||
|
<span class="dlw-status-badge" :class="`tone-${statusTone}`">{{ statusText }}</span>
|
||||||
|
<span class="truncate text-muted-foreground">
|
||||||
|
{{ formatByte(completedSize) }} / {{ formatTotal(totalSize) }} · {{ progress }}%
|
||||||
|
<template v-if="status === 'active' && speed > 0"> · {{ formatByte(speed) }}/s</template>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="dlw-bar mt-1.5">
|
||||||
|
<div class="dlw-bar-fill" :style="{ width: progress + '%' }" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 分段进度:横向分段条 -->
|
||||||
|
<div v-if="showSegments" class="mt-2">
|
||||||
|
<span class="text-[10px] text-muted-foreground">分段 ({{ segments.length }} 线程)</span>
|
||||||
|
<div class="dlw-seg-strip mt-1">
|
||||||
|
<div
|
||||||
|
v-for="(seg, i) in segments"
|
||||||
|
:key="i"
|
||||||
|
class="dlw-seg"
|
||||||
|
:style="{ width: ((segLen(seg) / totalSpan) * 100).toFixed(2) + '%' }"
|
||||||
|
:title="`#${i + 1} ${segPercent(seg)}%`"
|
||||||
|
>
|
||||||
|
<div class="dlw-seg-fill" :style="{ width: segPercent(seg) + '%' }" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="actionError" class="mt-1.5 truncate text-right text-[10px] text-red-500" @click="clearErrorSoon">
|
||||||
|
{{ actionError }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<div v-else class="dlw-loading">
|
||||||
|
<span class="flex items-center text-xs text-muted-foreground">
|
||||||
|
<AlertCircle class="size-4 mr-1.5" /> 任务已不存在
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.dlw-root {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
padding: 4px 6px 6px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
/* 标题栏 */
|
||||||
|
.dlw-titlebar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
height: 34px;
|
||||||
|
padding: 0 2px 0 8px;
|
||||||
|
gap: 6px;
|
||||||
|
user-select: none;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.dlw-title-left {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.dlw-title-name {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.3;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.dlw-title-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
/* 图标按钮(最小化/关闭) */
|
||||||
|
.dlw-icon-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: var(--muted-foreground);
|
||||||
|
}
|
||||||
|
.dlw-icon-btn:hover { background: var(--accent); color: var(--accent-foreground); }
|
||||||
|
|
||||||
|
/* 主体卡片:背景色由 --popup-bg 控制(mica/acrylic 下透明,普通模式不透明)。
|
||||||
|
flex:1 撑满 titlebar 下方的剩余高度,避免内容(尤其无分段时)比窗口矮导致底部露出
|
||||||
|
白色/透明的窗口背景区空白。 */
|
||||||
|
.dlw-body {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
flex: 1 1 auto;
|
||||||
|
min-height: 0;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 9px;
|
||||||
|
background: var(--popup-bg, transparent);
|
||||||
|
padding: 9px 11px 9px;
|
||||||
|
box-shadow: 0 8px 30px rgb(0 0 0 / 0.18);
|
||||||
|
}
|
||||||
|
/* 加载/任务缺失等仅有一行的场景,内容垂直居中于撑满的卡片内 */
|
||||||
|
.dlw-body > .dlw-loading { flex: 1 1 auto; margin: auto; }
|
||||||
|
.dlw-loading {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 56px;
|
||||||
|
}
|
||||||
|
.dlw-status-badge {
|
||||||
|
flex-shrink: 0;
|
||||||
|
font-size: 10px;
|
||||||
|
line-height: 1.6;
|
||||||
|
padding: 0 8px;
|
||||||
|
border-radius: 999px;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.dlw-status-badge.tone-active { background: var(--primary); color: var(--primary-foreground); }
|
||||||
|
.dlw-status-badge.tone-success { background: #10b981; color: #fff; }
|
||||||
|
.dlw-status-badge.tone-destructive { background: #ef4444; color: #fff; }
|
||||||
|
.dlw-status-badge.tone-muted { background: var(--muted); color: var(--muted-foreground); }
|
||||||
|
|
||||||
|
.dlw-bar { height: 7px; border-radius: 999px; background: var(--muted); overflow: hidden; }
|
||||||
|
.dlw-bar-fill { height: 100%; border-radius: 999px; background: var(--primary); transition: width 0.2s linear; }
|
||||||
|
|
||||||
|
.dlw-seg-strip { display: flex; gap: 2px; height: 7px; }
|
||||||
|
.dlw-seg { height: 100%; border-radius: 3px; background: var(--muted); overflow: hidden; }
|
||||||
|
.dlw-seg-fill { height: 100%; background: var(--primary); opacity: 0.75; transition: width 0.2s linear; }
|
||||||
|
|
||||||
|
/* 操作按钮(紧凑) */
|
||||||
|
.dlw-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
height: 24px;
|
||||||
|
padding: 0 8px;
|
||||||
|
font-size: 11px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
background: transparent;
|
||||||
|
color: var(--foreground);
|
||||||
|
cursor: pointer;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.dlw-btn:hover { background: var(--accent); color: var(--accent-foreground); }
|
||||||
|
.dlw-btn-danger { color: #ef4444; }
|
||||||
|
.dlw-btn-danger:hover { background: rgb(239 68 68 / 0.12); color: #dc2626; }
|
||||||
|
.dlw-btn-primary { background: var(--primary); color: var(--primary-foreground); border-color: transparent; }
|
||||||
|
/* hover 时显式保持前景色,避免被上面的 .dlw-btn:hover 覆盖成深色导致黑字黑底不可见 */
|
||||||
|
.dlw-btn-primary:hover { background: var(--primary); color: var(--primary-foreground); filter: brightness(1.05); }
|
||||||
|
</style>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -5,22 +5,44 @@ const searchItems: SearchIndexItem[] = [
|
|||||||
{
|
{
|
||||||
title: '下载任务',
|
title: '下载任务',
|
||||||
description: '查看与管理下载任务',
|
description: '查看与管理下载任务',
|
||||||
keywords: ['下载', 'download', '任务', 'task']
|
keywords: ['下载', 'download', '任务', 'task'],
|
||||||
|
tab: 'tasks'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '添加下载',
|
title: '添加下载',
|
||||||
description: '添加 HTTP/HTTPS 直链下载',
|
description: '添加 HTTP/HTTPS 直链下载',
|
||||||
keywords: ['添加', '链接', 'url', 'add', '新建']
|
keywords: ['添加', '链接', 'url', 'add', '新建'],
|
||||||
|
tab: 'tasks'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '下载设置',
|
title: '下载设置',
|
||||||
description: '配置下载目录、并发数与速度限制',
|
description: '配置下载目录、并发数与速度限制',
|
||||||
keywords: ['设置', 'setting', '速度', '目录', '并发']
|
keywords: ['设置', 'setting', '速度', '目录', '并发'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '下载目录',
|
||||||
|
description: '设置任务默认保存目录',
|
||||||
|
keywords: ['目录', '保存', '路径', 'dir', 'folder', '下载位置'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '并发下载数',
|
||||||
|
description: '设置同时下载的任务数量上限',
|
||||||
|
keywords: ['并发', '数量', 'concurrent', '线程'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '速度限制',
|
||||||
|
description: '设置全局下载/上传限速',
|
||||||
|
keywords: ['限速', '速度', '速率', 'rate', 'limit', '带宽'],
|
||||||
|
tab: 'settings'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '浏览器扩展',
|
title: '浏览器扩展',
|
||||||
description: '安装 Thing Extension 接管浏览器下载',
|
description: '安装 Thing Extension 接管浏览器下载',
|
||||||
keywords: ['扩展', 'extension', '浏览器', 'chrome', 'edge']
|
keywords: ['扩展', 'extension', '浏览器', 'chrome', 'edge'],
|
||||||
|
tab: 'extension'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ import {
|
|||||||
ShieldCheck, ShieldOff, Zap, Thermometer, Clock, ChevronDown,
|
ShieldCheck, ShieldOff, Zap, Thermometer, Clock, ChevronDown,
|
||||||
ArrowDown, ArrowUp, Wifi, FolderOpen, Copy, ListChecks,
|
ArrowDown, ArrowUp, Wifi, FolderOpen, Copy, ListChecks,
|
||||||
Monitor as MonitorIcon, GripVertical, SlidersHorizontal,
|
Monitor as MonitorIcon, GripVertical, SlidersHorizontal,
|
||||||
Eye, EyeOff, MousePointerClick,
|
Eye, EyeOff, MousePointerClick, Plus, PencilLine,
|
||||||
|
CircuitBoard, BatteryFull, Gamepad2,
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
|
import type { LucideIcon } from '@lucide/vue'
|
||||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import { VueDraggable } from 'vue-draggable-plus'
|
import { VueDraggable } from 'vue-draggable-plus'
|
||||||
@@ -23,8 +25,10 @@ import {
|
|||||||
type AlertConfig,
|
type AlertConfig,
|
||||||
DEFAULT_COLOR_THEME,
|
DEFAULT_COLOR_THEME,
|
||||||
} from '@/stores/monitorStore'
|
} from '@/stores/monitorStore'
|
||||||
|
import { STORAGE_KEYS } from '@/lib/constants'
|
||||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
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 { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
@@ -45,7 +49,7 @@ const store = useMonitorStore()
|
|||||||
|
|
||||||
// ===== Tab 配置(注册到 TitleBar 浮动切换器) =====
|
// ===== Tab 配置(注册到 TitleBar 浮动切换器) =====
|
||||||
const activeTab = ref('overview')
|
const activeTab = ref('overview')
|
||||||
const tabsListRef = useModuleTabs(activeTab, [
|
const tabsListRef = useModuleTabs('monitor', activeTab, [
|
||||||
{ value: 'overview', label: '概览' },
|
{ value: 'overview', label: '概览' },
|
||||||
{ value: 'details', label: '详细' },
|
{ value: 'details', label: '详细' },
|
||||||
{ value: 'osd', label: 'OSD 显示' },
|
{ value: 'osd', label: 'OSD 显示' },
|
||||||
@@ -193,6 +197,183 @@ const storageDrives = computed<StorageDrive[]>(() => {
|
|||||||
const downSpeed = computed(() => fmtSpeed(store.networkSpeed?.downloadBps ?? null))
|
const downSpeed = computed(() => fmtSpeed(store.networkSpeed?.downloadBps ?? null))
|
||||||
const upSpeed = computed(() => fmtSpeed(store.networkSpeed?.uploadBps ?? 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 }> = {
|
const stateMeta: Record<ConnectionState, { text: string; class: string }> = {
|
||||||
idle: { text: '未启动', class: 'bg-muted text-muted-foreground' },
|
idle: { text: '未启动', class: 'bg-muted text-muted-foreground' },
|
||||||
@@ -928,8 +1109,29 @@ function removeOsdItem(key: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 开启 OSD 但监控内核未运行时的提示对话框开关 */
|
||||||
|
const osdNeedsKernelOpen = ref(false)
|
||||||
|
|
||||||
|
/** 从对话框启动内核:先直接开启 OSD(立即显示),内核在后台自行启动 */
|
||||||
|
async function startKernelForOsd() {
|
||||||
|
osdNeedsKernelOpen.value = false
|
||||||
|
// 直接开启 OSD(绕过内联内核检查),store 的 overlayEnabled watch 立即创建/显示悬浮窗
|
||||||
|
osdConfig.value.overlayEnabled = true
|
||||||
|
saveOsdConfigDebounced(osdConfig.value)
|
||||||
|
// 后台启动内核(不 await,不阻塞 OSD 显示;内核就绪后 OSD 自动填充数据)
|
||||||
|
store.start().catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
/** OSD 配置项变更时自动保存(防抖:滑块拖动期间不逐帧写盘) */
|
/** OSD 配置项变更时自动保存(防抖:滑块拖动期间不逐帧写盘) */
|
||||||
function updateOsdConfig(field: keyof OsdConfig, value: unknown) {
|
function updateOsdConfig(field: keyof OsdConfig, value: unknown) {
|
||||||
|
// 开启 OSD 时,若监控内核未运行,弹出提示并取消本次开启(OSD 依赖内核提供数据)
|
||||||
|
if (field === 'overlayEnabled' && value === true) {
|
||||||
|
const kernelRunning = store.status?.running === true
|
||||||
|
if (!kernelRunning) {
|
||||||
|
osdNeedsKernelOpen.value = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
;(osdConfig.value as unknown as Record<string, unknown>)[field] = value
|
;(osdConfig.value as unknown as Record<string, unknown>)[field] = value
|
||||||
saveOsdConfigDebounced(osdConfig.value)
|
saveOsdConfigDebounced(osdConfig.value)
|
||||||
}
|
}
|
||||||
@@ -1102,8 +1304,9 @@ onUnmounted(() => {
|
|||||||
// 不 dispose store:SSE 订阅保持,确保切走监控模块后 OSD 仍有数据
|
// 不 dispose store:SSE 订阅保持,确保切走监控模块后 OSD 仍有数据
|
||||||
// store.subscribe() 内部有守卫(if unlistenFns.length return),重复 init 不会重复订阅
|
// store.subscribe() 内部有守卫(if unlistenFns.length return),重复 init 不会重复订阅
|
||||||
// 不关闭 OSD 窗口:切走监控模块时保持 OSD 显示,由模块禁用或应用退出时统一清理
|
// 不关闭 OSD 窗口:切走监控模块时保持 OSD 显示,由模块禁用或应用退出时统一清理
|
||||||
// 释放 OSD 事件监听(App 启动或模块重新挂载时会重新注册)
|
// 不调用 store.disposeOsd():tray:toggle-osd 监听与 OSD 配置 watcher 由 App.vue 的
|
||||||
store.disposeOsd()
|
// initOsd() 注册,属应用级常驻(与模块生命周期解耦);若在此释放,切走监控模块后
|
||||||
|
// 托盘菜单的 OSD 开关会失效。OSD 事件监听仅在 App 卸载(应用退出)时统一释放。
|
||||||
})
|
})
|
||||||
|
|
||||||
// 当 Kernel 从未就绪变成就绪时,主动拉一次快照填充 UI
|
// 当 Kernel 从未就绪变成就绪时,主动拉一次快照填充 UI
|
||||||
@@ -1138,144 +1341,127 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
<p class="text-sm">正在加载...</p>
|
<p class="text-sm">正在加载...</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 始终显示卡片网格,未启动时数据以占位符显示,保持画面完整 -->
|
<template v-else>
|
||||||
<div v-else key="content" class="grid grid-cols-1 md:grid-cols-3 gap-2.5">
|
<!-- ===== Kernel 状态栏(置顶紧凑横条) ===== -->
|
||||||
<!-- CPU(温度 + 功耗 + 频率,未读数据以 -- 占位) -->
|
<Card class="py-0 gap-0 mb-2.5">
|
||||||
<Card class="py-0 gap-0">
|
<CardContent class="px-3.5 py-2 flex flex-wrap items-center gap-x-3 gap-y-1.5 text-xs">
|
||||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
<span class="flex items-center gap-1.5 font-medium text-sm">
|
||||||
<CardTitle class="flex items-center justify-between text-sm">
|
<Activity class="size-4 text-primary" />Kernel
|
||||||
<span class="flex items-center gap-1.5"><Cpu class="size-4 text-primary" />CPU</span>
|
|
||||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="cpuModel ?? ''">{{ cpuModel ?? '--' }}</span>
|
|
||||||
</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>
|
|
||||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="gpuModel ?? ''">{{ gpuModel ?? '--' }}</span>
|
|
||||||
</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" />
|
|
||||||
</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>
|
|
||||||
<span class="text-xs text-muted-foreground font-normal truncate ml-2" :title="memModuleModels.join(', ')">
|
|
||||||
{{ memTotalGB != null ? fmt(memTotalGB, 0) + ' GB' : '--' }}
|
|
||||||
</span>
|
</span>
|
||||||
</CardTitle>
|
<span :class="['px-2 py-0.5 rounded-full', stateMeta[store.connState].class]">
|
||||||
</CardHeader>
|
{{ stateMeta[store.connState].text }}
|
||||||
<CardContent class="px-3.5 pb-2.5 space-y-1.5">
|
</span>
|
||||||
<!-- 已使用 / 总容量(主指标,与 CPU 温度对齐) -->
|
<Badge :variant="store.snapshot?.isAdmin ? 'default' : 'outline'" :class="store.snapshot?.isAdmin ? 'bg-emerald-500 hover:bg-emerald-500' : ''">
|
||||||
<div class="flex items-end justify-between gap-2">
|
{{ store.snapshot?.isAdmin ? '管理员' : '普通' }}
|
||||||
<div>
|
</Badge>
|
||||||
<div class="text-xs text-muted-foreground flex items-center gap-1"><MemoryStick class="size-3" />已使用</div>
|
<Badge v-if="store.status?.thingElevated" variant="outline" class="border-emerald-500/50 text-emerald-600 dark:text-emerald-400">
|
||||||
<div class="text-2xl font-bold tabular-nums leading-tight">
|
<ShieldCheck class="size-2.5 mr-0.5" />提权
|
||||||
{{ fmt(memUsedGB, 1) }}<span class="text-sm font-normal text-muted-foreground"> / {{ fmt(memTotalGB, 1) }} GB</span>
|
</Badge>
|
||||||
</div>
|
<span class="text-muted-foreground">PID: <span class="font-mono text-foreground">{{ store.status?.pid ?? '--' }}</span></span>
|
||||||
</div>
|
<span class="text-muted-foreground">传感器: <span class="font-mono text-foreground">{{ store.status?.sensorCount ?? '--' }}</span></span>
|
||||||
</div>
|
<span class="text-muted-foreground">重启: <span class="font-mono text-foreground">{{ store.status?.restartCount ?? 0 }}</span></span>
|
||||||
<!-- 负载进度条(与 CPU 负载对齐) -->
|
<span class="text-muted-foreground">事件: <span class="font-mono text-foreground">{{ store.eventCount }}</span></span>
|
||||||
<div>
|
<div class="flex items-center gap-1.5 ml-auto">
|
||||||
<div class="flex items-center justify-between text-xs mb-0.5">
|
<!-- 启动中 loading(starting=true 但状态还没变为 loading 时显示) -->
|
||||||
<span class="text-muted-foreground flex items-center gap-1"><Gauge class="size-3" />负载</span>
|
<Button v-if="store.starting && store.connState === 'idle'" size="xs" variant="outline" disabled>
|
||||||
<span :class="['font-medium tabular-nums', loadColor(memLoad)]">{{ fmt(memLoad, 0) }}%</span>
|
<Loader2 class="size-3 animate-spin" />启动中
|
||||||
</div>
|
</Button>
|
||||||
<Progress :model-value="memLoad ?? 0" class="h-1.5" />
|
<!-- 启动按钮(未运行且非启动中时显示) -->
|
||||||
|
<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>
|
||||||
|
<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>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<!-- 网络(跨3列,下载/上传速率,独立于 Kernel 由 Tauri 后台推送) -->
|
<!-- ===== 硬件信息卡片网格(模板化,可编辑:拖拽排序 / 删除 / 添加) ===== -->
|
||||||
<Card class="md:col-span-3 py-0 gap-0">
|
<VueDraggable
|
||||||
<CardHeader class="pb-1.5 px-3.5 pt-2.5">
|
v-model="overviewCards"
|
||||||
<CardTitle class="flex items-center gap-1.5 text-sm">
|
:animation="200"
|
||||||
<Wifi class="size-4 text-primary" />网络
|
:force-fallback="true"
|
||||||
</CardTitle>
|
handle=".overview-drag-handle"
|
||||||
</CardHeader>
|
ghost-class="opacity-40"
|
||||||
<CardContent class="px-3.5 pb-2.5">
|
chosen-class="drag-chosen"
|
||||||
<div class="grid grid-cols-2 gap-4">
|
:disabled="!overviewEditing"
|
||||||
<!-- 下载 -->
|
class="grid grid-cols-1 md:grid-cols-4 gap-2.5"
|
||||||
<div>
|
@end="onOverviewDragEnd()"
|
||||||
<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">
|
<OverviewCard
|
||||||
{{ downSpeed.value }}<span class="text-sm font-normal text-muted-foreground ml-0.5">{{ downSpeed.unit }}</span>
|
v-for="view in overviewCardViews"
|
||||||
</div>
|
:key="view.id"
|
||||||
</div>
|
:view="view"
|
||||||
<!-- 上传 -->
|
:editing="overviewEditing"
|
||||||
<div>
|
@remove="removeOverviewCard(view.id)"
|
||||||
<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>
|
<template v-if="view.id === 'storage'" #body>
|
||||||
</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-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 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">
|
<div class="flex items-center justify-between gap-2">
|
||||||
<span class="text-xs font-medium truncate" :title="drive.name">{{ drive.name }}</span>
|
<Tooltip>
|
||||||
|
<TooltipTrigger as-child>
|
||||||
|
<span class="text-xs font-medium truncate">{{ drive.name }}</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>{{ drive.name }}</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
<span :class="['text-xs font-mono tabular-nums shrink-0', tempColor(drive.temp)]">{{ fmt(drive.temp, 0) }}°C</span>
|
<span :class="['text-xs font-mono tabular-nums shrink-0', tempColor(drive.temp)]">{{ fmt(drive.temp, 0) }}°C</span>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
@@ -1291,66 +1477,19 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<!-- 无数据占位(保持卡片结构完整) -->
|
|
||||||
<div v-else class="text-xs text-muted-foreground py-2 text-center">暂无存储数据</div>
|
<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>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
</VueDraggable>
|
||||||
<!-- 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) -->
|
|
||||||
<Button v-if="!store.elevateOnLaunch" size="xs" variant="outline" class="gap-1 text-emerald-600 dark:text-emerald-400 border-emerald-500/40 hover:bg-emerald-500/10" :disabled="store.starting" title="以管理员权限重启 Thing(弹 UAC,ThingHK 子进程继承权限,后续启动自动提权,崩溃自动重启)" @click="handleElevateSelf">
|
|
||||||
<Loader2 v-if="store.starting" class="size-3 animate-spin" />
|
|
||||||
<ShieldCheck v-else class="size-3" />提权
|
|
||||||
</Button>
|
|
||||||
<!-- 取消提权按钮(标志已启用时显示:清除标志,下次启动不触发 UAC) -->
|
|
||||||
<Button v-else size="xs" variant="outline" class="gap-1 text-muted-foreground hover:text-foreground" title="取消提权,下次启动将以普通权限运行(不影响当前会话)" @click="handleCancelElevation">
|
|
||||||
<ShieldOff class="size-3" />取消提权
|
|
||||||
</Button>
|
|
||||||
<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>
|
|
||||||
|
|
||||||
<!-- 断线提示 -->
|
<!-- 断线提示 -->
|
||||||
<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">
|
<CardContent class="pt-3 flex items-start gap-2 text-sm">
|
||||||
<AlertTriangle class="size-4 text-orange-500 mt-0.5 shrink-0" />
|
<AlertTriangle class="size-4 text-orange-500 mt-0.5 shrink-0" />
|
||||||
<div>
|
<div>
|
||||||
@@ -1361,7 +1500,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
</Card>
|
</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">
|
<CardContent class="pt-3 flex items-start gap-2 text-sm">
|
||||||
<AlertTriangle class="size-4 text-red-500 mt-0.5 shrink-0" />
|
<AlertTriangle class="size-4 text-red-500 mt-0.5 shrink-0" />
|
||||||
<div>
|
<div>
|
||||||
@@ -1370,7 +1509,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</template>
|
||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
@@ -1420,7 +1559,12 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
<div class="text-[11px] uppercase tracking-wide text-muted-foreground/70 mb-1">{{ typeLabel(typeGroup.type) }}</div>
|
<div class="text-[11px] uppercase tracking-wide text-muted-foreground/70 mb-1">{{ typeLabel(typeGroup.type) }}</div>
|
||||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-0.5 text-xs">
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-0.5 text-xs">
|
||||||
<div v-for="s in typeGroup.items" :key="s.id" class="flex justify-between items-center py-0.5">
|
<div v-for="s in typeGroup.items" :key="s.id" class="flex justify-between items-center py-0.5">
|
||||||
<span class="text-muted-foreground truncate pr-2" :title="s.name">{{ s.name }}</span>
|
<Tooltip>
|
||||||
|
<TooltipTrigger as-child>
|
||||||
|
<span class="text-muted-foreground truncate pr-2">{{ s.name }}</span>
|
||||||
|
</TooltipTrigger>
|
||||||
|
<TooltipContent>{{ s.name }}</TooltipContent>
|
||||||
|
</Tooltip>
|
||||||
<span class="font-mono tabular-nums shrink-0" :class="{ 'text-muted-foreground/50': s.value == null }">
|
<span class="font-mono tabular-nums shrink-0" :class="{ 'text-muted-foreground/50': s.value == null }">
|
||||||
{{ s.value == null ? 'N/A' : s.value.toFixed(s.type === 'voltage' || s.type === 'power' ? 2 : 1) }}
|
{{ s.value == null ? 'N/A' : s.value.toFixed(s.type === 'voltage' || s.type === 'power' ? 2 : 1) }}
|
||||||
<span class="text-muted-foreground ml-0.5">{{ s.unit }}</span>
|
<span class="text-muted-foreground ml-0.5">{{ s.unit }}</span>
|
||||||
@@ -2012,6 +2156,20 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
@update:model-value="updateOsdConfig('clickThrough', Boolean($event))"
|
@update:model-value="updateOsdConfig('clickThrough', Boolean($event))"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
<!-- 游戏全屏自动隐藏 -->
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="flex flex-col gap-0.5">
|
||||||
|
<Label class="text-sm flex items-center gap-1.5 cursor-pointer">
|
||||||
|
<Gamepad2 class="size-3.5 text-muted-foreground" />
|
||||||
|
游戏全屏时自动隐藏
|
||||||
|
</Label>
|
||||||
|
<span class="text-[11px] text-muted-foreground">检测到全屏应用(游戏)前台时隐藏悬浮窗,退出后自动恢复,避免游戏掉帧</span>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
:model-value="osdConfig.gameAutoHide"
|
||||||
|
@update:model-value="updateOsdConfig('gameAutoHide', Boolean($event))"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<Separator />
|
<Separator />
|
||||||
@@ -2074,7 +2232,18 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div class="text-xs text-muted-foreground">
|
<div class="text-xs text-muted-foreground">
|
||||||
Kernel 由 ProcessManager 统一管理,应用启动时自动拉起,崩溃自动重启。
|
Kernel 由 ProcessManager 统一管理,崩溃自动重启。
|
||||||
|
</div>
|
||||||
|
<!-- 应用启动时自动启动 toggle(参照代理模块) -->
|
||||||
|
<div class="flex items-center justify-between rounded-md border p-3">
|
||||||
|
<div>
|
||||||
|
<p class="text-sm">应用启动时自动启动监控内核</p>
|
||||||
|
<p class="text-xs text-muted-foreground">软件启动时自动运行 ThingHK 内核</p>
|
||||||
|
</div>
|
||||||
|
<Switch
|
||||||
|
:model-value="store.autoStart"
|
||||||
|
@update:model-value="(v: boolean) => store.setAutoStart(v)"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -2108,7 +2277,7 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
>{{ pathDisplay || pathShort }}</span>
|
>{{ pathDisplay || pathShort }}</span>
|
||||||
<span v-else class="font-mono text-xs text-right cursor-default">{{ pathShort }}</span>
|
<span v-else class="font-mono text-xs text-right cursor-default">{{ pathShort }}</span>
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent class="max-w-[400px] break-all">{{ store.kernelInfo.path ?? '' }}</TooltipContent>
|
<TooltipContent class="max-w-[480px] break-words">{{ store.kernelInfo.path ?? '' }}</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<template v-if="store.kernelInfo.exists">
|
<template v-if="store.kernelInfo.exists">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -2270,6 +2439,28 @@ watch(() => store.status?.ready, (ready, prev) => {
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|
||||||
|
<!-- 开启 OSD 但监控内核未运行提示 -->
|
||||||
|
<Dialog v-model:open="osdNeedsKernelOpen">
|
||||||
|
<DialogContent class="max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle class="flex items-center gap-2">
|
||||||
|
<TriangleAlert class="size-4 text-amber-500" />
|
||||||
|
需先启动监控内核
|
||||||
|
</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
OSD 悬浮窗依赖监控内核提供数据。当前内核未运行,请先启动内核后再开启 OSD 显示。
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="outline" @click="osdNeedsKernelOpen = false">取消</Button>
|
||||||
|
<Button @click="startKernelForOsd">
|
||||||
|
<Play class="size-3.5" />
|
||||||
|
启动内核
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
|
||||||
<!-- OSD 显示项选择 Dialog -->
|
<!-- OSD 显示项选择 Dialog -->
|
||||||
<Dialog v-model:open="osdPickDialogOpen">
|
<Dialog v-model:open="osdPickDialogOpen">
|
||||||
<DialogContent class="max-w-lg">
|
<DialogContent class="max-w-lg">
|
||||||
|
|||||||
@@ -77,31 +77,19 @@ interface OsdConfig {
|
|||||||
overlayY?: number | null
|
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 {
|
interface NetworkSpeed {
|
||||||
downloadBps: number
|
downloadBps: number
|
||||||
uploadBps: number
|
uploadBps: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 配置通道载荷(低频:配置变化时推送) */
|
||||||
interface OsdStatePayload {
|
interface OsdStatePayload {
|
||||||
config: OsdConfig
|
config: OsdConfig
|
||||||
snapshot: SensorSnapshot | null
|
}
|
||||||
|
|
||||||
|
/** 数据通道载荷(高频:仅显示项 key→value 映射 + 网速) */
|
||||||
|
interface OsdDataPayload {
|
||||||
|
data: Record<string, number | null>
|
||||||
networkSpeed: NetworkSpeed | null
|
networkSpeed: NetworkSpeed | null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,7 +321,8 @@ function fmtFixedUnit(item: OsdItem): string {
|
|||||||
|
|
||||||
// ===== 状态 =====
|
// ===== 状态 =====
|
||||||
const config = ref<OsdConfig | null>(null)
|
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)
|
const networkSpeed = ref<NetworkSpeed | null>(null)
|
||||||
let unlistenFns: UnlistenFn[] = []
|
let unlistenFns: UnlistenFn[] = []
|
||||||
|
|
||||||
@@ -341,15 +330,7 @@ let unlistenFns: UnlistenFn[] = []
|
|||||||
function getOsdItemValue(item: OsdItem): number | null {
|
function getOsdItemValue(item: OsdItem): number | null {
|
||||||
if (item.special === 'net-up') return networkSpeed.value?.uploadBps ?? null
|
if (item.special === 'net-up') return networkSpeed.value?.uploadBps ?? null
|
||||||
if (item.special === 'net-down') return networkSpeed.value?.downloadBps ?? null
|
if (item.special === 'net-down') return networkSpeed.value?.downloadBps ?? null
|
||||||
if (!snapshot.value) return null
|
return dataMap.value[item.key] ?? 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
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 颜色主题 =====
|
// ===== 颜色主题 =====
|
||||||
@@ -463,6 +444,23 @@ function scheduleMeasure() {
|
|||||||
}, 50)
|
}, 50)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 内容尺寸监视器:内核未启动时显示占位符(如 '--' 很短),数据就绪后实际值更长,
|
||||||
|
* 导致 osd-bar 变宽。仅靠配置变化触发测量不够——需监听 osd-bar 尺寸变化,
|
||||||
|
* 任何内容变宽/变高(数据加载、配置变更)都自动重测上报,驱动主窗口放大。 */
|
||||||
|
let resizeObserver: ResizeObserver | null = null
|
||||||
|
function observeBarSize() {
|
||||||
|
resizeObserver?.disconnect()
|
||||||
|
resizeObserver = null
|
||||||
|
const root = osdRootEl.value
|
||||||
|
const bar = root?.querySelector<HTMLElement>('.osd-bar')
|
||||||
|
if (!bar) return
|
||||||
|
resizeObserver = new ResizeObserver(() => scheduleMeasure())
|
||||||
|
resizeObserver.observe(bar)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根容器就绪后(config 到达、v-if 挂载)开始监视 osd-bar 尺寸变化
|
||||||
|
watch(osdRootEl, () => { void nextTick(observeBarSize) })
|
||||||
|
|
||||||
// ===== 应用鼠标穿透 =====
|
// ===== 应用鼠标穿透 =====
|
||||||
// 同时调用 Tauri setIgnoreCursorEvents(处理 webview2 子窗口)和 Rust WS_EX_TRANSPARENT(处理原生窗口)
|
// 同时调用 Tauri setIgnoreCursorEvents(处理 webview2 子窗口)和 Rust WS_EX_TRANSPARENT(处理原生窗口)
|
||||||
// 仅靠原生 WS_EX_TRANSPARENT 不足:Tauri 窗口包含 webview2 子窗口,需两者都设置才能完全穿透
|
// 仅靠原生 WS_EX_TRANSPARENT 不足:Tauri 窗口包含 webview2 子窗口,需两者都设置才能完全穿透
|
||||||
@@ -514,15 +512,26 @@ onMounted(async () => {
|
|||||||
console.error('[OSD] 启动置顶监视失败:', e)
|
console.error('[OSD] 启动置顶监视失败:', e)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 监听主窗口推送的 OSD 状态
|
// 启动游戏全屏监视(前台全屏应用时通知主窗口隐藏 OSD,避免游戏掉帧)
|
||||||
unlistenFns.push(await listen<OsdStatePayload>('osd-state-update', (e) => {
|
try {
|
||||||
|
await invoke('osd_start_game_watch')
|
||||||
|
} catch (e) {
|
||||||
|
console.error('[OSD] 启动游戏全屏监视失败:', e)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听主窗口推送的 OSD 配置(低频通道)
|
||||||
|
unlistenFns.push(await listen<OsdStatePayload>(EVENTS.osdStateUpdate, (e) => {
|
||||||
config.value = e.payload.config
|
config.value = e.payload.config
|
||||||
snapshot.value = e.payload.snapshot
|
// 配置变化(字号/布局/显示项)后重新测量尺寸
|
||||||
networkSpeed.value = e.payload.networkSpeed
|
|
||||||
// 数据/配置变化后重新测量尺寸
|
|
||||||
scheduleMeasure()
|
scheduleMeasure()
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
// 监听主窗口推送的 OSD 数据(高频通道:key→value 映射 + 网速)
|
||||||
|
unlistenFns.push(await listen<OsdDataPayload>(EVENTS.osdDataUpdate, (e) => {
|
||||||
|
dataMap.value = e.payload.data
|
||||||
|
networkSpeed.value = e.payload.networkSpeed
|
||||||
|
}))
|
||||||
|
|
||||||
// 监听系统 UI 覆盖事件
|
// 监听系统 UI 覆盖事件
|
||||||
unlistenFns.push(await listen(EVENTS.osdSystemUiActive, async () => {
|
unlistenFns.push(await listen(EVENTS.osdSystemUiActive, async () => {
|
||||||
await applyTopmost(false)
|
await applyTopmost(false)
|
||||||
@@ -531,6 +540,10 @@ onMounted(async () => {
|
|||||||
unlistenFns.push(await listen(EVENTS.osdSystemUiInactive, async () => {
|
unlistenFns.push(await listen(EVENTS.osdSystemUiInactive, async () => {
|
||||||
await applyTopmost(true)
|
await applyTopmost(true)
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
// 监听注册完成后,主动请求主窗口补发配置+数据
|
||||||
|
// (数据通道不含配置;若窗口加载慢错过创建时的首推,需主动请求,否则会一直空白)
|
||||||
|
await emit(EVENTS.osdConfigRequest)
|
||||||
})
|
})
|
||||||
|
|
||||||
/** 鼠标按下:仅在关闭穿透时响应左键拖动 */
|
/** 鼠标按下:仅在关闭穿透时响应左键拖动 */
|
||||||
@@ -548,6 +561,9 @@ onUnmounted(() => {
|
|||||||
unlistenFns.forEach(fn => fn())
|
unlistenFns.forEach(fn => fn())
|
||||||
// 停止监视线程
|
// 停止监视线程
|
||||||
invoke('osd_stop_watch').catch(() => {})
|
invoke('osd_stop_watch').catch(() => {})
|
||||||
|
// 断开内容尺寸监视器
|
||||||
|
resizeObserver?.disconnect()
|
||||||
|
resizeObserver = null
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -652,6 +668,13 @@ onUnmounted(() => {
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
flex-wrap: nowrap;
|
flex-wrap: nowrap;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
|
/* 文本永不换行:配置变更(如中英文切换)到窗口 resize 之间存在异步窗口期,
|
||||||
|
若允许换行,中文标签(内存/网络)会在旧窗口宽度内竖排;禁止后仅临时溢出,
|
||||||
|
随内容测量上报触发 setSize 立即恢复 */
|
||||||
|
white-space: nowrap;
|
||||||
|
/* 不被 osd-root(100vw 旧窗口宽度)压缩:否则 getBoundingClientRect 测到的是
|
||||||
|
被旧窗口钳制的宽度而非真实内容宽度,上报后 setSize 不变,窗口永远无法变宽 */
|
||||||
|
flex-shrink: 0;
|
||||||
backdrop-filter: blur(8px);
|
backdrop-filter: blur(8px);
|
||||||
padding: 3px 4px;
|
padding: 3px 4px;
|
||||||
gap: 0;
|
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>
|
||||||
@@ -6,7 +6,56 @@ const searchItems: SearchIndexItem[] = [
|
|||||||
{
|
{
|
||||||
title: '硬件监控',
|
title: '硬件监控',
|
||||||
description: '查看系统硬件状态',
|
description: '查看系统硬件状态',
|
||||||
keywords: ['监控', '硬件', 'cpu', '内存', 'monitor', 'hardware']
|
keywords: ['监控', '硬件', 'cpu', '内存', 'monitor', 'hardware'],
|
||||||
|
tab: 'overview'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '详细数据',
|
||||||
|
description: '查看各传感器详细读数',
|
||||||
|
keywords: ['详细', '数据', '传感器', 'sensor', '温度', '转速'],
|
||||||
|
tab: 'details'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'OSD 显示',
|
||||||
|
description: '配置悬浮窗显示项、位置与外观',
|
||||||
|
keywords: ['osd', '悬浮窗', '小窗', '显示', 'overlay'],
|
||||||
|
tab: 'osd'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'OSD 悬浮窗位置',
|
||||||
|
description: '设置悬浮窗在屏幕中的位置',
|
||||||
|
keywords: ['位置', '悬浮窗', '屏幕', 'position', 'osd'],
|
||||||
|
tab: 'osd'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '警告阈值',
|
||||||
|
description: '设置传感器告警阈值与颜色',
|
||||||
|
keywords: ['阈值', '告警', '警告', 'threshold', '颜色'],
|
||||||
|
tab: 'osd'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '监控设置',
|
||||||
|
description: '内核控制、自动启动与监控项配置',
|
||||||
|
keywords: ['设置', 'setting', '配置', '选项'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '启动监控内核',
|
||||||
|
description: '启动或停止 ThingHK 监控内核',
|
||||||
|
keywords: ['内核', '启动', '停止', 'kernel', 'thinghk', '控制'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '自动启动监控内核',
|
||||||
|
description: '应用启动时自动运行监控内核',
|
||||||
|
keywords: ['自动启动', '开机', '内核', 'autoStart'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '监控项配置',
|
||||||
|
description: '选择要监控的传感器分组与项目',
|
||||||
|
keywords: ['监控项', '传感器', '分组', 'sensor', '配置'],
|
||||||
|
tab: 'settings'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -30,9 +79,12 @@ export const moduleConfig: ModuleConfig = {
|
|||||||
},
|
},
|
||||||
lifecycle: {
|
lifecycle: {
|
||||||
onEnable: async () => {
|
onEnable: async () => {
|
||||||
// 启用模块时拉起 Kernel 并开始 SSE 订阅
|
// 若用户在监控设置中开启了"自动启动",则随模块启用而运行 Kernel
|
||||||
try {
|
try {
|
||||||
|
const autoStart = await invoke<boolean>('monitor_get_auto_start')
|
||||||
|
if (autoStart) {
|
||||||
await invoke('monitor_start')
|
await invoke('monitor_start')
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* 忽略:可能 Kernel 未安装 */
|
/* 忽略:可能 Kernel 未安装 */
|
||||||
}
|
}
|
||||||
|
|||||||
+536
-113
@@ -2,17 +2,20 @@
|
|||||||
import {
|
import {
|
||||||
Globe, Play, Square, RotateCw, Power, Zap, Plus, RefreshCw, Trash2,
|
Globe, Play, Square, RotateCw, Power, Zap, Plus, RefreshCw, Trash2,
|
||||||
Check, AlertCircle, Server, Settings as SettingsIcon, ListChecks,
|
Check, AlertCircle, Server, Settings as SettingsIcon, ListChecks,
|
||||||
Upload, Link2, Loader2, Download, Timer, Target, FolderOpen, Copy, DownloadCloud
|
Upload, Link2, Loader2, Download, Timer, Target, FolderOpen, Copy, DownloadCloud,
|
||||||
|
Waypoints, ArrowDown, ArrowUp, Activity, X
|
||||||
} from '@lucide/vue'
|
} from '@lucide/vue'
|
||||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
import { toast } from 'vue-sonner'
|
import { toast } from 'vue-sonner'
|
||||||
import { invoke } from '@tauri-apps/api/core'
|
import { invoke } from '@tauri-apps/api/core'
|
||||||
|
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||||
import { appDataDir } from '@tauri-apps/api/path'
|
import { appDataDir } from '@tauri-apps/api/path'
|
||||||
import { revealItemInDir } from '@tauri-apps/plugin-opener'
|
import { revealItemInDir } from '@tauri-apps/plugin-opener'
|
||||||
import { useProxyStore, type ProxyNode } from '@/stores/proxyStore'
|
import { useProxyStore, type ProxyNode, type ProxyConnection } from '@/stores/proxyStore'
|
||||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||||
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
import { useModuleTabsStore } from '@/stores/moduleTabsStore'
|
||||||
import { createLogger } from '@/lib/logger'
|
import { createLogger } from '@/lib/logger'
|
||||||
|
import { EVENTS } from '@/lib/constants'
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import { Badge } from '@/components/ui/badge'
|
import { Badge } from '@/components/ui/badge'
|
||||||
@@ -66,15 +69,23 @@ const onConfirmCancel = () => {
|
|||||||
confirmState.value.resolve?.(false)
|
confirmState.value.resolve?.(false)
|
||||||
}
|
}
|
||||||
const onConfirmOpenChange = (open: boolean) => {
|
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
|
confirmState.value.open = open
|
||||||
}
|
}
|
||||||
|
|
||||||
const activeTab = ref('overview')
|
const activeTab = ref('overview')
|
||||||
// 浮动标签切换器:注册到 TitleBar,滚动遮挡时自动显示
|
// 浮动标签切换器:注册到 TitleBar,滚动遮挡时自动显示
|
||||||
const tabsStore = useModuleTabsStore()
|
const tabsStore = useModuleTabsStore()
|
||||||
const tabsListRef = useModuleTabs(activeTab, [
|
const tabsListRef = useModuleTabs('proxy', activeTab, [
|
||||||
{ value: 'overview', label: '概览' },
|
{ value: 'overview', label: '概览' },
|
||||||
|
{ value: 'connections', label: '连接' },
|
||||||
{ value: 'proxies', label: '节点' },
|
{ value: 'proxies', label: '节点' },
|
||||||
{ value: 'profiles', label: '订阅' },
|
{ value: 'profiles', label: '订阅' },
|
||||||
{ value: 'settings', label: '设置' }
|
{ value: 'settings', label: '设置' }
|
||||||
@@ -90,16 +101,13 @@ const testingGroups = ref<Set<string>>(new Set())
|
|||||||
const loadingProxies = ref(false)
|
const loadingProxies = ref(false)
|
||||||
const checkingUpdate = ref(false)
|
const checkingUpdate = ref(false)
|
||||||
const updatingKernel = 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 autoSwitchEnabled = ref(false)
|
||||||
const autoSwitchInterval = ref(5) // 分钟
|
const autoSwitchInterval = ref(5) // 分钟
|
||||||
const autoSwitchTargetGroup = ref('') // 目标代理组
|
const autoSwitchTargetGroup = ref('') // 目标代理组
|
||||||
const autoSwitchRegion = ref('') // 空=全部,否则按地区过滤
|
const autoSwitchRegion = ref('') // 空=全部,否则按地区过滤
|
||||||
let autoSwitchTimer: ReturnType<typeof setInterval> | null = null
|
|
||||||
/** 自动切换执行中标志(防重入:测速超时时上一轮未结束,间隔触发会重叠) */
|
|
||||||
let autoSwitchRunning = false
|
|
||||||
|
|
||||||
// 从 store.settings 同步自动切换设置
|
// 从 store.settings 同步自动切换设置
|
||||||
const syncAutoSwitchSettings = () => {
|
const syncAutoSwitchSettings = () => {
|
||||||
@@ -127,14 +135,187 @@ const saveAutoSwitchSettings = async () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 后端自动切换事件监听句柄(模块卸载时关闭)
|
||||||
|
let autoSwitchUnlisten: UnlistenFn[] = []
|
||||||
|
|
||||||
// 手风琴展开项
|
// 手风琴展开项
|
||||||
const accordionValue = ref<string>('')
|
const accordionValue = ref<string>('')
|
||||||
|
|
||||||
// 进程状态轮询
|
// 进程状态轮询
|
||||||
let statusTimer: ReturnType<typeof setInterval> | null = null
|
let statusTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
let trafficTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
let connTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
|
||||||
|
/** 字节 → 人类可读大小(B / KB / MB / GB / TB) */
|
||||||
|
function fmtBytes(v: number): string {
|
||||||
|
if (!v && v !== 0) return '--'
|
||||||
|
if (v < 1024) return v + ' B'
|
||||||
|
const units = ['KB', 'MB', 'GB', 'TB']
|
||||||
|
let n = v / 1024
|
||||||
|
let u = 0
|
||||||
|
while (n >= 1024 && u < units.length - 1) {
|
||||||
|
n /= 1024
|
||||||
|
u++
|
||||||
|
}
|
||||||
|
return (n >= 100 ? n.toFixed(0) : n >= 10 ? n.toFixed(1) : n.toFixed(2)) + ' ' + units[u]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 速率显示(字节/秒 → /s) */
|
||||||
|
function fmtSpeed(v: number): string {
|
||||||
|
return fmtBytes(v) + '/s'
|
||||||
|
}
|
||||||
|
|
||||||
const running = computed(() => store.status.running)
|
const running = computed(() => store.status.running)
|
||||||
|
|
||||||
|
// ===== 连接页签 =====
|
||||||
|
/** 当前连接列表(store.connections 可能为 null → 视为空) */
|
||||||
|
const connList = computed(() => store.connections ?? [])
|
||||||
|
const connFilter = ref('')
|
||||||
|
/** 内网/国内/国外 一键过滤('all' = 全部) */
|
||||||
|
const connScopeFilter = ref<'all' | ConnScope>('all')
|
||||||
|
/** 一键过滤选项 */
|
||||||
|
const scopeFilterOptions: { value: 'all' | ConnScope; label: string }[] = [
|
||||||
|
{ value: 'all', label: '全部' },
|
||||||
|
{ value: 'direct', label: '国内' },
|
||||||
|
{ value: 'proxy', label: '国外' }
|
||||||
|
]
|
||||||
|
/** 顶部下载/上传速率(复用实时流量快照的整体速率) */
|
||||||
|
const connTotalDownloadSec = computed(() => store.traffic?.downloadSpeed ?? 0)
|
||||||
|
const connTotalUploadSec = computed(() => store.traffic?.uploadSpeed ?? 0)
|
||||||
|
/** 命中规则总数 = 活跃连接数(每条连接命中一条规则) */
|
||||||
|
const ruleHitCount = computed(() => connList.value.length)
|
||||||
|
/** 按规则聚合当前连接,便于观察哪些规则被频繁命中 */
|
||||||
|
const ruleHits = computed(() => {
|
||||||
|
const map = new Map<string, number>()
|
||||||
|
for (const c of connList.value) {
|
||||||
|
const r = c.rule || 'DIRECT'
|
||||||
|
map.set(r, (map.get(r) ?? 0) + 1)
|
||||||
|
}
|
||||||
|
return [...map.entries()]
|
||||||
|
.map(([rule, count]) => ({ rule, count }))
|
||||||
|
.sort((a, b) => b.count - a.count)
|
||||||
|
})
|
||||||
|
/** 按内网/国内/国外、通用关键词过滤后的连接 */
|
||||||
|
const filteredConnections = computed(() => {
|
||||||
|
const q = connFilter.value.trim().toLowerCase()
|
||||||
|
return connList.value.filter((c) => {
|
||||||
|
if (connScopeFilter.value !== 'all' && connScopeOf(c) !== connScopeFilter.value) return false
|
||||||
|
if (!q) return true
|
||||||
|
const process = (c.metadata?.process ?? '').toLowerCase()
|
||||||
|
const host = (c.metadata?.host ?? '').toLowerCase()
|
||||||
|
const rule = (c.rule ?? '').toLowerCase()
|
||||||
|
return process.includes(q) || host.includes(q) || rule.includes(q)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
/** 连接进程显示名 */
|
||||||
|
const connProcess = (c: ProxyConnection) => c.metadata?.process || '未知'
|
||||||
|
/** 连接源地址显示(IP:端口) */
|
||||||
|
const connSource = (c: ProxyConnection) => {
|
||||||
|
const ip = c.metadata?.sourceIP
|
||||||
|
const port = c.metadata?.sourcePort
|
||||||
|
return ip ? `${ip}${port ? ':' + port : ''}` : '--'
|
||||||
|
}
|
||||||
|
/** 连接目标显示:优先 host,否则用 IP:端口 */
|
||||||
|
const connHost = (c: ProxyConnection) => {
|
||||||
|
const h = c.metadata?.host
|
||||||
|
if (h) return h
|
||||||
|
const ip = c.metadata?.destinationIP
|
||||||
|
const port = c.metadata?.destinationPort
|
||||||
|
return ip ? `${ip}${port ? ':' + port : ''}` : '--'
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== 规则中文名 / 内外网判断 =====
|
||||||
|
/** 规则类型归一化:忽略大小写与 "-" "_" 空格(订阅里可能写成 DomainSuffix / DOMAIN-SUFFIX) */
|
||||||
|
const normRuleType = (s: string) => s.trim().replace(/[-_\s]/g, '').toLowerCase()
|
||||||
|
const RULE_CN: Record<string, string> = {
|
||||||
|
// 匹配/动作
|
||||||
|
match: '兜底', final: '兜底', ruleset: '规则集', direct: '直连', reject: '拒绝',
|
||||||
|
// 域名
|
||||||
|
domain: '域名', domainsuffix: '域名后缀', domainkeyword: '域名关键字', domainregex: '域名正则',
|
||||||
|
// 地理 / 站点
|
||||||
|
geoip: '地区', geosite: '域名组', ipasn: 'ASN',
|
||||||
|
// 地址网段
|
||||||
|
ipcidr: 'IP段', ipcidr6: 'IP段(v6)', srcipcidr: '源IP段', srcipcidr6: '源IP段(v6)',
|
||||||
|
dstnet: '目标地址', srcnet: '源地址', network: '网络类型',
|
||||||
|
// 端口
|
||||||
|
srcport: '源端口', dstport: '目标端口', srcportrange: '源端口范围', dstportrange: '目标端口范围',
|
||||||
|
// 进程 / 用户
|
||||||
|
process: '进程', processname: '进程名', processpath: '进程路径', processpathregex: '进程路径正则', uid: '用户ID',
|
||||||
|
// 入站
|
||||||
|
intype: '入站类型', inuser: '入站用户', inname: '入站名称', inport: '入站端口',
|
||||||
|
// 规则集衍生
|
||||||
|
rulesetipcidr: '规则集IP', rulesetipcidr6: '规则集IP(v6)', rulesetdomainsuffix: '规则集域名后缀',
|
||||||
|
rulesetdomainkeyword: '规则集域名关键字', rulesetdomainregex: '规则集域名正则', rulesetgeoip: '规则集地区',
|
||||||
|
// 逻辑
|
||||||
|
and: '与', not: '非', or: '或', subrule: '子规则'
|
||||||
|
}
|
||||||
|
/** 将 mihomo 规则翻译为中文类型名(仅替换类型关键字,保留匹配内容) */
|
||||||
|
const translateRule = (rule: string): string => {
|
||||||
|
const parts = rule.split(',')
|
||||||
|
const mapped = RULE_CN[normRuleType(parts[0])]
|
||||||
|
if (!mapped) return rule
|
||||||
|
return [mapped, ...parts.slice(1)].join(',')
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* 连接走向分类:只区分国内/国外。
|
||||||
|
* - direct 国内(未走代理;内网/局域网因代理过滤也已直连,归入国内)
|
||||||
|
* - proxy 国外(已走代理节点;代理多用于访问境外,故视为国外)
|
||||||
|
* 判定依据:链路最后一跳是否为 DIRECT。
|
||||||
|
*/
|
||||||
|
type ConnScope = 'direct' | 'proxy'
|
||||||
|
const connScopeOf = (c: ProxyConnection): ConnScope => {
|
||||||
|
const chain = c.chains
|
||||||
|
if (chain && chain.length) {
|
||||||
|
return chain[chain.length - 1] === 'DIRECT' ? 'direct' : 'proxy'
|
||||||
|
}
|
||||||
|
// 退化:无链路信息时按国内直连兜底
|
||||||
|
return 'direct'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 各规则的简短释义(供「规则命中」展示),仅为便于理解,非精确语义 */
|
||||||
|
const RULE_DESC: Record<string, string> = {
|
||||||
|
// 匹配/动作
|
||||||
|
match: '未匹配任何规则时的兜底', final: '未匹配任何规则时的兜底', direct: '直连', reject: '拒绝访问',
|
||||||
|
// 域名
|
||||||
|
domain: '完全匹配该域名', domainsuffix: '匹配该域名及其子域名', domainkeyword: '域名包含该关键词', domainregex: '域名按正则匹配',
|
||||||
|
// 地理 / 站点
|
||||||
|
geoip: '按 IP 所属国家/地区', geosite: '按域名所属站点类别', ipasn: '按 IP 所属 ASN 自治域',
|
||||||
|
// 地址网段
|
||||||
|
ipcidr: '匹配该 IP 网段', ipcidr6: '匹配该 IPv6 网段', srcipcidr: '按源 IP 网段', srcipcidr6: '按源 IPv6 网段',
|
||||||
|
dstnet: '按目标 IP/域名', srcnet: '按源 IP/域名', network: '按网络类型(TCP/UDP)',
|
||||||
|
// 端口
|
||||||
|
srcport: '按源端口', dstport: '按目标端口', srcportrange: '按源端口范围', dstportrange: '按目标端口范围',
|
||||||
|
// 进程 / 用户
|
||||||
|
process: '按进程', processname: '按进程名', processpath: '按进程可执行路径', processpathregex: '按进程路径正则',
|
||||||
|
uid: '按 Linux 用户 ID',
|
||||||
|
// 入站
|
||||||
|
intype: '按入站类型', inuser: '按入站用户', inname: '按入站名称', inport: '按入站端口',
|
||||||
|
// 规则集衍生
|
||||||
|
ruleset: '按规则集内容匹配',
|
||||||
|
rulesetipcidr: '匹配规则集中任一 IP 网段', rulesetipcidr6: '匹配规则集中任一 IPv6 网段',
|
||||||
|
rulesetdomainsuffix: '匹配规则集中任一域名后缀', rulesetdomainkeyword: '匹配规则集中任一域名关键字',
|
||||||
|
rulesetdomainregex: '匹配规则集正则', rulesetgeoip: '匹配规则集中任一地区',
|
||||||
|
// 逻辑
|
||||||
|
and: '多个条件同时满足(与)', or: '任一条件满足(或)', not: '取反(非)', subrule: '子规则分发'
|
||||||
|
}
|
||||||
|
/** 取了某条规则的类型释义;未知类型返回空串 */
|
||||||
|
const ruleDesc = (rule: string): string => {
|
||||||
|
return RULE_DESC[normRuleType(rule.split(',')[0])] ?? ''
|
||||||
|
}
|
||||||
|
/** 断开全部连接 */
|
||||||
|
const closeAllConnections = async () => {
|
||||||
|
const ok = await showConfirm({
|
||||||
|
title: '断开全部连接',
|
||||||
|
description: `确定断开当前 ${connList.value.length} 条活跃连接吗?`,
|
||||||
|
confirmText: '断开',
|
||||||
|
destructive: true
|
||||||
|
})
|
||||||
|
if (!ok) return
|
||||||
|
for (const c of [...connList.value]) {
|
||||||
|
await store.closeConnection(c.id).catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 伪节点关键词:DIRECT/REJECT/流量/套餐等非具体代理节点
|
// 伪节点关键词:DIRECT/REJECT/流量/套餐等非具体代理节点
|
||||||
const PSEUDO_NODE_KEYWORDS = [
|
const PSEUDO_NODE_KEYWORDS = [
|
||||||
'DIRECT', 'REJECT', 'PASS', 'COMPATIBLE',
|
'DIRECT', 'REJECT', 'PASS', 'COMPATIBLE',
|
||||||
@@ -328,10 +509,6 @@ const init = async () => {
|
|||||||
await store.waitForApi()
|
await store.waitForApi()
|
||||||
store.refreshVersion()
|
store.refreshVersion()
|
||||||
loadProxiesWithError()
|
loadProxiesWithError()
|
||||||
// 若自动切换已开启,恢复定时器
|
|
||||||
if (autoSwitchEnabled.value) {
|
|
||||||
startAutoSwitch()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// 无论初始化链路是否出错,都结束"加载中"占位,避免模块永久卡死
|
// 无论初始化链路是否出错,都结束"加载中"占位,避免模块永久卡死
|
||||||
@@ -345,24 +522,48 @@ onMounted(() => {
|
|||||||
// 窗口/标签页不可见时暂停状态轮询,恢复可见后下个 tick 自动继续
|
// 窗口/标签页不可见时暂停状态轮询,恢复可见后下个 tick 自动继续
|
||||||
if (document.hidden) return
|
if (document.hidden) return
|
||||||
await store.refreshStatus()
|
await store.refreshStatus()
|
||||||
|
// 同步系统代理真实状态(注册表可能被外部改动,3s 周期足够感知)
|
||||||
|
await store.refreshSystemProxy()
|
||||||
}, 3000)
|
}, 3000)
|
||||||
|
// 流量采样:运行中每秒拉取一次实时速率/累计流量
|
||||||
|
trafficTimer = setInterval(async () => {
|
||||||
|
if (document.hidden) return
|
||||||
|
if (running.value) await store.refreshTraffic()
|
||||||
|
}, 1000)
|
||||||
|
// 连接列表:仅「连接」页签激活且运行时低频拉取
|
||||||
|
connTimer = setInterval(async () => {
|
||||||
|
if (document.hidden) return
|
||||||
|
if (activeTab.value === 'connections' && running.value) await store.refreshConnections()
|
||||||
|
}, 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(() => {
|
onUnmounted(() => {
|
||||||
if (statusTimer) clearInterval(statusTimer)
|
if (statusTimer) clearInterval(statusTimer)
|
||||||
stopAutoSwitch()
|
if (trafficTimer) clearInterval(trafficTimer)
|
||||||
|
if (connTimer) clearInterval(connTimer)
|
||||||
|
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||||
|
autoSwitchUnlisten.forEach(fn => fn())
|
||||||
|
autoSwitchUnlisten = []
|
||||||
})
|
})
|
||||||
|
|
||||||
|
/** 页面可见性变化时刷新系统代理状态(低成本感知外部修改) */
|
||||||
|
async function onVisibilityChange() {
|
||||||
|
if (!document.hidden) {
|
||||||
|
await store.refreshSystemProxy()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
watch(running, async (val, old) => {
|
watch(running, async (val, old) => {
|
||||||
if (val && !old) {
|
if (val && !old) {
|
||||||
await store.waitForApi()
|
await store.waitForApi()
|
||||||
await store.refreshVersion()
|
await store.refreshVersion()
|
||||||
await loadProxiesWithError()
|
await loadProxiesWithError()
|
||||||
// 自动切换若已开启,mihomo 启动/重启后恢复定时器
|
|
||||||
// (handleStop 会停掉旧定时器,此处统一接管启动路径,避免开关显示开但功能静默失效)
|
|
||||||
if (autoSwitchEnabled.value) {
|
|
||||||
startAutoSwitch()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -405,7 +606,6 @@ const handleStart = async () => {
|
|||||||
const handleStop = async () => {
|
const handleStop = async () => {
|
||||||
stopping.value = true
|
stopping.value = true
|
||||||
try {
|
try {
|
||||||
stopAutoSwitch()
|
|
||||||
await store.stop()
|
await store.stop()
|
||||||
toast.success('mihomo 已停止')
|
toast.success('mihomo 已停止')
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -436,6 +636,12 @@ const handleRestart = async () => {
|
|||||||
|
|
||||||
// ===== 系统代理 =====
|
// ===== 系统代理 =====
|
||||||
const onToggleSystemProxy = async (on: boolean) => {
|
const onToggleSystemProxy = async (on: boolean) => {
|
||||||
|
// 停机时禁止开启(正常情况下开关已禁用,此处兜底防止外部调用)
|
||||||
|
if (on && !running.value) {
|
||||||
|
toast.warning('请先启动 mihomo 再开启系统代理')
|
||||||
|
store.refreshSystemProxy()
|
||||||
|
return
|
||||||
|
}
|
||||||
sysProxyLoading.value = true
|
sysProxyLoading.value = true
|
||||||
try {
|
try {
|
||||||
await store.toggleSystemProxy(on)
|
await store.toggleSystemProxy(on)
|
||||||
@@ -473,41 +679,26 @@ const quickSwitchNode = async (name: string) => {
|
|||||||
try {
|
try {
|
||||||
await store.selectProxy(mainGroupName.value, name)
|
await store.selectProxy(mainGroupName.value, name)
|
||||||
toast.success('节点已切换', { description: name })
|
toast.success('节点已切换', { description: name })
|
||||||
// 测速新节点
|
// 测速新节点:用 testDelayBatch 以更新 history,保证节点 Badge 显示与结果一致
|
||||||
store.testDelay(name).then(delay => {
|
store.testDelayBatch([name]).then(() => {
|
||||||
|
const delay = store.proxies[name]?.history?.[0]?.delay
|
||||||
|
if (delay && delay > 0) {
|
||||||
toast.success(`${name}`, { description: `延迟 ${delay}ms` })
|
toast.success(`${name}`, { description: `延迟 ${delay}ms` })
|
||||||
|
}
|
||||||
}).catch(() => {})
|
}).catch(() => {})
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error('切换节点失败', { description: String(e) })
|
toast.error('切换节点失败', { description: String(e) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 自动切换节点 =====
|
// ===== 自动切换节点(执行由后端调度,前端仅负责维护设置并刷新/提示) =====
|
||||||
const startAutoSwitch = () => {
|
|
||||||
stopAutoSwitch()
|
|
||||||
if (!autoSwitchEnabled.value) return
|
|
||||||
const ms = autoSwitchInterval.value * 60 * 1000
|
|
||||||
autoSwitchTimer = setInterval(runAutoSwitch, ms)
|
|
||||||
toast.success('自动切换已开启', {
|
|
||||||
description: `每 ${autoSwitchInterval.value} 分钟测试并切换至最优节点`
|
|
||||||
})
|
|
||||||
// 立即执行一次
|
|
||||||
runAutoSwitch()
|
|
||||||
}
|
|
||||||
|
|
||||||
const stopAutoSwitch = () => {
|
|
||||||
if (autoSwitchTimer) {
|
|
||||||
clearInterval(autoSwitchTimer)
|
|
||||||
autoSwitchTimer = null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const onToggleAutoSwitch = (on: boolean) => {
|
const onToggleAutoSwitch = (on: boolean) => {
|
||||||
autoSwitchEnabled.value = on
|
autoSwitchEnabled.value = on
|
||||||
if (on) {
|
if (on) {
|
||||||
startAutoSwitch()
|
toast.success('自动切换已开启', {
|
||||||
|
description: `每 ${autoSwitchInterval.value} 分钟测试并切换至最优节点`
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
stopAutoSwitch()
|
|
||||||
toast.info('自动切换已关闭')
|
toast.info('自动切换已关闭')
|
||||||
}
|
}
|
||||||
saveAutoSwitchSettings()
|
saveAutoSwitchSettings()
|
||||||
@@ -515,53 +706,22 @@ const onToggleAutoSwitch = (on: boolean) => {
|
|||||||
|
|
||||||
const onAutoSwitchIntervalChange = (val: unknown) => {
|
const onAutoSwitchIntervalChange = (val: unknown) => {
|
||||||
autoSwitchInterval.value = Number(val) || 5
|
autoSwitchInterval.value = Number(val) || 5
|
||||||
if (autoSwitchEnabled.value) {
|
|
||||||
startAutoSwitch()
|
|
||||||
}
|
|
||||||
saveAutoSwitchSettings()
|
saveAutoSwitchSettings()
|
||||||
}
|
}
|
||||||
|
|
||||||
const runAutoSwitch = async () => {
|
/** 后端自动切换完成后刷新节点列表并提示(后台亦可运行,不依赖模块激活) */
|
||||||
if (autoSwitchRunning) return
|
const onProxyAutoSwitch = async (e: { payload: { switched?: boolean; group?: string; name?: string; delay?: number } }) => {
|
||||||
autoSwitchRunning = true
|
const p = e.payload
|
||||||
try {
|
try {
|
||||||
const groupName = autoSwitchTargetGroup.value || mainGroupName.value
|
await store.loadProxies()
|
||||||
if (!groupName || !running.value) return
|
} catch (err) {
|
||||||
const nodes = filteredNodes.value
|
logger.error('自动切换后刷新节点失败: ' + err)
|
||||||
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)
|
if (p?.switched && p.name && p.delay) {
|
||||||
const best = valid[0]
|
|
||||||
|
|
||||||
// 如果当前节点不是最优,则切换
|
|
||||||
const currentNow = store.proxies[groupName]?.now ?? ''
|
|
||||||
if (currentNow !== best.name) {
|
|
||||||
await store.selectProxy(groupName, best.name)
|
|
||||||
toast.success('已自动切换到最优节点', {
|
toast.success('已自动切换到最优节点', {
|
||||||
description: `${best.name} (${best.delay}ms)`
|
description: `${p.name} (${p.delay}ms)`
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} catch (e) {
|
|
||||||
logger.error('自动切换失败: ' + e)
|
|
||||||
} finally {
|
|
||||||
autoSwitchRunning = false
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== 内核更新 =====
|
// ===== 内核更新 =====
|
||||||
@@ -569,7 +729,7 @@ const handleCheckUpdate = async () => {
|
|||||||
checkingUpdate.value = true
|
checkingUpdate.value = true
|
||||||
try {
|
try {
|
||||||
const info = await store.checkKernelUpdate()
|
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) {
|
if (info.hasUpdate) {
|
||||||
toast.info('发现新版本', { description: `最新: ${info.latestVersion}` })
|
toast.info('发现新版本', { description: `最新: ${info.latestVersion}` })
|
||||||
} else {
|
} else {
|
||||||
@@ -590,31 +750,26 @@ const handleUpdateKernel = async () => {
|
|||||||
/** 是否展开"更新内核"区块(下载源 + 进度) */
|
/** 是否展开"更新内核"区块(下载源 + 进度) */
|
||||||
const updateExpanded = ref(false)
|
const updateExpanded = ref(false)
|
||||||
|
|
||||||
/** 开始更新:停止 mihomo → 调用 updateKernel(复用 installProgress 进度机制) */
|
/** 开始更新:确保有下载 URL → 调用 updateKernel(复用 installProgress 进度机制)。
|
||||||
|
* 下载阶段允许 mihomo 运行(可通过当前系统代理下载),
|
||||||
|
* 解压替换前由 need_stop 阶段弹窗要求停止 mihomo */
|
||||||
const handleStartUpdate = async () => {
|
const handleStartUpdate = async () => {
|
||||||
if (store.installing) return
|
if (store.installing) return
|
||||||
// 确认停止 mihomo
|
// 使用检查更新时获取的下载 URL(缺失时先补查一次,避免后端二次请求 GitHub)
|
||||||
if (running.value) {
|
let url = kernelUpdateInfo.value?.downloadUrl ?? ''
|
||||||
const ok = await showConfirm({
|
if (!url) {
|
||||||
title: '更新内核',
|
|
||||||
description: '更新内核需要先停止 mihomo,确认继续?',
|
|
||||||
confirmText: '继续更新'
|
|
||||||
})
|
|
||||||
if (!ok) return
|
|
||||||
updatingKernel.value = true
|
|
||||||
try {
|
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) {
|
} catch (e) {
|
||||||
toast.error('停止 mihomo 失败', { description: String(e) })
|
toast.error('获取更新信息失败', { description: String(e) })
|
||||||
updatingKernel.value = false
|
|
||||||
return
|
return
|
||||||
} finally {
|
|
||||||
updatingKernel.value = false
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
toast.info('开始下载更新...')
|
toast.info('开始下载更新...')
|
||||||
try {
|
try {
|
||||||
await store.updateKernel(selectedMirrorPrefix.value)
|
await store.updateKernel(selectedMirrorPrefix.value, url)
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast.error('内核更新失败', { description: String(e) })
|
toast.error('内核更新失败', { description: String(e) })
|
||||||
}
|
}
|
||||||
@@ -624,7 +779,9 @@ const handleStartUpdate = async () => {
|
|||||||
const installStageText = computed(() => {
|
const installStageText = computed(() => {
|
||||||
const stage = store.installProgress?.stage
|
const stage = store.installProgress?.stage
|
||||||
switch (stage) {
|
switch (stage) {
|
||||||
|
case 'checking': return '正在检查'
|
||||||
case 'downloading': return '正在下载'
|
case 'downloading': return '正在下载'
|
||||||
|
case 'need_stop': return '等待停止 mihomo'
|
||||||
case 'extracting': return '正在解压'
|
case 'extracting': return '正在解压'
|
||||||
case 'replacing': return '正在安装'
|
case 'replacing': return '正在安装'
|
||||||
case 'done': return '安装完成'
|
case 'done': return '安装完成'
|
||||||
@@ -637,6 +794,7 @@ const installStageColor = computed(() => {
|
|||||||
const stage = store.installProgress?.stage
|
const stage = store.installProgress?.stage
|
||||||
if (stage === 'done') return 'text-emerald-500'
|
if (stage === 'done') return 'text-emerald-500'
|
||||||
if (stage === 'error') return 'text-destructive'
|
if (stage === 'error') return 'text-destructive'
|
||||||
|
if (stage === 'need_stop') return 'text-amber-500'
|
||||||
return 'text-primary'
|
return 'text-primary'
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -655,6 +813,25 @@ const installPercentDisplay = computed(() => {
|
|||||||
|
|
||||||
const installHasTotal = computed(() => store.installProgress?.totalBytes != null)
|
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`
|
const formatMB = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)} MB`
|
||||||
|
|
||||||
// ===== 首次安装内核 =====
|
// ===== 首次安装内核 =====
|
||||||
@@ -692,12 +869,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 并延时清空进度
|
// 监听安装/更新进度终态,弹 toast 并延时清空进度
|
||||||
// 同时处理更新场景下的 updateExpanded 清理(与 installProgress 同步清除,避免更新区块闪烁)
|
// 同时处理更新场景下的 updateExpanded 清理(与 installProgress 同步清除,避免更新区块闪烁)
|
||||||
watch(
|
watch(
|
||||||
() => store.installProgress?.stage,
|
() => store.installProgress?.stage,
|
||||||
(stage) => {
|
(stage) => {
|
||||||
if (stage === 'done') {
|
if (stage === 'need_stop') {
|
||||||
|
handleNeedStop()
|
||||||
|
} else if (stage === 'done') {
|
||||||
toast.success('内核安装完成', {
|
toast.success('内核安装完成', {
|
||||||
description: store.installProgress?.message
|
description: store.installProgress?.message
|
||||||
})
|
})
|
||||||
@@ -882,12 +1102,35 @@ watch(() => store.settings, syncLocalSettings, { immediate: true })
|
|||||||
|
|
||||||
const saveSettingsForm = async () => {
|
const saveSettingsForm = async () => {
|
||||||
if (!store.settings) return
|
if (!store.settings) return
|
||||||
|
const prev = store.settings
|
||||||
try {
|
try {
|
||||||
await store.saveSettings({
|
await store.saveSettings({
|
||||||
...store.settings,
|
...store.settings,
|
||||||
...localSettings.value
|
...localSettings.value
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// 网络相关字段(端口/接口/密钥)变更需重启 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('设置已保存')
|
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) {
|
} catch (e) {
|
||||||
toast.error('保存失败', { description: String(e) })
|
toast.error('保存失败', { description: String(e) })
|
||||||
}
|
}
|
||||||
@@ -901,8 +1144,9 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
<div class="h-full p-6">
|
<div class="h-full p-6">
|
||||||
<Tabs v-model="activeTab" class="h-full flex flex-col">
|
<Tabs v-model="activeTab" class="h-full flex flex-col">
|
||||||
<div ref="tabsListRef">
|
<div ref="tabsListRef">
|
||||||
<TabsList class="grid w-full grid-cols-4 max-w-md !bg-transparent !p-0 !shadow-none">
|
<TabsList class="grid w-full grid-cols-5 max-w-md !bg-transparent !p-0 !shadow-none">
|
||||||
<TabsTrigger value="overview" class="gap-1.5"><Globe class="size-3.5" />概览</TabsTrigger>
|
<TabsTrigger value="overview" class="gap-1.5"><Globe class="size-3.5" />概览</TabsTrigger>
|
||||||
|
<TabsTrigger value="connections" class="gap-1.5"><Waypoints class="size-3.5" />连接</TabsTrigger>
|
||||||
<TabsTrigger value="proxies" class="gap-1.5"><Server class="size-3.5" />节点</TabsTrigger>
|
<TabsTrigger value="proxies" class="gap-1.5"><Server class="size-3.5" />节点</TabsTrigger>
|
||||||
<TabsTrigger value="profiles" class="gap-1.5"><ListChecks class="size-3.5" />订阅</TabsTrigger>
|
<TabsTrigger value="profiles" class="gap-1.5"><ListChecks class="size-3.5" />订阅</TabsTrigger>
|
||||||
<TabsTrigger value="settings" class="gap-1.5"><SettingsIcon class="size-3.5" />设置</TabsTrigger>
|
<TabsTrigger value="settings" class="gap-1.5"><SettingsIcon class="size-3.5" />设置</TabsTrigger>
|
||||||
@@ -913,6 +1157,42 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
<TabsContent value="overview" class="flex-1 mt-4 tab-animate">
|
<TabsContent value="overview" class="flex-1 mt-4 tab-animate">
|
||||||
<ScrollArea class="h-full pr-3">
|
<ScrollArea class="h-full pr-3">
|
||||||
<div class="columns-1 md:columns-2 gap-4 [&>*]:mb-4 [&>*]:break-inside-avoid">
|
<div class="columns-1 md:columns-2 gap-4 [&>*]:mb-4 [&>*]:break-inside-avoid">
|
||||||
|
<!-- 实时流量 -->
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle class="flex items-center justify-between text-base">
|
||||||
|
<span class="flex items-center gap-2"><Activity class="size-4 text-primary" />实时流量</span>
|
||||||
|
<Badge v-if="running" variant="outline" class="gap-1 text-xs">
|
||||||
|
<span class="size-1.5 rounded-full bg-emerald-500" />实时更新
|
||||||
|
</Badge>
|
||||||
|
</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent class="space-y-4 text-sm">
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center gap-1 text-muted-foreground text-xs mb-1">
|
||||||
|
<ArrowDown class="size-3.5 text-emerald-500" />下载
|
||||||
|
</div>
|
||||||
|
<p class="text-lg font-semibold tabular-nums">{{ fmtSpeed(store.traffic?.downloadSpeed ?? 0) }}</p>
|
||||||
|
<p class="text-xs text-muted-foreground tabular-nums">累计 {{ store.traffic ? fmtBytes(store.traffic.downloadTotal) : '--' }}</p>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="flex items-center gap-1 text-muted-foreground text-xs mb-1">
|
||||||
|
<ArrowUp class="size-3.5 text-rose-500" />上传
|
||||||
|
</div>
|
||||||
|
<p class="text-lg font-semibold tabular-nums">{{ fmtSpeed(store.traffic?.uploadSpeed ?? 0) }}</p>
|
||||||
|
<p class="text-xs text-muted-foreground tabular-nums">累计 {{ store.traffic ? fmtBytes(store.traffic.uploadTotal) : '--' }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Separator />
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="flex items-center gap-1.5 text-muted-foreground">
|
||||||
|
<Waypoints class="size-3.5" />活跃连接
|
||||||
|
</span>
|
||||||
|
<span class="font-semibold tabular-nums">{{ store.traffic?.activeConnections ?? '--' }}</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
<!-- 内核状态 -->
|
<!-- 内核状态 -->
|
||||||
<Card>
|
<Card>
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
@@ -978,13 +1258,9 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
<div class="flex items-center gap-1.5 min-w-0">
|
<div class="flex items-center gap-1.5 min-w-0">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
<TooltipTrigger as-child>
|
<TooltipTrigger as-child>
|
||||||
<span
|
<span class="font-mono text-xs text-right truncate cursor-default">{{ pathDisplay || pathShort }}</span>
|
||||||
v-if="store.kernel?.exists"
|
|
||||||
class="font-mono text-xs text-right truncate cursor-default"
|
|
||||||
>{{ pathDisplay || pathShort }}</span>
|
|
||||||
<span v-else class="font-mono text-xs text-right cursor-default">{{ pathShort }}</span>
|
|
||||||
</TooltipTrigger>
|
</TooltipTrigger>
|
||||||
<TooltipContent class="max-w-[400px] break-all">{{ store.kernel?.path ?? '' }}</TooltipContent>
|
<TooltipContent class="max-w-[480px] break-words">{{ store.kernel?.path ?? '' }}</TooltipContent>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
<template v-if="store.kernel?.exists">
|
<template v-if="store.kernel?.exists">
|
||||||
<Tooltip>
|
<Tooltip>
|
||||||
@@ -1115,12 +1391,12 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
<div class="flex items-center justify-between text-xs">
|
<div class="flex items-center justify-between text-xs">
|
||||||
<span :class="installStageColor" class="flex items-center gap-1.5 font-medium">
|
<span :class="installStageColor" class="flex items-center gap-1.5 font-medium">
|
||||||
<Loader2
|
<Loader2
|
||||||
v-if="['downloading', 'extracting', 'replacing'].includes(store.installProgress.stage)"
|
v-if="['checking', 'downloading', 'extracting', 'replacing'].includes(store.installProgress.stage)"
|
||||||
key="stage-loading"
|
key="stage-loading"
|
||||||
class="size-3 animate-spin"
|
class="size-3 animate-spin"
|
||||||
/>
|
/>
|
||||||
<Check v-else-if="store.installProgress.stage === 'done'" key="stage-done" class="size-3" />
|
<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 }}
|
{{ installStageText }}
|
||||||
</span>
|
</span>
|
||||||
<span v-if="installHasTotal && store.installProgress.stage === 'downloading'" class="font-mono text-muted-foreground">
|
<span v-if="installHasTotal && store.installProgress.stage === 'downloading'" class="font-mono text-muted-foreground">
|
||||||
@@ -1128,7 +1404,7 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<Progress
|
<Progress
|
||||||
v-if="installHasTotal || store.installProgress.stage !== 'downloading'"
|
v-if="installHasTotal || (store.installProgress.stage !== 'downloading' && store.installProgress.stage !== 'checking')"
|
||||||
key="progress-bar"
|
key="progress-bar"
|
||||||
:model-value="installPercentDisplay"
|
:model-value="installPercentDisplay"
|
||||||
class="h-2"
|
class="h-2"
|
||||||
@@ -1150,6 +1426,20 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
</template>
|
</template>
|
||||||
<template v-else>{{ store.installProgress.message }}</template>
|
<template v-else>{{ store.installProgress.message }}</template>
|
||||||
</p>
|
</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>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -1358,7 +1648,7 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
</div>
|
</div>
|
||||||
<Switch
|
<Switch
|
||||||
:model-value="store.systemProxy"
|
:model-value="store.systemProxy"
|
||||||
:disabled="sysProxyLoading"
|
:disabled="sysProxyLoading || !running"
|
||||||
@update:model-value="onToggleSystemProxy"
|
@update:model-value="onToggleSystemProxy"
|
||||||
/>
|
/>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@@ -1367,6 +1657,139 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
</ScrollArea>
|
</ScrollArea>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
|
<!-- 连接 -->
|
||||||
|
<TabsContent value="connections" class="flex-1 mt-4 tab-animate">
|
||||||
|
<div v-if="!running" key="conn-not-running" class="h-full flex flex-col items-center justify-center text-muted-foreground gap-2 pt-10 pr-10">
|
||||||
|
<Waypoints class="size-12 opacity-30" />
|
||||||
|
<p class="text-sm">mihomo 未运行,请先在概览页启动</p>
|
||||||
|
</div>
|
||||||
|
<div v-else class="h-full flex flex-col gap-4 pr-3">
|
||||||
|
<!-- 顶部统计 -->
|
||||||
|
<div class="grid grid-cols-2 md:grid-cols-4 gap-2">
|
||||||
|
<Card>
|
||||||
|
<CardContent class="py-3">
|
||||||
|
<div class="flex items-center gap-1.5 text-muted-foreground text-xs mb-1"><Waypoints class="size-3.5" />活跃连接</div>
|
||||||
|
<p class="text-xl font-semibold tabular-nums">{{ connList.length }}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent class="py-3">
|
||||||
|
<div class="flex items-center gap-1.5 text-muted-foreground text-xs mb-1"><ArrowDown class="size-3.5 text-emerald-500" />下载速率</div>
|
||||||
|
<p class="text-xl font-semibold tabular-nums">{{ fmtSpeed(connTotalDownloadSec) }}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent class="py-3">
|
||||||
|
<div class="flex items-center gap-1.5 text-muted-foreground text-xs mb-1"><ArrowUp class="size-3.5 text-rose-500" />上传速率</div>
|
||||||
|
<p class="text-xl font-semibold tabular-nums">{{ fmtSpeed(connTotalUploadSec) }}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
<Card>
|
||||||
|
<CardContent class="py-3">
|
||||||
|
<div class="flex items-center gap-1.5 text-muted-foreground text-xs mb-1"><Target class="size-3.5" />命中规则</div>
|
||||||
|
<p class="text-xl font-semibold tabular-nums">{{ ruleHitCount }}</p>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 规则命中分布 -->
|
||||||
|
<Card>
|
||||||
|
<CardHeader class="pb-2">
|
||||||
|
<CardTitle class="text-sm flex items-center gap-2"><Target class="size-3.5 text-primary" />规则命中</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent class="pt-0">
|
||||||
|
<div v-if="!ruleHits.length" class="text-xs text-muted-foreground py-2">暂无连接</div>
|
||||||
|
<div v-else class="space-y-1.5">
|
||||||
|
<div v-for="r in ruleHits.slice(0, 6)" :key="r.rule" class="flex items-baseline gap-2 text-xs">
|
||||||
|
<span class="w-1.5 h-1.5 rounded-full bg-primary shrink-0 self-center" />
|
||||||
|
<span class="font-medium shrink-0">{{ translateRule(r.rule) }}</span>
|
||||||
|
<span class="flex-1 min-w-0 truncate text-muted-foreground">
|
||||||
|
<template v-if="ruleDesc(r.rule)">({{ ruleDesc(r.rule) }})</template>
|
||||||
|
</span>
|
||||||
|
<span class="shrink-0 tabular-nums">×{{ r.count }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<!-- 连接列表 -->
|
||||||
|
<Card class="flex-1 min-h-0 flex flex-col">
|
||||||
|
<CardHeader class="pb-2 space-y-2">
|
||||||
|
<div class="flex items-center justify-between gap-3">
|
||||||
|
<CardTitle class="text-sm flex items-center gap-2"><Waypoints class="size-3.5 text-primary" />当前连接</CardTitle>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Input v-model="connFilter" placeholder="按进程/域名/规则过滤" class="h-8 w-56" />
|
||||||
|
<Button size="xs" variant="outline" :disabled="!connList.length" @click="closeAllConnections">
|
||||||
|
<Square class="size-3" />断开全部
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex flex-wrap items-center gap-1.5">
|
||||||
|
<span class="text-xs text-muted-foreground">走向:</span>
|
||||||
|
<Button
|
||||||
|
v-for="s in scopeFilterOptions"
|
||||||
|
:key="s.value"
|
||||||
|
size="xs"
|
||||||
|
:variant="connScopeFilter === s.value ? 'default' : 'outline'"
|
||||||
|
@click="connScopeFilter = s.value"
|
||||||
|
>{{ s.label }}</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent class="flex-1 min-h-0 overflow-hidden pt-0">
|
||||||
|
<ScrollArea class="h-full">
|
||||||
|
<table class="w-full text-xs">
|
||||||
|
<thead class="sticky top-0 z-10 bg-card text-muted-foreground">
|
||||||
|
<tr class="border-b">
|
||||||
|
<th class="text-left font-medium py-2 px-2">进程 / 源地址</th>
|
||||||
|
<th class="text-left font-medium py-2 px-2">目标</th>
|
||||||
|
<th class="text-left font-medium py-2 px-2">规则</th>
|
||||||
|
<th class="text-right font-medium py-2 px-2">下载</th>
|
||||||
|
<th class="text-right font-medium py-2 px-2">上传</th>
|
||||||
|
<th class="text-center font-medium py-2 px-2"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="c in filteredConnections" :key="c.id" class="border-b last:border-0 hover:bg-muted/40">
|
||||||
|
<td class="py-2 px-2 align-baseline">
|
||||||
|
<span class="font-medium truncate block max-w-[140px]">{{ connProcess(c) }}</span>
|
||||||
|
<span class="text-muted-foreground">{{ connSource(c) }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="py-2 px-2 align-baseline">
|
||||||
|
<div class="flex items-center gap-1.5">
|
||||||
|
<Badge
|
||||||
|
v-if="connScopeOf(c) === 'direct'"
|
||||||
|
variant="outline" class="h-4 px-1.5 text-[10px] shrink-0 border-emerald-500 text-emerald-500"
|
||||||
|
>国内</Badge>
|
||||||
|
<Badge
|
||||||
|
v-else
|
||||||
|
variant="outline" class="h-4 px-1.5 text-[10px] shrink-0 border-sky-500 text-sky-500"
|
||||||
|
>国外</Badge>
|
||||||
|
<span class="truncate block max-w-[140px]">{{ connHost(c) }}</span>
|
||||||
|
</div>
|
||||||
|
<span class="text-muted-foreground">{{ c.metadata?.network }} / {{ c.metadata?.type }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="py-2 px-2 align-baseline text-muted-foreground">
|
||||||
|
<span class="truncate block max-w-[160px]">{{ translateRule(c.rule || 'DIRECT') }}</span>
|
||||||
|
</td>
|
||||||
|
<td class="py-2 px-2 text-right tabular-nums align-baseline">{{ fmtBytes(c.download) }}</td>
|
||||||
|
<td class="py-2 px-2 text-right tabular-nums align-baseline">{{ fmtBytes(c.upload) }}</td>
|
||||||
|
<td class="py-2 px-2 text-center align-baseline">
|
||||||
|
<Button size="icon" variant="ghost" class="size-6" title="断开连接" @click="store.closeConnection(c.id)">
|
||||||
|
<X class="size-3.5" />
|
||||||
|
</Button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr v-if="!connList.length">
|
||||||
|
<td colspan="6" class="text-center text-muted-foreground py-8">暂无活跃连接</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</ScrollArea>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</TabsContent>
|
||||||
|
|
||||||
<!-- 节点 -->
|
<!-- 节点 -->
|
||||||
<TabsContent value="proxies" class="flex-1 mt-4 tab-animate">
|
<TabsContent value="proxies" class="flex-1 mt-4 tab-animate">
|
||||||
<div v-if="!running" key="not-running" class="h-full flex flex-col items-center justify-center text-muted-foreground gap-2 pt-10 pr-10">
|
<div v-if="!running" key="not-running" class="h-full flex flex-col items-center justify-center text-muted-foreground gap-2 pt-10 pr-10">
|
||||||
@@ -1614,7 +2037,7 @@ tabsStore.registerSave(saveSettingsForm)
|
|||||||
</Tabs>
|
</Tabs>
|
||||||
|
|
||||||
<!-- 通用确认对话框 -->
|
<!-- 通用确认对话框 -->
|
||||||
<AlertDialog :model-value="confirmState.open" @update:model-value="onConfirmOpenChange">
|
<AlertDialog :open="confirmState.open" @update:open="onConfirmOpenChange">
|
||||||
<AlertDialogContent>
|
<AlertDialogContent>
|
||||||
<AlertDialogHeader>
|
<AlertDialogHeader>
|
||||||
<AlertDialogTitle>{{ confirmState.opts.title }}</AlertDialogTitle>
|
<AlertDialogTitle>{{ confirmState.opts.title }}</AlertDialogTitle>
|
||||||
|
|||||||
@@ -7,22 +7,110 @@ const searchItems: SearchIndexItem[] = [
|
|||||||
{
|
{
|
||||||
title: '代理设置',
|
title: '代理设置',
|
||||||
description: '配置网络代理、端口与控制接口',
|
description: '配置网络代理、端口与控制接口',
|
||||||
keywords: ['代理', 'proxy', '网络', 'network', '端口', 'port']
|
keywords: ['代理', 'proxy', '网络', 'network', '端口', 'port'],
|
||||||
|
tab: 'settings'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '订阅管理',
|
title: '订阅管理',
|
||||||
description: '导入与更新 Clash/mihomo 订阅',
|
description: '导入与更新 Clash/mihomo 订阅',
|
||||||
keywords: ['订阅', 'subscription', 'profile', '导入']
|
keywords: ['订阅', 'subscription', 'profile', '导入'],
|
||||||
|
tab: 'profiles'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '节点选择',
|
title: '节点选择',
|
||||||
description: '切换代理节点并测试延迟',
|
description: '切换代理节点并测试延迟',
|
||||||
keywords: ['节点', 'node', '延迟', 'delay', '测速']
|
keywords: ['节点', 'node', '延迟', 'delay', '测速'],
|
||||||
|
tab: 'proxies'
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '系统代理',
|
title: '系统代理',
|
||||||
description: '开启或关闭 Windows 系统代理',
|
description: '开启或关闭 Windows 系统代理',
|
||||||
keywords: ['系统代理', 'system proxy', '开关', 'toggle']
|
keywords: ['系统代理', 'system proxy', '开关', 'toggle'],
|
||||||
|
tab: 'overview'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '导入订阅',
|
||||||
|
description: '填入订阅地址导入新配置',
|
||||||
|
keywords: ['导入', '订阅地址', 'import', 'url', '添加订阅'],
|
||||||
|
tab: 'profiles'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '更新订阅',
|
||||||
|
description: '手动更新订阅配置',
|
||||||
|
keywords: ['更新订阅', 'update', '刷新订阅'],
|
||||||
|
tab: 'profiles'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '自动切换节点',
|
||||||
|
description: '定时测速并自动切换到最优节点',
|
||||||
|
keywords: ['自动切换', 'auto switch', '智能', '最优节点', '测速'],
|
||||||
|
tab: 'overview'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '代理组测速',
|
||||||
|
description: '测试代理组所有节点的延迟',
|
||||||
|
keywords: ['测速', '延迟', 'delay', 'test', 'ping'],
|
||||||
|
tab: 'proxies'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '运行模式',
|
||||||
|
description: '规则 / 全局 / 直连模式切换',
|
||||||
|
keywords: ['模式', 'mode', 'rule', 'global', 'direct', '规则', '全局', '直连'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '混合代理端口',
|
||||||
|
description: '配置 mihomo 混合代理端口',
|
||||||
|
keywords: ['端口', 'port', 'mixed', '混合'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '控制接口地址',
|
||||||
|
description: '配置外部控制接口地址',
|
||||||
|
keywords: ['控制接口', 'external', 'controller', 'api', '地址'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'API 密钥',
|
||||||
|
description: '设置 mihomo 外部 API 密钥',
|
||||||
|
keywords: ['密钥', 'secret', 'token', '鉴权', 'api'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '允许局域网连接',
|
||||||
|
description: '允许其他设备通过本机代理上网',
|
||||||
|
keywords: ['局域网', 'lan', 'allowLan', '共享'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '日志级别',
|
||||||
|
description: '配置 mihomo 日志输出级别',
|
||||||
|
keywords: ['日志', 'log', 'level', 'debug', 'info'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '启动时自动启动 mihomo',
|
||||||
|
description: '应用启动时自动运行代理内核',
|
||||||
|
keywords: ['自动启动', 'autoStart', '开机', '启动内核'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '启动时自动开启系统代理',
|
||||||
|
description: 'mihomo 启动后自动设置 Windows 系统代理',
|
||||||
|
keywords: ['系统代理', '自动', 'autoSystemProxy'],
|
||||||
|
tab: 'settings'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '更新内核',
|
||||||
|
description: '检查并更新 mihomo 内核版本',
|
||||||
|
keywords: ['内核', '更新', 'kernel', 'update', '升级'],
|
||||||
|
tab: 'overview'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '安装内核',
|
||||||
|
description: '首次安装 mihomo 内核',
|
||||||
|
keywords: ['内核', '安装', 'kernel', 'install', '下载'],
|
||||||
|
tab: 'overview'
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -51,6 +139,10 @@ export const moduleConfig: ModuleConfig = {
|
|||||||
const s = await commands.proxyGetSettings()
|
const s = await commands.proxyGetSettings()
|
||||||
if (s.autoStart) {
|
if (s.autoStart) {
|
||||||
await commands.proxyStart()
|
await commands.proxyStart()
|
||||||
|
// 若同时开启了"启动时自动开启系统代理",则一并开启系统代理
|
||||||
|
if (s.autoSystemProxy) {
|
||||||
|
await commands.proxySetSystemProxy()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* 忽略:可能内核未安装 */
|
/* 忽略:可能内核未安装 */
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user