diff --git a/.gitignore b/.gitignore index d1ef8415b127c7fa45411f5ec8fea582e409db5d..7f78fe30547e09822cfb476a4d62d0da10d26724 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,4 @@ imgui.ini 7e644cf859a5e100a21ff67a63486ae0.json __pycache__/ +csharp/BrowserTool/db/sites.db diff --git a/csharp/BrowserTool/.cursorignore b/csharp/BrowserTool/.cursorignore new file mode 100644 index 0000000000000000000000000000000000000000..02193e824d812970b354ba347cadac10a4cd070d --- /dev/null +++ b/csharp/BrowserTool/.cursorignore @@ -0,0 +1,34 @@ +# Build outputs +bin/ +obj/ +dist/ +build/ + +# Dependencies +node_modules/ +packages/ +.vs/ + +# IDE files +.vscode/ +.idea/ + +# Logs and databases +*.log +*.sqlite +*.db + +# Temporary files +*.tmp +*.temp +*.swp +*~ + +# Large binary files +*.zip +*.rar +*.7z +*.tar +*.gz +*.iso +*.img \ No newline at end of file diff --git a/csharp/BrowserTool/.gitattributes b/csharp/BrowserTool/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..3e85c301857b88299cc96696cce47f4b013644fd --- /dev/null +++ b/csharp/BrowserTool/.gitattributes @@ -0,0 +1,72 @@ +*.7z filter=lfs diff=lfs merge=lfs -text +*.db filter=lfs diff=lfs merge=lfs -text +*.pdf filter=lfs diff=lfs merge=lfs -text +**/data/img/*.txt filter=lfs diff=lfs merge=lfs -text +src/WeChatOcrCpp/wco_data/**/* filter=lfs diff=lfs merge=lfs -text +*.aps filter=lfs diff=lfs merge=lfs -text +*.ico filter=lfs diff=lfs merge=lfs -text +*.pgm filter=lfs diff=lfs merge=lfs -text +*.exe filter=lfs diff=lfs merge=lfs -text +*.dll filter=lfs diff=lfs merge=lfs -text +*.lib filter=lfs diff=lfs merge=lfs -text +*.exp filter=lfs diff=lfs merge=lfs -text +data/img/*.txt filter=lfs diff=lfs merge=lfs -text +*.ttf filter=lfs diff=lfs merge=lfs -text +*.arrow filter=lfs diff=lfs merge=lfs -text +*.bin filter=lfs diff=lfs merge=lfs -text +*.bz2 filter=lfs diff=lfs merge=lfs -text +*.ckpt filter=lfs diff=lfs merge=lfs -text +*.ftz filter=lfs diff=lfs merge=lfs -text +*.gz filter=lfs diff=lfs merge=lfs -text +*.h5 filter=lfs diff=lfs merge=lfs -text +*.joblib filter=lfs diff=lfs merge=lfs -text +*.lfs.* filter=lfs diff=lfs merge=lfs -text +*.lz4 filter=lfs diff=lfs merge=lfs -text +*.mds filter=lfs diff=lfs merge=lfs -text +*.mlmodel filter=lfs diff=lfs merge=lfs -text +*.model filter=lfs diff=lfs merge=lfs -text +*.msgpack filter=lfs diff=lfs merge=lfs -text +*.npy filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text +*.ot filter=lfs diff=lfs merge=lfs -text +*.parquet filter=lfs diff=lfs merge=lfs -text +*.pb filter=lfs diff=lfs merge=lfs -text +*.pickle filter=lfs diff=lfs merge=lfs -text +*.pkl filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text +*.pth filter=lfs diff=lfs merge=lfs -text +*.rar filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +saved_model/**/* filter=lfs diff=lfs merge=lfs -text +*.tar.* filter=lfs diff=lfs merge=lfs -text +*.tar filter=lfs diff=lfs merge=lfs -text +*.tflite filter=lfs diff=lfs merge=lfs -text +*.tgz filter=lfs diff=lfs merge=lfs -text +*.wasm filter=lfs diff=lfs merge=lfs -text +*.xz filter=lfs diff=lfs merge=lfs -text +*.zip filter=lfs diff=lfs merge=lfs -text +*.zst filter=lfs diff=lfs merge=lfs -text +*tfevents* filter=lfs diff=lfs merge=lfs -text +# Audio files - uncompressed +*.pcm filter=lfs diff=lfs merge=lfs -text +*.sam filter=lfs diff=lfs merge=lfs -text +*.raw filter=lfs diff=lfs merge=lfs -text +# Audio files - compressed +*.aac filter=lfs diff=lfs merge=lfs -text +*.flac filter=lfs diff=lfs merge=lfs -text +*.mp3 filter=lfs diff=lfs merge=lfs -text +*.ogg filter=lfs diff=lfs merge=lfs -text +*.wav filter=lfs diff=lfs merge=lfs -text +# Image files - uncompressed +*.bmp filter=lfs diff=lfs merge=lfs -text +*.gif filter=lfs diff=lfs merge=lfs -text +*.png filter=lfs diff=lfs merge=lfs -text +*.tiff filter=lfs diff=lfs merge=lfs -text +# Image files - compressed +*.jpg filter=lfs diff=lfs merge=lfs -text +*.jpeg filter=lfs diff=lfs merge=lfs -text +*.webp filter=lfs diff=lfs merge=lfs -text +# Video files - compressed +*.mp4 filter=lfs diff=lfs merge=lfs -text +*.webm filter=lfs diff=lfs merge=lfs -text diff --git a/csharp/BrowserTool/.gitignore b/csharp/BrowserTool/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..31e08bafd9140be2e63cb1bb381cc3ec9c7fba05 --- /dev/null +++ b/csharp/BrowserTool/.gitignore @@ -0,0 +1,7 @@ +**/bin/ +**/obj/ +**/node_modules/ +**/packages/ +.vs +**/.vs/ +.vs/ diff --git a/csharp/BrowserTool/BrowserTool.sln b/csharp/BrowserTool/BrowserTool.sln new file mode 100644 index 0000000000000000000000000000000000000000..31a8e83978260331dea1b9e4b93d29ec97f86a27 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.12.35527.113 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BrowserTool", "BrowserTool\BrowserTool.csproj", "{D3A2273B-2DA3-4C63-9B54-DF3702B3D432}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Debug|Any CPU.ActiveCfg = Debug|x64 + {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Debug|Any CPU.Build.0 = Debug|x64 + {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D3A2273B-2DA3-4C63-9B54-DF3702B3D432}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/csharp/BrowserTool/BrowserTool/App.config b/csharp/BrowserTool/BrowserTool/App.config new file mode 100644 index 0000000000000000000000000000000000000000..c01eb64d96338fcb0b004b1aff2fd11072e8d11f --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/App.config @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/App.xaml b/csharp/BrowserTool/BrowserTool/App.xaml new file mode 100644 index 0000000000000000000000000000000000000000..d917afffe88c5af2828f14a3213fc308a4fd3927 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/App.xaml @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/csharp/BrowserTool/BrowserTool/App.xaml.cs b/csharp/BrowserTool/BrowserTool/App.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..f9b806f2c8c84052360c9aeed500ff3963c66626 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/App.xaml.cs @@ -0,0 +1,792 @@ +using System; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.IO.Pipes; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using CefSharp; +using Hardcodet.Wpf.TaskbarNotification; +using System.Runtime.InteropServices; +using BrowserTool.Database; +using BrowserTool.Utils; +using System.Windows.Controls; +using CefSharp.Wpf; +using FontStyle = System.Drawing.FontStyle; +using NLog; +using NLog.Config; +using NLog.Targets; + +namespace BrowserTool +{ + /// + /// App.xaml 的交互逻辑,提供应用程序的生命周期管理和单例模式支持 + /// + public partial class App : Application + { + #region 常量定义 + + private const string MUTEX_NAME = "BrowserTool_SingleInstance"; + private const string PIPE_NAME = "BrowserToolUrlPipe"; + private const string WINDOW_MESSAGE_NAME = "BrowserTool_ShowMainWindow"; + + #endregion + + #region Win32 API 导入 + + [DllImport("user32.dll", SetLastError = true)] + private static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern int RegisterWindowMessage(string lpString); + + [DllImport("user32.dll")] + private static extern bool SetForegroundWindow(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern bool IsIconic(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); + + [DllImport("user32.dll")] + private static extern bool PostMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); + + #endregion + + #region 字段和属性 + + /// + /// CEF初始化锁对象 + /// + private static readonly object _cefInitLock = new(); + + /// + /// 主窗口实例 + /// + private MainWindow _mainWindow; + + /// + /// 单例应用程序互斥锁 + /// + private static readonly Mutex _mutex = new(true, MUTEX_NAME); + + /// + /// 是否拥有互斥锁 + /// + private static bool _mutexOwned; + + /// + /// 命名管道服务器线程 + /// + private Thread _pipeServerThread; + + /// + /// 命名管道服务器取消令牌源 + /// + private CancellationTokenSource _pipeServerCancellation; + + /// + /// 鼠标活动模拟器 + /// + private static MouseActivitySimulator _mouseActivitySimulator; + + /// + /// 自动签到模拟器 + /// + private static AutoCheckInSimulator _checkInSimulator; + + /// + /// 自定义窗口消息ID + /// + private static readonly int WM_SHOWMAINWINDOW_CUSTOM = RegisterWindowMessage(WINDOW_MESSAGE_NAME); + + /// + /// 日志记录器 + /// + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + #endregion + + #region 托盘菜单事件处理 + + /// + /// 处理设置菜单点击事件 + /// + /// 事件发送者 + /// 事件参数 + private void TrayMenu_Settings_Click(object sender, RoutedEventArgs e) + { + if (!LoginManager.IsLoggedIn) return; + + try + { + var settingsWindow = new SettingsWindow + { + Owner = _mainWindow + }; + settingsWindow.ShowDialog(); + } + catch (Exception ex) + { + LogError("打开设置窗口时发生错误", ex); + ShowErrorMessage("无法打开设置窗口,请重试。"); + } + } + + /// + /// 处理退出菜单点击事件 + /// + /// 事件发送者 + /// 事件参数 + private void TrayMenu_Exit_Click(object sender, RoutedEventArgs e) => Shutdown(); + + /// + /// 处理修改密码菜单点击事件 + /// + /// 事件发送者 + /// 事件参数 + private void TrayMenu_ChangePassword_Click(object sender, RoutedEventArgs e) + { + if (!Utils.LoginManager.IsLoggedIn) return; + + try + { + var changePasswordWindow = new ChangePasswordWindow + { + Owner = _mainWindow + }; + changePasswordWindow.ShowDialog(); + } + catch (Exception ex) + { + LogError("打开修改密码窗口时发生错误", ex); + ShowErrorMessage("无法打开修改密码窗口,请重试。"); + } + } + + /// + /// 处理显示主窗口菜单点击事件 + /// + /// 事件发送者 + /// 事件参数 + private void TrayMenu_Show_Click(object sender, RoutedEventArgs e) + { + if (Utils.LoginManager.IsLoggedIn) + { + ShowMainWindow(); + } + } + + /// + /// 处理托盘图标双击事件 + /// + /// 事件发送者 + /// 事件参数 + private void TrayIcon_TrayMouseDoubleClick(object sender, RoutedEventArgs e) => ShowMainWindow(); + + #endregion + + #region 公共方法 + + /// + /// 显示主窗口并激活 + /// + public void ShowMainWindow() + { + if (_mainWindow == null) return; + + try + { + _mainWindow.Show(); + _mainWindow.WindowState = WindowState.Normal; + _mainWindow.Activate(); + + // 确保窗口在最前面,然后取消置顶 + _mainWindow.Topmost = true; + _mainWindow.Topmost = false; + } + catch (Exception ex) + { + LogError("显示主窗口时发生错误", ex); + } + } + + /// + /// 获取当前应用程序实例 + /// + /// 当前应用程序实例 + public static App GetCurrentApp() => Current as App; + + /// + /// 获取AutoCheckInSimulator实例 + /// + /// AutoCheckInSimulator实例 + public static AutoCheckInSimulator GetAutoCheckInSimulator() => _checkInSimulator; + + #endregion + + #region 私有方法 + + /// + /// 初始化CEF浏览器引擎 + /// + /// CEF初始化失败时抛出 + private void InitializeCef() + { + if (Cef.IsInitialized == true) return; + + lock (_cefInitLock) + { + if (Cef.IsInitialized == true) return; + + try + { + var settings = CreateCefSettings(); + Cef.Initialize(settings); + } + catch (Exception ex) + { + LogError("CEF初始化失败", ex); + ShowErrorMessage($"浏览器引擎初始化失败: {ex.Message}"); + throw new InvalidOperationException("CEF初始化失败", ex); + } + } + } + + /// + /// 创建CEF设置配置 + /// + /// 配置好的CEF设置 + private static CefSettings CreateCefSettings() + { + var settings = new CefSettings(); + string exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + ?? throw new InvalidOperationException("无法获取应用程序路径"); + + // 设置缓存路径 + string cachePath = Path.Combine(exePath, "CEF"); + Directory.CreateDirectory(cachePath); + settings.CachePath = cachePath; + + // 设置日志文件路径 + string logPath = Path.Combine(exePath, @"CEF\Log"); + Directory.CreateDirectory(logPath); + settings.LogFile = Path.Combine(logPath, "cef.log"); + + // 基本设置 + settings.Locale = "zh-CN"; + settings.PersistSessionCookies = true; + + // 性能优化设置 + ConfigureCefPerformance(settings); + + return settings; + } + + /// + /// 配置CEF性能优化参数 + /// + /// CEF设置对象 + private static void ConfigureCefPerformance(CefSettings settings) + { + var args = settings.CefCommandLineArgs; + + // 启用硬件加速 + args.Add("enable-gpu", "1"); + args.Add("enable-gpu-compositing", "1"); + args.Add("enable-gpu-rasterization", "1"); + + // 内存优化 + args.Add("disable-gpu-shader-disk-cache", "1"); + args.Add("renderer-process-limit", "1"); + args.Add("disable-extensions", "1"); + args.Add("disable-component-update", "1"); + } + + /// + /// 根据登录状态更新托盘菜单 + /// + /// 是否已登录 + private void UpdateTrayMenuState(bool isLoggedIn) + { + try + { + if (Current.Resources["TrayIcon"] is not TaskbarIcon trayIcon || + trayIcon.ContextMenu?.Items == null) return; + + foreach (var item in trayIcon.ContextMenu.Items) + { + if (item is not MenuItem menuItem) continue; + + switch (menuItem.Header?.ToString()) + { + case "设置": + UpdateMenuItem(menuItem, isLoggedIn, "请先登录后再使用设置功能"); + break; + case "修改密码": + UpdateMenuItem(menuItem, isLoggedIn, "请先登录后再修改密码"); + break; + } + } + + Debug.WriteLine($"[托盘菜单状态更新] 登录状态: {isLoggedIn}"); + } + catch (Exception ex) + { + LogError("更新托盘菜单状态时发生错误", ex); + } + } + + /// + /// 更新菜单项状态 + /// + /// 菜单项 + /// 是否启用 + /// 禁用时的提示文本 + private static void UpdateMenuItem(MenuItem menuItem, bool isEnabled, string disabledTooltip) + { + menuItem.IsEnabled = isEnabled; + menuItem.ToolTip = isEnabled ? null : disabledTooltip; + } + + /// + /// 启动命名管道服务器,用于接收其他实例发送的URL + /// + private void StartPipeServer() + { + _pipeServerCancellation = new CancellationTokenSource(); + var cancellationToken = _pipeServerCancellation.Token; + + _pipeServerThread = new Thread(() => RunPipeServer(cancellationToken)) + { + IsBackground = true, + Name = "PipeServerThread" + }; + _pipeServerThread.Start(); + } + + /// + /// 运行命名管道服务器循环 + /// + /// 取消令牌 + private void RunPipeServer(CancellationToken cancellationToken) + { + while (!cancellationToken.IsCancellationRequested) + { + try + { + using var pipeServer = new NamedPipeServerStream(PIPE_NAME, PipeDirection.In); + + // 使用异步等待连接,支持取消 + var connectTask = Task.Run(() => pipeServer.WaitForConnection(), cancellationToken); + connectTask.Wait(cancellationToken); + + using var reader = new StreamReader(pipeServer, Encoding.UTF8); + string url = reader.ReadLine(); + + if (!string.IsNullOrWhiteSpace(url)) + { + ProcessReceivedUrl(url); + } + } + catch (OperationCanceledException) + { + // 正常取消,退出循环 + break; + } + catch (Exception ex) + { + LogError("命名管道服务器运行时发生错误", ex); + + // 发生错误时短暂延迟后重试 + if (!cancellationToken.IsCancellationRequested) + { + Thread.Sleep(1000); + } + } + } + } + + /// + /// 处理从命名管道接收到的URL + /// + /// 接收到的URL + private void ProcessReceivedUrl(string url) + { + try + { + Dispatcher.BeginInvoke(new Action(() => + { + if (_mainWindow != null && Utils.LoginManager.IsLoggedIn) + { + _mainWindow.OpenUrlInTab("Loading...", url, false); + ShowMainWindow(); + } + })); + } + catch (Exception ex) + { + LogError("处理接收到的URL时发生错误", ex); + } + } + + /// + /// 通过命名管道发送URL到主实例 + /// + /// 要发送的URL + /// 是否发送成功 + private static bool SendUrlToPipe(string url) + { + try + { + using var pipeClient = new NamedPipeClientStream(".", PIPE_NAME, PipeDirection.Out); + pipeClient.Connect(1000); // 1秒超时 + + using var writer = new StreamWriter(pipeClient, Encoding.UTF8); + writer.WriteLine(url); + writer.Flush(); + + return true; + } + catch (Exception ex) + { + Debug.WriteLine($"[发送URL到管道失败] {ex.Message}"); + return false; + } + } + + /// + /// 初始化托盘图标 + /// + /// 是否初始化成功 + private bool InitializeTrayIcon() + { + try + { + if (Current.Resources["TrayIcon"] is not TaskbarIcon trayIcon) return false; + + var iconStream = GetResourceStream(new Uri("pack://application:,,,/Resources/app.ico"))?.Stream; + if (iconStream != null) + { + trayIcon.Icon = new Icon(iconStream); + } + + trayIcon.TrayMouseDoubleClick += TrayIcon_TrayMouseDoubleClick; + return true; + } + catch (Exception ex) + { + LogError("初始化托盘图标时发生错误", ex); + return false; + } + } + + /// + /// 处理命令行参数中的URL + /// + /// 命令行参数 + private void ProcessCommandLineUrl(string[] args) + { + if (args?.Length == 0) return; + + string url = args[0]; + if (string.IsNullOrWhiteSpace(url) || !IsValidUrl(url)) return; + + try + { + _mainWindow?.Dispatcher.Invoke(() => + { + _mainWindow.OpenUrlInTab("Loading...", url, false); + }); + } + catch (Exception ex) + { + LogError("处理命令行URL时发生错误", ex); + } + } + + /// + /// 验证URL格式是否有效 + /// + /// 要验证的URL + /// 是否为有效URL + private static bool IsValidUrl(string url) => + url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || + url.StartsWith("file://", StringComparison.OrdinalIgnoreCase); + + /// + /// 显示登录窗口并处理登录结果 + /// + /// 是否登录成功 + private bool ShowLoginWindow() + { + try + { + var loginWindow = new LoginWindow(); + if (loginWindow.ShowDialog() != true) return false; + + // 设置登录状态并订阅状态变化事件 + Utils.LoginManager.SetLoggedIn(); + Utils.LoginManager.OnLoginStatusChanged += UpdateTrayMenuState; + + // 初始化托盘菜单状态 + UpdateTrayMenuState(true); + + return true; + } + catch (Exception ex) + { + LogError("显示登录窗口时发生错误", ex); + ShowErrorMessage("登录窗口初始化失败,程序即将退出。"); + return false; + } + } + + /// + /// 记录错误日志 + /// + /// 错误消息 + /// 异常对象 + private static void LogError(string message, Exception exception) + { + _logger.Error($"[错误] {message}:", exception); + } + + /// + /// 显示错误消息框 + /// + /// 错误消息 + private static void ShowErrorMessage(string message) + { + MessageBox.Show(message, "错误", MessageBoxButton.OK, MessageBoxImage.Error); + } + + #endregion + + #region 应用程序生命周期 + + /// + /// 应用程序启动时的处理逻辑 + /// + /// 启动事件参数 + protected override void OnStartup(StartupEventArgs e) + { + base.OnStartup(e); + + try + { + // 初始化模拟器 + InitializeSimulators(); + + // 检查单例应用程序 + if (!CheckSingleInstance(e)) return; + + // 初始化应用程序核心组件 + if (!InitializeApplication(e)) return; + + // 显示登录窗口并处理结果 + if (ShowLoginWindow()) + { + ShowMainWindowAndActivate(); + } + else + { + Shutdown(); + } + } + catch (Exception ex) + { + MessageBox.Show($"应用程序启动失败: {ex.Message}\n{ex.StackTrace}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + /// + /// 初始化模拟器组件 + /// + private static void InitializeSimulators() + { + _checkInSimulator = new AutoCheckInSimulator(); + _checkInSimulator.Start(); + + _mouseActivitySimulator = new MouseActivitySimulator(); + _mouseActivitySimulator.Start(); + } + + /// + /// 检查单例应用程序实例 + /// + /// 启动参数 + /// 是否应该继续启动 + private bool CheckSingleInstance(StartupEventArgs e) + { + if (_mutex.WaitOne(TimeSpan.Zero, false)) + { + _mutexOwned = true; + StartPipeServer(); + return true; + } + + // 已有实例在运行,发送URL到主实例 + HandleExistingInstance(e.Args); + return false; + } + + /// + /// 处理已存在实例的情况 + /// + /// 命令行参数 + private void HandleExistingInstance(string[] args) + { + // 发送URL到主实例 + if (args?.Length > 0) + { + string url = args[0]; + if (IsValidUrl(url)) + { + SendUrlToPipe(url); + } + } + + // 激活已存在的窗口 + IntPtr hWnd = FindWindow(null, "Browser Tool"); + if (hWnd != IntPtr.Zero) + { + PostMessage(hWnd, WM_SHOWMAINWINDOW_CUSTOM, IntPtr.Zero, IntPtr.Zero); + } + + Shutdown(); + } + + /// + /// 初始化应用程序核心组件 + /// + /// 启动参数 + /// 是否初始化成功 + private bool InitializeApplication(StartupEventArgs e) + { + try + { + // 初始化CEF + InitializeCef(); + + // 初始化数据库 + //DatabaseInitializer.Initialize(); + + // 初始化托盘图标 + if (!InitializeTrayIcon()) return false; + + // 创建主窗口 + CreateMainWindow(e.Args); + + return true; + } + catch (Exception ex) + { + LogError("初始化应用程序组件时发生错误", ex); + return false; + } + } + + /// + /// 创建并配置主窗口 + /// + /// 命令行参数 + private void CreateMainWindow(string[] args) + { + _mainWindow = new MainWindow(); + MainWindow = _mainWindow; + + // 处理命令行参数 + ProcessCommandLineUrl(args); + + // 监听主窗口关闭事件 + _mainWindow.Closing += (_, e) => + { + e.Cancel = true; + _mainWindow.Hide(); + }; + } + + /// + /// 显示并激活主窗口 + /// + private void ShowMainWindowAndActivate() + { + _mainWindow.Show(); + _mainWindow.WindowState = WindowState.Normal; + _mainWindow.Activate(); + } + + /// + /// 应用程序退出时的清理逻辑 + /// + /// 退出事件参数 + protected override void OnExit(ExitEventArgs e) + { + try + { + CleanupResources(); + } + catch (Exception ex) + { + LogError("应用程序退出清理时发生错误", ex); + } + finally + { + base.OnExit(e); + } + } + + /// + /// 清理应用程序资源 + /// + private void CleanupResources() + { + // 释放互斥锁 + if (_mutexOwned) + { + _mutex.ReleaseMutex(); + _mutexOwned = false; + } + + // 停止模拟器 + _checkInSimulator?.Stop(); + _mouseActivitySimulator?.Stop(); + + // 停止命名管道服务器 + _pipeServerCancellation?.Cancel(); + _pipeServerThread?.Join(TimeSpan.FromSeconds(2)); + + // 清理浏览器相关资源 + CleanupBrowserResources(); + } + + /// + /// 清理浏览器相关资源 + /// + private static void CleanupBrowserResources() + { + try + { + Browser.BrowserInstanceManager.Instance?.CleanupAllBrowsers(); + ImageCache.ClearCache(); + + if (Cef.IsInitialized == true) + { + Cef.Shutdown(); + } + } + catch (Exception ex) + { + Debug.WriteLine($"清理浏览器资源时发生错误: {ex.Message}"); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs b/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..6d56803fa52e5ef03f756ab9aea85cdad77ace9e --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/BrowserInstanceManager.cs @@ -0,0 +1,214 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows; +using CefSharp; +using CefSharp.Wpf; + +namespace BrowserTool.Browser +{ + /// + /// 浏览器实例管理器,负责创建和管理浏览器实例 + /// 采用无缓存策略,确保每个标签页都是全新、干净的环境 + /// + public class BrowserInstanceManager + { + private static BrowserInstanceManager _instance; + private readonly Dictionary _activeBrowsers = new Dictionary(); + + // 单例模式 + public static BrowserInstanceManager Instance => _instance ??= new BrowserInstanceManager(); + + private BrowserInstanceManager() + { + // 私有构造函数,确保单例 + } + + /// + /// 创建一个新的浏览器实例 + /// + /// 要加载的URL(可为空,由调用方控制加载时机) + /// 标签页ID + /// 浏览器实例 + public ChromiumWebBrowser GetBrowser(string url, string tabId) + { + lock (_activeBrowsers) + { + // 如果该标签页已有浏览器实例,先清理 + if (_activeBrowsers.ContainsKey(tabId)) + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 标签页已存在浏览器实例,先清理 - TabId: {tabId}"); + ReleaseBrowser(tabId, dispose: true); + } + + // 总是创建全新的浏览器实例 + var browser = new ChromiumWebBrowser(); + + // 设置通用处理程序 + browser.DownloadHandler = new CefDownloadHandler(); + browser.MenuHandler = new CefMenuHandler(); + browser.LifeSpanHandler = new CefLifeSpanHandler(); + + // 添加页面加载完成事件,注入深色滚动条样式 + browser.FrameLoadEnd += (sender, args) => { + if (args.Frame.IsMain) + { + // 注入深色滚动条样式 + DarkThemeStyleInjector.InjectDarkThemeStyles(args.Frame); + } + }; + + // 注册到活动浏览器列表 + _activeBrowsers[tabId] = browser; + + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 创建新浏览器实例 - TabId: {tabId}"); + + // 只有在URL不为空且浏览器已初始化时才加载URL + if (!string.IsNullOrEmpty(url) && browser.IsBrowserInitialized) + { + browser.LoadUrl(url); + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 直接加载URL: {url}"); + } + else if (!string.IsNullOrEmpty(url)) + { + // 如果浏览器未初始化,等待初始化完成后加载 + DependencyPropertyChangedEventHandler browserInitializedHandler = null; + browserInitializedHandler = (sender, e) => + { + try + { + if (browser.IsBrowserInitialized) + { + browser.IsBrowserInitializedChanged -= browserInitializedHandler; + browser.LoadUrl(url); + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 浏览器初始化完成后加载URL: {url}"); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 延迟加载URL时发生异常: {ex.Message}"); + } + }; + browser.IsBrowserInitializedChanged += browserInitializedHandler; + } + + return browser; + } + } + + /// + /// 释放并销毁浏览器实例 + /// + /// 标签页ID + /// 是否销毁实例(默认为true,确保完全清理) + public void ReleaseBrowser(string tabId, bool dispose = true) + { + if (string.IsNullOrEmpty(tabId)) + { + System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] ReleaseBrowser: tabId为空"); + return; + } + + lock (_activeBrowsers) + { + if (_activeBrowsers.TryGetValue(tabId, out ChromiumWebBrowser browser)) + { + _activeBrowsers.Remove(tabId); + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 释放浏览器实例 - TabId: {tabId}"); + + // 总是销毁实例,确保完全清理 + DisposeBrowserInstance(browser, tabId); + } + else + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 未找到要释放的浏览器实例 - TabId: {tabId}"); + } + } + } + + /// + /// 安全地销毁浏览器实例 + /// + /// 浏览器实例 + /// 标签页ID + private void DisposeBrowserInstance(ChromiumWebBrowser browser, string tabId) + { + try + { + if (browser != null && !browser.IsDisposed) + { + // 清理事件处理器 + CleanupBrowserEventHandlers(browser); + + // 销毁浏览器实例 + browser.Dispose(); + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 浏览器实例已销毁 - TabId: {tabId}"); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 销毁浏览器实例时发生异常 - TabId: {tabId}, Error: {ex.Message}"); + } + } + + /// + /// 清理浏览器事件处理器 + /// + /// 浏览器实例 + private void CleanupBrowserEventHandlers(ChromiumWebBrowser browser) + { + try + { + if (browser?.Tag is Dictionary browserTags) + { + // 清理存储在Tag中的事件处理器引用 + if (browserTags.TryGetValue("titleUpdateHandler", out object titleHandler) && + titleHandler is EventHandler titleUpdateHandler) + { + browser.FrameLoadEnd -= titleUpdateHandler; + } + + if (browserTags.TryGetValue("loadingStateChangedHandler", out object loadingHandler) && + loadingHandler is EventHandler loadingStateChangedHandler) + { + browser.LoadingStateChanged -= loadingStateChangedHandler; + } + + browserTags.Clear(); + browser.Tag = null; + + System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] 浏览器事件处理器已清理"); + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 清理事件处理器时发生异常: {ex.Message}"); + } + } + + /// + /// 清理所有浏览器实例 + /// + public void CleanupAllBrowsers() + { + lock (_activeBrowsers) + { + // 清理所有活动的浏览器实例 + foreach (var kvp in _activeBrowsers.ToList()) + { + try + { + DisposeBrowserInstance(kvp.Value, kvp.Key); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"[BrowserInstanceManager] 清理浏览器实例时发生异常 - TabId: {kvp.Key}, Error: {ex.Message}"); + } + } + _activeBrowsers.Clear(); + + System.Diagnostics.Debug.WriteLine("[BrowserInstanceManager] 所有浏览器实例已清理"); + } + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs b/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d88b3563c68117b58e8ba962d6fc48d521f821b --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/BrowserTabManager.cs @@ -0,0 +1,79 @@ +using System.Windows.Controls; +using CefSharp; +using CefSharp.Wpf; + +namespace BrowserTool.Browser +{ + /// + /// 浏览器Tab管理器,负责Tab的添加、关闭等操作 + /// + public class BrowserTabManager + { + private TabControl _tabControl; + private MainWindow _mainWindow; + + public BrowserTabManager(TabControl tabControl, MainWindow mainWindow) + { + _tabControl = tabControl; + _mainWindow = mainWindow; + } + + /// + /// 添加新Tab + /// + public TabItem AddTab(string header, object content) + { + var tabItem = new TabItem(); + var customHeader = new CustomTabItem(); + customHeader.Content = header; + tabItem.Header = customHeader; + tabItem.Content = content; + + // 设置浏览器事件处理 + var chromiumBrowser = content as ChromiumWebBrowser; + if (chromiumBrowser != null) + { + var headerControl = tabItem.Header as CustomTabItem; + chromiumBrowser.TitleChanged += (s, e) => + { + if (headerControl != null) + { + headerControl.Content = e.NewValue; + } + }; + + chromiumBrowser.AddressChanged += (s, e) => + { + if (tabItem == _tabControl.SelectedItem) + { + var contentPresenter = tabItem.Content as ContentPresenter; + if (contentPresenter != null) + { + var grid = contentPresenter.Content as Grid; + if (grid != null) + { + var urlTextBox = grid.FindName("UrlTextBox") as TextBox; + if (urlTextBox != null) + { + urlTextBox.Text = chromiumBrowser.Address; + } + } + } + } + }; + } + + _tabControl.Items.Add(tabItem); + _tabControl.SelectedItem = tabItem; + return tabItem; + } + + /// + /// 关闭指定Tab + /// + public void CloseTab(TabItem tabItem) + { + _tabControl.Items.Remove(tabItem); + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs new file mode 100644 index 0000000000000000000000000000000000000000..33b7418dcd14de9e4587dedea83750b9e5ff9ac3 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CefDownloadHandler.cs @@ -0,0 +1,69 @@ +using CefSharp; +using System; +using System.Windows; + +namespace BrowserTool.Browser +{ + /// + /// CefSharp下载处理器,支持文件下载 + /// + public class CefDownloadHandler : IDownloadHandler + { + public event Action OnBeforeDownloadFired; + public event Action OnDownloadUpdatedFired; + + public bool OnBeforeDownload(IWebBrowser browserControl, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback) + { + // 下载前回调,可自定义保存路径 + Application.Current.Dispatcher.Invoke(() => + { + OnBeforeDownloadFired?.Invoke(downloadItem.SuggestedFileName); + // 新建或更新下载任务 + DownloadManager.Instance.AddOrUpdateTask(new DownloadTask + { + FileName = downloadItem.SuggestedFileName, + FullPath = downloadItem.FullPath, + ReceivedBytes = downloadItem.ReceivedBytes, + TotalBytes = downloadItem.TotalBytes, + IsComplete = false, + Status = "正在下载" + }); + }); + if (!callback.IsDisposed) + { + // 默认保存到用户下载目录 + string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads", downloadItem.SuggestedFileName); + callback.Continue(path, showDialog: true); + } + // 返回true表示下载应该继续 + return true; + } + + public void OnDownloadUpdated(IWebBrowser browserControl, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback) + { + // 下载进度更新 + Application.Current.Dispatcher.Invoke(() => + { + OnDownloadUpdatedFired?.Invoke(downloadItem.FullPath); + DownloadManager.Instance.AddOrUpdateTask(new DownloadTask + { + FileName = downloadItem.SuggestedFileName, + FullPath = downloadItem.FullPath, + ReceivedBytes = downloadItem.ReceivedBytes, + TotalBytes = downloadItem.TotalBytes, + IsComplete = downloadItem.IsComplete, + IsCancelled = downloadItem.IsCancelled, + IsError = downloadItem.IsCancelled || downloadItem.IsCancelled, + Status = downloadItem.IsComplete ? "已完成" : (downloadItem.IsCancelled ? "已取消" : "正在下载"), + Callback = callback + }); + }); + } + + // 新增:实现IDownloadHandler接口的CanDownload方法,允许所有下载 + public bool CanDownload(IWebBrowser browserControl, IBrowser browser, string url, string requestMethod) + { + return true; + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs b/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..d338e2742947d0913d96d63a842d496dae1c3b99 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CefHelper.cs @@ -0,0 +1,21 @@ +using CefSharp.Wpf; + +namespace BrowserTool.Browser +{ + /// + /// CefSharp浏览器辅助方法 + /// + public static class CefHelper + { + /// + /// 打开开发者工具(F12) + /// + public static void ShowDevTools(ChromiumWebBrowser browser) + { + if (browser != null && browser.GetBrowser() != null) + { + browser.GetBrowser().GetHost().ShowDevTools(); + } + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs new file mode 100644 index 0000000000000000000000000000000000000000..75d9593811c80f1343754770e71b3c80c64647dc --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CefLifeSpanHandler.cs @@ -0,0 +1,25 @@ +using CefSharp; +using CefSharp.Wpf; + +namespace BrowserTool.Browser +{ + /// + /// 拦截target=_blank等新窗口请求,在当前Tab打开 + /// + public class CefLifeSpanHandler : ILifeSpanHandler + { + public bool DoClose(IWebBrowser chromiumWebBrowser, IBrowser browser) => false; + public void OnAfterCreated(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + public void OnBeforeClose(IWebBrowser chromiumWebBrowser, IBrowser browser) { } + + public bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, + string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, + IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) + { + newBrowser = null; + // 在当前Tab打开新链接 + chromiumWebBrowser.Load(targetUrl); + return true; // 阻止新窗口 + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs b/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs new file mode 100644 index 0000000000000000000000000000000000000000..7967abc12565ab58503ee59649860e4ef0cf238a --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CefMenuHandler.cs @@ -0,0 +1,170 @@ +using CefSharp; +using System; +using System.Windows; +using System.Windows.Controls; +using System.Threading; +using System.Threading.Tasks; +using System.Windows.Controls.Primitives; +using BrowserTool; + +namespace BrowserTool.Browser +{ + /// + /// CefSharp右键菜单处理器,支持自定义菜单项 + /// + public class CefMenuHandler : IContextMenuHandler + { + private const int CMD_VIEW_SOURCE = 26501; + private const int CMD_COPY_URL = 26502; + private const int CMD_DOWNLOAD_MANAGER = 26503; + private const int CMD_TOGGLE_URL_BAR = 26504; + private const int CMD_GO_TO_URL = 26505; + private const int CMD_GO_TO_URL_NEW_WINDOW = 26506; + private const int CMD_REFRESH = 26507; + private const int CMD_OPEN_LINK_NEW_TAB = 26508; + private const int CMD_COPY_SELECTION = 26509; + + public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model) + { + // 清除默认菜单 + model.Clear(); + + // 如果右键点击的是链接,添加"在新标签页中打开"选项 + if (!string.IsNullOrEmpty(parameters.LinkUrl)) + { + model.AddItem((CefMenuCommand)CMD_OPEN_LINK_NEW_TAB, "在新标签页中打开"); + model.AddSeparator(); + } + + // 如果有选中的文本,添加复制选项 + if (!string.IsNullOrEmpty(parameters.SelectionText)) + { + model.AddItem((CefMenuCommand)CMD_COPY_SELECTION, "复制选中内容"); + model.AddSeparator(); + } + + model.AddItem((CefMenuCommand)CMD_VIEW_SOURCE, "查看源代码"); + model.AddItem((CefMenuCommand)CMD_COPY_URL, "复制网址"); + model.AddSeparator(); + model.AddItem((CefMenuCommand)CMD_DOWNLOAD_MANAGER, "下载管理器"); + model.AddSeparator(); + model.AddItem((CefMenuCommand)CMD_TOGGLE_URL_BAR, "显示/隐藏地址栏"); + model.AddItem((CefMenuCommand)CMD_GO_TO_URL, "粘贴并访问"); + model.AddItem((CefMenuCommand)CMD_GO_TO_URL_NEW_WINDOW, "粘贴并在新标签页中访问"); + model.AddSeparator(); + model.AddItem((CefMenuCommand)CMD_REFRESH, "刷新"); + } + + public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags) + { + //粘贴并前往 + if ((int)commandId == CMD_GO_TO_URL) + { + string clipboardText = Clipboard.GetText(); + if (!string.IsNullOrWhiteSpace(clipboardText) && (clipboardText.StartsWith("http://") || clipboardText.StartsWith("https://"))) + { + browserControl.Load(clipboardText); + } + return true; + } + //粘贴并在新标签页中访问 + if ((int)commandId == CMD_GO_TO_URL_NEW_WINDOW) + { + string clipboardText = Clipboard.GetText(); + if (!string.IsNullOrWhiteSpace(clipboardText) && (clipboardText.StartsWith("http://") || clipboardText.StartsWith("https://"))) + { + System.Windows.Application.Current.Dispatcher.Invoke(() => { + var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow; + if (mainWindow != null) + { + // 在新标签页中打开URL + // 直接使用 OpenUrlInTab 方法,并设置初始标题为 "Loading..." + // 浏览器会自动更新标题为网站标题 + mainWindow.Dispatcher.BeginInvoke(new Action(() => { + // 不传入 keepOriginalTitle 参数或设置为 false,允许标题动态更新 + mainWindow.OpenUrlInTab("Loading...", clipboardText, false); + })); + } + }); + } + return true; + } + if ((int)commandId == CMD_OPEN_LINK_NEW_TAB) + { + // 在新标签页中打开链接 + // 先保存LinkUrl,防止parameters对象被释放 + string linkUrl = parameters.LinkUrl; + System.Windows.Application.Current.Dispatcher.Invoke(() => { + var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow; + if (mainWindow != null) + { + mainWindow.Dispatcher.BeginInvoke(new Action(() => { + mainWindow.OpenUrlInTab("Loading...", linkUrl, false,false,0,null,false); + })); + } + }); + return true; + } + if ((int)commandId == CMD_VIEW_SOURCE) + { + // 查看源代码 + frame.ViewSource(); + return true; + } + if ((int)commandId == CMD_COPY_URL) + { + // 复制当前URL + Clipboard.SetText(frame.Url); + return true; + } + if ((int)commandId == CMD_DOWNLOAD_MANAGER) + { + // 打开下载管理器窗口 + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + BrowserTool.Browser.DownloadManagerWindow.ShowSingleton(); + }); + return true; + } + if ((int)commandId == CMD_TOGGLE_URL_BAR) + { + // 显示/隐藏地址栏 + System.Windows.Application.Current.Dispatcher.Invoke(() => + { + var mainWindow = System.Windows.Application.Current.MainWindow as MainWindow; + if (mainWindow != null) + { + mainWindow.ToggleUrlBar(); + } + }); + return true; + } + if ((int)commandId == CMD_REFRESH) + { + // 刷新页面 + browser.Reload(); + return true; + } + if ((int)commandId == CMD_COPY_SELECTION) + { + // 复制选中的内容 + if (!string.IsNullOrEmpty(parameters.SelectionText)) + { + Clipboard.SetText(parameters.SelectionText); + } + return true; + } + return false; + } + + public void OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame) + { + } + + public bool RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback) + { + // 返回 false 使用默认菜单显示方式 + return false; + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml new file mode 100644 index 0000000000000000000000000000000000000000..30e058608ac8d5fab292c0fbf9817ba3e122611f --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..ebe7f51660a06dc1b54f6880ed5369fe03820e5e --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/CustomTabItem.xaml.cs @@ -0,0 +1,115 @@ +using System.Windows; +using System.Windows.Controls; +using CefSharp; +using CefSharp.Wpf; +using System.Windows.Media; + +namespace BrowserTool.Browser +{ + /// + /// Chrome风格TabItem,带关闭按钮 + /// + public partial class CustomTabItem : UserControl + { + public CustomTabItem() + { + InitializeComponent(); + } + + // 关闭按钮点击事件,触发Tab关闭 + private void CloseButton_Click(object sender, RoutedEventArgs e) + { + // 向父级TabControl冒泡关闭事件 + var tabItem = this.FindParent(); + if (tabItem != null) + { + var tabControl = tabItem.FindParent(); + if (tabControl != null) + { + tabControl.Items.Remove(tabItem); + } + } + } + + // 复制标签页 + private void CopyTab_Click(object sender, RoutedEventArgs e) + { + var tabItem = this.FindParent(); + if (tabItem != null) + { + var tabControl = tabItem.FindParent(); + if (tabControl != null) + { + // 获取当前标签页的浏览器控件 + var browser = tabItem.Content as ChromiumWebBrowser; + if (browser != null) + { + // 获取当前URL + string currentUrl = browser.Address; + string currentTitle = browser.Title; + + // 创建新标签页 + var newTab = new TabItem(); + var newBrowser = new ChromiumWebBrowser(currentUrl); + + // 创建新的标题控件 + var newHeader = new CustomTabItem(); + newHeader.Content = GetNextTabTitle(currentTitle, tabControl); + + newTab.Header = newHeader; + newTab.Content = newBrowser; + + // 在当前标签页后插入新标签页 + int currentIndex = tabControl.Items.IndexOf(tabItem); + tabControl.Items.Insert(currentIndex + 1, newTab); + tabControl.SelectedItem = newTab; + } + } + } + } + + // 获取下一个标签页标题(自动添加数字) + private string GetNextTabTitle(string baseTitle, TabControl tabControl) + { + string newTitle = baseTitle; + int counter = 2; + + // 检查是否存在相同标题的标签页 + while (true) + { + bool exists = false; + foreach (TabItem item in tabControl.Items) + { + var header = item.Header as CustomTabItem; + if (header != null && header.Content.ToString() == newTitle) + { + exists = true; + break; + } + } + + if (!exists) + break; + + newTitle = $"{baseTitle} {counter}"; + counter++; + } + + return newTitle; + } + } + + // 辅助方法:查找父级控件 + public static class VisualTreeHelperExtensions + { + public static T FindParent(this DependencyObject child) where T : DependencyObject + { + DependencyObject parent = System.Windows.Media.VisualTreeHelper.GetParent(child); + while (parent != null && !(parent is T)) + { + parent = System.Windows.Media.VisualTreeHelper.GetParent(parent); + } + return parent as T; + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs b/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs new file mode 100644 index 0000000000000000000000000000000000000000..53c6bf950f7a2b937a0468b37892b8faf90f40b3 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/DarkThemeStyleInjector.cs @@ -0,0 +1,77 @@ +using CefSharp; +using System; +using System.Text; + +namespace BrowserTool.Browser +{ + /// + /// 负责向CefSharp浏览器注入深色主题样式的工具类 + /// + public class DarkThemeStyleInjector + { + // 深色滚动条CSS样式 + private const string DarkScrollbarCss = @" + ::-webkit-scrollbar { + width: 12px; + height: 12px; + background-color: #2D2D30; + } + + ::-webkit-scrollbar-track { + background-color: #2D2D30; + border-radius: 6px; + } + + ::-webkit-scrollbar-thumb { + background-color: #686868; + border-radius: 6px; + } + + ::-webkit-scrollbar-thumb:hover { + background-color: #9E9E9E; + } + + ::-webkit-scrollbar-thumb:active { + background-color: #BFBFBF; + } + + ::-webkit-scrollbar-corner { + background-color: #2D2D30; + } + "; + + /// + /// 将深色主题样式注入到浏览器中 + /// + /// 要注入样式的浏览器框架 + public static void InjectDarkThemeStyles(IFrame frame) + { + if (frame == null || !frame.IsValid) + return; + + // 创建一个JavaScript,将CSS样式注入到页面头部 + string script = @" + (function() { + var style = document.createElement('style'); + style.type = 'text/css'; + style.id = 'browser-tool-dark-theme'; + style.innerHTML = `" + DarkScrollbarCss + @"`; + + // 如果已存在相同ID的样式,则先移除 + var existingStyle = document.getElementById('browser-tool-dark-theme'); + if (existingStyle) { + existingStyle.parentNode.removeChild(existingStyle); + } + + // 将样式添加到文档头部 + (document.head || document.documentElement).appendChild(style); + + return true; + })(); + "; + + // 异步执行JavaScript + frame.ExecuteJavaScriptAsync(script); + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs b/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs new file mode 100644 index 0000000000000000000000000000000000000000..585a3ad1348d9950a5be2d58de250bee1892352b --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadManager.cs @@ -0,0 +1,57 @@ +using System.Collections.ObjectModel; +using System.Linq; + +namespace BrowserTool.Browser +{ + /// + /// 下载任务管理器,集中管理所有下载任务(单例) + /// + public class DownloadManager + { + private static DownloadManager _instance; + public static DownloadManager Instance => _instance ?? (_instance = new DownloadManager()); + + // 下载任务列表,便于UI绑定 + public ObservableCollection Tasks { get; } = new ObservableCollection(); + + /// + /// 添加或更新下载任务 + /// + public void AddOrUpdateTask(DownloadTask task) + { + // 检查是否存在相同文件名的正在下载的任务 + var existingTask = Tasks.FirstOrDefault(t => + t.FileName == task.FileName && + !t.IsComplete && + !t.IsCancelled && + !t.IsError); + + if (existingTask == null) + { + // 如果不存在,添加新任务 + Tasks.Add(task); + } + else + { + // 更新现有任务的进度和状态 + existingTask.ReceivedBytes = task.ReceivedBytes; + existingTask.TotalBytes = task.TotalBytes; + existingTask.IsComplete = task.IsComplete; + existingTask.IsCancelled = task.IsCancelled; + existingTask.IsError = task.IsError; + existingTask.Status = task.Status; + } + } + + /// + /// 移除任务 + /// + public void RemoveTask(DownloadTask task) + { + if (Tasks.Contains(task)) + { + Tasks.Remove(task); + } + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml new file mode 100644 index 0000000000000000000000000000000000000000..60ace68819d7c0c476114b3434ca214c58252588 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Browser/DownloadManagerWindow.xaml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..b04c10b70f67621d4cfa64fb5c116f49904deacd --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Controls/SearchBar.xaml.cs @@ -0,0 +1,221 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Input; +using CefSharp; +using CefSharp.Wpf; + +namespace BrowserTool.Controls +{ + /// + /// SearchBar.xaml 的交互逻辑 + /// + public partial class SearchBar : UserControl + { + private ChromiumWebBrowser _browser; + private int _currentMatchIndex = 0; + private int _totalMatches = 0; + private bool _isMatchCase = false; + + public event EventHandler CloseRequested; + + public bool IsMatchCase + { + get { return _isMatchCase; } + set + { + _isMatchCase = value; + UpdateMatchCaseButtonStyle(); + } + } + + public SearchBar() + { + InitializeComponent(); + UpdateUI(); + } + + public void SetBrowser(ChromiumWebBrowser browser) + { + _browser = browser; + } + + public void FocusSearchBox() + { + SearchTextBox.Focus(); + SearchTextBox.SelectAll(); + } + + private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e) + { + var searchText = SearchTextBox.Text; + + if (string.IsNullOrEmpty(searchText)) + { + StopFind(); + return; + } + + StartFind(searchText); + } + + private void SearchTextBox_KeyDown(object sender, KeyEventArgs e) + { + switch (e.Key) + { + case Key.Enter: + if (Keyboard.Modifiers == ModifierKeys.Shift) + { + FindPrevious(); + } + else + { + FindNext(); + } + e.Handled = true; + break; + case Key.Escape: + CloseRequested?.Invoke(this, EventArgs.Empty); + e.Handled = true; + break; + } + } + + private void PreviousButton_Click(object sender, RoutedEventArgs e) + { + FindPrevious(); + } + + private void NextButton_Click(object sender, RoutedEventArgs e) + { + FindNext(); + } + + private void MatchCaseButton_Click(object sender, RoutedEventArgs e) + { + IsMatchCase = !IsMatchCase; + + // 重新搜索 + var searchText = SearchTextBox.Text; + if (!string.IsNullOrEmpty(searchText)) + { + StartFind(searchText); + } + } + + private void CloseButton_Click(object sender, RoutedEventArgs e) + { + CloseRequested?.Invoke(this, EventArgs.Empty); + } + + private void StartFind(string searchText) + { + if (_browser == null || !_browser.IsBrowserInitialized) + return; + + try + { + _browser.Find(searchText, forward: true, matchCase: IsMatchCase, findNext: false); + + // 简单的UI更新,显示搜索中状态 + ResultCountText.Text = "搜索中..."; + SearchTextBox.Background = System.Windows.Media.Brushes.DarkSlateGray; + + // 启用按钮 + PreviousButton.IsEnabled = true; + NextButton.IsEnabled = true; + } + catch (Exception ex) + { + ResultCountText.Text = "搜索失败"; + SearchTextBox.Background = System.Windows.Media.Brushes.DarkRed; + } + } + + private void FindNext() + { + var searchText = SearchTextBox.Text; + if (string.IsNullOrEmpty(searchText) || _browser == null || !_browser.IsBrowserInitialized) + return; + + try + { + _browser.Find(searchText, forward: true, matchCase: IsMatchCase, findNext: true); + } + catch (Exception ex) + { + // 忽略错误 + } + } + + private void FindPrevious() + { + var searchText = SearchTextBox.Text; + if (string.IsNullOrEmpty(searchText) || _browser == null || !_browser.IsBrowserInitialized) + return; + + try + { + _browser.Find(searchText, forward: false, matchCase: IsMatchCase, findNext: true); + } + catch (Exception ex) + { + // 忽略错误 + } + } + + private void StopFind() + { + if (_browser == null || !_browser.IsBrowserInitialized) + return; + + try + { + _browser.StopFinding(clearSelection: true); + } + catch (Exception ex) + { + // 忽略错误 + } + + _currentMatchIndex = 0; + _totalMatches = 0; + UpdateUI(); + } + + private void UpdateUI() + { + if (_totalMatches > 0) + { + ResultCountText.Text = $"{_currentMatchIndex}/{_totalMatches}"; + SearchTextBox.Background = System.Windows.Media.Brushes.DarkSlateGray; + } + else if (!string.IsNullOrEmpty(SearchTextBox.Text)) + { + ResultCountText.Text = "0/0"; + SearchTextBox.Background = System.Windows.Media.Brushes.DarkRed; + } + else + { + ResultCountText.Text = "0/0"; + SearchTextBox.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(30, 30, 30)); + } + + PreviousButton.IsEnabled = !string.IsNullOrEmpty(SearchTextBox.Text); + NextButton.IsEnabled = !string.IsNullOrEmpty(SearchTextBox.Text); + } + + private void UpdateMatchCaseButtonStyle() + { + // 触发数据绑定更新 + var binding = MatchCaseButton.GetBindingExpression(Button.StyleProperty); + binding?.UpdateTarget(); + } + + public void Clear() + { + SearchTextBox.Clear(); + StopFind(); + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs b/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs new file mode 100644 index 0000000000000000000000000000000000000000..900600482edc7a2b4f52aada1d6496f14661491e --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Converters/BooleanToVisibilityConverter.cs @@ -0,0 +1,28 @@ +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Data; + +namespace BrowserTool.Converters +{ + public class BooleanToVisibilityConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is bool boolValue) + { + return boolValue ? Visibility.Visible : Visibility.Collapsed; + } + return Visibility.Collapsed; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) + { + if (value is Visibility visibility) + { + return visibility == Visibility.Visible; + } + return false; + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs b/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..0b1a0d000313ee9a408225d276665a439389363b --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/AppDbContext.cs @@ -0,0 +1,100 @@ +using Microsoft.EntityFrameworkCore; +using System; + +namespace BrowserTool.Database +{ + /// + /// 应用程序数据库上下文 + /// + public class AppDbContext : DbContext + { + /// + /// 站点组集合 + /// + public DbSet SiteGroups { get; set; } + + /// + /// 站点项集合 + /// + public DbSet SiteItems { get; set; } + + /// + /// 配置数据库连接 + /// + /// 数据库上下文选项构建器 + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + try + { + var dbPath = DatabaseInitializer.GetDbPath(); + optionsBuilder.UseSqlite($"Data Source={dbPath}"); + } + catch (Exception ex) + { + throw new Exception($"配置数据库连接时出错:{ex.Message}", ex); + } + } + + /// + /// 配置实体模型 + /// + /// 模型构建器 + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + try + { + // 配置 SiteGroup 实体 + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.SortOrder).HasDefaultValue(0); + entity.Property(e => e.IsEnabled).HasDefaultValue(true); + entity.Property(e => e.IsDefaultExpanded).HasDefaultValue(false); + entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + }); + + // 配置 SiteItem 实体 + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.DisplayName).IsRequired().HasMaxLength(200); + entity.Property(e => e.Url).IsRequired().HasMaxLength(500); + entity.Property(e => e.SortOrder).HasDefaultValue(0); + entity.Property(e => e.Username).HasMaxLength(200); + entity.Property(e => e.Password).HasMaxLength(200); + entity.Property(e => e.CommonUsername).HasMaxLength(200); + entity.Property(e => e.CommonPassword).HasMaxLength(200); + entity.Property(e => e.UseCommonCredentials).HasDefaultValue(false); + entity.Property(e => e.AutoLogin).HasDefaultValue(false); + entity.Property(e => e.IsEnabled).HasDefaultValue(true); + entity.Property(e => e.Icon).HasMaxLength(1000); + entity.Property(e => e.Description).HasMaxLength(1000); + entity.Property(e => e.Tags).HasMaxLength(500); + entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.AccessCount).HasDefaultValue(0); + entity.Property(e => e.UsernameSelector).HasMaxLength(200); + entity.Property(e => e.PasswordSelector).HasMaxLength(200); + entity.Property(e => e.CaptchaSelector).HasMaxLength(200); + entity.Property(e => e.LoginButtonSelector).HasMaxLength(200); + entity.Property(e => e.LoginPageFeature).HasMaxLength(500); + entity.Property(e => e.CaptchaValue).HasMaxLength(200); + entity.Property(e => e.CaptchaMode).HasDefaultValue(0); + entity.Property(e => e.GoogleSecret).HasMaxLength(200); + + // 配置外键关系 + entity.HasOne(e => e.Group) + .WithMany(g => g.Sites) + .HasForeignKey(e => e.GroupId) + .OnDelete(DeleteBehavior.Cascade); + }); + } + catch (Exception ex) + { + throw new Exception($"配置实体模型时出错:{ex.Message}", ex); + } + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs b/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..0f47a1e24816f707158d9f67ad90634ada252095 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/ApplicationDbContext.cs @@ -0,0 +1,58 @@ +using BrowserTool.Database.Entities; +using Microsoft.EntityFrameworkCore; +using System; +using System.IO; + +namespace BrowserTool.Database +{ + public class ApplicationDbContext : DbContext + { + private static readonly string DbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sites.db"); + + public DbSet SiteGroups { get; set; } + public DbSet SiteItems { get; set; } + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlite($"Data Source={DbPath}"); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + // Configure SiteGroup + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.Name).IsRequired().HasMaxLength(100); + entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.IsEnabled).HasDefaultValue(true); + entity.Property(e => e.SortOrder).HasDefaultValue(0); + }); + + // Configure SiteItem + modelBuilder.Entity(entity => + { + entity.HasKey(e => e.Id); + entity.Property(e => e.DisplayName).IsRequired().HasMaxLength(200); + entity.Property(e => e.Url).IsRequired().HasMaxLength(500); + entity.Property(e => e.CreateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.UpdateTime).HasDefaultValueSql("CURRENT_TIMESTAMP"); + entity.Property(e => e.IsEnabled).HasDefaultValue(true); + entity.Property(e => e.SortOrder).HasDefaultValue(0); + entity.Property(e => e.UseCommonCredentials).HasDefaultValue(false); + entity.Property(e => e.AutoLogin).HasDefaultValue(false); + entity.Property(e => e.AccessCount).HasDefaultValue(0); + entity.Property(e => e.CaptchaMode).HasDefaultValue(0); + + // Configure relationship + entity.HasOne(e => e.Group) + .WithMany(g => g.Sites) + .HasForeignKey(e => e.GroupId) + .OnDelete(DeleteBehavior.Cascade); + }); + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs b/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..492faea242c8c2fee2142cd60bc388fc37a2afc5 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/DatabaseInitializer.cs @@ -0,0 +1,66 @@ +using System; +using System.IO; +using System.Linq; +using Microsoft.EntityFrameworkCore; + +namespace BrowserTool.Database +{ + /// + /// 数据库初始化器 + /// + public static class DatabaseInitializer + { + /// + /// 初始化数据库 + /// + public static void Initialize() + { + // 确保数据库目录存在 + var dbPath = GetDbPath(); + var dbDirectory = Path.GetDirectoryName(dbPath); + if (!Directory.Exists(dbDirectory)) + { + Directory.CreateDirectory(dbDirectory); + } + + using (var context = new AppDbContext()) + { + try + { + // 确保数据库存在 + context.Database.EnsureCreated(); + + // 检查是否需要迁移 + var pendingMigrations = context.Database.GetPendingMigrations().ToList(); + if (pendingMigrations.Any()) + { + context.Database.Migrate(); + } + } + catch (Exception ex) + { + throw new Exception($"初始化数据库时出错:{ex.Message}", ex); + } + } + } + + /// + /// 获取数据库文件路径 + /// + /// 数据库文件的完整路径 + public static string GetDbPath() + { + try + { + // 获取应用程序目录 + var appPath = AppDomain.CurrentDomain.BaseDirectory; + var dbPath = Path.Combine(appPath, "sites.db"); + return dbPath; + } + catch (Exception ex) + { + throw new Exception($"获取数据库路径时出错:{ex.Message}", ex); + } + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs new file mode 100644 index 0000000000000000000000000000000000000000..636de23ee4de39e4c34deba6083cb8fdcb3dbbc2 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteGroup.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace BrowserTool.Database.Entities +{ + [Table("SiteGroups")] + public class SiteGroup + { + [Key] + public int Id { get; set; } + + [Required] + [MaxLength(100)] + public string Name { get; set; } + + public int SortOrder { get; set; } + + public bool IsEnabled { get; set; } + + /// + /// 是否默认展开(用于控制一级菜单的默认展开状态) + /// + public bool IsDefaultExpanded { get; set; } = false; + + public DateTime CreateTime { get; set; } + + public DateTime UpdateTime { get; set; } + + // Navigation property + public virtual ICollection Sites { get; set; } = new List(); + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs new file mode 100644 index 0000000000000000000000000000000000000000..57548130880e9c19fa78e27416c047ceb8b34024 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/Entities/SiteItem.cs @@ -0,0 +1,88 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace BrowserTool.Database.Entities +{ + [Table("SiteItems")] + public class SiteItem + { + [Key] + public int Id { get; set; } + + [Required] + public int GroupId { get; set; } + + [Required] + [MaxLength(200)] + public string DisplayName { get; set; } + + [Required] + [MaxLength(500)] + public string Url { get; set; } + + public int SortOrder { get; set; } + + [MaxLength(200)] + public string Username { get; set; } + + [MaxLength(200)] + public string Password { get; set; } + + [MaxLength(200)] + public string CommonUsername { get; set; } + + [MaxLength(200)] + public string CommonPassword { get; set; } + + public bool UseCommonCredentials { get; set; } + + public bool AutoLogin { get; set; } + + public bool IsEnabled { get; set; } + + [MaxLength(1000)] + public string Icon { get; set; } + + [MaxLength(1000)] + public string Description { get; set; } + + [MaxLength(500)] + public string Tags { get; set; } + + public DateTime CreateTime { get; set; } + + public DateTime UpdateTime { get; set; } + + public DateTime? LastAccessTime { get; set; } + + public int AccessCount { get; set; } + + [MaxLength(200)] + public string UsernameSelector { get; set; } + + [MaxLength(200)] + public string PasswordSelector { get; set; } + + [MaxLength(200)] + public string CaptchaSelector { get; set; } + + [MaxLength(200)] + public string LoginButtonSelector { get; set; } + + [MaxLength(500)] + public string LoginPageFeature { get; set; } + + [MaxLength(200)] + public string CaptchaValue { get; set; } + + public int CaptchaMode { get; set; } + + [MaxLength(200)] + public string GoogleSecret { get; set; } + + // Navigation property + [ForeignKey("GroupId")] + public virtual SiteGroup Group { get; set; } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs b/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs new file mode 100644 index 0000000000000000000000000000000000000000..bbf881d42febb584f0d87c577fa8fb12050562cd --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/Migrations/AddIsDefaultExpandedToSiteGroup.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace BrowserTool.Database.Migrations +{ + public partial class AddIsDefaultExpandedToSiteGroup : Migration + { + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "IsDefaultExpanded", + table: "SiteGroups", + type: "INTEGER", + nullable: false, + defaultValue: false); + } + + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "IsDefaultExpanded", + table: "SiteGroups"); + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs b/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs new file mode 100644 index 0000000000000000000000000000000000000000..9e5206ff23a2379280dc03f2bd401305ed1cc991 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/Migrations/InitialCreate.cs @@ -0,0 +1,104 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace BrowserTool.Database.Migrations +{ + public partial class InitialCreate : Migration + { + /// + /// 创建数据库表结构 + /// + /// 迁移构建器 + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "SiteGroups", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Name = table.Column(type: "TEXT", maxLength: 100, nullable: false), + SortOrder = table.Column(type: "INTEGER", nullable: false, defaultValue: 0), + IsEnabled = table.Column(type: "INTEGER", nullable: false, defaultValue: true), + CreateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + UpdateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP") + }, + constraints: table => + { + table.PrimaryKey("PK_SiteGroups", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "SiteItems", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + GroupId = table.Column(type: "INTEGER", nullable: false), + DisplayName = table.Column(type: "TEXT", maxLength: 200, nullable: false), + Url = table.Column(type: "TEXT", maxLength: 500, nullable: false), + SortOrder = table.Column(type: "INTEGER", nullable: false, defaultValue: 0), + Username = table.Column(type: "TEXT", maxLength: 200, nullable: true), + Password = table.Column(type: "TEXT", maxLength: 200, nullable: true), + CommonUsername = table.Column(type: "TEXT", maxLength: 200, nullable: true), + CommonPassword = table.Column(type: "TEXT", maxLength: 200, nullable: true), + UseCommonCredentials = table.Column(type: "INTEGER", nullable: false, defaultValue: false), + AutoLogin = table.Column(type: "INTEGER", nullable: false, defaultValue: false), + IsEnabled = table.Column(type: "INTEGER", nullable: false, defaultValue: true), + Icon = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + Description = table.Column(type: "TEXT", maxLength: 1000, nullable: true), + Tags = table.Column(type: "TEXT", maxLength: 500, nullable: true), + CreateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + UpdateTime = table.Column(type: "TEXT", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + LastAccessTime = table.Column(type: "TEXT", nullable: true), + AccessCount = table.Column(type: "INTEGER", nullable: false, defaultValue: 0), + UsernameSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true), + PasswordSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true), + CaptchaSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true), + LoginButtonSelector = table.Column(type: "TEXT", maxLength: 200, nullable: true), + LoginPageFeature = table.Column(type: "TEXT", maxLength: 500, nullable: true), + CaptchaValue = table.Column(type: "TEXT", maxLength: 200, nullable: true), + CaptchaMode = table.Column(type: "INTEGER", nullable: false, defaultValue: 0), + GoogleSecret = table.Column(type: "TEXT", maxLength: 200, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_SiteItems", x => x.Id); + table.ForeignKey( + name: "FK_SiteItems_SiteGroups_GroupId", + column: x => x.GroupId, + principalTable: "SiteGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_SiteItems_GroupId", + table: "SiteItems", + column: "GroupId"); + + migrationBuilder.CreateIndex( + name: "IX_SiteItems_SortOrder", + table: "SiteItems", + column: "SortOrder"); + + migrationBuilder.CreateIndex( + name: "IX_SiteGroups_SortOrder", + table: "SiteGroups", + column: "SortOrder"); + } + + /// + /// 删除数据库表结构 + /// + /// 迁移构建器 + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "SiteItems"); + + migrationBuilder.DropTable( + name: "SiteGroups"); + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs b/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..7377f6134be459197022dfbdd482e19e7c6bdf6d --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Database/SiteConfig.cs @@ -0,0 +1,553 @@ +using BrowserTool.Database.Entities; +using BrowserTool.Utils; +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace BrowserTool.Database +{ + public static class SiteConfig + { + /// + /// 添加数据变更事件 + /// + public static event EventHandler DataChanged; + + /// + /// 触发数据变更事件的方法 + /// + private static void OnDataChanged() + { + DataChanged?.Invoke(null, EventArgs.Empty); + } + + /// + /// 解密网站敏感信息 + /// + /// 要解密的网站对象 + private static void DecryptSiteInfo(SiteItem site) + { + if (site == null) return; + + try + { + // 检查DisplayName和Url是否已经是明文 + bool isDisplayNameEncrypted = IsEncryptedString(site.DisplayName); + bool isUrlEncrypted = IsEncryptedString(site.Url); + + + if (!string.IsNullOrEmpty(site.Username)) + { + try { site.Username = CryptoHelper.Decrypt(site.Username); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Username失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.Password)) + { + try { site.Password = CryptoHelper.Decrypt(site.Password); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Password失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.CommonUsername)) + { + try { site.CommonUsername = CryptoHelper.Decrypt(site.CommonUsername); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密CommonUsername失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.CommonPassword)) + { + try { site.CommonPassword = CryptoHelper.Decrypt(site.CommonPassword); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密CommonPassword失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.GoogleSecret)) + { + try { site.GoogleSecret = CryptoHelper.Decrypt(site.GoogleSecret); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密GoogleSecret失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.Url) && isUrlEncrypted) + { + try { site.Url = CryptoHelper.Decrypt(site.Url); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密Url失败: {ex}"); } + } + if (!string.IsNullOrEmpty(site.DisplayName) && isDisplayNameEncrypted) + { + try { site.DisplayName = CryptoHelper.Decrypt(site.DisplayName); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"解密DisplayName失败: {ex}"); } + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"解密站点信息时出错: {ex}"); + } + } + + private static bool IsEncryptedString(string str) + { + if (string.IsNullOrEmpty(str)) return false; + + // 检查是否是有效的Base64字符串 + if (!IsValidBase64String(str)) return false; + + // 检查长度是否足够长(加密后的字符串通常较长) + if (str.Length < 16) return false; + + return true; + } + + private static bool IsValidBase64String(string str) + { + if (string.IsNullOrEmpty(str)) return false; + + // 检查长度是否为4的倍数 + if (str.Length % 4 != 0) return false; + + // 检查是否只包含有效的Base64字符 + foreach (char c in str) + { + if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=')) + { + return false; + } + } + + // 检查填充字符 + int paddingCount = str.Count(c => c == '='); + if (paddingCount > 2) return false; + + return true; + } + + /// + /// 批量解密网站敏感信息 + /// + /// 要解密的网站集合 + private static void DecryptSiteInfoBatch(ICollection sites) + { + if (sites == null) return; + + foreach (var site in sites) + { + DecryptSiteInfo(site); + } + } + + /// + /// 获取所有启用的分组 + /// + /// 启用的分组列表 + public static List GetGroups() + { + using (var context = new AppDbContext()) + { + return context.SiteGroups + .Where(g => g.IsEnabled) + .OrderBy(g => g.SortOrder) + .ThenBy(g => g.Name) + .ToList(); + } + } + + /// + /// 根据分组ID获取该分组下的所有网站 + /// + /// 分组ID + /// 该分组下的网站列表 + public static List GetSitesByGroup(int groupId) + { + using (var context = new AppDbContext()) + { + var sites = context.SiteItems + .Where(s => s.GroupId == groupId && s.IsEnabled) + .OrderBy(s => s.SortOrder) + .ThenBy(s => s.DisplayName) + .ToList(); + + // 解密敏感信息 + DecryptSiteInfoBatch(sites); + + return sites; + } + } + + /// + /// 保存分组信息 + /// + /// 要保存的分组 + public static void SaveGroup(SiteGroup group) + { + using (var context = new AppDbContext()) + { + if (group.Id == 0) + { + group.CreateTime = DateTime.Now; + group.UpdateTime = DateTime.Now; + context.SiteGroups.Add(group); + } + else + { + var existingGroup = context.SiteGroups.Find(group.Id); + if (existingGroup != null) + { + context.Entry(existingGroup).CurrentValues.SetValues(group); + existingGroup.UpdateTime = DateTime.Now; + } + } + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + + /// + /// 保存网站信息 + /// + /// 要保存的网站 + public static void SaveSite(SiteItem site) + { + using (var context = new AppDbContext()) + { + // 创建副本以避免修改原对象 + var siteToSave = new SiteItem + { + Id = site.Id, + GroupId = site.GroupId, + DisplayName = site.DisplayName, + Username = site.Username, + Password = site.Password, + CommonUsername = site.CommonUsername, + CommonPassword = site.CommonPassword, + GoogleSecret = site.GoogleSecret, + Url = site.Url, + IsEnabled = site.IsEnabled, + SortOrder = site.SortOrder, + CreateTime = site.CreateTime, + UpdateTime = site.UpdateTime, + LastAccessTime = site.LastAccessTime, + Icon = site.Icon, + AccessCount = site.AccessCount + }; + + // 加密敏感信息 + if (!string.IsNullOrEmpty(siteToSave.Username)) + { + siteToSave.Username = CryptoHelper.Encrypt(siteToSave.Username); + } + if (!string.IsNullOrEmpty(siteToSave.Password)) + { + siteToSave.Password = CryptoHelper.Encrypt(siteToSave.Password); + } + if (!string.IsNullOrEmpty(siteToSave.CommonUsername)) + { + siteToSave.CommonUsername = CryptoHelper.Encrypt(siteToSave.CommonUsername); + } + if (!string.IsNullOrEmpty(siteToSave.CommonPassword)) + { + siteToSave.CommonPassword = CryptoHelper.Encrypt(siteToSave.CommonPassword); + } + if (!string.IsNullOrEmpty(siteToSave.GoogleSecret)) + { + siteToSave.GoogleSecret = CryptoHelper.Encrypt(siteToSave.GoogleSecret); + } + if (!string.IsNullOrEmpty(siteToSave.Url)) + { + siteToSave.Url = CryptoHelper.Encrypt(siteToSave.Url); + } + if (!string.IsNullOrEmpty(siteToSave.DisplayName)) + { + siteToSave.DisplayName = CryptoHelper.Encrypt(siteToSave.DisplayName); + } + + if (siteToSave.Id == 0) + { + siteToSave.CreateTime = DateTime.Now; + siteToSave.UpdateTime = DateTime.Now; + context.SiteItems.Add(siteToSave); + } + else + { + var existingSite = context.SiteItems.Find(siteToSave.Id); + if (existingSite != null) + { + context.Entry(existingSite).CurrentValues.SetValues(siteToSave); + existingSite.UpdateTime = DateTime.Now; + } + } + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + + /// + /// 删除指定ID的分组 + /// + /// 要删除的分组ID + public static void DeleteGroup(int groupId) + { + using (var context = new AppDbContext()) + { + var group = context.SiteGroups.Find(groupId); + if (group != null) + { + context.SiteGroups.Remove(group); + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + } + + /// + /// 删除指定ID的网站 + /// + /// 要删除的网站ID + public static void DeleteSite(int siteId) + { + using (var context = new AppDbContext()) + { + var site = context.SiteItems.Find(siteId); + if (site != null) + { + context.SiteItems.Remove(site); + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + } + + /// + /// 更新网站的访问信息 + /// + /// 要更新的网站ID + public static void UpdateSiteAccess(int siteId) + { + using (var context = new AppDbContext()) + { + var site = context.SiteItems.Find(siteId); + if (site != null) + { + site.LastAccessTime = DateTime.Now; + site.AccessCount++; + context.SaveChanges(); + } + } + } + + /// + /// 获取所有分组(包括未启用的) + /// + /// 所有分组的列表 + public static List GetAllGroups() + { + try + { + using (var context = new AppDbContext()) + { + // 检查数据库连接 + System.Diagnostics.Debug.WriteLine($"数据库路径: {DatabaseInitializer.GetDbPath()}"); + + // 检查是否有任何分组 + var groupCount = context.SiteGroups.Count(); + + // 先获取所有分组,不使用Include + var groups = context.SiteGroups + .OrderBy(g => g.SortOrder) + .ThenBy(g => g.Name) + .ToList(); + + // 手动加载每个分组的站点并解密 + foreach (var group in groups) + { + try + { + // 确保IsDefaultExpanded有有效值 + if (group.IsDefaultExpanded != true && group.IsDefaultExpanded != false) + { + System.Diagnostics.Debug.WriteLine($"警告:分组 {group.Name} (ID: {group.Id}) 的IsDefaultExpanded值无效,设置为默认值false"); + group.IsDefaultExpanded = false; + } + + // 获取站点数据 + var sites = context.SiteItems + .Where(s => s.GroupId == group.Id) + .OrderBy(s => s.SortOrder) + .ToList(); + + + // 检查每个站点的数据 + foreach (var site in sites) + { + try + { + + // 确保所有必需字段都有有效值 + if (string.IsNullOrEmpty(site.DisplayName)) + { + System.Diagnostics.Debug.WriteLine($"警告:站点 ID={site.Id} 的DisplayName为空"); + site.DisplayName = "未命名站点"; + } + if (string.IsNullOrEmpty(site.Url)) + { + System.Diagnostics.Debug.WriteLine($"警告:站点 ID={site.Id} 的Url为空"); + site.Url = "about:blank"; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"处理站点 ID={site.Id} 时出错: {ex}"); + } + } + + group.Sites = sites; + + // 解密站点敏感信息 + if (group.Sites != null) + { + try + { + DecryptSiteInfoBatch(group.Sites); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"解密分组 {group.Name} 的站点信息时出错: {ex}"); + } + } + + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"处理分组 {group.Name} (ID: {group.Id}) 时出错: {ex}"); + throw; + } + } + + return groups; + } + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"获取分组时出错: {ex}"); + throw; + } + } + + /// + /// 获取所有网站(包括未启用的) + /// + /// 所有网站的列表 + public static List GetAllSites() + { + using (var context = new AppDbContext()) + { + var sites = context.SiteItems + .OrderBy(s => s.SortOrder) + .ThenBy(s => s.DisplayName) + .ToList(); + + // 解密敏感信息 + DecryptSiteInfoBatch(sites); + + return sites; + } + } + + /// + /// 初始化数据库 + /// + public static void InitializeDatabase() + { + DatabaseInitializer.Initialize(); + } + + /// + /// 添加分组 + /// + /// 要添加的分组 + public static void AddGroup(SiteGroup group) + { + using (var context = new AppDbContext()) + { + context.SiteGroups.Add(group); + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + + /// + /// 更新分组 + /// + /// 要更新的分组 + public static void UpdateGroup(SiteGroup group) + { + using (var context = new AppDbContext()) + { + context.SiteGroups.Update(group); + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + + /// + /// 添加网站 + /// + /// 要添加的网站 + public static void AddSite(SiteItem site) + { + using (var context = new AppDbContext()) + { + // 创建副本并加密敏感信息 + var siteToAdd = new SiteItem + { + GroupId = site.GroupId, + DisplayName = !string.IsNullOrEmpty(site.DisplayName) ? CryptoHelper.Encrypt(site.DisplayName) : site.DisplayName, + Username = !string.IsNullOrEmpty(site.Username) ? CryptoHelper.Encrypt(site.Username) : site.Username, + Password = !string.IsNullOrEmpty(site.Password) ? CryptoHelper.Encrypt(site.Password) : site.Password, + CommonUsername = !string.IsNullOrEmpty(site.CommonUsername) ? CryptoHelper.Encrypt(site.CommonUsername) : site.CommonUsername, + CommonPassword = !string.IsNullOrEmpty(site.CommonPassword) ? CryptoHelper.Encrypt(site.CommonPassword) : site.CommonPassword, + GoogleSecret = !string.IsNullOrEmpty(site.GoogleSecret) ? CryptoHelper.Encrypt(site.GoogleSecret) : site.GoogleSecret, + Url = !string.IsNullOrEmpty(site.Url) ? CryptoHelper.Encrypt(site.Url) : site.Url, + IsEnabled = site.IsEnabled, + SortOrder = site.SortOrder, + CreateTime = DateTime.Now, + UpdateTime = DateTime.Now, + LastAccessTime = site.LastAccessTime, + AccessCount = site.AccessCount + }; + + context.SiteItems.Add(siteToAdd); + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + + /// + /// 更新网站 + /// + /// 要更新的网站 + public static void UpdateSite(SiteItem site) + { + using (var context = new AppDbContext()) + { + var existingSite = context.SiteItems.Find(site.Id); + if (existingSite != null) + { + // 更新非敏感字段 + existingSite.GroupId = site.GroupId; + //existingSite.DisplayName = site.DisplayName; + existingSite.IsEnabled = site.IsEnabled; + existingSite.SortOrder = site.SortOrder; + existingSite.UpdateTime = DateTime.Now; + existingSite.LastAccessTime = site.LastAccessTime; + existingSite.AccessCount = site.AccessCount; + + // 加密并更新敏感字段 + existingSite.Username = !string.IsNullOrEmpty(site.Username) ? CryptoHelper.Encrypt(site.Username) : site.Username; + existingSite.Password = !string.IsNullOrEmpty(site.Password) ? CryptoHelper.Encrypt(site.Password) : site.Password; + existingSite.CommonUsername = !string.IsNullOrEmpty(site.CommonUsername) ? CryptoHelper.Encrypt(site.CommonUsername) : site.CommonUsername; + existingSite.CommonPassword = !string.IsNullOrEmpty(site.CommonPassword) ? CryptoHelper.Encrypt(site.CommonPassword) : site.CommonPassword; + existingSite.GoogleSecret = !string.IsNullOrEmpty(site.GoogleSecret) ? CryptoHelper.Encrypt(site.GoogleSecret) : site.GoogleSecret; + existingSite.Url = !string.IsNullOrEmpty(site.Url) ? CryptoHelper.Encrypt(site.Url) : site.Url; + existingSite.DisplayName = !string.IsNullOrEmpty(site.DisplayName) ? CryptoHelper.Encrypt(site.DisplayName) : site.DisplayName; + + context.SaveChanges(); + OnDataChanged(); // 触发数据变更事件 + } + } + } + } +} \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml new file mode 100644 index 0000000000000000000000000000000000000000..e5e557a594c4aa9c46e74a669b53824f23ab1149 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/GroupEditDialog.xaml @@ -0,0 +1,122 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs b/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs new file mode 100644 index 0000000000000000000000000000000000000000..f7bbf9abf890fc2adbb2d02b407aec77d6415fe0 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/MainWindow.xaml.cs @@ -0,0 +1,2413 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Configuration; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Security.Policy; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Data; +using System.Windows.Documents; +using System.Windows.Input; +using System.Windows.Interop; +using System.Windows.Media; +using System.Windows.Media.Animation; +using System.Windows.Media.Imaging; +using System.Windows.Navigation; +using System.Windows.Shapes; +using System.Windows.Threading; +using BrowserTool.Browser; +using BrowserTool.Database; +using BrowserTool.Database.Entities; +using BrowserTool.Utils; +using CefSharp; +using CefSharp.Wpf; +using Hardcodet.Wpf.TaskbarNotification; +using NLog; + +namespace BrowserTool; + +/// +/// 标签页信息类,用于存储标签页的URL和ID +/// +public sealed record TabInfo +{ + /// + /// 获取或设置当前URL + /// + public string Url { get; set; } = string.Empty; + + /// + /// 获取或设置标签页唯一标识符 + /// + public string TabId { get; set; } = string.Empty; + + /// + /// 获取或设置原始URL,用于标识标签页来源的菜单项 + /// + public string OriginalUrl { get; set; } = string.Empty; + + /// + /// 获取或设置菜单项ID,用于唯一标识来源的二级菜单 + /// + public int? MenuItemId { get; set; } + + /// + /// 获取或设置菜单项标题,用于显示和调试 + /// + public string MenuItemTitle { get; set; } = string.Empty; +} + +/// +/// MainWindow.xaml 的交互逻辑类 +/// +public partial class MainWindow : Window +{ + #region 嵌套类型定义 + + /// + /// 菜单组数据结构 + /// + public sealed record MenuGroup + { + /// + /// 获取或设置组名称 + /// + public string GroupName { get; set; } = string.Empty; + + /// + /// 获取或设置是否默认展开 + /// + public bool IsDefaultExpanded { get; set; } + + /// + /// 获取或设置菜单项列表 + /// + public List Items { get; set; } = new(); + } + + /// + /// 菜单项数据结构 + /// + public sealed record MenuItemData + { + /// + /// 获取或设置菜单项的数据库ID + /// + public int Id { get; set; } + + /// + /// 获取或设置菜单项名称 + /// + public string Name { get; set; } = string.Empty; + + /// + /// 获取或设置菜单项URL + /// + public string Url { get; set; } = string.Empty; + + /// + /// 获取或设置菜单项图标 + /// + public string Icon { get; set; } = string.Empty; + } + + /// + /// 浏览器上下文类,实现属性变更通知 + /// + public sealed class BrowserContext : INotifyPropertyChanged + { + private bool _isLoading; + + /// + /// 获取或设置是否正在加载 + /// + public bool IsLoading + { + get => _isLoading; + set + { + if (_isLoading != value) + { + _isLoading = value; + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsLoading))); + } + } + } + + /// + /// 属性变更通知事件 + /// + public event PropertyChangedEventHandler? PropertyChanged; + } + + + + #endregion + + #region 字段和属性 + + /// + /// 菜单数据集合 + /// + private readonly List _menuGroups = new(); + + /// + /// 抽屉是否打开 + /// + private bool _isDrawerOpen = true; + + /// + /// 最后的窗口状态 + /// + private WindowState _lastWindowState = WindowState.Normal; + + /// + /// 恢复边界 + /// + private Rect _restoreBounds; + + /// + /// 日志记录器 + /// + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + /// + /// Windows消息常量 + /// + private static readonly int WM_SHOWMAINWINDOW = RegisterWindowMessage("BrowserTool_ShowMainWindow"); + + /// + /// 获取抽屉是否打开状态 + /// + public bool IsDrawerOpen => _isDrawerOpen; + + #endregion + + #region Windows API 声明 + + /// + /// 注册自定义Windows消息 + /// + /// 消息字符串 + /// 消息ID + [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] + private static extern int RegisterWindowMessage(string lpString); + + #endregion + + #region 构造函数 + + /// + /// 初始化MainWindow的新实例 + /// + public MainWindow() + { + try + { + InitializeComponent(); + InitializeMainWindow(); + } + catch (Exception ex) + { + _logger.Error("初始化主窗口时发生异常", ex); + Application.Current.Shutdown(); + } + } + + /// + /// 初始化主窗口设置 + /// + private void InitializeMainWindow() + { + // 监听标签页切换 + MainTabControl.SelectionChanged += MainTabControl_SelectionChanged; + + // 窗口居中显示 + WindowStartupLocation = WindowStartupLocation.CenterScreen; + + // 订阅数据变更事件 + SiteConfig.DataChanged += OnDataChanged; + + // 添加Windows消息处理 + SourceInitialized += MainWindow_SourceInitialized; + + // 订阅登录状态变化事件 + LoginManager.OnLoginStatusChanged += OnLoginStatusChanged; + + // 设置ContextMenu的PlacementTarget + TabContextMenu.Opened += (s, e) => + { + if (TabContextMenu.PlacementTarget == null) + { + TabContextMenu.PlacementTarget = MainTabControl; + } + }; + + // 根据配置控制手动打卡按钮的显示 + bool showManualCheckInButton = true; + if (bool.TryParse(ConfigurationManager.AppSettings["ShowManualCheckInButton"], out bool configValue)) + { + showManualCheckInButton = configValue; + } + ManualCheckInButton.Visibility = showManualCheckInButton ? Visibility.Visible : Visibility.Collapsed; + } + + #endregion + + #region Windows 消息处理 + + /// + /// 窗口源初始化事件处理器 + /// + private void MainWindow_SourceInitialized(object sender, EventArgs e) + { + var source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); + source.AddHook(WndProc); + } + + /// + /// Windows消息处理程序 + /// + /// 窗口句柄 + /// 消息类型 + /// 消息参数 + /// 消息参数 + /// 是否已处理 + /// 处理结果 + private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) + { + if (msg == WM_SHOWMAINWINDOW) + { + _logger.Debug($"收到WM_SHOWMAINWINDOW消息: {msg}"); + + Dispatcher.BeginInvoke(new Action(() => + { + var app = App.GetCurrentApp(); + if (app is not null) + { + _logger.Debug("调用App.ShowMainWindow"); + app.ShowMainWindow(); + } + else + { + _logger.Debug("App实例为null"); + } + })); + + handled = true; + } + + return IntPtr.Zero; + } + + #endregion + + #region 数据变更处理 + + /// + /// 数据变更事件处理器 + /// + private void OnDataChanged(object sender, EventArgs e) => + Dispatcher.Invoke(LoadMenuGroupsFromDb); + + /// + /// 登录状态变化事件处理器 + /// + /// 是否已登录 + private void OnLoginStatusChanged(bool isLoggedIn) + { + Dispatcher.BeginInvoke(new Action(() => + { + if (isLoggedIn) + { + RefreshMenuFromSettings(); + } + })); + } + + #endregion + + #region 资源清理 + + /// + /// 窗口关闭时的清理工作 + /// + protected override void OnClosed(EventArgs e) + { + base.OnClosed(e); + SiteConfig.DataChanged -= OnDataChanged; + } + + #endregion + + #region 菜单管理 + + /// + /// 从数据库加载菜单组数据 + /// + private void LoadMenuGroupsFromDb() + { + try + { + SiteConfig.InitializeDatabase(); + var allGroups = SiteConfig.GetAllGroups(); + + _logger.Debug($"加载到 {allGroups.Count} 个分组"); + + _menuGroups.Clear(); + _menuGroups.AddRange(allGroups.Select(g => new MenuGroup + { + GroupName = g.Name, + IsDefaultExpanded = g.IsDefaultExpanded, + Items = g.Sites + .Where(s => s.IsEnabled) + .OrderBy(s => s.SortOrder) + .Select(s => new MenuItemData + { + Id = s.Id, + Name = s.DisplayName, + Url = s.Url, + Icon = s.Icon + }).ToList() + })); + + RefreshMenuTreeUI(); + } + catch (Exception ex) + { + _logger.Error("加载菜单数据时出错", ex); + MessageBox.Show($"加载菜单数据时出错:{ex.Message}", "错误", + MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + /// + /// 刷新菜单树UI + /// + private void RefreshMenuTreeUI() + { + if (MenuTree is null) + { + return; + } + + MenuTree.Items.Clear(); + + foreach (var group in _menuGroups) + { + var groupItem = new TreeViewItem + { + Header = group.GroupName, + IsExpanded = group.IsDefaultExpanded + }; + + foreach (var item in group.Items) + { + var stackPanel = CreateMenuItemPanel(item); + var subItem = new TreeViewItem { Header = stackPanel, Tag = item }; + groupItem.Items.Add(subItem); + } + + MenuTree.Items.Add(groupItem); + } + + _logger.Debug($"UI 更新完成,共添加 {MenuTree.Items.Count} 个分组"); + } + + /// + /// 创建菜单项面板 + /// + /// 菜单项数据 + /// 菜单项面板 + private StackPanel CreateMenuItemPanel(MenuItemData item) + { + var stackPanel = new StackPanel { Orientation = Orientation.Horizontal }; + + if (!string.IsNullOrEmpty(item.Icon)) + { + var image = CreateMenuItemIcon(item.Icon); + if (image is not null) + { + stackPanel.Children.Add(image); + } + } + + var textBlock = new TextBlock + { + Text = item.Name, + VerticalAlignment = VerticalAlignment.Center, + Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#CCCCCC")) + }; + + stackPanel.Children.Add(textBlock); + return stackPanel; + } + + /// + /// 创建菜单项图标 + /// + /// 图标路径 + /// 图像控件,如果创建失败则返回null + private Image? CreateMenuItemIcon(string iconPath) + { + try + { + var image = new Image + { + Width = 16, + Height = 16, + Margin = new Thickness(0, 0, 5, 0) + }; + + var bitmap = Utils.ImageCache.GetImage(iconPath); + if (bitmap is not null) + { + image.Source = bitmap; + return image; + } + } + catch (Exception ex) + { + _logger.Error("加载图标时出错", ex); + } + + return null; + } + + /// + /// 初始化左侧菜单树,支持可选过滤 + /// + /// 过滤条件 + private void InitMenuTree(string filter = "") + { + MenuTree.Items.Clear(); + + foreach (var group in _menuGroups) + { + var filteredItems = string.IsNullOrWhiteSpace(filter) + ? group.Items + : group.Items.Where(i => i.Name.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToList(); + + if (filteredItems.Count == 0 && !string.IsNullOrWhiteSpace(filter)) + { + continue; + } + + var groupItem = new TreeViewItem + { + Header = group.GroupName, + IsExpanded = group.IsDefaultExpanded + }; + + foreach (var item in filteredItems) + { + var stackPanel = CreateMenuItemPanel(item); + var subItem = new TreeViewItem { Header = stackPanel, Tag = item }; + groupItem.Items.Add(subItem); + } + + MenuTree.Items.Add(groupItem); + } + } + + /// + /// 刷新主窗口菜单,可以被设置窗口直接调用 + /// + public void RefreshMenuFromSettings() + { + Dispatcher.BeginInvoke(new Action(() => + { + try + { + _logger.Debug("[MainWindow.RefreshMenuFromSettings] 开始重新加载菜单"); + LoadMenuGroupsFromDb(); + MenuTree.Items.Refresh(); + _logger.Debug("[MainWindow.RefreshMenuFromSettings] 菜单刷新完成"); + } + catch (Exception ex) + { + _logger.Error("[MainWindow.RefreshMenuFromSettings] 刷新菜单时出错", ex); + MessageBox.Show($"刷新菜单时出错:{ex.Message}", "错误", + MessageBoxButton.OK, MessageBoxImage.Error); + } + }), DispatcherPriority.Render); + } + + #endregion + + #region 搜索功能 + + /// + /// 搜索框文本变更事件处理器 + /// + private void SearchBox_TextChanged(object sender, TextChangedEventArgs e) => + InitMenuTree(SearchBox.Text.Trim()); + + #endregion + + #region 菜单事件处理 + + /// + /// 菜单项选择变更事件处理器 + /// + private void MenuTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs e) + { + if (MenuTree.SelectedItem is not TreeViewItem selected || selected.Tag is not MenuItemData data) + { + return; + } + + var parentItem = selected.Parent as TreeViewItem; + var parentName = parentItem?.Header?.ToString() ?? ""; + var combinedTitle = string.IsNullOrEmpty(parentName) ? data.Name : $"{parentName}-{data.Name}"; + + OpenUrlInTab(combinedTitle, data.Url, true, false, data.Id, data.Name); + } + + /// + /// TreeView双击事件处理器,实现一级菜单的展开/收缩 + /// + private void MenuTree_MouseDoubleClick(object sender, MouseButtonEventArgs e) + { + _logger.Debug("[双击事件] MouseDoubleClick 被触发"); + + var clickedItem = FindClickedTreeViewItem(e.OriginalSource as DependencyObject); + if (clickedItem is null) + { + _logger.Debug("[双击事件] 未找到TreeViewItem"); + return; + } + + var isTopLevel = IsTopLevelTreeViewItem(clickedItem); + _logger.Debug($"[双击检测] 项目: {clickedItem.Header}, 是否顶级: {isTopLevel}"); + + if (isTopLevel) + { + var currentState = clickedItem.IsExpanded; + _logger.Debug($"[一级菜单双击] {clickedItem.Header} - 当前展开状态: {currentState}"); + + clickedItem.IsExpanded = !currentState; + _logger.Debug($"[一级菜单双击] {clickedItem.Header} - 新展开状态: {clickedItem.IsExpanded}"); + + e.Handled = true; + } + else + { + _logger.Debug("[二级菜单双击] 忽略处理"); + } + } + + /// + /// 查找被点击的TreeViewItem + /// + /// 命中测试对象 + /// TreeViewItem或null + private static TreeViewItem? FindClickedTreeViewItem(DependencyObject? hitTest) + { + while (hitTest is not null) + { + if (hitTest is TreeViewItem treeViewItem) + { + return treeViewItem; + } + hitTest = VisualTreeHelper.GetParent(hitTest); + } + return null; + } + + /// + /// 判断是否为顶级TreeViewItem + /// + /// TreeViewItem + /// 是否为顶级项 + private bool IsTopLevelTreeViewItem(TreeViewItem item) + { + var parent = VisualTreeHelper.GetParent(item); + while (parent is not null) + { + if (parent == MenuTree) + { + return true; + } + if (parent is TreeViewItem) + { + return false; + } + parent = VisualTreeHelper.GetParent(parent); + } + return false; + } + + #endregion + + #region 标签页管理 + + /// + /// 在标签页中打开网址 + /// + /// 标签页标题 + /// 要打开的URL + /// 是否保持原始标题 + /// 是否强制重新加载页面 + /// 菜单项ID + /// 菜单项标题 + /// 是否选择新标签页 + /// 创建的标签页对象 + public TabItem? OpenUrlInTab(string title, string url, bool keepOriginalTitle = false, + bool forceReload = false, int menuItemId = 0, string? menuItemTitle = null, bool selectedNewTab = true) + { + try + { + if (string.IsNullOrWhiteSpace(url)) + { + _logger.Warn("OpenUrlInTab调用失败:URL为空"); + return null; + } + + title = string.IsNullOrWhiteSpace(title) ? "新标签页" : title; + url = NormalizeUrl(url); + + _logger.Debug($"开始处理OpenUrlInTab - 标题: {title}, URL: {url}, 菜单ID: {menuItemId}, 强制重载: {forceReload}"); + + var existingTab = FindExistingTab(menuItemId, url); + if (existingTab is not null) + { + return HandleExistingTab(existingTab, url, title, forceReload, selectedNewTab, menuItemId); + } + + _logger.Info($"创建新标签页 - 标题: {title}, URL: {url}, 菜单ID: {menuItemId}"); + return CreateNewTab(title, url, keepOriginalTitle, menuItemId, menuItemTitle, selectedNewTab); + } + catch (Exception ex) + { + _logger.Error("OpenUrlInTab发生异常", ex); + MessageBox.Show($"打开标签页时发生错误: {ex.Message}", "错误", + MessageBoxButton.OK, MessageBoxImage.Error); + return null; + } + } + + /// + /// 查找已存在的标签页 + /// + /// 菜单项ID + /// URL + /// 已存在的标签页或null + private TabItem? FindExistingTab(int menuItemId, string url) + { + foreach (TabItem tab in MainTabControl.Items) + { + if (tab.Tag is not TabInfo tabInfo) + { + continue; + } + + if (menuItemId > 0 && tabInfo.MenuItemId == menuItemId) + { + return tab; + } + + if (menuItemId == 0 && tabInfo.OriginalUrl == url) + { + return tab; + } + } + return null; + } + + /// + /// 处理已存在的标签页 + /// + /// 已存在的标签页 + /// URL + /// 标题 + /// 是否强制重载 + /// 是否选择新标签页 + /// 菜单项ID + /// 处理后的标签页 + private TabItem HandleExistingTab(TabItem tab, string url, string title, bool forceReload, + bool selectedNewTab, int menuItemId) + { + if (selectedNewTab) + { + MainTabControl.SelectedItem = tab; + } + + if (tab.Tag is TabInfo tabInfo) + { + var urlChanged = tabInfo.OriginalUrl != url; + var needReload = forceReload || urlChanged; + + if (needReload && tab.Content is ChromiumWebBrowser browser) + { + tabInfo.Url = url; + tabInfo.OriginalUrl = url; + LoadUrlSafely(browser, url); + _logger.Info($"标签页重新加载 - {title} - {url} (菜单ID: {menuItemId}, URL变化: {urlChanged})"); + } + else + { + _logger.Debug($"标签页切换 - {title} - {url} (菜单ID: {menuItemId})"); + } + } + + return tab; + } + + /// + /// 标准化URL格式 + /// + /// 原始URL + /// 标准化后的URL + private static string NormalizeUrl(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + return url; + } + + url = url.Trim(); + + if (!url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && + !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase) && + !url.StartsWith("about:", StringComparison.OrdinalIgnoreCase) && + !url.StartsWith("file://", StringComparison.OrdinalIgnoreCase)) + { + url = "https://" + url; + } + + return url; + } + + /// + /// 安全地加载URL到浏览器 + /// + /// 浏览器实例 + /// 要加载的URL + private void LoadUrlSafely(ChromiumWebBrowser browser, string url) + { + try + { + if (browser.IsBrowserInitialized) + { + browser.Load(url); + _logger.Debug($"直接加载URL: {url}"); + } + else + { + DependencyPropertyChangedEventHandler? browserInitializedHandler = null; + browserInitializedHandler = (sender, args) => + { + try + { + if (browser.IsBrowserInitialized) + { + browser.IsBrowserInitializedChanged -= browserInitializedHandler; + browser.Load(url); + _logger.Debug($"浏览器初始化完成后加载URL: {url}"); + } + } + catch (Exception ex) + { + _logger.Error("延迟加载时发生异常", ex); + } + }; + browser.IsBrowserInitializedChanged += browserInitializedHandler; + } + } + catch (Exception ex) + { + _logger.Error("加载URL时发生异常", ex); + throw; + } + } + + /// + /// 确保浏览器正确加载URL + /// + /// 浏览器实例 + /// URL + private void EnsureBrowserLoadsUrl(ChromiumWebBrowser browser, string url) + { + try + { + if (!browser.IsBrowserInitialized) + { + DependencyPropertyChangedEventHandler? browserInitializedHandler = null; + browserInitializedHandler = (sender, args) => + { + try + { + if (browser.IsBrowserInitialized) + { + browser.IsBrowserInitializedChanged -= browserInitializedHandler; + browser.Load(url); + _logger.Debug($"浏览器初始化完成后加载URL: {url}"); + } + } + catch (Exception ex) + { + _logger.Error("延迟加载时发生异常", ex); + } + }; + browser.IsBrowserInitializedChanged += browserInitializedHandler; + } + else + { + browser.Load(url); + _logger.Debug($"直接加载URL: {url}"); + } + } + catch (Exception ex) + { + _logger.Error("确保浏览器加载URL时发生异常", ex); + } + } + + /// + /// 创建新标签页 + /// + /// 标题 + /// URL + /// 是否保持原始标题 + /// 菜单项ID + /// 菜单项标题 + /// 是否选择新标签页 + /// 新创建的标签页 + private TabItem CreateNewTab(string title, string url, bool keepOriginalTitle, + int menuItemId, string? menuItemTitle, bool selectedNewTab = true) + { + try + { + _logger.Debug($"创建新标签页 - URL: {url}"); + + var tabId = Guid.NewGuid().ToString(); + var newBrowser = Browser.BrowserInstanceManager.Instance.GetBrowser("", tabId); + + EnsureBrowserLoadsUrl(newBrowser, url); + + var browserContext = new BrowserContext { IsLoading = true }; + var newTabInfo = new TabInfo + { + Url = url, + TabId = tabId, + OriginalUrl = url, + MenuItemId = menuItemId, + MenuItemTitle = menuItemTitle ?? string.Empty + }; + + var tabItem = new TabItem + { + Header = title, + Tag = newTabInfo, + Content = newBrowser, + DataContext = browserContext + }; + + SetupBrowserEventHandlers(newBrowser, tabId, keepOriginalTitle, browserContext); + SetupAutoLogin(newBrowser, url); + SetupTabUnloadHandler(tabItem, newBrowser); + + MainTabControl.Items.Add(tabItem); + if (selectedNewTab) + { + MainTabControl.SelectedItem = tabItem; + } + + _logger.Debug($"新标签页创建完成 - 标题: {title}, URL: {url}"); + return tabItem; + } + catch (Exception ex) + { + _logger.Error("创建新标签页时发生异常", ex); + throw; + } + } + + /// + /// 设置浏览器事件处理器 + /// + /// 浏览器实例 + /// 标签页ID + /// 是否保持原始标题 + /// 浏览器上下文 + private void SetupBrowserEventHandlers(ChromiumWebBrowser browser, string tabId, + bool keepOriginalTitle, BrowserContext browserContext) + { + EventHandler? titleUpdateHandler = null; + titleUpdateHandler = (sender, args) => + { + if (keepOriginalTitle || !args.Frame.IsMain) + { + return; + } + + args.Frame.EvaluateScriptAsync("document.title").ContinueWith(t => + { + if (!t.IsFaulted && t.Result.Success && t.Result.Result is not null) + { + var pageTitle = t.Result.Result.ToString(); + if (!string.IsNullOrWhiteSpace(pageTitle)) + { + UpdateTabTitle(tabId, pageTitle); + } + } + }); + }; + + browser.FrameLoadEnd += titleUpdateHandler; + + EventHandler? loadingStateChangedHandler = null; + loadingStateChangedHandler = (sender, args) => + { + Application.Current.Dispatcher.InvokeAsync(() => + { + if (browserContext is not null) + { + browserContext.IsLoading = args.IsLoading; + } + }, DispatcherPriority.Background); + + // 页面加载完成后检查是否为打卡页面 + if (!args.IsLoading) + { + Task.Run(async () => + { + await Task.Delay(2000); // 等待页面稳定 + await CheckAndEnqueueCheckInResult(browser); + }); + } + }; + + browser.LoadingStateChanged += loadingStateChangedHandler; + + StoreBrowserEventHandlers(browser, titleUpdateHandler, loadingStateChangedHandler); + } + + /// + /// 更新标签页标题 + /// + /// 标签页ID + /// 页面标题 + private void UpdateTabTitle(string tabId, string pageTitle) + { + Dispatcher.BeginInvoke(new Action(() => + { + foreach (TabItem tab in MainTabControl.Items) + { + if (tab.Tag is TabInfo info && info.TabId == tabId) + { + tab.Header = pageTitle; + _logger.Debug("标签页标题已更新"); + break; + } + } + })); + } + + /// + /// 存储浏览器事件处理器引用 + /// + /// 浏览器实例 + /// 标题更新处理器 + /// 加载状态变更处理器 + private static void StoreBrowserEventHandlers(ChromiumWebBrowser browser, + EventHandler titleUpdateHandler, + EventHandler loadingStateChangedHandler) + { + browser.Tag ??= new Dictionary(); + + if (browser.Tag is Dictionary browserTags) + { + browserTags["titleUpdateHandler"] = titleUpdateHandler; + browserTags["loadingStateChangedHandler"] = loadingStateChangedHandler; + } + } + + /// + /// 设置自动登录 + /// + /// 浏览器实例 + /// URL + private void SetupAutoLogin(ChromiumWebBrowser browser, string url) + { + var siteItem = FindSiteItemByUrl(url); + if (siteItem is null || !siteItem.AutoLogin) + { + return; + } + + EventHandler? frameLoadEndHandler = null; + frameLoadEndHandler = (sender, args) => + { + if (args.Frame.IsMain) + { + ExecuteAutoLoginScript(args.Frame, siteItem); + browser.FrameLoadEnd -= frameLoadEndHandler; + } + }; + + browser.FrameLoadEnd += frameLoadEndHandler; + } + + /// + /// 设置标签页卸载事件处理器 + /// + /// 标签页 + /// 浏览器实例 + private void SetupTabUnloadHandler(TabItem tabItem, ChromiumWebBrowser browser) + { + tabItem.Unloaded += (sender, e) => + { + try + { + _logger.Debug("标签页卸载开始"); + + CleanupBrowserEventHandlers(browser); + + if (sender is TabItem tab && tab.Tag is TabInfo info) + { + Browser.BrowserInstanceManager.Instance.ReleaseBrowser(info.TabId); + _logger.Debug($"浏览器实例已释放 - TabId: {info.TabId}"); + } + + _logger.Debug("标签页卸载完成"); + } + catch (Exception ex) + { + _logger.Error("标签页卸载时发生异常", ex); + } + }; + } + + /// + /// 清理浏览器事件处理器 + /// + /// 浏览器实例 + private static void CleanupBrowserEventHandlers(ChromiumWebBrowser browser) + { + if (browser.Tag is not Dictionary browserTags) + { + return; + } + + if (browserTags.TryGetValue("titleUpdateHandler", out var titleHandler) && + titleHandler is EventHandler titleUpdateHandler) + { + browser.FrameLoadEnd -= titleUpdateHandler; + } + + if (browserTags.TryGetValue("loadingStateChangedHandler", out var loadingHandler) && + loadingHandler is EventHandler loadingStateChangedHandler) + { + browser.LoadingStateChanged -= loadingStateChangedHandler; + } + + browserTags.Clear(); + } + + /// + /// 执行自动登录脚本 + /// + /// 浏览器框架 + /// 站点配置项 + private static void ExecuteAutoLoginScript(IFrame frame, SiteItem siteItem) + { + var username = siteItem.UseCommonCredentials ? siteItem.CommonUsername : siteItem.Username; + var password = siteItem.UseCommonCredentials ? siteItem.CommonPassword : siteItem.Password; + var usernameSelector = string.IsNullOrWhiteSpace(siteItem.UsernameSelector) + ? "input[type=email],input[type=text],input[name*=user],input[name*=email],input[name*=login]" + : siteItem.UsernameSelector; + var passwordSelector = string.IsNullOrWhiteSpace(siteItem.PasswordSelector) + ? "input[type=password]" + : siteItem.PasswordSelector; + var captchaSelector = siteItem.CaptchaSelector; + var loginButtonSelector = string.IsNullOrWhiteSpace(siteItem.LoginButtonSelector) + ? "button[type=submit],input[type=submit]" + : siteItem.LoginButtonSelector; + var loginPageFeature = siteItem.LoginPageFeature; + var captchaValue = siteItem.CaptchaValue ?? ""; + + if (siteItem.CaptchaMode == 1 && !string.IsNullOrWhiteSpace(siteItem.GoogleSecret)) + { + captchaValue = BrowserTool.Utils.GoogleAuthenticator.GenerateCode(siteItem.GoogleSecret); + } + + var featureCheck = string.IsNullOrWhiteSpace(loginPageFeature) + ? "" + : $"if(!document.querySelector('{loginPageFeature}')) return;"; + var captchaJs = string.IsNullOrWhiteSpace(captchaSelector) + ? "" + : $"var captchaInput = document.querySelector('{captchaSelector}'); if(captchaInput) captchaInput.value = '{captchaValue.Replace("'", "\\'")}';"; + + var js = $@" + (function() {{ + {featureCheck} + var userInput = document.querySelector('{usernameSelector}'); + var passInput = document.querySelector('{passwordSelector}'); + {captchaJs} + if(userInput) userInput.value = '{username?.Replace("'", "\\'") ?? ""}'; + if(passInput) passInput.value = '{password?.Replace("'", "\\'") ?? ""}'; + var form = userInput ? userInput.form : (passInput ? passInput.form : null); + if(form) {{ + form.submit(); + }} else {{ + var btn = document.querySelector('{loginButtonSelector}'); + if(btn) btn.click(); + }} + }})(); + "; + + frame.ExecuteJavaScriptAsync(js); + } + + /// + /// 根据URL查找站点配置项 + /// + /// URL + /// 站点配置项或null + private static SiteItem? FindSiteItemByUrl(string url) + { + var allGroups = BrowserTool.Database.SiteConfig.GetAllGroups(); + return allGroups.SelectMany(group => group.Sites) + .FirstOrDefault(site => site.Url == url); + } + + /// + /// 清除TreeView的选中状态 + /// + private void ClearTreeViewSelection() + { + foreach (TreeViewItem item in MenuTree.Items) + { + item.IsSelected = false; + foreach (TreeViewItem child in item.Items) + { + child.IsSelected = false; + } + } + } + + /// + /// 关闭指定的标签页 + /// + /// 要关闭的标签页 + public void CloseTab(TabItem? tabItem) + { + if (tabItem is not null) + { + MainTabControl.Items.Remove(tabItem); + ClearTreeViewSelection(); + } + } + + /// + /// 关闭当前标签页 + /// + private void CloseCurrentTab() + { + if (MainTabControl.SelectedItem is TabItem tab) + { + CloseTab(tab); + } + } + + #endregion + + #region 键盘事件处理 + + /// + /// 主窗口键盘事件处理器 + /// + private void MainWindow_KeyDown(object sender, KeyEventArgs e) + { + try + { + switch (e.Key) + { + case Key.F12: + HandleF12KeyPress(); + break; + + case Key.F when Keyboard.Modifiers == ModifierKeys.Control: + ShowSearchBar(); + e.Handled = true; + break; + + case Key.W when Keyboard.Modifiers == ModifierKeys.Control: + CloseCurrentTab(); + e.Handled = true; + break; + + case Key.Escape when PageSearchBar.Visibility == Visibility.Visible: + HideSearchBar(); + e.Handled = true; + break; + } + } + catch (Exception ex) + { + _logger.Error("键盘事件处理错误", ex); + } + } + + /// + /// 处理F12按键(开发者工具) + /// + private void HandleF12KeyPress() + { + if (MainTabControl.SelectedItem is TabItem tab && tab.Content is ChromiumWebBrowser currentBrowser) + { + CefHelper.ShowDevTools(currentBrowser); + } + } + + #endregion + + #region 搜索栏功能 + + /// + /// 显示搜索栏 + /// + private void ShowSearchBar() + { + try + { + var currentTab = MainTabControl.SelectedItem as TabItem; + if (currentTab?.Content is ChromiumWebBrowser browser) + { + PageSearchBar.SetBrowser(browser); + PageSearchBar.Visibility = Visibility.Visible; + PageSearchBar.FocusSearchBox(); + } + } + catch (Exception ex) + { + _logger.Error("显示搜索栏错误", ex); + } + } + + /// + /// 隐藏搜索栏 + /// + private void HideSearchBar() + { + try + { + PageSearchBar.Visibility = Visibility.Collapsed; + PageSearchBar.Clear(); + + var currentTab = MainTabControl.SelectedItem as TabItem; + if (currentTab?.Content is ChromiumWebBrowser browser) + { + browser.Focus(); + } + } + catch (Exception ex) + { + _logger.Error("隐藏搜索栏错误", ex); + } + } + + /// + /// 搜索栏关闭请求事件处理器 + /// + private void PageSearchBar_CloseRequested(object sender, EventArgs e) => HideSearchBar(); + + #endregion + + #region UI控件事件处理 + + /// + /// 测试环境按钮点击事件处理器 + /// + private void TestEnvButton_Click(object sender, RoutedEventArgs e) + { + var testUrl = System.Configuration.ConfigurationManager.AppSettings["TestEnvironmentUrl"]; + + if (!string.IsNullOrEmpty(testUrl)) + { + OpenUrlInTab("测试环境", testUrl, true); + } + else + { + MessageBox.Show("测试环境URL未配置,请在App.config中设置TestEnvironmentUrl", "配置错误", + MessageBoxButton.OK, MessageBoxImage.Warning); + } + } + + /// + /// 手动打卡按钮点击事件处理器 + /// + private async void ManualCheckInButton_Click(object sender, RoutedEventArgs e) + { + try + { + _logger.Debug("手动打卡按钮被点击"); + + await App.GetAutoCheckInSimulator().ExecuteManualCheckIn(); + } + catch (Exception ex) + { + _logger.Error("手动打卡时发生异常", ex); + MessageBox.Show($"手动打卡失败:{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); + } + } + + /// + /// 抽屉开关按钮点击事件处理器 + /// + private void DrawerToggleBtn_Click(object sender, RoutedEventArgs e) + { + ToggleDrawer(); + NotifyBrowserLayoutChange(); + } + + /// + /// 切换抽屉状态 + /// + private void ToggleDrawer() + { + if (_isDrawerOpen) + { + DrawerCol.Width = new GridLength(0); + DrawerBorder.Visibility = Visibility.Collapsed; + } + else + { + DrawerCol.Width = new GridLength(200); + DrawerBorder.Visibility = Visibility.Visible; + } + _isDrawerOpen = !_isDrawerOpen; + } + + /// + /// 通知浏览器布局变化 + /// + private void NotifyBrowserLayoutChange() + { + try + { + if (MainTabControl?.Items.Count == 0) + { + return; + } + + var selectedItem = MainTabControl.SelectedItem as TabItem; + if (selectedItem is null || !MainTabControl.Items.Contains(selectedItem)) + { + if (MainTabControl.Items.Count > 0) + { + MainTabControl.SelectedIndex = 0; + } + return; + } + + if (selectedItem.Content is ChromiumWebBrowser browser && !browser.IsDisposed) + { + var browserInstance = browser.GetBrowser(); + if (browserInstance is not null && !browserInstance.IsDisposed) + { + var host = browserInstance.GetHost(); + if (host is not null && !host.IsDisposed) + { + host.NotifyMoveOrResizeStarted(); + host.NotifyScreenInfoChanged(); + host.WasResized(); + } + } + } + } + catch (ObjectDisposedException ex) + { + _logger.Error("浏览器对象已释放", ex); + } + catch (Exception ex) + { + _logger.Error("通知浏览器布局变化时出错", ex); + } + } + + /// + /// 后退按钮点击事件处理器 + /// + private void BackButton_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser && browser.CanGoBack) + { + browser.Back(); + } + } + + /// + /// 前进按钮点击事件处理器 + /// + private void ForwardButton_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser && browser.CanGoForward) + { + browser.Forward(); + } + } + + /// + /// 刷新按钮点击事件处理器 + /// + private void RefreshButton_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser) + { + browser.Reload(); + } + } + + /// + /// URL输入框键盘事件处理器 + /// + private void UrlTextBox_KeyDown(object sender, KeyEventArgs e) + { + if (e.Key != Key.Enter || MainTabControl.SelectedItem is not TabItem tabItem || + tabItem.Content is not ChromiumWebBrowser browser) + { + return; + } + + var url = UrlTextBox.Text; + if (!url.StartsWith("http://") && !url.StartsWith("https://")) + { + url = "https://" + url; + } + browser.LoadUrl(url); + } + + /// + /// 开发者工具按钮点击事件处理器 + /// + private void DevToolsButton_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem || + tabItem.Content is not ChromiumWebBrowser browser) + { + return; + } + + var url = UrlTextBox.Text; + if (!string.IsNullOrWhiteSpace(url)) + { + if (!url.StartsWith("http://") && !url.StartsWith("https://")) + { + url = "https://" + url; + } + browser.LoadUrl(url); + } + } + + /// + /// 切换地址栏的显示/隐藏状态 + /// + public void ToggleUrlBar() + { + if (this.FindName("UrlBar") is not Grid urlBar) + { + return; + } + + urlBar.Visibility = urlBar.Visibility == Visibility.Visible + ? Visibility.Collapsed + : Visibility.Visible; + + if (urlBar.Visibility == Visibility.Visible && + MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser) + { + UrlTextBox.Text = browser.Address; + } + } + + /// + /// 标签页选择变更事件处理器 + /// + private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) + { + try + { + ClearTreeViewSelection(); + + if (PageSearchBar.Visibility == Visibility.Visible) + { + var currentTab = MainTabControl.SelectedItem as TabItem; + if (currentTab?.Content is ChromiumWebBrowser browser) + { + PageSearchBar.SetBrowser(browser); + } + else + { + HideSearchBar(); + } + } + + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser selectedBrowser) + { + UrlTextBox.Text = selectedBrowser.Address; + } + } + catch (Exception ex) + { + _logger.Error("标签页切换错误", ex); + } + } + + #endregion + + #region 右键菜单处理 + + /// + /// 标签页右键按下事件处理器 + /// + private void MainTabControl_MouseRightButtonDown(object sender, MouseButtonEventArgs e) + { + var tabItem = GetTabItemAtPosition(e.GetPosition(MainTabControl)); + if (tabItem is not null) + { + MainTabControl.SelectedItem = tabItem; + } + } + + /// + /// 获取指定位置的标签页 + /// + /// 位置 + /// 标签页或null + private TabItem? GetTabItemAtPosition(Point position) + { + var result = VisualTreeHelper.HitTest(MainTabControl, position); + if (result is null) + { + return null; + } + + var element = result.VisualHit; + while (element is not null && element is not TabItem) + { + element = VisualTreeHelper.GetParent(element); + } + return element as TabItem; + } + + /// + /// 关闭标签页菜单项点击事件处理器 + /// + private void CloseTabMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem) + { + return; + } + + if (tabItem.Tag is TabInfo tabInfo) + { + Browser.BrowserInstanceManager.Instance.ReleaseBrowser(tabInfo.TabId); + } + + MainTabControl.Items.Remove(tabItem); + ClearTreeViewSelection(); + } + + /// + /// 关闭其他标签页菜单项点击事件处理器 + /// + private void CloseOtherTabsMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem selectedTab) + { + return; + } + + var tabsToRemove = MainTabControl.Items.Cast() + .Where(tab => tab != selectedTab) + .ToList(); + + foreach (var tab in tabsToRemove) + { + MainTabControl.Items.Remove(tab); + } + } + + /// + /// 关闭右侧标签页菜单项点击事件处理器 + /// + private void CloseRightTabsMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem selectedTab) + { + return; + } + + var selectedIndex = MainTabControl.Items.IndexOf(selectedTab); + var tabsToRemove = MainTabControl.Items.Cast() + .Where((tab, index) => index > selectedIndex) + .ToList(); + + foreach (var tab in tabsToRemove) + { + MainTabControl.Items.Remove(tab); + } + } + + /// + /// 刷新标签页菜单项点击事件处理器 + /// + private void RefreshTabMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser) + { + browser.Reload(); + } + } + + /// + /// 复制URL菜单项点击事件处理器 + /// + private void CopyUrlMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem) + { + return; + } + + var textToCopy = tabItem.Content switch + { + ChromiumWebBrowser browser => browser.Address, + _ when tabItem.Tag is TabInfo tabInfo => tabInfo.Url, + _ => null + }; + + if (!string.IsNullOrEmpty(textToCopy)) + { + Clipboard.SetText(textToCopy); + } + } + + /// + /// 复制标题菜单项点击事件处理器 + /// + private void CopyTitleMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem) + { + Clipboard.SetText(tabItem.Header.ToString()); + } + } + + /// + /// 复制选中内容菜单项点击事件处理器 + /// + private void CopyMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser) + { + browser.Copy(); + } + } + + /// + /// 粘贴菜单项点击事件处理器 + /// + private void PasteMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is TabItem tabItem && + tabItem.Content is ChromiumWebBrowser browser) + { + browser.Paste(); + } + } + + /// + /// 粘贴并访问菜单项点击事件处理器 + /// + private void PasteAndGoMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem || + tabItem.Content is not ChromiumWebBrowser browser) + { + return; + } + + var url = Clipboard.GetText(); + if (string.IsNullOrWhiteSpace(url)) + { + return; + } + + if (!url.StartsWith("http://") && !url.StartsWith("https://")) + { + url = "https://" + url; + } + browser.LoadUrl(url); + } + + /// + /// 复制标签页菜单项点击事件处理器 + /// + private void DuplicateTabMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem) + { + return; + } + + var (baseTitle, url) = GetTabDuplicationInfo(tabItem); + var newTitle = GenerateUniqueTabTitle(baseTitle); + + var newBrowser = new ChromiumWebBrowser(url) + { + DownloadHandler = new CefDownloadHandler(), + MenuHandler = new CefMenuHandler(), + LifeSpanHandler = new Browser.CefLifeSpanHandler() + }; + + var newTabItem = new TabItem + { + Header = newTitle, + Tag = GetTabTag(tabItem, url), + Content = newBrowser + }; + + MainTabControl.Items.Add(newTabItem); + MainTabControl.SelectedItem = newTabItem; + } + + /// + /// 获取标签页复制信息 + /// + /// 标签页 + /// 基础标题和URL + private static (string baseTitle, string url) GetTabDuplicationInfo(TabItem tabItem) + { + var baseTitle = Regex.Replace(tabItem.Header.ToString(), @"\d+$", "").Trim(); + + var url = tabItem.Content switch + { + ChromiumWebBrowser browser => browser.Address, + _ when tabItem.Tag is TabInfo tabInfo => tabInfo.Url, + _ => string.Empty + }; + + return (baseTitle, url); + } + + /// + /// 生成唯一的标签页标题 + /// + /// 基础标题 + /// 唯一标题 + private string GenerateUniqueTabTitle(string baseTitle) + { + var existingTabs = MainTabControl.Items.Cast() + .Where(t => t.Header.ToString().StartsWith(baseTitle)) + .ToList(); + + var newNumber = 1; + if (existingTabs.Any()) + { + var numbers = existingTabs + .Select(t => t.Header.ToString()) + .Select(title => Regex.Match(title, @"\d+$")) + .Where(m => m.Success) + .Select(m => int.Parse(m.Value)) + .ToList(); + + if (numbers.Any()) + { + newNumber = numbers.Max() + 1; + } + } + + return $"{baseTitle}{newNumber}"; + } + + /// + /// 获取标签页标记 + /// + /// 原始标签页 + /// URL + /// 标签页标记 + private static object GetTabTag(TabItem originalTab, string url) + { + return originalTab.Tag switch + { + TabInfo tabInfo => tabInfo, + _ => url + }; + } + + /// + /// 在新标签页中打开菜单项点击事件处理器 + /// + private void OpenInNewTabMenuItem_Click(object sender, RoutedEventArgs e) + { + if (MainTabControl.SelectedItem is not TabItem tabItem) + { + return; + } + + var (title, url) = GetTabOpenInfo(tabItem); + if (!string.IsNullOrEmpty(url)) + { + OpenUrlInTab(title, url); + } + } + + /// + /// 获取标签页打开信息 + /// + /// 标签页 + /// 标题和URL + private static (string title, string url) GetTabOpenInfo(TabItem tabItem) + { + var title = tabItem.Header.ToString(); + + var url = tabItem.Content switch + { + ChromiumWebBrowser browser => browser.Address, + _ when tabItem.Tag is TabInfo tabInfo => tabInfo.Url, + _ => string.Empty + }; + + return (title, url); + } + + #endregion + + #region 窗口控制 + + /// + /// 最小化按钮点击事件处理器 + /// + private void MinimizeButton_Click(object sender, RoutedEventArgs e) => + WindowState = WindowState.Minimized; + + /// + /// 最小化按钮点击事件处理器(备用) + /// + private void btnMinimize_Click(object sender, RoutedEventArgs e) => + WindowState = WindowState.Minimized; + + /// + /// 最大化按钮点击事件处理器 + /// + private void MaximizeButton_Click(object sender, RoutedEventArgs e) + { + if (WindowState == WindowState.Maximized) + { + WindowState = WindowState.Normal; + } + else + { + WindowState = WindowState.Maximized; + MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight; + MaxWidth = SystemParameters.MaximizedPrimaryScreenWidth; + } + } + + /// + /// 关闭按钮点击事件处理器 + /// + private void CloseButton_Click(object sender, RoutedEventArgs e) => Close(); + + /// + /// 标题栏鼠标左键按下事件处理器 - 支持拖拽和双击最大化/还原 + /// + private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) + { + if (e.ClickCount == 2) + { + MaximizeButton_Click(sender, e); + } + else if (e.ButtonState == MouseButtonState.Pressed) + { + DragMove(); + } + } + + /// + /// 窗口关闭事件处理 - 最小化到托盘而不是退出 + /// + protected override void OnClosing(CancelEventArgs e) + { + e.Cancel = true; + Hide(); + + if (Application.Current.Resources["TrayIcon"] is TaskbarIcon trayIcon) + { + trayIcon.ShowBalloonTip("Browser Tool", "程序已最小化到系统托盘", BalloonIcon.Info); + } + } + + /// + /// 主窗体大小改变事件处理器 + /// + private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e) + { + Dispatcher.BeginInvoke(new Action(() => + { + try + { + foreach (TabItem tab in MainTabControl.Items) + { + if (tab.Content is not ChromiumWebBrowser browser) + { + continue; + } + + browser.InvalidateVisual(); + browser.UpdateLayout(); + + if (!browser.IsLoading && browser.CanExecuteJavascriptInMainFrame) + { + browser.ExecuteScriptAsync("if(window.dispatchEvent) { window.dispatchEvent(new Event('resize')); }"); + } + } + + _logger.Debug($"[窗口大小改变] 新尺寸: {e.NewSize.Width}x{e.NewSize.Height}"); + } + catch (Exception ex) + { + _logger.Error("窗口大小改变处理错误", ex); + } + }), DispatcherPriority.Background); + } + + /// + /// 关闭标签页按钮点击事件处理器 + /// + private void CloseTabButton_Click(object sender, RoutedEventArgs e) + { + try + { + if (sender is not Button button || button.Tag is not TabItem tabItem || + !MainTabControl.Items.Contains(tabItem)) + { + return; + } + + if (MainTabControl.SelectedItem == tabItem && MainTabControl.Items.Count > 1) + { + var index = MainTabControl.Items.IndexOf(tabItem); + MainTabControl.SelectedIndex = index > 0 ? index - 1 : index + 1; + } + + if (tabItem.Content is ChromiumWebBrowser browser) + { + browser.Dispose(); + } + + MainTabControl.Items.Remove(tabItem); + ClearTreeViewSelection(); + } + catch (Exception ex) + { + _logger.Error("关闭标签页错误", ex); + } + } + + #endregion + + #region 设置相关 + + /// + /// 设置按钮点击事件处理器 + /// + private void btnSettings_Click(object sender, RoutedEventArgs e) + { + var settingsWindow = new SettingsWindow(this); + + _logger.Debug("[MainWindow.btnSettings_Click] 准备订阅 SettingsSaved 事件"); + settingsWindow.SettingsSaved += SettingsWindow_SettingsSaved; + + settingsWindow.ShowDialog(); + + _logger.Debug("[MainWindow.btnSettings_Click] 设置窗口已关闭,准备刷新菜单"); + RefreshMenuFromSettings(); + } + + /// + /// 设置保存事件处理器 + /// + private void SettingsWindow_SettingsSaved(object sender, EventArgs args) + { + _logger.Debug("[MainWindow] SettingsSaved 事件被触发,准备刷新菜单"); + + Dispatcher.BeginInvoke(new Action(() => + { + try + { + _logger.Debug("[MainWindow] 开始重新加载菜单"); + LoadMenuGroupsFromDb(); + MenuTree.Items.Refresh(); + _logger.Debug("[MainWindow] 菜单刷新完成"); + } + catch (Exception ex) + { + _logger.Error("[MainWindow] 刷新菜单时出错", ex); + MessageBox.Show($"刷新菜单时出错:{ex.Message}", "错误", + MessageBoxButton.OK, MessageBoxImage.Error); + } + }), DispatcherPriority.Render); + } + + #endregion + + #region 上下文菜单位置回调 + + /// + /// 上下文菜单位置回调 + /// + /// 弹出框大小 + /// 目标大小 + /// 偏移量 + /// 自定义弹出框位置数组 + private CustomPopupPlacement[] ContextMenu_PlacementCallback(Size popupSize, Size targetSize, Point offset) + { + var mousePosition = Mouse.GetPosition(MainTabControl); + mousePosition = MainTabControl.PointToScreen(mousePosition); + + var placementPoint = new Point(mousePosition.X, mousePosition.Y); + + if (_isDrawerOpen) + { + placementPoint.X -= DrawerCol.Width.Value; + } + + return new[] + { + new CustomPopupPlacement(placementPoint, PopupPrimaryAxis.Horizontal) + }; + } + + #endregion + + #region 辅助方法 + + /// + /// 获取当前标签页的浏览器控件 + /// + /// 当前浏览器控件或null + private ChromiumWebBrowser? GetCurrentBrowser() + { + if (MainTabControl.SelectedItem is not TabItem selectedTab) + { + return null; + } + + return selectedTab.Content switch + { + ChromiumWebBrowser browser => browser, + ContentPresenter contentPresenter when contentPresenter.Content is Grid grid => + grid.Children.OfType().FirstOrDefault(), + _ => null + }; + } + + /// + /// 更新URL输入框内容 + /// + /// 新的URL + public void UpdateUrl(string url) + { + if (MainTabControl.SelectedItem is not TabItem selectedTab) + { + return; + } + + switch (selectedTab.Content) + { + case ContentPresenter contentPresenter when contentPresenter.Content is Grid grid: + { + var urlTextBox = grid.FindName("UrlTextBox") as TextBox; + if (urlTextBox is not null) + { + urlTextBox.Text = url; + } + break; + } + } + } + + #endregion + + #region 自动打卡相关 + + /// + /// 检查页面并将打卡结果加入队列 + /// + /// 浏览器控件 + private async Task CheckAndEnqueueCheckInResult(ChromiumWebBrowser browser) + { + try + { + await Dispatcher.InvokeAsync(async () => + { + string currentUrl = browser.Address ?? ""; + _logger.Debug($"检查页面打卡结果: {currentUrl}"); + + // 检查域名是否为打卡相关域名 + List _checkInDomains = ConfigurationManager.AppSettings["CheckInDomains"]? + .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(d => d.Trim()) + .ToList() ?? new List(); + + bool isDomainMatch = _checkInDomains.Any(domain => currentUrl.Contains(domain)); + if (!isDomainMatch) + { + _logger.Debug($"当前域名不在打卡域名列表中: {currentUrl}"); + return; + } + + _logger.Debug("域名匹配,开始检查页面内容"); + + // 等待页面稳定(给页面一些时间完成加载和渲染) + await Task.Delay(2000); + + // 再次检查浏览器状态 + if (browser.IsDisposed) + { + _logger.Debug("浏览器已被释放,跳过检查"); + return; + } + + // 检查页面内容是否包含成功标识 + bool hasSuccessContent = await CheckPageContentForSuccess(browser); + + // 创建检查结果并加入队列 + var result = new CheckInResult + { + IsSuccess = hasSuccessContent, + Url = currentUrl, + CheckTime = DateTime.Now, + Message = hasSuccessContent ? "检测到打卡成功" : "未检测到打卡成功标识" + }; + + CheckInResultQueue.Instance.EnqueueResult(result); + _logger.Debug($"打卡结果已加入队列: 成功={hasSuccessContent}, URL={currentUrl}"); + }); + } + catch (Exception ex) + { + _logger.Error("检查并入队打卡结果时发生异常", ex); + } + } + + /// + /// 检查页面内容是否包含成功标识 + /// + /// 浏览器控件 + /// 是否包含成功标识 + private async Task CheckPageContentForSuccess(ChromiumWebBrowser browser) + { + try + { + // 首先使用简单的方法检查URL和基本信息 + string url = browser.Address ?? ""; + _logger.Debug($"当前页面URL: {url}"); + + //// 先检查URL是否包含成功标识(最快的方法) + //if (CheckUrlForSuccess(url)) + //{ + // _logger.Debug("URL包含成功标识,直接返回成功"); + // return true; + //} + + // 检查浏览器状态 + if (browser.IsDisposed) + { + _logger.Debug("浏览器已被释放,使用URL判断"); + return CheckUrlForSuccess(url); + } + + var cefBrowser = browser.GetBrowser(); + if (cefBrowser == null || cefBrowser.IsDisposed) + { + _logger.Debug("CEF浏览器实例无效,使用URL判断"); + return CheckUrlForSuccess(url); + } + + // 检查浏览器是否正在加载 + if (browser.IsLoading) + { + _logger.Debug("浏览器正在加载,等待加载完成..."); + // 等待最多3秒让页面加载完成 + int waitCount = 0; + while (browser.IsLoading && waitCount < 6) + { + await Task.Delay(500); + waitCount++; + } + + if (browser.IsLoading) + { + _logger.Debug("页面仍在加载,使用URL判断"); + return CheckUrlForSuccess(url); + } + } + + _logger.Debug($"浏览器状态检查通过,BrowserId: {cefBrowser.Identifier}"); + + // 使用多种方法获取页面内容 + string bodyText = ""; + string titleText = ""; + + // 方法1: 尝试使用扩展方法(减少超时时间到5秒) + try + { + _logger.Debug("开始使用扩展方法获取页面内容..."); + + var sourceTask = browser.GetSourceAsync(); + var textTask = browser.GetTextAsync(); + + // 减少超时时间到5秒 + var timeoutTask = Task.Delay(5000); + var completedTask = await Task.WhenAny( + Task.WhenAll(sourceTask, textTask), + timeoutTask + ); + + if (completedTask != timeoutTask) + { + var source = await sourceTask; + var text = await textTask; + + // 从HTML源码中提取标题 + var titleMatch = System.Text.RegularExpressions.Regex.Match(source, @"]*>([^<]*)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); + titleText = titleMatch.Success ? titleMatch.Groups[1].Value.Trim() : ""; + + // 使用页面文本内容,限制长度 + bodyText = text.Length > 1000 ? text.Substring(0, 1000) : text; + + _logger.Debug($"扩展方法获取成功 - 标题: {titleText}, 内容长度: {bodyText.Length}"); + } + else + { + _logger.Debug("扩展方法获取超时,尝试备用方法"); + // 继续尝试其他方法 + } + } + catch (Exception ex) + { + _logger.Error($"扩展方法获取时发生异常: {ex.Message}"); + // 继续尝试其他方法 + } + + // 方法2: 如果扩展方法失败,尝试获取页面标题 + if (string.IsNullOrEmpty(titleText)) + { + try + { + _logger.Debug("尝试直接获取页面标题..."); + var mainFrame = cefBrowser.MainFrame; + if (mainFrame != null && !mainFrame.IsDisposed) + { + // 使用主框架的URL作为备用 + var frameUrl = mainFrame.Url ?? ""; + if (!string.IsNullOrEmpty(frameUrl) && frameUrl != url) + { + _logger.Debug($"使用主框架URL: {frameUrl}"); + if (CheckUrlForSuccess(frameUrl)) + { + return true; + } + } + } + } + catch (Exception ex) + { + _logger.Error($"获取主框架信息时发生异常: {ex.Message}"); + } + } + + // 方法3: 检查浏览器标题(如果可用) + if (string.IsNullOrEmpty(titleText)) + { + try + { + // 尝试从浏览器获取标题 + var browserHost = cefBrowser.GetHost(); + if (browserHost != null && !browserHost.IsDisposed) + { + // 这里可以添加更多的检查逻辑 + _logger.Debug("浏览器主机可用,但无法获取内容"); + } + } + catch (Exception ex) + { + _logger.Error($"获取浏览器主机信息时发生异常: {ex.Message}"); + } + } + + // 如果所有方法都失败,使用URL判断 + if (string.IsNullOrEmpty(titleText) && string.IsNullOrEmpty(bodyText)) + { + _logger.Debug("所有内容获取方法都失败,使用URL判断"); + return CheckUrlForSuccess(url); + } + + // 检查是否包含打卡成功的关键字 + string[] successKeywords = { "打卡成功", "签到成功", "考勤成功", "上班打卡成功", "下班打卡成功", "check-in successful", "attendance successful", "签到完成", "打卡完成", "google" }; + + bool hasSuccessKeyword = successKeywords.Any(keyword => + bodyText.Contains(keyword, StringComparison.OrdinalIgnoreCase) || + titleText.Contains(keyword, StringComparison.OrdinalIgnoreCase) || + url.Contains(keyword, StringComparison.OrdinalIgnoreCase)); + + if (hasSuccessKeyword) + { + _logger.Debug("页面包含成功标识"); + return true; + } + + _logger.Debug("页面不包含成功标识"); + return false; + } + catch (Exception ex) + { + _logger.Error("检查页面内容时发生异常", ex); + return CheckUrlForSuccess(browser.Address ?? ""); + } + } + + /// + /// 基于URL检查是否成功(备用方法) + /// + /// 页面URL + /// 是否包含成功标识 + private bool CheckUrlForSuccess(string url) + { + if (string.IsNullOrEmpty(url)) + return false; + + string[] urlSuccessKeywords = { "success", "complete", "done", "成功", "完成", "google" }; + bool hasSuccessInUrl = urlSuccessKeywords.Any(keyword => url.Contains(keyword, StringComparison.OrdinalIgnoreCase)); + + _logger.Debug($"URL成功检查结果: {hasSuccessInUrl} (URL: {url})"); + return hasSuccessInUrl; + } + + #endregion +} + diff --git a/csharp/BrowserTool/BrowserTool/NLog.config b/csharp/BrowserTool/BrowserTool/NLog.config new file mode 100644 index 0000000000000000000000000000000000000000..aa559a8dbcd2d40d48110472686b9b0eb5afe2e2 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/NLog.config @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Properties/AssemblyInfo.cs b/csharp/BrowserTool/BrowserTool/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..62fed720b5685725d502270cb8fea7ea4e44beff --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Properties/AssemblyInfo.cs @@ -0,0 +1,52 @@ +using System.Reflection; +using System.Resources; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Windows; + +// 有关程序集的一般信息由以下 +// 控制。更改这些特性值可修改 +// 与程序集关联的信息。 +// [assembly: AssemblyTitle("BrowserTool")] +// [assembly: AssemblyDescription("")] +// [assembly: AssemblyConfiguration("")] +// [assembly: AssemblyCompany("")] +// [assembly: AssemblyProduct("BrowserTool")] +// [assembly: AssemblyCopyright("Copyright © 2025")] +// [assembly: AssemblyTrademark("")] +// [assembly: AssemblyCulture("")] + +// 将 ComVisible 设置为 false 会使此程序集中的类型 +//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 +//请将此类型的 ComVisible 特性设置为 true。 +[assembly: ComVisible(false)] + +//若要开始生成可本地化的应用程序,请设置 +//.csproj 文件中的 CultureYouAreCodingWith +//在 中。例如,如果你使用的是美国英语。 +//使用的是美国英语,请将 设置为 en-US。 然后取消 +//对以下 NeutralResourceLanguage 特性的注释。 更新 +//以下行中的"en-US"以匹配项目文件中的 UICulture 设置。 + +//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] + + +[assembly: ThemeInfo( + ResourceDictionaryLocation.None, //主题特定资源词典所处位置 + //(未在页面中找到资源时使用, + //或应用程序资源字典中找到时使用) + ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 + //(未在页面中找到资源时使用, + //、应用程序或任何主题专用资源字典中找到时使用) +)] + + +// 程序集的版本信息由下列四个值组成: +// +// 主版本 +// 次版本 +// 生成号 +// 修订号 +// +// [assembly: AssemblyVersion("1.0.0.0")] +// [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/csharp/BrowserTool/BrowserTool/Properties/Resources.Designer.cs b/csharp/BrowserTool/BrowserTool/Properties/Resources.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..236a70d14ed6ea353c99f9308152602c9c6d3433 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// 此代码由工具生成。 +// 运行时版本: 4.0.30319.42000 +// +// 对此文件的更改可能导致不正确的行为,如果 +// 重新生成代码,则所做更改将丢失。 +// +//------------------------------------------------------------------------------ + +namespace BrowserTool.Properties +{ + + + /// + /// 强类型资源类,用于查找本地化字符串等。 + /// + // 此类是由 StronglyTypedResourceBuilder + // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 + // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen + // (以 /str 作为命令选项),或重新生成 VS 项目。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// 返回此类使用的缓存 ResourceManager 实例。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("BrowserTool.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// 重写当前线程的 CurrentUICulture 属性,对 + /// 使用此强类型资源类的所有资源查找执行重写。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Properties/Resources.resx b/csharp/BrowserTool/BrowserTool/Properties/Resources.resx new file mode 100644 index 0000000000000000000000000000000000000000..af7dbebbacef595e3089c01c05671016c21a8304 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Properties/Settings.Designer.cs b/csharp/BrowserTool/BrowserTool/Properties/Settings.Designer.cs new file mode 100644 index 0000000000000000000000000000000000000000..07bcb22f6250eee00e95a8354c6c85b67c17396e --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace BrowserTool.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/csharp/BrowserTool/BrowserTool/Properties/Settings.settings b/csharp/BrowserTool/BrowserTool/Properties/Settings.settings new file mode 100644 index 0000000000000000000000000000000000000000..033d7a5e9e2266753180f4e3a9299f575046701e --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/Resources/app.ico b/csharp/BrowserTool/BrowserTool/Resources/app.ico new file mode 100644 index 0000000000000000000000000000000000000000..90027e337004d67993522b57874be347d931af26 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Resources/app.ico @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ef4cec35012d46e714c97b9a587ac0b29acf966ef772505c6d5ff0f21d8757c +size 67646 diff --git a/csharp/BrowserTool/BrowserTool/Resources/checkin_icon1.png b/csharp/BrowserTool/BrowserTool/Resources/checkin_icon1.png new file mode 100644 index 0000000000000000000000000000000000000000..21489b01c2240c28a631d9873c790b9c377f56fa --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Resources/checkin_icon1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdb36f9b008c3ab4cfa4adfab4b28fc32c07a66b7597b10d6957bfae9fc99f9b +size 1103 diff --git a/csharp/BrowserTool/BrowserTool/Resources/checkin_icon2.png b/csharp/BrowserTool/BrowserTool/Resources/checkin_icon2.png new file mode 100644 index 0000000000000000000000000000000000000000..e210ae9b93328766978f58c6ecefb2006b2314ac --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Resources/checkin_icon2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa91bbed35706b3e8efde664bd2030fa06dd31ff3d852b4fd99248dc7e9d462e +size 12616 diff --git a/csharp/BrowserTool/BrowserTool/Resources/default_icon.png b/csharp/BrowserTool/BrowserTool/Resources/default_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..35c7664a9f6737ff41236349aca066b5c5281c45 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Resources/default_icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:906fbfdb40752d88a55cacba55f36a1e9e1cb9124d0cfbd91c4b86e426dffbdd +size 1752 diff --git a/csharp/BrowserTool/BrowserTool/Resources/image_matcher.py b/csharp/BrowserTool/BrowserTool/Resources/image_matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..46a9be167469f68d12d3308d8dea41a9dfecfc5d --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/Resources/image_matcher.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +图像匹配脚本 - image_matcher.py +使用pyautogui在屏幕上查找指定图片并返回坐标 +放在exe所在目录即可 +""" + +import sys +import os +import pyautogui +import time +import logging +from datetime import datetime + +# 配置日志 +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler('log/image_matcher.log', encoding='utf-8'), + logging.StreamHandler() + ] +) + +logger = logging.getLogger(__name__) + +def find_image_on_screen(image_path, confidence=0.8, timeout=10): + """ + 在屏幕上查找指定图片 + + Args: + image_path (str): 图片文件路径 + confidence (float): 匹配置信度 (0.0-1.0) + timeout (int): 超时时间(秒) + + Returns: + tuple: (x, y) 坐标,找不到返回 None + """ + try: + # 检查图片文件是否存在 + if not os.path.exists(image_path): + logger.error(f"图片文件不存在: {image_path}") + return None + + logger.info(f"开始查找图片: {image_path}") + logger.info(f"置信度: {confidence}, 超时时间: {timeout}秒") + + start_time = time.time() + + while time.time() - start_time < timeout: + try: + # 使用pyautogui查找图片 + location = pyautogui.locateOnScreen( + image_path, + confidence=confidence + ) + + if location is not None: + # 获取图片中心坐标 + center_x, center_y = pyautogui.center(location) + logger.info(f"找到图片位置: ({center_x}, {center_y})") + logger.info(f"图片区域: {location}") + return (center_x, center_y) + + except pyautogui.ImageNotFoundException: + # 图片未找到,继续等待 + pass + except Exception as e: + logger.warning(f"查找图片时发生异常: {e}") + + # 等待一段时间后再次尝试 + time.sleep(0.5) + + logger.warning(f"超时未找到图片: {image_path}") + return None + + except Exception as e: + logger.error(f"查找图片时发生严重异常: {e}") + return None + +def capture_screen_for_debug(save_path="debug_screenshot.png"): + """ + 截取当前屏幕用于调试 + + Args: + save_path (str): 截图保存路径 + """ + try: + screenshot = pyautogui.screenshot() + screenshot.save(save_path) + logger.info(f"调试截图已保存: {save_path}") + except Exception as e: + logger.error(f"截图失败: {e}") + +def check_pyautogui_environment(): + """ + 检查pyautogui环境是否正常 + """ + try: + # 获取屏幕分辨率 + screen_width, screen_height = pyautogui.size() + logger.info(f"屏幕分辨率: {screen_width}x{screen_height}") + + # 检查pyautogui版本 + logger.info(f"PyAutoGUI版本: {pyautogui.__version__}") + + # 测试截图功能 + screenshot = pyautogui.screenshot() + logger.info(f"截图测试成功,图片大小: {screenshot.size}") + + return True + except Exception as e: + logger.error(f"PyAutoGUI环境检查失败: {e}") + return False + +def main(): + """ + 主函数 + """ + try: + # 检查命令行参数 + if len(sys.argv) != 2: + logger.error("用法: python image_matcher.py <图片路径>") + print("用法: python image_matcher.py <图片路径>") + sys.exit(1) + + image_path = sys.argv[1] + logger.info(f"接收到图片路径: {image_path}") + + # 检查pyautogui环境 + if not check_pyautogui_environment(): + logger.error("PyAutoGUI环境检查失败") + sys.exit(1) + + # 禁用pyautogui的安全特性(允许在屏幕边角移动鼠标) + pyautogui.FAILSAFE = False + + # 设置pyautogui的暂停时间 + pyautogui.PAUSE = 0.1 + + # 查找图片 + coordinates = find_image_on_screen( + image_path, + confidence=0.8, # 可以根据需要调整置信度 + timeout=10 # 查找超时时间 + ) + + if coordinates is not None: + x, y = coordinates + # 输出坐标供C#程序读取(重要:这是C#程序读取的内容) + print(f"{x},{y}") + logger.info(f"成功找到图片,坐标: ({x}, {y})") + sys.exit(0) # 成功退出 + else: + logger.error("未找到指定图片") + # 保存调试截图 + debug_filename = f"debug_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png" + capture_screen_for_debug(debug_filename) + logger.info(f"已保存调试截图: {debug_filename}") + sys.exit(1) # 失败退出 + + except KeyboardInterrupt: + logger.info("用户中断程序") + sys.exit(1) + except Exception as e: + logger.error(f"程序执行异常: {e}") + sys.exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/csharp/BrowserTool/BrowserTool/SettingsWindow.xaml b/csharp/BrowserTool/BrowserTool/SettingsWindow.xaml new file mode 100644 index 0000000000000000000000000000000000000000..64000ce18865df8d66d677cc46c8b40063ab25d6 --- /dev/null +++ b/csharp/BrowserTool/BrowserTool/SettingsWindow.xaml @@ -0,0 +1,307 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +