Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
Replace C# Avalonia GUI with a native C GUI
AnoF-Cyber3593cbe84ed2
diff --git a/Windows/README.md b/Windows/README.mdindex fd13ae6..e524735 100644--- a/Windows/README.md+++ b/Windows/README.md@@ -417,7 +417,7 @@ The script automatically:- Locates your Visual Studio installation via `vswhere`- Compiles `ProxyBridgeCore.dll` (C, MSVC, WinDivert)- Compiles `ProxyBridge_CLI.exe` (C, MSVC, native)-- Builds `ProxyBridge.exe` (C#, .NET 10, Avalonia GUI)+- Builds `ProxyBridge.exe` (C GUI, MSVC, self-contained)- Copies all outputs to `Windows\output\`### Manual Build - DLL (MSVC)diff --git a/Windows/compile.ps1 b/Windows/compile.ps1index 36af882..a12306b 100644--- a/Windows/compile.ps1+++ b/Windows/compile.ps1@@ -196,38 +196,43 @@ if ($success) {}}- Write-Host "`nPublishing GUI..." -ForegroundColor Green- $publishResult = dotnet publish gui/ProxyBridge.GUI.csproj -c Release -r win-x64 --self-contained `- /p:PublishTrimmed=true `- /p:PublishSingleFile=false `- /p:EnableCompressionInSingleFile=true `- /p:DebugType=None `- /p:DebugSymbols=false `- /p:Optimize=true `- /p:TieredCompilation=true `- /p:TieredCompilationQuickJit=false `- /p:ReadyToRun=true `- -o gui/bin/Release/net10.0-windows/win-x64/publish 2>&1- if ($LASTEXITCODE -eq 0) {- Write-Host " GUI published successfully" -ForegroundColor Gray-- Write-Host "`nCopying GUI files to output..." -ForegroundColor Green- $guiPublishPath = "gui\bin\Release\net10.0-windows\win-x64\publish"-- Copy-Item "$guiPublishPath\ProxyBridge.exe" -Destination $OutputDir -Force- Write-Host " Copied: ProxyBridge.exe" -ForegroundColor Gray-- Get-ChildItem "$guiPublishPath\*.dll" | ForEach-Object {- Copy-Item $_.FullName -Destination $OutputDir -Force- Write-Host " Copied: $($_.Name)" -ForegroundColor Gray- }+ # ── C GUI (MSVC) ─────────────────────────────────────────────────────────+ # Single self-contained ProxyBridge.exe (~0.5 MB, static CRT) that loads+ # ProxyBridgeCore.dll from its own folder. No extra runtime or DLLs.+ Write-Host "`nBuilding C GUI (MSVC)..." -ForegroundColor Green+ if ($script:foundVcvarsPath -and (Test-Path $script:foundVcvarsPath)) {+ # Production build. Compiler: size-optimized static-CRT release with the security+ # hardening set — /GS (stack cookies), /guard:cf (Control Flow Guard), /sdl (extra+ # security diagnostics), /GL + /Gy for whole-program opt & COMDAT folding.+ # Linker: /DYNAMICBASE + /HIGHENTROPYVA (64-bit ASLR), /NXCOMPAT (DEP),+ # /guard:cf (CFG), /CETCOMPAT (shadow-stack), /LTCG, dead-code strip.+ $guiClArgs = "/nologo /utf-8 /O1 /Os /MT /GL /Gy /GS /guard:cf /sdl /W4 " ++ "/DNDEBUG /D_CRT_SECURE_NO_WARNINGS /DUNICODE /D_UNICODE " ++ "main.c profile\profile.c app.res " ++ "/Fe:ProxyBridge.exe " ++ "/link /LTCG /SUBSYSTEM:WINDOWS /OPT:REF /OPT:ICF /RELEASE " ++ "/DYNAMICBASE /HIGHENTROPYVA /NXCOMPAT /guard:cf /CETCOMPAT " ++ "user32.lib gdi32.lib comctl32.lib shell32.lib comdlg32.lib winhttp.lib"++ # Sources live in subfolders. rc runs from res\ so app.rc's relative paths+ # (resource.h, app.manifest, logo.ico) resolve; it writes app.res back to gui\.+ Push-Location "gui"+ $guiCmd = "`"$script:foundVcvarsPath`" $script:foundArch >nul && " ++ "pushd res && rc /nologo /fo ..\app.res app.rc && popd && cl.exe $guiClArgs"+ $guiOut = cmd /c $guiCmd '2>&1'+ $guiExit = $LASTEXITCODE+ Pop-Location- Write-Host "`nCleaning up GUI build artifacts..." -ForegroundColor Yellow- Remove-Item "gui\bin" -Recurse -Force -ErrorAction SilentlyContinue- Remove-Item "gui\obj" -Recurse -Force -ErrorAction SilentlyContinue+ if ($guiExit -eq 0 -and (Test-Path "gui\ProxyBridge.exe")) {+ Move-Item "gui\ProxyBridge.exe" -Destination $OutputDir -Force+ Write-Host " C GUI built: ProxyBridge.exe" -ForegroundColor Gray+ Remove-Item "gui\*.obj","gui\app.res" -Force -ErrorAction SilentlyContinue+ } else {+ Write-Host " C GUI build failed!" -ForegroundColor Red+ Write-Host $guiOut+ }} else {- Write-Host " GUI publish failed!" -ForegroundColor Red- Write-Host $publishResult+ Write-Host " Skipped: MSVC not found" -ForegroundColor Yellow}# ── Build CLI ────────────────────────────────────────────────────────────diff --git a/Windows/gui/App.axaml b/Windows/gui/App.axamldeleted file mode 100644index b16f1ad..0000000--- a/Windows/gui/App.axaml+++ /dev/null@@ -1,25 +0,0 @@-<Application xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- x:Class="ProxyBridge.GUI.App"- RequestedThemeVariant="Dark">- <Application.Styles>- <FluentTheme />- <StyleInclude Source="/Styles/SharedStyles.axaml"/>- </Application.Styles>-- <TrayIcon.Icons>- <TrayIcons>- <TrayIcon Icon="/Assets/logo.ico"- ToolTipText="ProxyBridge"- Clicked="TrayIcon_Show">- <TrayIcon.Menu>- <NativeMenu>- <NativeMenuItem Header="Open" Click="TrayIcon_Show" />- <NativeMenuItemSeparator />- <NativeMenuItem Header="Exit" Click="TrayIcon_Exit" />- </NativeMenu>- </TrayIcon.Menu>- </TrayIcon>- </TrayIcons>- </TrayIcon.Icons>-</Application>diff --git a/Windows/gui/App.axaml.cs b/Windows/gui/App.axaml.csdeleted file mode 100644index 3ce6da0..0000000--- a/Windows/gui/App.axaml.cs+++ /dev/null@@ -1,104 +0,0 @@-using Avalonia;-using Avalonia.Controls.ApplicationLifetimes;-using Avalonia.Markup.Xaml;-using Avalonia.Controls;-using ProxyBridge.GUI.ViewModels;-using ProxyBridge.GUI.Views;-using System;-using System.Threading;-using System.Threading.Tasks;--namespace ProxyBridge.GUI;--public class App : Application-{- public static bool StartMinimized { get; set; }- private EventWaitHandle? _showWindowEvent;- private CancellationTokenSource? _eventListenerCts;- private const string EventName = "Global\\ProxyBridge_ShowWindow_Event_v3.1";-- public override void Initialize() => AvaloniaXamlLoader.Load(this);-- public override void OnFrameworkInitializationCompleted()- {- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)- {- var mainWindow = new MainWindow { DataContext = new MainWindowViewModel() };- desktop.MainWindow = mainWindow;-- if (StartMinimized)- {- // surpress the window before avalonia shows it for the first time.- // Setting these before opened fires prevents any visible window.- mainWindow.ShowInTaskbar = false;- mainWindow.WindowState = WindowState.Minimized;- // usin a oone handler and unsubscribe immediately so subsequent- // Show() calls from the tray "Open" menu are not swallowed.- EventHandler? onOpened = null;- onOpened = (_, _) =>- {- mainWindow.Opened -= onOpened;- mainWindow.Hide();- };- mainWindow.Opened += onOpened;- }-- try- {- _showWindowEvent = new EventWaitHandle(false, EventResetMode.AutoReset, EventName);- _eventListenerCts = new CancellationTokenSource();- Task.Run(() => ListenForActivationSignal(_eventListenerCts.Token));- }- catch { }-- desktop.ShutdownRequested += (s, e) =>- {- _eventListenerCts?.Cancel();- _showWindowEvent?.Dispose();- (desktop.MainWindow?.DataContext as MainWindowViewModel)?.Cleanup();- };-- desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;- }-- base.OnFrameworkInitializationCompleted();- }-- private async Task ListenForActivationSignal(CancellationToken token)- {- while (!token.IsCancellationRequested)- {- try- {- var signaled = await Task.Run(() => _showWindowEvent?.WaitOne(1000) ?? false, token);- if (signaled && !token.IsCancellationRequested)- {- await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>- TrayIcon_Show(null, EventArgs.Empty));- }- }- catch (OperationCanceledException) { break; }- catch { }- }- }-- public void TrayIcon_Show(object? sender, EventArgs e)- {- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)- {- var mainWindow = desktop.MainWindow;- if (mainWindow != null)- {- mainWindow.ShowInTaskbar = true;- mainWindow.Show();- mainWindow.WindowState = WindowState.Normal;- mainWindow.Activate();- }- }- }-- public void TrayIcon_Exit(object? sender, EventArgs e)- {- (ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();- }-}diff --git a/Windows/gui/Common/RelayCommand.cs b/Windows/gui/Common/RelayCommand.csdeleted file mode 100644index f940cd3..0000000--- a/Windows/gui/Common/RelayCommand.cs+++ /dev/null@@ -1,53 +0,0 @@-using System;-using System.Windows.Input;--namespace ProxyBridge.GUI.Common;--public class RelayCommand : ICommand-{- private readonly Action _execute;- private readonly Func<bool>? _canExecute;-- public RelayCommand(Action execute, Func<bool>? canExecute = null)- {- _execute = execute ?? throw new ArgumentNullException(nameof(execute));- _canExecute = canExecute;- }-- public event EventHandler? CanExecuteChanged;-- public bool CanExecute(object? parameter) => _canExecute?.Invoke() ?? true;-- public void Execute(object? parameter) => _execute();-- public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);-}--public class RelayCommandWithParameter<T> : ICommand-{- private readonly Action<T> _execute;- private readonly Func<T, bool>? _canExecute;-- public RelayCommandWithParameter(Action<T> execute, Func<T, bool>? canExecute = null)- {- _execute = execute ?? throw new ArgumentNullException(nameof(execute));- _canExecute = canExecute;- }-- public event EventHandler? CanExecuteChanged;-- public bool CanExecute(object? parameter)- {- if (parameter is T typedParameter)- return _canExecute?.Invoke(typedParameter) ?? true;- return false;- }-- public void Execute(object? parameter)- {- if (parameter is T typedParameter)- _execute(typedParameter);- }-- public void RaiseCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);-}diff --git a/Windows/gui/Common/ValidationHelper.cs b/Windows/gui/Common/ValidationHelper.csdeleted file mode 100644index de3d381..0000000--- a/Windows/gui/Common/ValidationHelper.cs+++ /dev/null@@ -1,59 +0,0 @@-using System;--namespace ProxyBridge.GUI.Common;--// handles common validation patterns-public static class ValidationHelper-{- public static string DefaultIfEmpty(string value, string defaultValue = "*")- {- return string.IsNullOrWhiteSpace(value) ? defaultValue : value;- }-- public static bool ValidateNotEmpty(string value, string errorMessage, Action<string> setError)- {- if (string.IsNullOrWhiteSpace(value))- {- setError(errorMessage);- return false;- }- setError("");- return true;- }-- public static bool ValidatePort(string portStr, Action<string> setError)- {- if (string.IsNullOrWhiteSpace(portStr))- {- setError("Port is required");- return false;- }-- if (!int.TryParse(portStr, out int port) || port < 1 || port > 65535)- {- setError("Port must be between 1 and 65535");- return false;- }-- setError("");- return true;- }-- public static bool ValidateIpOrDomain(string value, Func<string, bool> validator, Action<string> setError)- {- if (string.IsNullOrWhiteSpace(value))- {- setError("IP address or hostname is required");- return false;- }-- if (!validator(value))- {- setError("Invalid IP address or hostname");- return false;- }-- setError("");- return true;- }-}diff --git a/Windows/gui/Interop/ProxyBridgeNative.cs b/Windows/gui/Interop/ProxyBridgeNative.csdeleted file mode 100644index 7d7af51..0000000--- a/Windows/gui/Interop/ProxyBridgeNative.cs+++ /dev/null@@ -1,187 +0,0 @@-using System;-using System.Runtime.InteropServices;-using System.IO;-using System.Reflection;--namespace ProxyBridge.GUI.Interop;--public static class ProxyBridgeNative-{- private const string DllName = "ProxyBridgeCore.dll";-- static ProxyBridgeNative()- {- var assemblyPath = AppContext.BaseDirectory;- if (!string.IsNullOrEmpty(assemblyPath))- {- var dllPath = Path.Combine(assemblyPath, DllName);- if (File.Exists(dllPath))- {- NativeLibrary.Load(dllPath);- }- }- }-- public enum ProxyType- {- HTTP = 0,- SOCKS5 = 1- }-- public enum RuleAction- {- PROXY = 0,- DIRECT = 1,- BLOCK = 2- }-- public enum RuleProtocol- {- TCP = 0,- UDP = 1,- BOTH = 2- }-- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]- public delegate void LogCallback([MarshalAs(UnmanagedType.LPStr)] string message);-- [UnmanagedFunctionPointer(CallingConvention.Cdecl)]- public delegate void ConnectionCallback(- [MarshalAs(UnmanagedType.LPUTF8Str)] string processName,- uint pid,- [MarshalAs(UnmanagedType.LPStr)] string destIp,- ushort destPort,- [MarshalAs(UnmanagedType.LPStr)] string proxyInfo);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern uint ProxyBridge_AddRule(- [MarshalAs(UnmanagedType.LPUTF8Str)] string processName,- [MarshalAs(UnmanagedType.LPStr)] string targetHosts,- [MarshalAs(UnmanagedType.LPStr)] string targetPorts,- [MarshalAs(UnmanagedType.LPStr)] string targetDomains,- RuleProtocol protocol,- RuleAction action,- uint proxyConfigId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_EnableRule(uint ruleId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_DisableRule(uint ruleId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_DeleteRule(uint ruleId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_EditRule(- uint ruleId,- [MarshalAs(UnmanagedType.LPUTF8Str)] string processName,- [MarshalAs(UnmanagedType.LPStr)] string targetHosts,- [MarshalAs(UnmanagedType.LPStr)] string targetPorts,- [MarshalAs(UnmanagedType.LPStr)] string targetDomains,- RuleProtocol protocol,- RuleAction action,- uint proxyConfigId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern uint ProxyBridge_GetRulePosition(uint ruleId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_MoveRuleToPosition(uint ruleId, uint newPosition);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ProxyBridge_AddProxyConfig")]- private static extern uint ProxyBridge_AddProxyConfig_Native(- ProxyType type,- [MarshalAs(UnmanagedType.LPStr)] string proxyIp,- ushort proxyPort,- [MarshalAs(UnmanagedType.LPStr)] string username,- [MarshalAs(UnmanagedType.LPStr)] string password);-- public static uint ProxyBridge_AddProxyConfig(- ProxyType type,- string proxyIp,- ushort proxyPort,- string username,- string password)- {- if (string.IsNullOrWhiteSpace(proxyIp))- throw new ArgumentException("Proxy IP must not be null or empty.", nameof(proxyIp));- username ??= string.Empty;- password ??= string.Empty;- return ProxyBridge_AddProxyConfig_Native(type, proxyIp, proxyPort, username, password);- }-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ProxyBridge_EditProxyConfig")]- [return: MarshalAs(UnmanagedType.Bool)]- private static extern bool ProxyBridge_EditProxyConfig_Native(- uint configId,- ProxyType type,- [MarshalAs(UnmanagedType.LPStr)] string proxyIp,- ushort proxyPort,- [MarshalAs(UnmanagedType.LPStr)] string username,- [MarshalAs(UnmanagedType.LPStr)] string password);-- public static bool ProxyBridge_EditProxyConfig(- uint configId,- ProxyType type,- string proxyIp,- ushort proxyPort,- string username,- string password)- {- username ??= string.Empty;- password ??= string.Empty;- return ProxyBridge_EditProxyConfig_Native(configId, type, proxyIp, proxyPort, username, password);- }-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_DeleteProxyConfig(uint configId);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "ProxyBridge_TestProxyConfig")]- private static extern int ProxyBridge_TestProxyConfig_Native(- uint configId,- [MarshalAs(UnmanagedType.LPStr)] string targetHost,- ushort targetPort,- [MarshalAs(UnmanagedType.LPStr)] System.Text.StringBuilder resultBuffer,- UIntPtr bufferSize);-- public static int ProxyBridge_TestProxyConfig(- uint configId,- string targetHost,- ushort targetPort,- System.Text.StringBuilder resultBuffer,- UIntPtr bufferSize)- {- ArgumentNullException.ThrowIfNull(targetHost);- ArgumentNullException.ThrowIfNull(resultBuffer);- var effectiveSize = bufferSize == UIntPtr.Zero ? (UIntPtr)resultBuffer.Capacity : bufferSize;- return ProxyBridge_TestProxyConfig_Native(configId, targetHost, targetPort, resultBuffer, effectiveSize);- }-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern void ProxyBridge_SetLogCallback(LogCallback callback);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern void ProxyBridge_SetConnectionCallback(ConnectionCallback callback);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern void ProxyBridge_SetTrafficLoggingEnabled([MarshalAs(UnmanagedType.Bool)] bool enable);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- public static extern void ProxyBridge_SetLocalhostViaProxy([MarshalAs(UnmanagedType.Bool)] bool enable);-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_Start();-- [DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]- [return: MarshalAs(UnmanagedType.Bool)]- public static extern bool ProxyBridge_Stop();--}diff --git a/Windows/gui/Program.cs b/Windows/gui/Program.csdeleted file mode 100644index 3d873bb..0000000--- a/Windows/gui/Program.cs+++ /dev/null@@ -1,51 +0,0 @@-using Avalonia;-using System;-using System.Threading;--namespace ProxyBridge.GUI;--class Program-{- private static Mutex? _instanceMutex;- private const string MutexName = "Global\\ProxyBridge_SingleInstance_Mutex_v3.1";- private const string EventName = "Global\\ProxyBridge_ShowWindow_Event_v3.1";-- [STAThread]- public static void Main(string[] args)- {- _instanceMutex = new Mutex(true, MutexName, out bool isNewInstance);-- if (!isNewInstance)- {- SignalExistingInstance();- return;- }-- try- {- App.StartMinimized = args.Length > 0 && args[0] == "--minimized";- BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);- }- finally- {- _instanceMutex?.ReleaseMutex();- _instanceMutex?.Dispose();- }- }-- private static void SignalExistingInstance()- {- try- {- using var showEvent = EventWaitHandle.OpenExisting(EventName);- showEvent.Set();- }- catch { }- }-- public static AppBuilder BuildAvaloniaApp()- => AppBuilder.Configure<App>()- .UsePlatformDetect()- .WithInterFont()- .LogToTrace();-}diff --git a/Windows/gui/ProxyBridge.GUI.csproj b/Windows/gui/ProxyBridge.GUI.csprojdeleted file mode 100644index 1e6c4fe..0000000--- a/Windows/gui/ProxyBridge.GUI.csproj+++ /dev/null@@ -1,64 +0,0 @@-<Project Sdk="Microsoft.NET.Sdk">- <PropertyGroup>- <OutputType>WinExe</OutputType>- <TargetFramework>net10.0-windows</TargetFramework>- <Nullable>enable</Nullable>- <BuiltInComInteropSupport>true</BuiltInComInteropSupport>- <ApplicationManifest>app.manifest</ApplicationManifest>- <AssemblyName>ProxyBridge</AssemblyName>- <RootNamespace>ProxyBridge.GUI</RootNamespace>- <Version>4.0.9-Beta</Version>- <AssemblyVersion>4.0.9</AssemblyVersion>- <FileVersion>4.0.9</FileVersion>- <ApplicationIcon>Assets\logo.ico</ApplicationIcon>- <Company>InterceptSuite</Company>- <Product>ProxyBridge</Product>- <Copyright>Copyright © 2026 InterceptSuite</Copyright>- <Description>Universal proxy client for Windows applications</Description>- <NeutralLanguage>en-US</NeutralLanguage>- <PublishAot>true</PublishAot>- <PublishTrimmed>true</PublishTrimmed>- <TrimMode>link</TrimMode>-- <IlcOptimizationPreference>Size</IlcOptimizationPreference>- <IlcFoldIdenticalMethodBodies>true</IlcFoldIdenticalMethodBodies>- <IlcGenerateDgmlFile>false</IlcGenerateDgmlFile>- <StripSymbols>true</StripSymbols>- <EventSourceSupport>false</EventSourceSupport>- <UseSystemResourceKeys>true</UseSystemResourceKeys>- <DebuggerSupport>false</DebuggerSupport>- <MetadataUpdaterSupport>false</MetadataUpdaterSupport>- <HttpActivityPropagationSupport>false</HttpActivityPropagationSupport>- <InvariantGlobalization>false</InvariantGlobalization>- </PropertyGroup>-- <ItemGroup>- <AvaloniaResource Include="Assets\logo.ico" />- </ItemGroup>-- <ItemGroup>- <EmbeddedResource Update="Resources\Resources.resx">- <Generator>ResXFileCodeGenerator</Generator>- <LastGenOutput>Resources.Designer.cs</LastGenOutput>- </EmbeddedResource>- <EmbeddedResource Update="Resources\Resources.zh.resx">- <DependentUpon>Resources.resx</DependentUpon>- </EmbeddedResource>- </ItemGroup>-- <ItemGroup>- <Compile Update="Resources\Resources.Designer.cs">- <DesignTime>True</DesignTime>- <AutoGen>True</AutoGen>- <DependentUpon>Resources.resx</DependentUpon>- </Compile>- </ItemGroup>-- <ItemGroup>- <PackageReference Include="Avalonia" Version="12.0.5" />- <PackageReference Include="Avalonia.Desktop" Version="12.0.5" />- <PackageReference Include="Avalonia.Themes.Fluent" Version="12.0.5" />- <PackageReference Include="Avalonia.Fonts.Inter" Version="12.0.5" />- <PackageReference Include="Avalonia.Diagnostics" Version="12.0.5" Condition="'$(Configuration)' == 'Debug'" />- </ItemGroup>-</Project>diff --git a/Windows/gui/Resources/Resources.Designer.cs b/Windows/gui/Resources/Resources.Designer.csdeleted file mode 100644index fdf0989..0000000--- a/Windows/gui/Resources/Resources.Designer.cs+++ /dev/null@@ -1,457 +0,0 @@-//-------------------------------------------------------------------------------// <auto-generated>-// 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.-// </auto-generated>-//--------------------------------------------------------------------------------namespace ProxyBridge.GUI.Resources {- using System;--- /// <summary>- /// A strongly-typed resource class, for looking up localized strings, etc.- /// </summary>- [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.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() {- }-- /// <summary>- /// Returns the cached ResourceManager instance used by this class.- /// </summary>- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]- internal static global::System.Resources.ResourceManager ResourceManager {- get {- if (object.ReferenceEquals(resourceMan, null)) {- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProxyBridge.GUI.Resources.Resources", typeof(Resources).Assembly);- resourceMan = temp;- }- return resourceMan;- }- }-- /// <summary>- /// Overrides the current thread's CurrentUICulture property for all- /// resource lookups using this strongly typed resource class.- /// </summary>- [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]- public static global::System.Globalization.CultureInfo Culture {- get {- return resourceCulture;- }- set {- resourceCulture = value;- }- }-- /// <summary>- /// Looks up a localized string similar to Proxy.- /// </summary>- internal static string MenuProxy {- get {- return ResourceManager.GetString("MenuProxy", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Proxy Settings.- /// </summary>- internal static string MenuProxySettings {- get {- return ResourceManager.GetString("MenuProxySettings", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Proxy Rules.- /// </summary>- internal static string MenuProxyRules {- get {- return ResourceManager.GetString("MenuProxyRules", resourceCulture);- }- }-- internal static string MenuLocalhostViaProxy {- get {- return ResourceManager.GetString("MenuLocalhostViaProxy", resourceCulture);- }- }-- internal static string MenuEnableTrafficLogging {- get {- return ResourceManager.GetString("MenuEnableTrafficLogging", resourceCulture);- }- }-- internal static string MenuLogFilters {- get {- return ResourceManager.GetString("MenuLogFilters", resourceCulture);- }- }-- internal static string LogFiltersDesc1 =>- ResourceManager.GetString("LogFiltersDesc1", resourceCulture);-- internal static string LogFiltersDesc2 =>- ResourceManager.GetString("LogFiltersDesc2", resourceCulture);-- internal static string MenuAutoClearLogs {- get {- return ResourceManager.GetString("MenuAutoClearLogs", resourceCulture);- }- }-- internal static string MenuSettings {- get {- return ResourceManager.GetString("MenuSettings", resourceCulture);- }- }-- internal static string MenuCloseToTray {- get {- return ResourceManager.GetString("MenuCloseToTray", resourceCulture);- }- }-- internal static string MenuRunAtStartup {- get {- return ResourceManager.GetString("MenuRunAtStartup", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Language.- /// </summary>- internal static string MenuLanguage {- get {- return ResourceManager.GetString("MenuLanguage", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to About.- /// </summary>- internal static string MenuAbout {- get {- return ResourceManager.GetString("MenuAbout", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to About ProxyBridge.- /// </summary>- internal static string MenuAboutProxyBridge {- get {- return ResourceManager.GetString("MenuAboutProxyBridge", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Check for Updates.- /// </summary>- internal static string MenuCheckUpdates {- get {- return ResourceManager.GetString("MenuCheckUpdates", resourceCulture);- }- }-- internal static string MenuProfile => ResourceManager.GetString("MenuProfile", resourceCulture);- internal static string MenuNewProfile => ResourceManager.GetString("MenuNewProfile", resourceCulture);- internal static string MenuRenameProfile => ResourceManager.GetString("MenuRenameProfile", resourceCulture);- internal static string MenuDeleteProfile => ResourceManager.GetString("MenuDeleteProfile", resourceCulture);- internal static string MenuSwitchProfile => ResourceManager.GetString("MenuSwitchProfile", resourceCulture);- internal static string MenuImportProfile => ResourceManager.GetString("MenuImportProfile", resourceCulture);- internal static string MenuExportProfile => ResourceManager.GetString("MenuExportProfile", resourceCulture);-- /// <summary>- /// Looks up a localized string similar to 🔌 Connections.- /// </summary>- internal static string TabConnections {- get {- return ResourceManager.GetString("TabConnections", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to 📝 Activity Logs.- /// </summary>- internal static string TabActivity {- get {- return ResourceManager.GetString("TabActivity", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Clear All Connections.- /// </summary>- internal static string ButtonClearAllConnections {- get {- return ResourceManager.GetString("ButtonClearAllConnections", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Clear All Logs.- /// </summary>- internal static string ButtonClearAllLogs {- get {- return ResourceManager.GetString("ButtonClearAllLogs", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Save.- /// </summary>- internal static string ButtonSave {- get {- return ResourceManager.GetString("ButtonSave", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Cancel.- /// </summary>- internal static string ButtonCancel {- get {- return ResourceManager.GetString("ButtonCancel", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Close.- /// </summary>- internal static string ButtonClose {- get {- return ResourceManager.GetString("ButtonClose", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Add.- /// </summary>- internal static string ButtonAdd {- get {- return ResourceManager.GetString("ButtonAdd", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Edit.- /// </summary>- internal static string ButtonEdit {- get {- return ResourceManager.GetString("ButtonEdit", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Delete.- /// </summary>- internal static string ButtonDelete {- get {- return ResourceManager.GetString("ButtonDelete", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to 🔍 Search connections....- /// </summary>- internal static string SearchConnectionsPlaceholder {- get {- return ResourceManager.GetString("SearchConnectionsPlaceholder", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to 🔍 Search activity logs....- /// </summary>- internal static string SearchActivityPlaceholder {- get {- return ResourceManager.GetString("SearchActivityPlaceholder", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to ProxyBridge initialized successfully.- /// </summary>- internal static string LogInitialized {- get {- return ResourceManager.GetString("LogInitialized", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to ProxyBridge service started successfully.- /// </summary>- internal static string LogServiceStarted {- get {- return ResourceManager.GetString("LogServiceStarted", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to ERROR: Failed to start ProxyBridge service.- /// </summary>- internal static string LogServiceStartFailed {- get {- return ResourceManager.GetString("LogServiceStartFailed", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Restored proxy settings.- /// </summary>- internal static string LogRestoredProxySettings {- get {- return ResourceManager.GetString("LogRestoredProxySettings", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Restored {0} proxy rule(s).- /// </summary>- internal static string LogRestoredRules {- get {- return ResourceManager.GetString("LogRestoredRules", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Configuration saved successfully.- /// </summary>- internal static string LogConfigSaved {- get {- return ResourceManager.GetString("LogConfigSaved", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Failed to load configuration.- /// </summary>- internal static string LogConfigLoadFailed {- get {- return ResourceManager.GetString("LogConfigLoadFailed", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Failed to save configuration.- /// </summary>- internal static string LogConfigSaveFailed {- get {- return ResourceManager.GetString("LogConfigSaveFailed", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Saved proxy settings.- /// </summary>- internal static string LogProxySettingsSaved {- get {- return ResourceManager.GetString("LogProxySettingsSaved", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to ERROR: Failed to set proxy config.- /// </summary>- internal static string LogProxySettingsFailed {- get {- return ResourceManager.GetString("LogProxySettingsFailed", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Added rule.- /// </summary>- internal static string LogRuleAdded {- get {- return ResourceManager.GetString("LogRuleAdded", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to ERROR: Failed to add rule.- /// </summary>- internal static string LogRuleAddFailed {- get {- return ResourceManager.GetString("LogRuleAddFailed", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to Language changed to.- /// </summary>- internal static string LogLanguageChanged {- get {- return ResourceManager.GetString("LogLanguageChanged", resourceCulture);- }- }-- /// <summary>- /// Looks up a localized string similar to with auth.- /// </summary>- internal static string LogWithAuth {- get {- return ResourceManager.GetString("LogWithAuth", resourceCulture);- }- }-- // Proxy Settings Window- internal static string WindowProxySettings => ResourceManager.GetString("WindowProxySettings", resourceCulture);- internal static string LabelProxyType => ResourceManager.GetString("LabelProxyType", resourceCulture);- internal static string LabelProxyIp => ResourceManager.GetString("LabelProxyIp", resourceCulture);- internal static string LabelProxyPort => ResourceManager.GetString("LabelProxyPort", resourceCulture);- internal static string LabelUsername => ResourceManager.GetString("LabelUsername", resourceCulture);- internal static string LabelPassword => ResourceManager.GetString("LabelPassword", resourceCulture);- internal static string LabelRequiredFields => ResourceManager.GetString("LabelRequiredFields", resourceCulture);- internal static string LabelTestConnection => ResourceManager.GetString("LabelTestConnection", resourceCulture);- internal static string ButtonTestProxy => ResourceManager.GetString("ButtonTestProxy", resourceCulture);- internal static string LabelTargetHost => ResourceManager.GetString("LabelTargetHost", resourceCulture);- internal static string LabelPort => ResourceManager.GetString("LabelPort", resourceCulture);- internal static string ButtonStartTest => ResourceManager.GetString("ButtonStartTest", resourceCulture);- internal static string LabelOutput => ResourceManager.GetString("LabelOutput", resourceCulture);- internal static string ButtonSaveChanges => ResourceManager.GetString("ButtonSaveChanges", resourceCulture);- internal static string PlaceholderIpAddress => ResourceManager.GetString("PlaceholderIpAddress", resourceCulture);- internal static string PlaceholderPort => ResourceManager.GetString("PlaceholderPort", resourceCulture);- internal static string PlaceholderNoAuth => ResourceManager.GetString("PlaceholderNoAuth", resourceCulture);-- // Proxy Rules Window- internal static string WindowProxyRules => ResourceManager.GetString("WindowProxyRules", resourceCulture);- internal static string LabelEnabled => ResourceManager.GetString("LabelEnabled", resourceCulture);- internal static string LabelActions => ResourceManager.GetString("LabelActions", resourceCulture);- internal static string LabelSR => ResourceManager.GetString("LabelSR", resourceCulture);- internal static string LabelProcess => ResourceManager.GetString("LabelProcess", resourceCulture);- internal static string LabelTargetHosts => ResourceManager.GetString("LabelTargetHosts", resourceCulture);- internal static string LabelTargetPorts => ResourceManager.GetString("LabelTargetPorts", resourceCulture);- internal static string LabelProtocol => ResourceManager.GetString("LabelProtocol", resourceCulture);- internal static string LabelAction => ResourceManager.GetString("LabelAction", resourceCulture);- internal static string LabelApplications => ResourceManager.GetString("LabelApplications", resourceCulture);- internal static string ButtonBrowse => ResourceManager.GetString("ButtonBrowse", resourceCulture);- internal static string ExampleApplications => ResourceManager.GetString("ExampleApplications", resourceCulture);- internal static string ExampleTargetHosts => ResourceManager.GetString("ExampleTargetHosts", resourceCulture);- internal static string ExampleTargetPorts => ResourceManager.GetString("ExampleTargetPorts", resourceCulture);- internal static string LabelTargetDomains => ResourceManager.GetString("LabelTargetDomains", resourceCulture);- internal static string ExampleTargetDomains => ResourceManager.GetString("ExampleTargetDomains", resourceCulture);- internal static string ProtocolTCP => ResourceManager.GetString("ProtocolTCP", resourceCulture);- internal static string ProtocolUDP => ResourceManager.GetString("ProtocolUDP", resourceCulture);- internal static string ProtocolBoth => ResourceManager.GetString("ProtocolBoth", resourceCulture);- internal static string UDPProxyNote => ResourceManager.GetString("UDPProxyNote", resourceCulture);- internal static string ActionProxy => ResourceManager.GetString("ActionProxy", resourceCulture);- internal static string ActionDirect => ResourceManager.GetString("ActionDirect", resourceCulture);- internal static string ActionBlock => ResourceManager.GetString("ActionBlock", resourceCulture);- internal static string ButtonSaveRule => ResourceManager.GetString("ButtonSaveRule", resourceCulture);- }-}diff --git a/Windows/gui/Resources/Resources.resx b/Windows/gui/Resources/Resources.resxdeleted file mode 100644index 013e2ea..0000000--- a/Windows/gui/Resources/Resources.resx+++ /dev/null@@ -1,297 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<root>- <resheader name="resmimetype">- <value>text/microsoft-resx</value>- </resheader>- <resheader name="version">- <value>2.0</value>- </resheader>- <resheader name="reader">- <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>- </resheader>- <resheader name="writer">- <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>- </resheader>-- <!-- Menu Items -->- <data name="MenuProxy" xml:space="preserve">- <value>Proxy</value>- </data>- <data name="MenuProxySettings" xml:space="preserve">- <value>Proxy Settings</value>- </data>- <data name="MenuProxyRules" xml:space="preserve">- <value>Proxy Rules</value>- </data>- <data name="MenuLocalhostViaProxy" xml:space="preserve">- <value>Localhost via Proxy</value>- </data>- <data name="MenuEnableTrafficLogging" xml:space="preserve">- <value>Enable Traffic Logging</value>- </data>- <data name="MenuLogFilters" xml:space="preserve">- <value>Log Filters...</value>- </data>- <data name="LogFiltersDesc1" xml:space="preserve">- <value>Each rule can match on any combination of fields leave a field empty or set to "All" to ignore it. Include rules show only matching connections. Exclude rules hide matching connections. Excludes run first.</value>- </data>- <data name="LogFiltersDesc2" xml:space="preserve">- <value>Use * as a wildcard in text fields: chrome* = starts with, *.exe = ends with, *ch* = contains anywhere.</value>- </data>- <data name="MenuAutoClearLogs" xml:space="preserve">- <value>Auto Clear Logs</value>- </data>- <data name="MenuSettings" xml:space="preserve">- <value>Settings</value>- </data>- <data name="MenuCloseToTray" xml:space="preserve">- <value>Close to System Tray</value>- </data>- <data name="MenuRunAtStartup" xml:space="preserve">- <value>Run at Startup</value>- </data>- <data name="MenuLanguage" xml:space="preserve">- <value>Language</value>- </data>- <data name="MenuAbout" xml:space="preserve">- <value>About</value>- </data>- <data name="MenuAboutProxyBridge" xml:space="preserve">- <value>About ProxyBridge</value>- </data>- <data name="MenuCheckUpdates" xml:space="preserve">- <value>Check for Updates</value>- </data>- <!-- Profile Menu -->- <data name="MenuProfile" xml:space="preserve">- <value>Profile</value>- </data>- <data name="MenuNewProfile" xml:space="preserve">- <value>New Profile</value>- </data>- <data name="MenuRenameProfile" xml:space="preserve">- <value>Rename Profile</value>- </data>- <data name="MenuDeleteProfile" xml:space="preserve">- <value>Delete Profile</value>- </data>- <data name="MenuSwitchProfile" xml:space="preserve">- <value>Switch Profile</value>- </data>- <data name="MenuImportProfile" xml:space="preserve">- <value>Import Profile</value>- </data>- <data name="MenuExportProfile" xml:space="preserve">- <value>Export Profile</value>- </data>-- <!-- Tabs -->- <data name="TabConnections" xml:space="preserve">- <value>Connections</value>- </data>- <data name="TabActivity" xml:space="preserve">- <value>Activity Logs</value>- </data>-- <!-- Buttons -->- <data name="ButtonClearAllConnections" xml:space="preserve">- <value>Clear All Connections</value>- </data>- <data name="ButtonClearAllLogs" xml:space="preserve">- <value>Clear All Logs</value>- </data>- <data name="ButtonSave" xml:space="preserve">- <value>Save</value>- </data>- <data name="ButtonCancel" xml:space="preserve">- <value>Cancel</value>- </data>- <data name="ButtonClose" xml:space="preserve">- <value>Close</value>- </data>- <data name="ButtonAdd" xml:space="preserve">- <value>Add</value>- </data>- <data name="ButtonEdit" xml:space="preserve">- <value>Edit</value>- </data>- <data name="ButtonDelete" xml:space="preserve">- <value>Delete</value>- </data>-- <!-- Search Placeholders -->- <data name="SearchConnectionsPlaceholder" xml:space="preserve">- <value>🔍 Search connections...</value>- </data>- <data name="SearchActivityPlaceholder" xml:space="preserve">- <value>🔍 Search activity logs...</value>- </data>-- <!-- Log Messages -->- <data name="LogServiceStarted" xml:space="preserve">- <value>ProxyBridge service started successfully</value>- </data>- <data name="LogServiceStartFailed" xml:space="preserve">- <value>ERROR: Failed to start ProxyBridge service</value>- </data>- <data name="LogRestoredProxySettings" xml:space="preserve">- <value>Restored proxy settings</value>- </data>- <data name="LogRestoredRules" xml:space="preserve">- <value>Restored {0} proxy rule(s)</value>- </data>- <data name="LogConfigSaved" xml:space="preserve">- <value>Configuration saved successfully</value>- </data>- <data name="LogConfigLoadFailed" xml:space="preserve">- <value>Failed to load configuration</value>- </data>- <data name="LogConfigSaveFailed" xml:space="preserve">- <value>Failed to save configuration</value>- </data>- <data name="LogProxySettingsSaved" xml:space="preserve">- <value>Saved proxy settings</value>- </data>- <data name="LogProxySettingsFailed" xml:space="preserve">- <value>ERROR: Failed to set proxy config</value>- </data>- <data name="LogRuleAdded" xml:space="preserve">- <value>Added rule</value>- </data>- <data name="LogRuleAddFailed" xml:space="preserve">- <value>ERROR: Failed to add rule</value>- </data>- <data name="LogLanguageChanged" xml:space="preserve">- <value>Language changed to</value>- </data>- <data name="LogWithAuth" xml:space="preserve">- <value>with auth</value>- </data>-- <!-- Proxy Settings Window -->- <data name="WindowProxySettings" xml:space="preserve">- <value>Proxy Settings</value>- </data>- <data name="LabelProxyType" xml:space="preserve">- <value>Proxy Type</value>- </data>- <data name="LabelProxyIp" xml:space="preserve">- <value>Proxy IP Address *</value>- </data>- <data name="LabelProxyPort" xml:space="preserve">- <value>Proxy Port *</value>- </data>- <data name="LabelUsername" xml:space="preserve">- <value>Username (Optional)</value>- </data>- <data name="LabelPassword" xml:space="preserve">- <value>Password (Optional)</value>- </data>- <data name="LabelRequiredFields" xml:space="preserve">- <value>* Required fields</value>- </data>- <data name="LabelTestConnection" xml:space="preserve">- <value>Test Connection</value>- </data>- <data name="ButtonTestProxy" xml:space="preserve">- <value>Test Proxy Connection</value>- </data>- <data name="LabelTargetHost" xml:space="preserve">- <value>Target Host</value>- </data>- <data name="LabelPort" xml:space="preserve">- <value>Port</value>- </data>- <data name="ButtonStartTest" xml:space="preserve">- <value>▶ Start Test</value>- </data>- <data name="LabelOutput" xml:space="preserve">- <value>Output</value>- </data>- <data name="ButtonSaveChanges" xml:space="preserve">- <value>Save Changes</value>- </data>- <data name="PlaceholderIpAddress" xml:space="preserve">- <value>e.g., 127.0.0.1</value>- </data>- <data name="PlaceholderPort" xml:space="preserve">- <value>e.g., 1080</value>- </data>- <data name="PlaceholderNoAuth" xml:space="preserve">- <value>Leave empty if no auth required</value>- </data>-- <!-- Proxy Rules Window -->- <data name="WindowProxyRules" xml:space="preserve">- <value>Process Rules</value>- </data>- <data name="LabelEnabled" xml:space="preserve">- <value>Enabled</value>- </data>- <data name="LabelActions" xml:space="preserve">- <value>Actions</value>- </data>- <data name="LabelSR" xml:space="preserve">- <value>SR</value>- </data>- <data name="LabelProcess" xml:space="preserve">- <value>Process</value>- </data>- <data name="LabelTargetHosts" xml:space="preserve">- <value>Target Hosts</value>- </data>- <data name="LabelTargetPorts" xml:space="preserve">- <value>Target Ports</value>- </data>- <data name="LabelTargetDomains" xml:space="preserve">- <value>Target Domains</value>- </data>- <data name="LabelProtocol" xml:space="preserve">- <value>Protocol</value>- </data>- <data name="LabelAction" xml:space="preserve">- <value>Action</value>- </data>- <data name="LabelApplications" xml:space="preserve">- <value>Applications</value>- </data>- <data name="ButtonBrowse" xml:space="preserve">- <value>Browse...</value>- </data>- <data name="ExampleApplications" xml:space="preserve">- <value>Example: iexplore.exe; "C:\some app.exe"; fire*.exe; *.bin</value>- </data>- <data name="ExampleTargetHosts" xml:space="preserve">- <value>Example: 127.0.0.1; 192.168.1.*; 10.1.0.0-10.5.255.255; ::1; 2001:db8::/32; fe80::1-fe80::ff</value>- </data>- <data name="ExampleTargetPorts" xml:space="preserve">- <value>Example: 80; 8000-9000; 3128</value>- </data>- <data name="ExampleTargetDomains" xml:space="preserve">- <value>Example: google.com; *.google.com; *.gstatic.com (requires unencrypted DNS)</value>- </data>- <data name="ProtocolTCP" xml:space="preserve">- <value>TCP</value>- </data>- <data name="ProtocolUDP" xml:space="preserve">- <value>UDP</value>- </data>- <data name="ProtocolBoth" xml:space="preserve">- <value>Both (TCP + UDP)</value>- </data>- <data name="UDPProxyNote" xml:space="preserve">- <value>⚠ UDP only works with SOCKS5 proxy. Not all SOCKS5 proxies support UDP by default. SOCKS5 UDP support does not guarantee QUIC or HTTP/3 support, verify your proxy supports these protocols separately.</value>- </data>- <data name="ActionProxy" xml:space="preserve">- <value>PROXY</value>- </data>- <data name="ActionDirect" xml:space="preserve">- <value>DIRECT</value>- </data>- <data name="ActionBlock" xml:space="preserve">- <value>BLOCK</value>- </data>- <data name="ButtonSaveRule" xml:space="preserve">- <value>Save Rule</value>- </data>-</root>diff --git a/Windows/gui/Resources/Resources.zh.resx b/Windows/gui/Resources/Resources.zh.resxdeleted file mode 100644index 9cfd826..0000000--- a/Windows/gui/Resources/Resources.zh.resx+++ /dev/null@@ -1,298 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<root>- <resheader name="resmimetype">- <value>text/microsoft-resx</value>- </resheader>- <resheader name="version">- <value>2.0</value>- </resheader>- <resheader name="reader">- <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>- </resheader>- <resheader name="writer">- <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>- </resheader>-- <!-- Menu Items -->- <data name="MenuProxy" xml:space="preserve">- <value>代理</value>- </data>- <data name="MenuProxySettings" xml:space="preserve">- <value>代理设置</value>- </data>- <data name="MenuProxyRules" xml:space="preserve">- <value>代理规则</value>- </data>- <data name="MenuLocalhostViaProxy" xml:space="preserve">- <value>本地主机通过代理</value>- </data>- <data name="MenuEnableTrafficLogging" xml:space="preserve">- <value>启用流量日志</value>- </data>- <data name="MenuLogFilters" xml:space="preserve">- <value>日志过滤...</value>- </data>- <data name="LogFiltersDesc1" xml:space="preserve">- <value>每条规则可同时匹配多个字段 留空或选"全部"表示忽略该字段。Include规则只显示匹配的连接,Exclude规则隐藏匹配的连接,排除优先执行。</value>- </data>- <data name="LogFiltersDesc2" xml:space="preserve">- <value>文本字段支持 * 通配符:chrome* = 以此开头,*.exe = 以此结尾,*ch* = 包含此内容。</value>- </data>- <data name="MenuAutoClearLogs" xml:space="preserve">- <value>自动清除日志</value>- </data>- <data name="MenuSettings" xml:space="preserve">- <value>设置</value>- </data>- <data name="MenuCloseToTray" xml:space="preserve">- <value>关闭到系统托盘</value>- </data> <data name="MenuRunAtStartup" xml:space="preserve">- <value>开机启动</value>- </data> <data name="MenuLanguage" xml:space="preserve">- <value>语言</value>- </data>- <data name="MenuAbout" xml:space="preserve">- <value>关于</value>- </data>- <data name="MenuAboutProxyBridge" xml:space="preserve">- <value>关于ProxyBridge</value>- </data>- <data name="MenuCheckUpdates" xml:space="preserve">- <value>检查更新</value>- </data>- <!-- Profile Menu -->- <data name="MenuProfile" xml:space="preserve">- <value>配置文件</value>- </data>- <data name="MenuNewProfile" xml:space="preserve">- <value>新建配置</value>- </data>- <data name="MenuRenameProfile" xml:space="preserve">- <value>重命名配置</value>- </data>- <data name="MenuDeleteProfile" xml:space="preserve">- <value>删除配置</value>- </data>- <data name="MenuSwitchProfile" xml:space="preserve">- <value>切换配置</value>- </data>- <data name="MenuImportProfile" xml:space="preserve">- <value>导入配置</value>- </data>- <data name="MenuExportProfile" xml:space="preserve">- <value>导出配置</value>- </data>-- <!-- Tabs -->- <data name="TabConnections" xml:space="preserve">- <value>网络连接</value>- </data>- <data name="TabActivity" xml:space="preserve">- <value>活动日志</value>- </data>-- <!-- Buttons -->- <data name="ButtonClearAllConnections" xml:space="preserve">- <value>清除所有连接</value>- </data>- <data name="ButtonClearAllLogs" xml:space="preserve">- <value>清除所有日志</value>- </data>- <data name="ButtonSave" xml:space="preserve">- <value>保存</value>- </data>- <data name="ButtonCancel" xml:space="preserve">- <value>取消</value>- </data>- <data name="ButtonClose" xml:space="preserve">- <value>关闭</value>- </data>- <data name="ButtonAdd" xml:space="preserve">- <value>添加</value>- </data>- <data name="ButtonEdit" xml:space="preserve">- <value>编辑</value>- </data>- <data name="ButtonDelete" xml:space="preserve">- <value>删除</value>- </data>-- <!-- Search Placeholders -->- <data name="SearchConnectionsPlaceholder" xml:space="preserve">- <value>🔍 搜索连接...</value>- </data>- <data name="SearchActivityPlaceholder" xml:space="preserve">- <value>🔍 搜索活动日志...</value>- </data>-- <!-- Log Messages -->- <data name="LogInitialized" xml:space="preserve">- <value>ProxyBridge初始化成功</value>- </data>- <data name="LogServiceStarted" xml:space="preserve">- <value>ProxyBridge服务启动成功</value>- </data>- <data name="LogServiceStartFailed" xml:space="preserve">- <value>错误: ProxyBridge服务启动失败</value>- </data>- <data name="LogRestoredProxySettings" xml:space="preserve">- <value>已恢复代理设置</value>- </data>- <data name="LogRestoredRules" xml:space="preserve">- <value>已恢复 {0} 条代理规则</value>- </data>- <data name="LogConfigSaved" xml:space="preserve">- <value>配置保存成功</value>- </data>- <data name="LogConfigLoadFailed" xml:space="preserve">- <value>配置加载失败</value>- </data>- <data name="LogConfigSaveFailed" xml:space="preserve">- <value>配置保存失败</value>- </data>- <data name="LogProxySettingsSaved" xml:space="preserve">- <value>已保存代理设置</value>- </data>- <data name="LogProxySettingsFailed" xml:space="preserve">- <value>错误: 代理配置设置失败</value>- </data>- <data name="LogRuleAdded" xml:space="preserve">- <value>已添加规则</value>- </data>- <data name="LogRuleAddFailed" xml:space="preserve">- <value>错误: 添加规则失败</value>- </data>- <data name="LogLanguageChanged" xml:space="preserve">- <value>语言已更改为</value>- </data>- <data name="LogWithAuth" xml:space="preserve">- <value>需要认证</value>- </data>-- <!-- Proxy Settings Window -->- <data name="WindowProxySettings" xml:space="preserve">- <value>代理设置</value>- </data>- <data name="LabelProxyType" xml:space="preserve">- <value>代理类型</value>- </data>- <data name="LabelProxyIp" xml:space="preserve">- <value>代理IP地址 *</value>- </data>- <data name="LabelProxyPort" xml:space="preserve">- <value>代理端口 *</value>- </data>- <data name="LabelUsername" xml:space="preserve">- <value>用户名(可选)</value>- </data>- <data name="LabelPassword" xml:space="preserve">- <value>密码(可选)</value>- </data>- <data name="LabelRequiredFields" xml:space="preserve">- <value>* 必填字段</value>- </data>- <data name="LabelTestConnection" xml:space="preserve">- <value>测试连接</value>- </data>- <data name="ButtonTestProxy" xml:space="preserve">- <value>测试代理连接</value>- </data>- <data name="LabelTargetHost" xml:space="preserve">- <value>目标主机</value>- </data>- <data name="LabelPort" xml:space="preserve">- <value>端口</value>- </data>- <data name="ButtonStartTest" xml:space="preserve">- <value>▶ 开始测试</value>- </data>- <data name="LabelOutput" xml:space="preserve">- <value>输出</value>- </data>- <data name="ButtonSaveChanges" xml:space="preserve">- <value>保存更改</value>- </data>- <data name="PlaceholderIpAddress" xml:space="preserve">- <value>例如: 127.0.0.1</value>- </data>- <data name="PlaceholderPort" xml:space="preserve">- <value>例如: 1080</value>- </data>- <data name="PlaceholderNoAuth" xml:space="preserve">- <value>如不需要认证请留空</value>- </data>-- <!-- Proxy Rules Window -->- <data name="WindowProxyRules" xml:space="preserve">- <value>进程规则</value>- </data>- <data name="LabelEnabled" xml:space="preserve">- <value>启用</value>- </data>- <data name="LabelActions" xml:space="preserve">- <value>操作</value>- </data>- <data name="LabelSR" xml:space="preserve">- <value>序号</value>- </data>- <data name="LabelProcess" xml:space="preserve">- <value>进程</value>- </data>- <data name="LabelTargetHosts" xml:space="preserve">- <value>目标主机</value>- </data>- <data name="LabelTargetPorts" xml:space="preserve">- <value>目标端口</value>- </data>- <data name="LabelTargetDomains" xml:space="preserve">- <value>目标域名</value>- </data>- <data name="LabelProtocol" xml:space="preserve">- <value>协议</value>- </data>- <data name="LabelAction" xml:space="preserve">- <value>动作</value>- </data>- <data name="LabelApplications" xml:space="preserve">- <value>应用程序</value>- </data>- <data name="ButtonBrowse" xml:space="preserve">- <value>浏览...</value>- </data>- <data name="ExampleApplications" xml:space="preserve">- <value>示例: iexplore.exe; "C:\某个应用.exe"; fire*.exe; *.bin</value>- </data>- <data name="ExampleTargetHosts" xml:space="preserve">- <value>示例: 127.0.0.1; 192.168.1.*; 10.1.0.0-10.5.255.255; ::1; 2001:db8::/32; fe80::1-fe80::ff</value>- </data>- <data name="ExampleTargetPorts" xml:space="preserve">- <value>示例: 80; 8000-9000; 3128</value>- </data>- <data name="ExampleTargetDomains" xml:space="preserve">- <value>示例: google.com; *.google.com; *.gstatic.com (需要未加密的 DNS)</value>- </data>- <data name="ProtocolTCP" xml:space="preserve">- <value>TCP</value>- </data>- <data name="ProtocolUDP" xml:space="preserve">- <value>UDP</value>- </data>- <data name="ProtocolBoth" xml:space="preserve">- <value>两者 (TCP + UDP)</value>- </data>- <data name="UDPProxyNote" xml:space="preserve">- <value>⚠ UDP 仅支持 SOCKS5 代理。并非所有 SOCKS5 代理默认支持 UDP。SOCKS5 UDP 支持并不保证支持 QUIC 或 HTTP/3 —— 请单独确认您的代理是否支持这些协议。</value>- </data>- <data name="ActionProxy" xml:space="preserve">- <value>代理</value>- </data>- <data name="ActionDirect" xml:space="preserve">- <value>直连</value>- </data>- <data name="ActionBlock" xml:space="preserve">- <value>阻止</value>- </data>- <data name="ButtonSaveRule" xml:space="preserve">- <value>保存规则</value>- </data>-</root>diff --git a/Windows/gui/Services/Loc.cs b/Windows/gui/Services/Loc.csdeleted file mode 100644index e7e0f0a..0000000--- a/Windows/gui/Services/Loc.cs+++ /dev/null@@ -1,143 +0,0 @@-using System;-using System.ComponentModel;-using System.Globalization;-using System.Runtime.CompilerServices;--namespace ProxyBridge.GUI.Services;--public class Loc : INotifyPropertyChanged-{- private static readonly Loc _instance = new();- public static Loc Instance => _instance;-- private CultureInfo _currentCulture = CultureInfo.CurrentUICulture;-- public event PropertyChangedEventHandler? PropertyChanged;-- public CultureInfo CurrentCulture- {- get => _currentCulture;- set- {- if (_currentCulture.Equals(value)) return;- _currentCulture = value;-- CultureInfo.CurrentUICulture = value;- CultureInfo.CurrentCulture = value;- Resources.Resources.Culture = value;-- // refresh UI- OnPropertyChanged(string.Empty);- }- }-- private void OnPropertyChanged([CallerMemberName] string? propertyName = null)- {- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));- }-- // Menu Items- public string MenuProxy => Resources.Resources.MenuProxy;- public string MenuProxySettings => Resources.Resources.MenuProxySettings;- public string MenuProxyRules => Resources.Resources.MenuProxyRules;- public string MenuLocalhostViaProxy => Resources.Resources.MenuLocalhostViaProxy;- public string MenuEnableTrafficLogging => Resources.Resources.MenuEnableTrafficLogging;- public string MenuLogFilters => Resources.Resources.MenuLogFilters;- public string LogFiltersDesc1 => Resources.Resources.LogFiltersDesc1;- public string LogFiltersDesc2 => Resources.Resources.LogFiltersDesc2;- public string MenuAutoClearLogs => Resources.Resources.MenuAutoClearLogs;- public string MenuSettings => Resources.Resources.MenuSettings;- public string MenuCloseToTray => Resources.Resources.MenuCloseToTray;- public string MenuRunAtStartup => Resources.Resources.MenuRunAtStartup;- public string MenuLanguage => Resources.Resources.MenuLanguage;- public string MenuAbout => Resources.Resources.MenuAbout;- public string MenuAboutProxyBridge => Resources.Resources.MenuAboutProxyBridge;- public string MenuCheckUpdates => Resources.Resources.MenuCheckUpdates;- public string MenuProfile => Resources.Resources.MenuProfile;- public string MenuNewProfile => Resources.Resources.MenuNewProfile;- public string MenuRenameProfile => Resources.Resources.MenuRenameProfile;- public string MenuDeleteProfile => Resources.Resources.MenuDeleteProfile;- public string MenuSwitchProfile => Resources.Resources.MenuSwitchProfile;- public string MenuImportProfile => Resources.Resources.MenuImportProfile;- public string MenuExportProfile => Resources.Resources.MenuExportProfile;-- // Tabs- public string TabConnections => Resources.Resources.TabConnections;- public string TabActivity => Resources.Resources.TabActivity;-- // Buttons- public string ButtonClearAllConnections => Resources.Resources.ButtonClearAllConnections;- public string ButtonClearAllLogs => Resources.Resources.ButtonClearAllLogs;- public string ButtonSave => Resources.Resources.ButtonSave;- public string ButtonCancel => Resources.Resources.ButtonCancel;- public string ButtonClose => Resources.Resources.ButtonClose;- public string ButtonAdd => Resources.Resources.ButtonAdd;- public string ButtonEdit => Resources.Resources.ButtonEdit;- public string ButtonDelete => Resources.Resources.ButtonDelete;-- // Search Placeholders- public string SearchConnectionsPlaceholder => Resources.Resources.SearchConnectionsPlaceholder;- public string SearchActivityPlaceholder => Resources.Resources.SearchActivityPlaceholder;-- // Log Messages- public string LogInitialized => Resources.Resources.LogInitialized;- public string LogServiceStarted => Resources.Resources.LogServiceStarted;- public string LogServiceStartFailed => Resources.Resources.LogServiceStartFailed;- public string LogRestoredProxySettings => Resources.Resources.LogRestoredProxySettings;- public string LogRestoredRules => Resources.Resources.LogRestoredRules;- public string LogConfigSaved => Resources.Resources.LogConfigSaved;- public string LogConfigLoadFailed => Resources.Resources.LogConfigLoadFailed;- public string LogConfigSaveFailed => Resources.Resources.LogConfigSaveFailed;- public string LogProxySettingsSaved => Resources.Resources.LogProxySettingsSaved;- public string LogProxySettingsFailed => Resources.Resources.LogProxySettingsFailed;- public string LogRuleAdded => Resources.Resources.LogRuleAdded;- public string LogRuleAddFailed => Resources.Resources.LogRuleAddFailed;- public string LogLanguageChanged => Resources.Resources.LogLanguageChanged;- public string LogWithAuth => Resources.Resources.LogWithAuth;-- // Proxy Settings Window- public string ProxySettingsTitle => Resources.Resources.WindowProxySettings;- public string ProxyTypeLabel => Resources.Resources.LabelProxyType;- public string ProxyIpLabel => Resources.Resources.LabelProxyIp;- public string ProxyPortLabel => Resources.Resources.LabelProxyPort;- public string UsernameLabel => Resources.Resources.LabelUsername;- public string PasswordLabel => Resources.Resources.LabelPassword;- public string RequiredFieldsNote => Resources.Resources.LabelRequiredFields;- public string TestConnectionTitle => Resources.Resources.LabelTestConnection;- public string TestConnectionButton => Resources.Resources.ButtonTestProxy;- public string TargetHostLabel => Resources.Resources.LabelTargetHost;- public string PortLabel => Resources.Resources.LabelPort;- public string StartTestButton => Resources.Resources.ButtonStartTest;- public string OutputLabel => Resources.Resources.LabelOutput;- public string SaveChangesButton => Resources.Resources.ButtonSaveChanges;- public string ProxyIpPlaceholder => Resources.Resources.PlaceholderIpAddress;- public string ProxyPortPlaceholder => Resources.Resources.PlaceholderPort;- public string UsernamePlaceholder => Resources.Resources.PlaceholderNoAuth;- public string PasswordPlaceholder => Resources.Resources.PlaceholderNoAuth;-- // Proxy Rules Window- public string ProxyRulesTitle => Resources.Resources.WindowProxyRules;- public string EnabledLabel => Resources.Resources.LabelEnabled;- public string ActionsLabel => Resources.Resources.LabelActions;- public string SRLabel => Resources.Resources.LabelSR;- public string ProcessLabel => Resources.Resources.LabelProcess;- public string TargetHostsLabel => Resources.Resources.LabelTargetHosts;- public string TargetPortsLabel => Resources.Resources.LabelTargetPorts;- public string TargetDomainsLabel => Resources.Resources.LabelTargetDomains;- public string ProtocolLabel => Resources.Resources.LabelProtocol;- public string ActionLabel => Resources.Resources.LabelAction;- public string ApplicationsLabel => Resources.Resources.LabelApplications;- public string BrowseButton => Resources.Resources.ButtonBrowse;- public string ExampleApplications => Resources.Resources.ExampleApplications;- public string ExampleTargetHosts => Resources.Resources.ExampleTargetHosts;- public string ExampleTargetPorts => Resources.Resources.ExampleTargetPorts;- public string ExampleTargetDomains => Resources.Resources.ExampleTargetDomains;- public string ProtocolTCP => Resources.Resources.ProtocolTCP;- public string ProtocolUDP => Resources.Resources.ProtocolUDP;- public string ProtocolBoth => Resources.Resources.ProtocolBoth;- public string UDPProxyNote => Resources.Resources.UDPProxyNote;- public string ActionProxy => Resources.Resources.ActionProxy;- public string ActionDirect => Resources.Resources.ActionDirect;- public string ActionBlock => Resources.Resources.ActionBlock;- public string SaveRuleButton => Resources.Resources.ButtonSaveRule;-}diff --git a/Windows/gui/Services/ProfileManager.cs b/Windows/gui/Services/ProfileManager.csdeleted file mode 100644index 765ca50..0000000--- a/Windows/gui/Services/ProfileManager.cs+++ /dev/null@@ -1,251 +0,0 @@-using System;-using System.Collections.Generic;-using System.IO;-using System.Linq;-using System.Text.Json;-using System.Text.Json.Serialization;--namespace ProxyBridge.GUI.Services;--public class LogFilterEntry-{- public string Mode { get; set; } = "Include"; // Include or Exclude- public string ProcessName { get; set; } = ""; // empty = any- public string Ip { get; set; } = ""; // empty = any- public string Port { get; set; } = ""; // empty = any- public string Protocol { get; set; } = "All"; // All, TCP, UDP- public string Action { get; set; } = "All"; // All, Proxy, Direct, Blocked-}--public class ProxyConfigEntry-{- public uint Id { get; set; }- public string Type { get; set; } = "SOCKS5";- public string Host { get; set; } = "";- public string Port { get; set; } = "";- public string Username { get; set; } = "";- public string Password { get; set; } = "";-}--public class ProxyRuleConfig-{- public string ProcessName { get; set; } = "";- public string TargetHosts { get; set; } = "*";- public string TargetPorts { get; set; } = "*";- public string TargetDomains { get; set; } = "*";- public string Protocol { get; set; } = "TCP";- public string Action { get; set; } = "PROXY";- public bool IsEnabled { get; set; } = true;- public uint ProxyConfigId { get; set; } = 0;-}--public class ProxyProfile-{- public string Version { get; set; } = "1.0";- public string Name { get; set; } = "Default";- public bool LocalhostViaProxy { get; set; } = false;- public bool IsTrafficLoggingEnabled { get; set; } = true;- public bool AutoClearConnectionLogs { get; set; } = true;- public string Language { get; set; } = "en";- public bool CloseToTray { get; set; } = true;- public List<ProxyConfigEntry> ProxyConfigs { get; set; } = new();- public List<ProxyRuleConfig> ProxyRules { get; set; } = new();- public List<LogFilterEntry> LogFilters { get; set; } = new();-}--[JsonSourceGenerationOptions(WriteIndented = true)]-[JsonSerializable(typeof(ProxyProfile))]-[JsonSerializable(typeof(ProxyConfigEntry))]-[JsonSerializable(typeof(List<ProxyConfigEntry>))]-[JsonSerializable(typeof(ProxyRuleConfig))]-[JsonSerializable(typeof(List<ProxyRuleConfig>))]-[JsonSerializable(typeof(LogFilterEntry))]-[JsonSerializable(typeof(List<LogFilterEntry>))]-internal partial class ProxyProfileJsonContext : JsonSerializerContext { }--internal static class AtomicFileHelper-{- public static bool AtomicWrite(string filePath, string content)- {- var tempPath = filePath + ".tmp";- try- {- var directory = Path.GetDirectoryName(filePath);- if (directory != null && !Directory.Exists(directory))- Directory.CreateDirectory(directory);-- File.WriteAllText(tempPath, content);- File.Move(tempPath, filePath, overwrite: true);- return true;- }- catch- {- try { if (File.Exists(tempPath)) File.Delete(tempPath); } catch { }- return false;- }- }-- public static string? SafeReadFile(string filePath)- {- try- {- if (!File.Exists(filePath)) return null;- var content = File.ReadAllText(filePath);- return string.IsNullOrWhiteSpace(content) ? null : content;- }- catch { return null; }- }-}--public static class ProfileManager-{- private const string ProfileVersion = "1.0";- public const string ProfileExtension = ".pbprofile";- public const string DefaultProfileName = "Default";-- private static readonly HashSet<char> _invalidFileNameChars =- new(Path.GetInvalidFileNameChars());-- private static readonly string ProfilesDirectory = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),- "ProxyBridge".TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar),- "profiles".TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)- );-- public static string[] GetProfileNames()- {- EnsureDirectory();- return Directory.GetFiles(ProfilesDirectory, $"*{ProfileExtension}")- .Select(f => Path.GetFileNameWithoutExtension(f))- .OrderBy(n => n, StringComparer.OrdinalIgnoreCase)- .ToArray();- }-- public static bool ProfileExists(string name)- => File.Exists(GetProfilePath(name));-- public static ProxyProfile LoadProfile(string name)- {- var json = AtomicFileHelper.SafeReadFile(GetProfilePath(name));- if (json == null) return CreateDefault(name);-- try- {- var profile = JsonSerializer.Deserialize(json, ProxyProfileJsonContext.Default.ProxyProfile);- if (profile == null || profile.Version != ProfileVersion) return CreateDefault(name);-- profile.ProxyRules ??= new List<ProxyRuleConfig>();- profile.ProxyConfigs ??= new List<ProxyConfigEntry>();- profile.Name = name;- return profile;- }- catch- {- return CreateDefault(name);- }- }-- public static bool SaveProfile(string name, ProxyProfile profile)- {- EnsureDirectory();- profile.Name = name;- profile.Version = ProfileVersion;- var json = JsonSerializer.Serialize(profile, ProxyProfileJsonContext.Default.ProxyProfile);- return AtomicFileHelper.AtomicWrite(GetProfilePath(name), json);- }-- public static bool DeleteProfile(string name)- {- try- {- var path = GetProfilePath(name);- if (!File.Exists(path)) return false;- File.Delete(path);- return true;- }- catch { return false; }- }-- public static bool RenameProfile(string oldName, string newName)- {- try- {- var oldPath = GetProfilePath(oldName);- var newPath = GetProfilePath(newName);- if (!File.Exists(oldPath) || File.Exists(newPath)) return false;- File.Move(oldPath, newPath);- return true;- }- catch { return false; }- }-- // Returns the name assigned to the imported profile, or null on failure.- public static string? ImportProfile(string sourcePath)- {- try- {- sourcePath = Path.GetFullPath(sourcePath);- var json = File.ReadAllText(sourcePath);- var profile = JsonSerializer.Deserialize(json, ProxyProfileJsonContext.Default.ProxyProfile);- if (profile == null) return null;-- profile.Version = ProfileVersion;- profile.ProxyRules ??= new List<ProxyRuleConfig>();- profile.ProxyConfigs ??= new List<ProxyConfigEntry>();-- var baseName = SanitizeProfileName(Path.GetFileNameWithoutExtension(sourcePath));- var name = GetUniqueName(baseName);- SaveProfile(name, profile);- return name;- }- catch { return null; }- }-- public static bool ExportProfile(string name, string destinationPath)- {- try- {- var sourcePath = GetProfilePath(name);- if (!File.Exists(sourcePath)) return false;- destinationPath = Path.GetFullPath(destinationPath);- File.Copy(sourcePath, destinationPath, overwrite: true);- return true;- }- catch { return false; }- }-- public static bool IsValidProfileName(string name)- {- if (string.IsNullOrWhiteSpace(name) || name.Length > 64) return false;- return !name.Any(c => _invalidFileNameChars.Contains(c));- }-- private static string GetProfilePath(string name)- => Path.Combine(ProfilesDirectory, Path.GetFileName(name) + ProfileExtension);-- private static void EnsureDirectory()- {- if (!Directory.Exists(ProfilesDirectory))- Directory.CreateDirectory(ProfilesDirectory);- }-- private static ProxyProfile CreateDefault(string name) => new() { Name = name };-- private static string SanitizeProfileName(string name)- {- var sanitized = new string(name.Select(c => _invalidFileNameChars.Contains(c) ? '_' : c).ToArray()).Trim();- if (string.IsNullOrWhiteSpace(sanitized)) return "Imported";- return sanitized.Length <= 64 ? sanitized : sanitized[..64];- }-- private static string GetUniqueName(string baseName)- {- if (!ProfileExists(baseName)) return baseName;- for (int i = 2; i <= 99; i++)- {- var candidate = $"{baseName} ({i})";- if (!ProfileExists(candidate)) return candidate;- }- return baseName + "_" + Guid.NewGuid().ToString("N")[..8];- }-}diff --git a/Windows/gui/Services/ProxyBridgeService.cs b/Windows/gui/Services/ProxyBridgeService.csdeleted file mode 100644index e33e0f6..0000000--- a/Windows/gui/Services/ProxyBridgeService.cs+++ /dev/null@@ -1,174 +0,0 @@-using System;-using ProxyBridge.GUI.Interop;--namespace ProxyBridge.GUI.Services;--public class ProxyBridgeService : IDisposable-{- private ProxyBridgeNative.LogCallback? _logCallback;- private ProxyBridgeNative.ConnectionCallback? _connectionCallback;- private bool _isRunning;-- public event Action<string>? LogReceived;- public event Action<string, uint, string, ushort, string>? ConnectionReceived;-- public ProxyBridgeService()- {- _logCallback = OnLogReceived;- _connectionCallback = OnConnectionReceived;-- ProxyBridgeNative.ProxyBridge_SetLogCallback(_logCallback);- ProxyBridgeNative.ProxyBridge_SetConnectionCallback(_connectionCallback);- }-- private void OnLogReceived(string message)- {- LogReceived?.Invoke(message);- }-- private void OnConnectionReceived(string processName, uint pid, string destIp, ushort destPort, string proxyInfo)- {- ConnectionReceived?.Invoke(processName, pid, destIp, destPort, proxyInfo);- }-- public bool Start()- {- if (_isRunning)- return true;-- _isRunning = ProxyBridgeNative.ProxyBridge_Start();- return _isRunning;- }-- public bool Stop()- {- if (!_isRunning)- return true;-- _isRunning = !ProxyBridgeNative.ProxyBridge_Stop();- return !_isRunning;- }-- public uint AddProxyConfig(string type, string ip, ushort port, string username, string password)- {- var proxyType = string.Equals(type, "HTTP", StringComparison.OrdinalIgnoreCase)- ? ProxyBridgeNative.ProxyType.HTTP- : ProxyBridgeNative.ProxyType.SOCKS5;-- return AddProxyConfigCore(proxyType, ip, port, username, password);- }-- private static uint AddProxyConfigCore(ProxyBridgeNative.ProxyType proxyType, string ip, ushort port, string username, string password)- {- return ProxyBridgeNative.ProxyBridge_AddProxyConfig(proxyType, ip, port, username, password);- }-- public bool EditProxyConfig(uint configId, string type, string ip, ushort port, string username, string password)- {- var proxyType = string.Equals(type, "HTTP", StringComparison.OrdinalIgnoreCase)- ? ProxyBridgeNative.ProxyType.HTTP- : ProxyBridgeNative.ProxyType.SOCKS5;-- return ProxyBridgeNative.ProxyBridge_EditProxyConfig(configId, proxyType, ip, port, username, password);- }-- public bool DeleteProxyConfig(uint configId)- {- return ProxyBridgeNative.ProxyBridge_DeleteProxyConfig(configId);- }-- public string TestProxyConfig(uint configId, string targetHost, ushort targetPort)- {- var buffer = new System.Text.StringBuilder(4096);- ProxyBridgeNative.ProxyBridge_TestProxyConfig(configId, targetHost, targetPort, buffer, (UIntPtr)buffer.Capacity);- return buffer.ToString();- }-- public uint AddRule(string processName, string targetHosts, string targetPorts, string targetDomains, string protocol, string action, uint proxyConfigId = 0)- {- ProxyBridgeNative.RuleAction ruleAction;- if (string.Equals(action, "DIRECT", StringComparison.OrdinalIgnoreCase))- ruleAction = ProxyBridgeNative.RuleAction.DIRECT;- else if (string.Equals(action, "BLOCK", StringComparison.OrdinalIgnoreCase))- ruleAction = ProxyBridgeNative.RuleAction.BLOCK;- else- ruleAction = ProxyBridgeNative.RuleAction.PROXY;-- ProxyBridgeNative.RuleProtocol ruleProtocol;- if (string.Equals(protocol, "UDP", StringComparison.OrdinalIgnoreCase))- ruleProtocol = ProxyBridgeNative.RuleProtocol.UDP;- else if (string.Equals(protocol, "BOTH", StringComparison.OrdinalIgnoreCase) ||- string.Equals(protocol, "TCP+UDP", StringComparison.OrdinalIgnoreCase))- ruleProtocol = ProxyBridgeNative.RuleProtocol.BOTH;- else- ruleProtocol = ProxyBridgeNative.RuleProtocol.TCP;-- return ProxyBridgeNative.ProxyBridge_AddRule(processName, targetHosts, targetPorts, targetDomains ?? "*", ruleProtocol, ruleAction, proxyConfigId);- }-- public bool EnableRule(uint ruleId)- {- return ProxyBridgeNative.ProxyBridge_EnableRule(ruleId);- }-- public bool DisableRule(uint ruleId)- {- return ProxyBridgeNative.ProxyBridge_DisableRule(ruleId);- }-- public bool DeleteRule(uint ruleId)- {- return ProxyBridgeNative.ProxyBridge_DeleteRule(ruleId);- }-- public bool EditRule(uint ruleId, string processName, string targetHosts, string targetPorts, string targetDomains, string protocol, string action, uint proxyConfigId = 0)- {- ProxyBridgeNative.RuleAction ruleAction;- if (string.Equals(action, "DIRECT", StringComparison.OrdinalIgnoreCase))- ruleAction = ProxyBridgeNative.RuleAction.DIRECT;- else if (string.Equals(action, "BLOCK", StringComparison.OrdinalIgnoreCase))- ruleAction = ProxyBridgeNative.RuleAction.BLOCK;- else- ruleAction = ProxyBridgeNative.RuleAction.PROXY;-- ProxyBridgeNative.RuleProtocol ruleProtocol;- if (string.Equals(protocol, "UDP", StringComparison.OrdinalIgnoreCase))- ruleProtocol = ProxyBridgeNative.RuleProtocol.UDP;- else if (string.Equals(protocol, "BOTH", StringComparison.OrdinalIgnoreCase) ||- string.Equals(protocol, "TCP+UDP", StringComparison.OrdinalIgnoreCase))- ruleProtocol = ProxyBridgeNative.RuleProtocol.BOTH;- else- ruleProtocol = ProxyBridgeNative.RuleProtocol.TCP;-- return ProxyBridgeNative.ProxyBridge_EditRule(ruleId, processName, targetHosts, targetPorts, targetDomains ?? "*", ruleProtocol, ruleAction, proxyConfigId);- }-- public uint GetRulePosition(uint ruleId)- {- return ProxyBridgeNative.ProxyBridge_GetRulePosition(ruleId);- }-- public bool MoveRuleToPosition(uint ruleId, uint newPosition)- {- return ProxyBridgeNative.ProxyBridge_MoveRuleToPosition(ruleId, newPosition);- }-- public void SetLocalhostViaProxy(bool enable)- {- ProxyBridgeNative.ProxyBridge_SetLocalhostViaProxy(enable);- }-- public static void SetTrafficLoggingEnabled(bool enable)- {- ProxyBridgeNative.ProxyBridge_SetTrafficLoggingEnabled(enable);- }-- public void Dispose()- {- if (_isRunning)- {- Stop(); // removing the threads, C code handle close no need to manually handle drives- }- GC.SuppressFinalize(this);- }-}diff --git a/Windows/gui/Services/SettingsService.cs b/Windows/gui/Services/SettingsService.csdeleted file mode 100644index 60eaba7..0000000--- a/Windows/gui/Services/SettingsService.cs+++ /dev/null@@ -1,134 +0,0 @@-using System;-using System.IO;-using System.Text.Json;-using System.Text.Json.Serialization;--namespace ProxyBridge.GUI.Services;--[JsonSourceGenerationOptions(WriteIndented = true)]-[JsonSerializable(typeof(AppSettings))]-internal partial class AppSettingsContext : JsonSerializerContext-{-}--public class SettingsService-{- private static readonly string SettingsPath = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),- "ProxyBridge",- "settings.json");-- public AppSettings LoadSettings()- {- var json = AtomicFileHelper.SafeReadFile(SettingsPath);- if (json == null)- {- return new AppSettings();- }-- try- {- var settings = JsonSerializer.Deserialize(json, AppSettingsContext.Default.AppSettings);- return settings ?? new AppSettings();- }- catch- {- return new AppSettings();- }- }-- public void SaveSettings(AppSettings settings)- {- var json = JsonSerializer.Serialize(settings, AppSettingsContext.Default.AppSettings);- AtomicFileHelper.AtomicWrite(SettingsPath, json);- }-- public void SetStartupWithWindows(bool enable)- {- const string taskName = "ProxyBridge";-- try- {- var exePath = Environment.ProcessPath;- if (exePath == null) return;-- if (enable)- {- // Adding in registy in Software\Microsoft\Windows\CurrentVersion\Run is not possible or bad idea- // app need admin permisison to run with registy not posible or uac at startup whicih is bad idea- // Possible solution - Windows Service - Have no experience developing serice and its too much work for simple startup load- // Solution 2 - Task schedule - implemented- var arguments = $"/Create /F /TN \"{taskName}\" /TR \"\\\"{exePath}\\\" --minimized\" /SC ONLOGON /RL HIGHEST";-- var startInfo = new System.Diagnostics.ProcessStartInfo- {- FileName = "schtasks.exe",- Arguments = arguments,- UseShellExecute = false,- CreateNoWindow = true,- RedirectStandardOutput = true,- RedirectStandardError = true- };-- using var process = System.Diagnostics.Process.Start(startInfo);- process?.WaitForExit();- }- else- {- var arguments = $"/Delete /F /TN \"{taskName}\"";-- var startInfo = new System.Diagnostics.ProcessStartInfo- {- FileName = "schtasks.exe",- Arguments = arguments,- UseShellExecute = false,- CreateNoWindow = true,- RedirectStandardOutput = true,- RedirectStandardError = true- };-- using var process = System.Diagnostics.Process.Start(startInfo);- process?.WaitForExit();- }- }- catch- {- }- }-- public bool IsStartupEnabled()- {- const string taskName = "ProxyBridge";-- try- {- var startInfo = new System.Diagnostics.ProcessStartInfo- {- FileName = "schtasks.exe",- Arguments = $"/Query /TN \"{taskName}\"",- UseShellExecute = false,- CreateNoWindow = true,- RedirectStandardOutput = true,- RedirectStandardError = true- };-- using var process = System.Diagnostics.Process.Start(startInfo);- if (process == null) return false;-- process.WaitForExit();- return process.ExitCode == 0;- }- catch- {- return false;- }- }-}--public class AppSettings-{- public bool CheckForUpdatesOnStartup { get; set; } = true;- public DateTime LastUpdateCheck { get; set; } = DateTime.MinValue;- public bool StartWithWindows { get; set; } = false;- public string ActiveProfileName { get; set; } = ProfileManager.DefaultProfileName;-}\ No newline at end of filediff --git a/Windows/gui/Services/UpdateService.cs b/Windows/gui/Services/UpdateService.csdeleted file mode 100644index 2edebba..0000000--- a/Windows/gui/Services/UpdateService.cs+++ /dev/null@@ -1,211 +0,0 @@-using System;-using System.IO;-using System.Net.Http;-using System.Text.Json;-using System.Text.Json.Serialization;-using System.Threading.Tasks;-using System.Reflection;-using System.Diagnostics;-using System.Linq;--namespace ProxyBridge.GUI.Services;--[JsonSourceGenerationOptions(WriteIndented = true)]-[JsonSerializable(typeof(GitHubRelease))]-[JsonSerializable(typeof(GitHubAsset))]-internal partial class SourceGenerationContext : JsonSerializerContext-{-}--public class UpdateService-{- private static readonly HttpClient _httpClient;- private static readonly Version _currentVersion;- private const string GitHubApiUrl = "https://api.github.com/repos/InterceptSuite/ProxyBridge/releases/latest";-- static UpdateService()- {- _httpClient = new HttpClient();- _httpClient.DefaultRequestHeaders.Add("User-Agent", "ProxyBridge-UpdateChecker");- _currentVersion = Assembly.GetExecutingAssembly().GetName().Version ?? new Version(1, 0, 0);- }-- public async Task<VersionInfo> CheckForUpdatesAsync()- {- try- {- var response = await _httpClient.GetStringAsync(GitHubApiUrl);- var release = JsonSerializer.Deserialize(response, SourceGenerationContext.Default.GitHubRelease);-- var currentVersion = GetCurrentVersion();- var latestVersion = ParseVersion(release?.TagName);-- // Find the setup executable in assets- var setupAsset = release?.Assets?.FirstOrDefault(a =>- a.Name?.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) == true &&- (a.Name.Contains("setup", StringComparison.OrdinalIgnoreCase) ||- a.Name.Contains("installer", StringComparison.OrdinalIgnoreCase) ||- a.Name.Contains("ProxyBridge", StringComparison.OrdinalIgnoreCase)));-- // Only mark update as available if:- // 1. Version is newer AND- // 2. Windows installer (.exe) exists in release (platform-specific check)- var hasWindowsInstaller = setupAsset != null && !string.IsNullOrEmpty(setupAsset.BrowserDownloadUrl);- var isNewerVersion = IsNewerVersion(latestVersion, currentVersion);-- return new VersionInfo- {- CurrentVersion = currentVersion,- LatestVersion = latestVersion,- IsUpdateAvailable = isNewerVersion && hasWindowsInstaller,- LatestVersionString = release?.TagName ?? "Unknown",- CurrentVersionString = FormatVersion(currentVersion),- DownloadUrl = setupAsset?.BrowserDownloadUrl,- SetupFileName = setupAsset?.Name- };- }- catch (Exception ex)- {- return new VersionInfo- {- CurrentVersion = GetCurrentVersion(),- LatestVersion = GetCurrentVersion(),- IsUpdateAvailable = false,- Error = ex.Message,- LatestVersionString = "Error",- CurrentVersionString = FormatVersion(GetCurrentVersion())- };- }- }-- private Version GetCurrentVersion() => _currentVersion;-- private Version ParseVersion(string? tagName)- {- if (string.IsNullOrEmpty(tagName))- return new Version(0, 0, 0);-- // Remove 'v' prefix if present- var versionString = tagName.StartsWith("v") ? tagName.Substring(1) : tagName;-- if (Version.TryParse(versionString, out var version))- return version;-- return new Version(0, 0, 0);- }-- private bool IsNewerVersion(Version latest, Version current)- {- return latest.CompareTo(current) > 0;- }-- private string FormatVersion(Version version)- {- return $"v{version.Major}.{version.Minor}.{version.Build}";- }-- public async Task<string?> DownloadUpdateAsync(string downloadUrl, string fileName, IProgress<int>? progress = null)- {- try- {- var tempPath = Path.Combine(Path.GetTempPath(), fileName);-- using var response = await _httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead);- response.EnsureSuccessStatusCode();-- var totalBytes = response.Content.Headers.ContentLength ?? 0;- var downloadedBytes = 0L;-- using var contentStream = await response.Content.ReadAsStreamAsync();- using var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.Write, FileShare.None);-- var buffer = new byte[8192];- int bytesRead;-- while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)- {- await fileStream.WriteAsync(buffer, 0, bytesRead);- downloadedBytes += bytesRead;-- if (totalBytes > 0)- {- var progressPercentage = (int)((downloadedBytes * 100) / totalBytes);- progress?.Report(progressPercentage);- }- }-- return tempPath;- }- catch- {- return null;- }- }-- public void InstallUpdateAndExit(string installerPath)- {- try- {- // Start the installer- var startInfo = new ProcessStartInfo- {- FileName = installerPath,- UseShellExecute = true,- Verb = "runas" // Run as administrator- };-- Process.Start(startInfo);-- // Exit the current application- Environment.Exit(0);- }- catch (Exception ex)- {- throw new InvalidOperationException($"Failed to start installer: {ex.Message}", ex);- }- }-- public void Dispose() { }-}--public class VersionInfo-{- public Version CurrentVersion { get; set; } = new(1, 0, 0);- public Version LatestVersion { get; set; } = new(1, 0, 0);- public bool IsUpdateAvailable { get; set; }- public string? Error { get; set; }- public string LatestVersionString { get; set; } = "";- public string CurrentVersionString { get; set; } = "";- public string? DownloadUrl { get; set; }- public string? SetupFileName { get; set; }-}--public class GitHubRelease-{- [JsonPropertyName("tag_name")]- public string? TagName { get; set; }-- [JsonPropertyName("name")]- public string? Name { get; set; }-- [JsonPropertyName("prerelease")]- public bool Prerelease { get; set; }-- [JsonPropertyName("published_at")]- public DateTime PublishedAt { get; set; }-- [JsonPropertyName("assets")]- public GitHubAsset[]? Assets { get; set; }-}--public class GitHubAsset-{- [JsonPropertyName("name")]- public string? Name { get; set; }-- [JsonPropertyName("browser_download_url")]- public string? BrowserDownloadUrl { get; set; }-- [JsonPropertyName("size")]- public long Size { get; set; }-}\ No newline at end of filediff --git a/Windows/gui/Styles/SharedStyles.axaml b/Windows/gui/Styles/SharedStyles.axamldeleted file mode 100644index 17c38b9..0000000--- a/Windows/gui/Styles/SharedStyles.axaml+++ /dev/null@@ -1,85 +0,0 @@-<Styles xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">-- <Style Selector="TextBlock.label">- <Setter Property="Foreground" Value="#FFE0E0E0"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="FontWeight" Value="Medium"/>- </Style>-- <Style Selector="TextBlock.error">- <Setter Property="Foreground" Value="#FFF48771"/>- <Setter Property="FontSize" Value="12"/>- <Setter Property="Margin" Value="0,4,0,0"/>- </Style>-- <Style Selector="TextBlock.secondary">- <Setter Property="Foreground" Value="#FF999999"/>- </Style>-- <Style Selector="TextBox">- <Setter Property="Background" Value="#FF1E1E1E"/>- <Setter Property="Foreground" Value="#FFE0E0E0"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="BorderThickness" Value="1"/>- <Setter Property="Padding" Value="10,8"/>- <Setter Property="FontFamily" Value="Consolas,monospace"/>- <Setter Property="FontSize" Value="13"/>- </Style>-- <Style Selector="TextBox:focus">- <Setter Property="BorderBrush" Value="#FF007ACC"/>- </Style>-- <Style Selector="ComboBox">- <Setter Property="Background" Value="#FF1E1E1E"/>- <Setter Property="Foreground" Value="#FFE0E0E0"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="Padding" Value="10,8"/>- </Style>-- <Style Selector="ListBox">- <Setter Property="Background" Value="#FF252526"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- </Style>-- <Style Selector="ListBoxItem">- <Setter Property="Padding" Value="16,14"/>- <Setter Property="Margin" Value="0"/>- <Setter Property="MinHeight" Value="68"/>- </Style>-- <Style Selector="ListBoxItem:selected /template/ ContentPresenter">- <Setter Property="Background" Value="#FF094771"/>- </Style>-- <Style Selector="ListBoxItem:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF2A2D2E"/>- </Style>-- <Style Selector="CheckBox">- <Setter Property="Foreground" Value="#FFE0E0E0"/>- </Style>-- <Style Selector="Button">- <Setter Property="Background" Value="#FF0E639C"/>- <Setter Property="Foreground" Value="White"/>- <Setter Property="BorderThickness" Value="0"/>- <Setter Property="Padding" Value="16,8"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="Cursor" Value="Hand"/>- </Style>-- <Style Selector="Button:pointerover">- <Setter Property="Background" Value="#FF1177BB"/>- </Style>-- <Style Selector="Button.secondary">- <Setter Property="Background" Value="#FF3E3E42"/>- </Style>-- <Style Selector="Button.secondary:pointerover">- <Setter Property="Background" Value="#FF4E4E52"/>- </Style>--</Styles>diff --git a/Windows/gui/ViewModels/AboutViewModel.cs b/Windows/gui/ViewModels/AboutViewModel.csdeleted file mode 100644index b85f932..0000000--- a/Windows/gui/ViewModels/AboutViewModel.cs+++ /dev/null@@ -1,32 +0,0 @@-using System;-using System.Reflection;-using System.Windows.Input;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class AboutViewModel-{- public string Version { get; }- public ICommand CloseCommand { get; }-- public AboutViewModel() : this(() => { })- {- }-- public AboutViewModel(Action onClose)- {- // AssemblyVersion (AssemblyName.Version) is strictly numeric — .NET drops any- // "-Beta" suffix before it gets there. The csproj's <Version> (which does keep- // suffixes like "4.0.8-Beta") is embedded as AssemblyInformationalVersionAttribute,- // so read that instead to show the real product version, beta tag included.- var infoVersion = Assembly.GetExecutingAssembly()- .GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion;-- Version = !string.IsNullOrWhiteSpace(infoVersion)- ? $"Version {infoVersion}"- : "Version 1.0.0";-- CloseCommand = new RelayCommand(onClose);- }-}diff --git a/Windows/gui/ViewModels/LogFiltersViewModel.cs b/Windows/gui/ViewModels/LogFiltersViewModel.csdeleted file mode 100644index 648f038..0000000--- a/Windows/gui/ViewModels/LogFiltersViewModel.cs+++ /dev/null@@ -1,96 +0,0 @@-using System;-using System.Collections.Generic;-using System.Collections.ObjectModel;-using System.Linq;-using System.Windows.Input;-using Avalonia.Controls;-using ProxyBridge.GUI.Common;-using ProxyBridge.GUI.Services;--namespace ProxyBridge.GUI.ViewModels;--public class LogFilterRuleViewModel : ViewModelBase-{- public static readonly string[] Modes = { "Include", "Exclude" };- public static readonly string[] ProtocolOptions = { "All", "TCP", "UDP" };- public static readonly string[] ActionOptions = { "All", "Proxy", "Direct", "Blocked" };-- private string _mode = "Include";- private string _processName = "";- private string _ip = "";- private string _port = "";- private string _protocol = "All";- private string _action = "All";-- public string[] ModeList => Modes;- public string[] ProtocolList => ProtocolOptions;- public string[] ActionList => ActionOptions;-- public string Mode { get => _mode; set => SetProperty(ref _mode, value); }- public string ProcessName { get => _processName; set => SetProperty(ref _processName, value); }- public string Ip { get => _ip; set => SetProperty(ref _ip, value); }- public string Port { get => _port; set => SetProperty(ref _port, value); }- public string Protocol { get => _protocol; set => SetProperty(ref _protocol, value); }- public string Action { get => _action; set => SetProperty(ref _action, value); }-}--public class LogFiltersViewModel : ViewModelBase-{- private readonly Action<List<LogFilterEntry>> _onSave;- private readonly Action _onClose;-- public Loc Loc => Loc.Instance;-- public ObservableCollection<LogFilterRuleViewModel> Rules { get; } = new();-- public ICommand AddRuleCommand { get; }- public ICommand RemoveRuleCommand { get; }- public ICommand ClearAllCommand { get; }- public ICommand SaveCommand { get; }- public ICommand CloseCommand { get; }-- public LogFiltersViewModel(- List<LogFilterEntry> existingFilters,- Action<List<LogFilterEntry>> onSave,- Action onClose)- {- _onSave = onSave;- _onClose = onClose;-- foreach (var f in existingFilters)- {- Rules.Add(new LogFilterRuleViewModel- {- Mode = f.Mode,- ProcessName = f.ProcessName,- Ip = f.Ip,- Port = f.Port,- Protocol = f.Protocol,- Action = f.Action- });- }-- AddRuleCommand = new RelayCommand(() => Rules.Add(new LogFilterRuleViewModel()));- RemoveRuleCommand = new RelayCommandWithParameter<LogFilterRuleViewModel>(rule => Rules.Remove(rule));- ClearAllCommand = new RelayCommand(() => Rules.Clear());-- SaveCommand = new RelayCommand(() =>- {- var filters = Rules- .Select(r => new LogFilterEntry- {- Mode = r.Mode,- ProcessName = r.ProcessName,- Ip = r.Ip,- Port = r.Port,- Protocol = r.Protocol,- Action = r.Action- })- .ToList();- _onSave(filters);- _onClose();- });-- CloseCommand = new RelayCommand(() => _onClose());- }-}diff --git a/Windows/gui/ViewModels/MainWindowViewModel.cs b/Windows/gui/ViewModels/MainWindowViewModel.csdeleted file mode 100644index 8796759..0000000--- a/Windows/gui/ViewModels/MainWindowViewModel.cs+++ /dev/null@@ -1,1477 +0,0 @@-using System;-using System.Collections.Generic;-using System.Collections.ObjectModel;-using System.Windows.Input;-using System.Linq;-using System.Text;-using System.Threading;-using System.Threading.Tasks;-using Avalonia.Threading;-using Avalonia.Controls;-using Avalonia.Platform.Storage;-using ProxyBridge.GUI.Views;-using ProxyBridge.GUI.Services;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class MainWindowViewModel : ViewModelBase-{- private const int MAX_CONNECTION_LOG_LINES = 100;- private const int MAX_ACTIVITY_LOG_LINES = 100;-- private string _title = "ProxyBridge";- private int _selectedTabIndex;- private string _connectionsLog = "";- private string _activityLog = "";- private string _connectionsSearchText = "";- private string _activitySearchText = "";- private string _filteredConnectionsLog = "";- private string _filteredActivityLog = "";- private bool _isProxyRulesDialogOpen;- private bool _isProxySettingsDialogOpen;- private bool _isAddRuleViewOpen;- private string _newProcessName = "";- private string _newProxyAction = "PROXY";- private bool _startWithWindows;- private Window? _mainWindow;- private ProxyBridgeService? _proxyService;- private bool _isServiceInitialized = false;- private readonly SettingsService _settingsService = new();- private string _activeProfileName = ProfileManager.DefaultProfileName;-- public ObservableCollection<ProxyConfig> ProxyConfigs { get; } = new();- public ObservableCollection<ProxyRule> ProxyRules { get; } = new();- public ObservableCollection<string> SwitchProfileItems { get; } = new();-- private readonly List<string> _pendingConnectionLogs = new(128);- private readonly List<string> _pendingActivityLogs = new(64);- private readonly object _connectionLogLock = new();- private readonly object _activityLogLock = new();- private DispatcherTimer? _connectionLogTimer;- private DispatcherTimer? _activityLogTimer;- private int _connectionLogLineCount = 0;- private int _activityLogLineCount = 0;- private CancellationTokenSource? _saveCts;- private volatile LogFilterEntry[] _activeFilters = Array.Empty<LogFilterEntry>();- private List<LogFilterEntry> _currentLogFilters = new();-- public void SetMainWindow(Window window)- {- _mainWindow = window;-- if (_isServiceInitialized)- return;-- _isServiceInitialized = true;- LoadConfiguration();-- try- {- _proxyService = new ProxyBridgeService();- _proxyService.LogReceived += (msg) =>- {- lock (_activityLogLock)- _pendingActivityLogs.Add($"[{DateTime.Now:HH:mm:ss}] {msg}\n");- };-- _proxyService.ConnectionReceived += (processName, pid, destIp, destPort, proxyInfo) =>- {- if (!_isTrafficLoggingEnabled)- return;-- if (!PassesLogFilters(processName, destIp, destPort, proxyInfo))- return;-- lock (_connectionLogLock)- {- var addr = destIp.Contains(':') ? $"[{destIp}]" : destIp;- _pendingConnectionLogs.Add($"[{DateTime.Now:HH:mm:ss}] {processName} (PID:{pid}) -> {addr}:{destPort} via {proxyInfo}\n");- }- };-- _connectionLogTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };- _connectionLogTimer.Tick += (s, e) =>- {- List<string> logsToAdd;- lock (_connectionLogLock)- {- if (_pendingConnectionLogs.Count == 0) return;- logsToAdd = new List<string>(_pendingConnectionLogs);- _pendingConnectionLogs.Clear();- }-- var newConnLog = _connectionsLog + string.Concat(logsToAdd);- _connectionLogLineCount += logsToAdd.Count;- if (_autoClearConnectionLogs && _connectionLogLineCount > MAX_CONNECTION_LOG_LINES)- newConnLog = TrimToLastNLines(newConnLog, MAX_CONNECTION_LOG_LINES, out _connectionLogLineCount);- ConnectionsLog = newConnLog;- };- _connectionLogTimer.Start();-- _activityLogTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };- _activityLogTimer.Tick += (s, e) =>- {- List<string> logsToAdd;- lock (_activityLogLock)- {- if (_pendingActivityLogs.Count == 0) return;- logsToAdd = new List<string>(_pendingActivityLogs);- _pendingActivityLogs.Clear();- }- var newActLog = _activityLog + string.Concat(logsToAdd);- _activityLogLineCount += logsToAdd.Count;- if (_activityLogLineCount > MAX_ACTIVITY_LOG_LINES)- newActLog = TrimToLastNLines(newActLog, MAX_ACTIVITY_LOG_LINES, out _activityLogLineCount);- ActivityLog = newActLog;- };- _activityLogTimer.Start();-- _proxyService.SetLocalhostViaProxy(_localhostViaProxy);-- // Build stored-ID to native-ID map while registering proxy configs- var configIdMap = new Dictionary<uint, uint>();- foreach (var pc in ProxyConfigs)- {- if (string.IsNullOrWhiteSpace(pc.Host) || !ushort.TryParse(pc.Port, out ushort port)) continue;- uint nativeId = _proxyService.AddProxyConfig(pc.Type, pc.Host, port, pc.Username, pc.Password);- if (nativeId > 0)- {- if (pc.Id > 0) configIdMap[pc.Id] = nativeId;- pc.Id = nativeId;- }- }-- if (_proxyService.Start())- {- foreach (var rule in ProxyRules)- {- uint nativeProxyId = 0;- if (rule.ProxyConfigId > 0)- configIdMap.TryGetValue(rule.ProxyConfigId, out nativeProxyId);- rule.ProxyConfigId = nativeProxyId;-- uint ruleId = _proxyService.AddRule(- rule.ProcessName, rule.TargetHosts, rule.TargetPorts, rule.TargetDomains,- rule.Protocol, rule.Action, nativeProxyId);-- if (ruleId > 0)- {- rule.RuleId = ruleId;- rule.Index = ProxyRules.IndexOf(rule) + 1;- if (!rule.IsEnabled)- _proxyService.DisableRule(ruleId);- }- }-- foreach (var rule in ProxyRules.Where(r => r.Action == "PROXY" && r.ProxyConfigId > 0))- {- var pc = ProxyConfigs.FirstOrDefault(p => p.Id == rule.ProxyConfigId);- rule.ProxyConfigDisplay = pc?.DisplayName ?? "";- }- }- else- {- QueueActivityLog("ERROR: Failed to start ProxyBridge service");- }- }- catch (Exception ex)- {- QueueActivityLog($"ERROR: {ex.Message}");- }-- _ = CheckForUpdatesOnStartupAsync();- }-- public string Title- {- get => _title;- set => SetProperty(ref _title, value);- }-- public string ActiveProfileName- {- get => _activeProfileName;- private set => SetProperty(ref _activeProfileName, value);- }-- public int SelectedTabIndex- {- get => _selectedTabIndex;- set => SetProperty(ref _selectedTabIndex, value);- }-- public string ConnectionsLog- {- get => _connectionsLog;- set- {- if (SetProperty(ref _connectionsLog, value))- {- if (string.IsNullOrWhiteSpace(_connectionsSearchText))- FilteredConnectionsLog = _connectionsLog;- }- }- }-- public string ActivityLog- {- get => _activityLog;- set- {- if (SetProperty(ref _activityLog, value))- {- if (string.IsNullOrWhiteSpace(_activitySearchText))- FilteredActivityLog = _activityLog;- }- }- }-- public bool IsProxyRulesDialogOpen- {- get => _isProxyRulesDialogOpen;- set => SetProperty(ref _isProxyRulesDialogOpen, value);- }-- public bool IsProxySettingsDialogOpen- {- get => _isProxySettingsDialogOpen;- set => SetProperty(ref _isProxySettingsDialogOpen, value);- }-- public bool IsAddRuleViewOpen- {- get => _isAddRuleViewOpen;- set => SetProperty(ref _isAddRuleViewOpen, value);- }-- public string ConnectionsSearchText- {- get => _connectionsSearchText;- set => SetProperty(ref _connectionsSearchText, value);- }-- public string ActivitySearchText- {- get => _activitySearchText;- set => SetProperty(ref _activitySearchText, value);- }-- public string FilteredConnectionsLog- {- get => _filteredConnectionsLog;- set => SetProperty(ref _filteredConnectionsLog, value);- }-- public string FilteredActivityLog- {- get => _filteredActivityLog;- set => SetProperty(ref _filteredActivityLog, value);- }-- public string NewProcessName- {- get => _newProcessName;- set => SetProperty(ref _newProcessName, value);- }-- public string NewProxyAction- {- get => _newProxyAction;- set => SetProperty(ref _newProxyAction, value);- }-- private bool _localhostViaProxy = false;- public bool LocalhostViaProxy- {- get => _localhostViaProxy;- set- {- if (SetProperty(ref _localhostViaProxy, value))- {- _proxyService?.SetLocalhostViaProxy(value);- SaveCurrentProfileAsync();- }- }- }-- private bool _autoClearConnectionLogs = true;- public bool AutoClearConnectionLogs- {- get => _autoClearConnectionLogs;- set- {- if (SetProperty(ref _autoClearConnectionLogs, value))- SaveCurrentProfileAsync();- }- }-- private bool _isTrafficLoggingEnabled = true;- public bool IsTrafficLoggingEnabled- {- get => _isTrafficLoggingEnabled;- set- {- if (SetProperty(ref _isTrafficLoggingEnabled, value))- {- if (value)- {- ProxyBridgeService.SetTrafficLoggingEnabled(true);- _connectionLogTimer?.Start();- }- else- {- _connectionLogTimer?.Stop();- lock (_connectionLogLock)- {- _pendingConnectionLogs.Clear();- }-- ProxyBridgeService.SetTrafficLoggingEnabled(false);-- _connectionLogLineCount = 0;- ConnectionsLog = "";- FilteredConnectionsLog = "";- }- SaveCurrentProfileAsync();- }- }- }-- private bool _closeToTray = true;- public bool CloseToTray- {- get => _closeToTray;- set => SetProperty(ref _closeToTray, value);- }-- private readonly Loc _loc = Loc.Instance;- public Loc Loc => _loc;-- private string _currentLanguage = "en";- private string _englishCheckmark = "✓";- private string _chineseCheckmark = "";-- public string EnglishCheckmark- {- get => _englishCheckmark;- set => SetProperty(ref _englishCheckmark, value);- }-- public string ChineseCheckmark- {- get => _chineseCheckmark;- set => SetProperty(ref _chineseCheckmark, value);- }-- public bool StartWithWindows- {- get => _startWithWindows;- set => SetProperty(ref _startWithWindows, value);- }-- public ICommand ShowProxySettingsCommand { get; }- public ICommand ShowProxyRulesCommand { get; }- public ICommand ShowLogFiltersCommand { get; }- public ICommand ShowAboutCommand { get; }- public ICommand CheckForUpdatesCommand { get; }- public ICommand ToggleLocalhostViaProxyCommand { get; }- public ICommand ToggleTrafficLoggingCommand { get; }- public ICommand ToggleAutoClearConnectionLogsCommand { get; }- public ICommand ToggleCloseToTrayCommand { get; }- public ICommand ToggleStartWithWindowsCommand { get; }- public ICommand CloseDialogCommand { get; }- public ICommand ClearConnectionsLogCommand { get; }- public ICommand ClearActivityLogCommand { get; }- public ICommand SearchConnectionsCommand { get; }- public ICommand SearchActivityCommand { get; }- public ICommand AddRuleCommand { get; }- public ICommand SaveNewRuleCommand { get; }- public ICommand CancelAddRuleCommand { get; }- public ICommand NewProfileCommand { get; }- public ICommand RenameProfileCommand { get; }- public ICommand DeleteProfileCommand { get; }- public ICommand ImportProfileCommand { get; }- public ICommand ExportProfileCommand { get; }- public ICommand SwitchProfileCommand { get; }-- public MainWindowViewModel()- {- SwitchProfileCommand = new RelayCommandWithParameter<string>(name =>- {- if (string.IsNullOrEmpty(name) || name == _activeProfileName) return;- SaveCurrentProfile();- SwitchToProfile(name);- });-- ShowProxySettingsCommand = new RelayCommand(async () =>- {- var window = new ProxySettingsWindow();-- var viewModel = new ProxySettingsViewModel(- proxyConfigs: ProxyConfigs,- proxyService: _proxyService,- onConfigsChanged: SaveCurrentProfileAsync,- onClose: () => window.Close(),- countRulesUsingConfig: (id) =>- ProxyRules.Count(r => r.Action == "PROXY" && r.ProxyConfigId == id),- deleteRulesForConfig: (id) =>- {- var toDelete = ProxyRules.Where(r => r.Action == "PROXY" && r.ProxyConfigId == id).ToList();- foreach (var rule in toDelete)- {- _proxyService?.DeleteRule(rule.RuleId);- ProxyRules.Remove(rule);- }- if (toDelete.Count > 0)- SaveCurrentProfileAsync();- }- );-- window.DataContext = viewModel;- viewModel.SetWindow(window);-- if (_mainWindow != null)- await window.ShowDialog(_mainWindow);- });-- ShowProxyRulesCommand = new RelayCommand(async () =>- {- var window = new ProxyRulesWindow();-- var viewModel = new ProxyRulesViewModel(- proxyRules: ProxyRules,- availableProxyConfigs: ProxyConfigs,- onAddRule: (rule) =>- {- if (_proxyService != null)- {- uint ruleId = _proxyService.AddRule(- rule.ProcessName, rule.TargetHosts, rule.TargetPorts, rule.TargetDomains,- rule.Protocol, rule.Action, rule.ProxyConfigId);- if (ruleId > 0)- {- rule.RuleId = ruleId;- rule.Index = ProxyRules.Count + 1;- ProxyRules.Add(rule);- SaveCurrentProfileAsync();- }- else- {- QueueActivityLog("ERROR: Failed to add rule");- }- }- },- onClose: () => window.Close(),- proxyService: _proxyService,- onConfigChanged: SaveCurrentProfileAsync- );-- window.DataContext = viewModel;- viewModel.SetWindow(window);-- if (_mainWindow != null)- await window.ShowDialog(_mainWindow);- });-- ShowAboutCommand = new RelayCommand(async () =>- {- var viewModel = new AboutViewModel(() => { });- var window = new AboutWindow { DataContext = viewModel };- if (_mainWindow != null)- await window.ShowDialog(_mainWindow);- });-- CheckForUpdatesCommand = new RelayCommand(async () =>- {- var updateWindow = new UpdateCheckWindow();- var viewModel = new UpdateCheckViewModel(() => updateWindow.Close());- updateWindow.DataContext = viewModel;- if (_mainWindow != null)- await updateWindow.ShowDialog(_mainWindow);- });-- ToggleLocalhostViaProxyCommand = new RelayCommand(() => { LocalhostViaProxy = !LocalhostViaProxy; });- ToggleTrafficLoggingCommand = new RelayCommand(() => { IsTrafficLoggingEnabled = !IsTrafficLoggingEnabled; });- ToggleAutoClearConnectionLogsCommand = new RelayCommand(() => { AutoClearConnectionLogs = !AutoClearConnectionLogs; });-- ShowLogFiltersCommand = new RelayCommand(async () =>- {- var window = new LogFiltersWindow();- var viewModel = new LogFiltersViewModel(- existingFilters: new List<LogFilterEntry>(_currentLogFilters),- onSave: filters => UpdateLogFilters(filters),- onClose: () => window.Close()- );- window.DataContext = viewModel;- if (_mainWindow != null)- await window.ShowDialog(_mainWindow);- });-- ToggleCloseToTrayCommand = new RelayCommand(() =>- {- CloseToTray = !CloseToTray;- SaveCurrentProfileAsync();- });-- ToggleStartWithWindowsCommand = new RelayCommand(() =>- {- StartWithWindows = !StartWithWindows;- var settings = _settingsService.LoadSettings();- settings.StartWithWindows = StartWithWindows;- _settingsService.SaveSettings(settings);- _settingsService.SetStartupWithWindows(StartWithWindows);- });-- CloseDialogCommand = new RelayCommand(CloseDialogs);-- ClearConnectionsLogCommand = new RelayCommand(() =>- {- lock (_connectionLogLock)- {- _pendingConnectionLogs.Clear();- }-- _connectionLogLineCount = 0;- ConnectionsLog = "";- FilteredConnectionsLog = "";- });-- ClearActivityLogCommand = new RelayCommand(() =>- {- lock (_activityLogLock)- {- _pendingActivityLogs.Clear();- }-- _activityLogLineCount = 0;- ActivityLog = "";- FilteredActivityLog = "";- });-- SearchConnectionsCommand = new RelayCommand(() =>- {- FilteredConnectionsLog = FilterLog(_connectionsLog, _connectionsSearchText);- });-- SearchActivityCommand = new RelayCommand(() =>- {- FilteredActivityLog = FilterLog(_activityLog, _activitySearchText);- });-- AddRuleCommand = new RelayCommand(() =>- {- IsAddRuleViewOpen = true;- NewProcessName = "";- NewProxyAction = "PROXY";- });-- SaveNewRuleCommand = new RelayCommand(() =>- {- if (string.IsNullOrWhiteSpace(NewProcessName))- return;-- var rule = new ProxyRule- {- ProcessName = NewProcessName,- TargetHosts = "*",- TargetPorts = "*",- Protocol = "TCP",- Action = NewProxyAction,- IsEnabled = true- };-- if (_proxyService != null)- {- var ruleId = _proxyService.AddRule(NewProcessName, "*", "*", "*", "TCP", NewProxyAction);- if (ruleId > 0)- {- rule.RuleId = ruleId;- ProxyRules.Add(rule);- SaveCurrentProfileAsync();- IsAddRuleViewOpen = false;- NewProcessName = "";- }- else- {- QueueActivityLog("ERROR: Failed to add rule");- }- }- });-- CancelAddRuleCommand = new RelayCommand(() =>- {- IsAddRuleViewOpen = false;- NewProcessName = "";- });-- NewProfileCommand = new RelayCommand(async () =>- {- if (_mainWindow == null) return;-- var dialog = new ProfileDialogWindow(- "New Profile",- "Enter a name for the new profile:",- isInputMode: true,- "New Profile");-- await dialog.ShowDialog(_mainWindow);-- if (!dialog.Confirmed) return;-- var name = dialog.InputValue;- if (!ProfileManager.IsValidProfileName(name))- {- QueueActivityLog("Invalid profile name");- return;- }- if (ProfileManager.ProfileExists(name))- {- QueueActivityLog($"Profile '{name}' already exists");- return;- }-- SaveCurrentProfile();- ProfileManager.SaveProfile(name, new ProxyProfile { Name = name });- SwitchToProfile(name);- QueueActivityLog($"Profile created: {name}");- });-- RenameProfileCommand = new RelayCommand(async () =>- {- if (_mainWindow == null) return;-- var dialog = new ProfileDialogWindow(- "Rename Profile",- "Enter a new name for the current profile:",- isInputMode: true,- _activeProfileName);-- await dialog.ShowDialog(_mainWindow);-- if (!dialog.Confirmed) return;-- var newName = dialog.InputValue;- if (newName == _activeProfileName) return;-- if (!ProfileManager.IsValidProfileName(newName))- {- QueueActivityLog("Invalid profile name");- return;- }- if (ProfileManager.ProfileExists(newName))- {- QueueActivityLog($"Profile '{newName}' already exists");- return;- }-- SaveCurrentProfile();-- if (ProfileManager.RenameProfile(_activeProfileName, newName))- {- _activeProfileName = newName;- ActiveProfileName = newName;- Title = $"ProxyBridge - {newName}";- UpdateSettingsProfile(newName);- RefreshProfileList();- QueueActivityLog($"Profile renamed to: {newName}");- }- });-- DeleteProfileCommand = new RelayCommand(async () =>- {- if (_mainWindow == null) return;-- var profiles = ProfileManager.GetProfileNames();- if (profiles.Length <= 1)- {- QueueActivityLog("Cannot delete the only profile");- return;- }-- var dialog = new ProfileDialogWindow(- "Delete Profile",- $"Delete profile '{_activeProfileName}'? This cannot be undone.",- isInputMode: false);-- await dialog.ShowDialog(_mainWindow);-- if (!dialog.Confirmed) return;-- var nameToDelete = _activeProfileName;- var nextProfile = profiles.FirstOrDefault(p => p != nameToDelete)- ?? ProfileManager.DefaultProfileName;-- SwitchToProfile(nextProfile);- ProfileManager.DeleteProfile(nameToDelete);- RefreshProfileList();- QueueActivityLog($"Profile deleted: {nameToDelete}");- });-- ImportProfileCommand = new RelayCommand(async () =>- {- if (_mainWindow == null) return;- var topLevel = TopLevel.GetTopLevel(_mainWindow);- if (topLevel == null) return;-- var files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions- {- Title = "Import Profile",- AllowMultiple = false,- FileTypeFilter = new[]- {- new FilePickerFileType("ProxyBridge Profile") { Patterns = new[] { "*.pbprofile" } },- new FilePickerFileType("All Files") { Patterns = new[] { "*.*" } }- }- });-- if (files.Count == 0) return;-- try- {- var localPath = files[0].TryGetLocalPath();- if (string.IsNullOrEmpty(localPath))- {- QueueActivityLog("Import failed: cannot access file");- return;- }-- var importedName = ProfileManager.ImportProfile(localPath);- if (importedName == null)- {- QueueActivityLog("Import failed: invalid profile file");- return;- }-- RefreshProfileList();- QueueActivityLog($"Profile imported as: {importedName}");- }- catch (Exception ex)- {- QueueActivityLog($"Import failed: {ex.Message}");- }- });-- ExportProfileCommand = new RelayCommand(async () =>- {- if (_mainWindow == null) return;- var topLevel = TopLevel.GetTopLevel(_mainWindow);- if (topLevel == null) return;-- SaveCurrentProfile();-- var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions- {- Title = "Export Profile",- SuggestedFileName = $"{_activeProfileName}.pbprofile",- FileTypeChoices = new[]- {- new FilePickerFileType("ProxyBridge Profile") { Patterns = new[] { "*.pbprofile" } }- }- });-- if (file == null) return;-- try- {- var localPath = file.TryGetLocalPath();- if (string.IsNullOrEmpty(localPath))- {- QueueActivityLog("Export failed: cannot access path");- return;- }-- if (ProfileManager.ExportProfile(_activeProfileName, localPath))- QueueActivityLog($"Profile exported: {_activeProfileName}");- else- QueueActivityLog("Export failed");- }- catch (Exception ex)- {- QueueActivityLog($"Export failed: {ex.Message}");- }- });- }-- public void ChangeLanguage(string languageCode)- {- if (string.IsNullOrEmpty(languageCode)) return;-- _currentLanguage = languageCode;- EnglishCheckmark = languageCode == "en" ? "✓" : "";- ChineseCheckmark = languageCode == "zh" ? "✓" : "";- _loc.CurrentCulture = new System.Globalization.CultureInfo(languageCode);- SaveCurrentProfileAsync();- }-- private void CloseDialogs()- {- IsProxyRulesDialogOpen = false;- IsProxySettingsDialogOpen = false;- }-- private async Task CheckForUpdatesOnStartupAsync()- {- try- {- var settings = _settingsService.LoadSettings();- if (!settings.CheckForUpdatesOnStartup)- return;-- var updateService = new UpdateService();- var versionInfo = await updateService.CheckForUpdatesAsync();-- if (versionInfo.IsUpdateAvailable && _mainWindow != null)- {- var notificationWindow = new UpdateNotificationWindow();- var viewModel = new UpdateNotificationViewModel(() => notificationWindow.Close(), versionInfo);- notificationWindow.DataContext = viewModel;- _ = notificationWindow.ShowDialog(_mainWindow);- }- }- catch { }- }-- public void Cleanup()- {- try { _saveCts?.Cancel(); _saveCts?.Dispose(); _saveCts = null; } catch { }- try { SaveCurrentProfile(); } catch { }- try { _proxyService?.Dispose(); _proxyService = null; } catch { }- }-- private void UpdateLogFilters(List<LogFilterEntry> filters)- {- _currentLogFilters = filters;- _activeFilters = filters.ToArray();-- // Re-filter the existing connection log keep lines that still pass the new rules,- // remove lines that don't, without discarding the whole history.- lock (_connectionLogLock)- _pendingConnectionLogs.Clear();-- if (filters.Count == 0)- {- // No filters → keep everything as-is- }- else- {- // parse each existing line and drop ones that no longer pass- var lines = _connectionsLog.Split('\n', StringSplitOptions.RemoveEmptyEntries);- var kept = new System.Text.StringBuilder(_connectionsLog.Length);- int keptCount = 0;- foreach (var line in lines)- {- if (LinePassesLogFilters(line))- {- kept.Append(line);- kept.Append('\n');- keptCount++;- }- }- _connectionLogLineCount = keptCount;- ConnectionsLog = kept.ToString();- }-- SaveCurrentProfileAsync();- }-- // parse a rendered connection log line and run it through PassesLogFilters.- // format: [HH:mm:ss] processName (PID:pid) -> ip:port via proxyInfo- private bool LinePassesLogFilters(string line)- {- // quick path no filters active- if (_activeFilters.Length == 0) return true;-- try- {- // Extract process name between "] " and " (PID:"- int procStart = line.IndexOf("] ", StringComparison.Ordinal);- if (procStart < 0) return true;- procStart += 2;- int pidStart = line.IndexOf(" (PID:", procStart, StringComparison.Ordinal);- if (pidStart < 0) return true;- string processName = line[procStart..pidStart];-- // extract destination after " -> " and before last " via "- int arrowIdx = line.IndexOf(" -> ", pidStart, StringComparison.Ordinal);- if (arrowIdx < 0) return true;- int viaIdx = line.LastIndexOf(" via ", StringComparison.Ordinal);- if (viaIdx < 0 || viaIdx <= arrowIdx) return true;- string dest = line[(arrowIdx + 4)..viaIdx];-- // exract proxyInfo after last " via "- string proxyInfo = line[(viaIdx + 5)..];-- // Parse ip:port handle IPv6 [addr]:port- string destIp;- ushort destPort = 0;- if (dest.StartsWith('['))- {- int closeBracket = dest.IndexOf(']');- if (closeBracket < 0) return true;- destIp = dest[1..closeBracket];- if (closeBracket + 2 < dest.Length)- ushort.TryParse(dest[(closeBracket + 2)..], out destPort);- }- else- {- int lastColon = dest.LastIndexOf(':');- if (lastColon < 0) return true;- destIp = dest[..lastColon];- ushort.TryParse(dest[(lastColon + 1)..], out destPort);- }-- return PassesLogFilters(processName, destIp, destPort, proxyInfo);- }- catch- {- return true; // keep lines we cant parse- }- }-- private bool PassesLogFilters(string processName, string destIp, ushort destPort, string proxyInfo)- {- var filters = _activeFilters; // single volatile read → local snapshot- if (filters.Length == 0) return true;-- string protocol = proxyInfo.Contains("(UDP)", StringComparison.OrdinalIgnoreCase) ? "UDP" : "TCP";- string action = proxyInfo.StartsWith("Direct", StringComparison.OrdinalIgnoreCase) ? "Direct"- : proxyInfo.StartsWith("Proxy", StringComparison.OrdinalIgnoreCase) ? "Proxy"- : proxyInfo.StartsWith("Block", StringComparison.OrdinalIgnoreCase) ? "Blocked"- : "";-- bool TextMatch(string actual, string pattern)- {- if (string.IsNullOrEmpty(pattern) || pattern == "*") return true;- return pattern.Contains('*')- ? WildcardMatch(actual, pattern)- : actual.Contains(pattern, StringComparison.OrdinalIgnoreCase);- }-- bool RuleMatches(LogFilterEntry r)- {- if (!TextMatch(processName, r.ProcessName)) return false;- if (!TextMatch(destIp, r.Ip)) return false;- if (!TextMatch(destPort.ToString(), r.Port)) return false;- if (r.Protocol is not ("" or "All") && !r.Protocol.Equals(protocol, StringComparison.OrdinalIgnoreCase)) return false;- if (r.Action is not ("" or "All") && !r.Action.Equals(action, StringComparison.OrdinalIgnoreCase)) return false;- return true;- }-- // Exclude rules run first — any match hides the entry- foreach (var f in filters)- if (f.Mode == "Exclude" && RuleMatches(f)) return false;-- // Include rules — at least one must match if any exist- bool hasInclude = false;- foreach (var f in filters)- if (f.Mode == "Include") { hasInclude = true; if (RuleMatches(f)) return true; }-- return !hasInclude;- }-- private static bool WildcardMatch(string text, string pattern)- {- if (pattern == "*") return true;-- if (!pattern.Contains('*'))- return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);-- // simple glob: split on * and require ordered subsequence- var parts = pattern.Split('*');- int pos = 0;- for (int i = 0; i < parts.Length; i++)- {- if (parts[i].Length == 0) continue;- int idx = text.IndexOf(parts[i], pos, StringComparison.OrdinalIgnoreCase);- if (idx < 0) return false;- if (i == 0 && idx != 0) return false; // no leading * → must start with first part- pos = idx + parts[i].Length;- }- // no trailing * → text must end with last non-empty part- var lastPart = parts[^1];- if (lastPart.Length > 0 && !text.EndsWith(lastPart, StringComparison.OrdinalIgnoreCase))- return false;-- return true;- }-- private string FilterLog(string log, string searchText)- {- if (string.IsNullOrWhiteSpace(searchText))- return log;-- var sb = new StringBuilder(log.Length / 2);- var lines = log.Split('\n');-- foreach (var line in lines)- {- if (line.Contains(searchText, StringComparison.OrdinalIgnoreCase))- {- sb.Append(line);- sb.Append('\n');- }- }-- return sb.ToString();- }-- private static string TrimToLastNLines(string log, int maxLines, out int actualLines)- {- int newlines = 0;- for (int i = log.Length - 1; i >= 0; i--)- {- if (log[i] == '\n')- {- newlines++;- if (newlines > maxLines)- {- actualLines = maxLines;- return log.Substring(i + 1);- }- }- }- actualLines = newlines;- return log;- }-- private static int CountNewlines(string log)- {- return log.Count(c => c == '\n');- }-- private void LoadConfiguration()- {- try- {- var settings = _settingsService.LoadSettings();- StartWithWindows = settings.StartWithWindows && _settingsService.IsStartupEnabled();-- var profileName = settings.ActiveProfileName;- if (!ProfileManager.ProfileExists(profileName))- profileName = ProfileManager.DefaultProfileName;-- _activeProfileName = profileName;- ActiveProfileName = profileName;- Title = $"ProxyBridge - {profileName}";-- var profile = ProfileManager.LoadProfile(profileName);-- _localhostViaProxy = profile.LocalhostViaProxy;- OnPropertyChanged(nameof(LocalhostViaProxy));-- _closeToTray = profile.CloseToTray;- OnPropertyChanged(nameof(CloseToTray));-- _isTrafficLoggingEnabled = profile.IsTrafficLoggingEnabled;- OnPropertyChanged(nameof(IsTrafficLoggingEnabled));-- _autoClearConnectionLogs = profile.AutoClearConnectionLogs;- OnPropertyChanged(nameof(AutoClearConnectionLogs));-- _currentLogFilters = profile.LogFilters ?? new List<LogFilterEntry>();- _activeFilters = _currentLogFilters.ToArray();-- if (!string.IsNullOrWhiteSpace(profile.Language))- {- _currentLanguage = profile.Language;- _loc.CurrentCulture = new System.Globalization.CultureInfo(profile.Language);- EnglishCheckmark = profile.Language == "en" ? "✓" : "";- ChineseCheckmark = profile.Language == "zh" ? "✓" : "";- }-- if (profile.ProxyConfigs != null)- {- foreach (var pc in profile.ProxyConfigs.Where(pc => !string.IsNullOrWhiteSpace(pc.Host)))- {- ProxyConfigs.Add(new ProxyConfig- {- Id = pc.Id,- Type = pc.Type,- Host = pc.Host,- Port = pc.Port,- Username = pc.Username ?? "",- Password = pc.Password ?? ""- });- }- }-- if (profile.ProxyRules != null)- {- foreach (var rc in profile.ProxyRules)- {- if (string.IsNullOrWhiteSpace(rc.ProcessName)) continue;- var pc = rc.ProxyConfigId > 0- ? ProxyConfigs.FirstOrDefault(p => p.Id == rc.ProxyConfigId)- : null;- ProxyRules.Add(new ProxyRule- {- ProcessName = rc.ProcessName,- TargetHosts = ValidationHelper.DefaultIfEmpty(rc.TargetHosts),- TargetPorts = ValidationHelper.DefaultIfEmpty(rc.TargetPorts),- TargetDomains = ValidationHelper.DefaultIfEmpty(rc.TargetDomains),- Protocol = ValidationHelper.DefaultIfEmpty(rc.Protocol, "TCP"),- Action = ValidationHelper.DefaultIfEmpty(rc.Action, "PROXY"),- IsEnabled = rc.IsEnabled,- ProxyConfigId = rc.ProxyConfigId,- ProxyConfigDisplay = pc?.DisplayName ?? ""- });- }- }-- RefreshProfileList();- QueueActivityLog("Configuration loaded");- }- catch (Exception ex)- {- QueueActivityLog($"Failed to load configuration: {ex.Message}");- }- }-- private void SwitchToProfile(string name)- {- foreach (var rule in ProxyRules.ToList())- _proxyService?.DeleteRule(rule.RuleId);- ProxyRules.Clear();-- foreach (var pc in ProxyConfigs.ToList())- _proxyService?.DeleteProxyConfig(pc.Id);- ProxyConfigs.Clear();-- var profile = ProfileManager.LoadProfile(name);- _activeProfileName = name;- ActiveProfileName = name;- Title = $"ProxyBridge - {name}";-- _localhostViaProxy = profile.LocalhostViaProxy;- OnPropertyChanged(nameof(LocalhostViaProxy));- _proxyService?.SetLocalhostViaProxy(profile.LocalhostViaProxy);-- _closeToTray = profile.CloseToTray;- OnPropertyChanged(nameof(CloseToTray));-- if (profile.IsTrafficLoggingEnabled != _isTrafficLoggingEnabled)- {- _isTrafficLoggingEnabled = profile.IsTrafficLoggingEnabled;- OnPropertyChanged(nameof(IsTrafficLoggingEnabled));- ProxyBridgeService.SetTrafficLoggingEnabled(profile.IsTrafficLoggingEnabled);- }-- _autoClearConnectionLogs = profile.AutoClearConnectionLogs;- OnPropertyChanged(nameof(AutoClearConnectionLogs));-- _currentLogFilters = profile.LogFilters ?? new List<LogFilterEntry>();- _activeFilters = _currentLogFilters.ToArray();-- if (!string.IsNullOrWhiteSpace(profile.Language))- {- _currentLanguage = profile.Language;- _loc.CurrentCulture = new System.Globalization.CultureInfo(profile.Language);- EnglishCheckmark = profile.Language == "en" ? "✓" : "";- ChineseCheckmark = profile.Language == "zh" ? "✓" : "";- }-- var configIdMap = new Dictionary<uint, uint>();- foreach (var pc in (profile.ProxyConfigs ?? Enumerable.Empty<ProxyConfigEntry>()).Where(pc => !string.IsNullOrWhiteSpace(pc.Host) && ushort.TryParse(pc.Port, out _)))- {- ushort.TryParse(pc.Port, out ushort port);-- uint nativeId = _proxyService != null- ? _proxyService.AddProxyConfig(pc.Type, pc.Host, port, pc.Username ?? "", pc.Password ?? "")- : 0;-- uint assignedId = nativeId > 0 ? nativeId : pc.Id;- if (pc.Id > 0) configIdMap[pc.Id] = assignedId;-- ProxyConfigs.Add(new ProxyConfig- {- Id = assignedId,- Type = pc.Type,- Host = pc.Host,- Port = pc.Port,- Username = pc.Username ?? "",- Password = pc.Password ?? ""- });- }-- foreach (var rc in profile.ProxyRules ?? new List<ProxyRuleConfig>())- {- if (string.IsNullOrWhiteSpace(rc.ProcessName)) continue;-- uint nativeProxyId = 0;- if (rc.ProxyConfigId > 0)- configIdMap.TryGetValue(rc.ProxyConfigId, out nativeProxyId);-- var pcVm = nativeProxyId > 0 ? ProxyConfigs.FirstOrDefault(p => p.Id == nativeProxyId) : null;- var rule = new ProxyRule- {- ProcessName = rc.ProcessName,- TargetHosts = ValidationHelper.DefaultIfEmpty(rc.TargetHosts),- TargetPorts = ValidationHelper.DefaultIfEmpty(rc.TargetPorts),- TargetDomains = ValidationHelper.DefaultIfEmpty(rc.TargetDomains),- Protocol = ValidationHelper.DefaultIfEmpty(rc.Protocol, "TCP"),- Action = ValidationHelper.DefaultIfEmpty(rc.Action, "PROXY"),- IsEnabled = rc.IsEnabled,- ProxyConfigId = nativeProxyId,- ProxyConfigDisplay = pcVm?.DisplayName ?? ""- };-- if (_proxyService != null)- {- uint ruleId = _proxyService.AddRule(- rule.ProcessName, rule.TargetHosts, rule.TargetPorts, rule.TargetDomains,- rule.Protocol, rule.Action, nativeProxyId);- if (ruleId > 0)- {- rule.RuleId = ruleId;- rule.Index = ProxyRules.Count + 1;- if (!rule.IsEnabled)- _proxyService.DisableRule(ruleId);- }- }-- ProxyRules.Add(rule);- }-- UpdateSettingsProfile(name);- RefreshProfileList();- }-- private void SaveCurrentProfile()- {- ProfileManager.SaveProfile(_activeProfileName, BuildCurrentProfile());- }-- private void SaveCurrentProfileAsync()- {- var oldCts = _saveCts;- _saveCts = new CancellationTokenSource();- oldCts?.Cancel();- oldCts?.Dispose();- var token = _saveCts.Token;- var name = _activeProfileName;- var profile = BuildCurrentProfile();- _ = Task.Run(async () =>- {- try- {- await Task.Delay(150, token);- ProfileManager.SaveProfile(name, profile);- }- catch (OperationCanceledException) { }- });- }-- private ProxyProfile BuildCurrentProfile()- {- return new ProxyProfile- {- LocalhostViaProxy = _localhostViaProxy,- IsTrafficLoggingEnabled = _isTrafficLoggingEnabled,- AutoClearConnectionLogs = _autoClearConnectionLogs,- Language = _currentLanguage,- CloseToTray = _closeToTray,- LogFilters = new List<LogFilterEntry>(_currentLogFilters),- ProxyConfigs = ProxyConfigs.Select(pc => new ProxyConfigEntry- {- Id = pc.Id,- Type = pc.Type,- Host = pc.Host,- Port = pc.Port,- Username = pc.Username,- Password = pc.Password- }).ToList(),- ProxyRules = ProxyRules.Select(r => new ProxyRuleConfig- {- ProcessName = r.ProcessName,- TargetHosts = r.TargetHosts,- TargetPorts = r.TargetPorts,- TargetDomains = r.TargetDomains,- Protocol = r.Protocol,- Action = r.Action,- IsEnabled = r.IsEnabled,- ProxyConfigId = r.ProxyConfigId- }).ToList()- };- }-- private void RefreshProfileList()- {- SwitchProfileItems.Clear();- foreach (var name in ProfileManager.GetProfileNames())- SwitchProfileItems.Add(name);- }-- private void UpdateSettingsProfile(string name)- {- var settings = _settingsService.LoadSettings();- settings.ActiveProfileName = name;- _settingsService.SaveSettings(settings);- }-- private void QueueActivityLog(string message)- {- lock (_activityLogLock)- _pendingActivityLogs.Add($"[{DateTime.Now:HH:mm:ss}] {message}\n");- }-}--public class ProxyRule : ViewModelBase-{- private string _processName = "*";- private string _targetHosts = "*";- private string _targetPorts = "*";- private string _targetDomains = "*";- private string _protocol = "TCP";- private string _action = "PROXY";- private bool _isEnabled = true;- private bool _isSelected = false;- private int _index;- private uint _ruleId;-- public int Index- {- get => _index;- set => SetProperty(ref _index, value);- }-- public uint RuleId- {- get => _ruleId;- set => SetProperty(ref _ruleId, value);- }-- public string ProcessName- {- get => _processName;- set => SetProperty(ref _processName, value);- }-- public string TargetHosts- {- get => _targetHosts;- set => SetProperty(ref _targetHosts, value);- }-- public string TargetPorts- {- get => _targetPorts;- set => SetProperty(ref _targetPorts, value);- }-- public string TargetDomains- {- get => _targetDomains;- set => SetProperty(ref _targetDomains, value);- }-- public string Protocol- {- get => _protocol;- set => SetProperty(ref _protocol, value);- }-- public string Action- {- get => _action;- set- {- if (SetProperty(ref _action, value))- OnPropertyChanged(nameof(ActionDisplay));- }- }-- private uint _proxyConfigId;- public uint ProxyConfigId- {- get => _proxyConfigId;- set => SetProperty(ref _proxyConfigId, value);- }-- private string _proxyConfigDisplay = "";- public string ProxyConfigDisplay- {- get => _proxyConfigDisplay;- set- {- if (SetProperty(ref _proxyConfigDisplay, value))- OnPropertyChanged(nameof(ActionDisplay));- }- }-- public string ActionDisplay => Action == "PROXY"- ? (string.IsNullOrEmpty(_proxyConfigDisplay) ? "PROXY" : _proxyConfigDisplay)- : Action;-- public bool IsEnabled- {- get => _isEnabled;- set => SetProperty(ref _isEnabled, value);- }-- public bool IsSelected- {- get => _isSelected;- set => SetProperty(ref _isSelected, value);- }-}--public class ProxyConfig : ViewModelBase-{- private uint _id;- private string _type = "SOCKS5";- private string _host = "";- private string _port = "";- private string _username = "";- private string _password = "";-- public uint Id- {- get => _id;- set => SetProperty(ref _id, value);- }-- public string Type- {- get => _type;- set- {- if (SetProperty(ref _type, value))- OnPropertyChanged(nameof(DisplayName));- }- }-- public string Host- {- get => _host;- set- {- if (SetProperty(ref _host, value))- OnPropertyChanged(nameof(DisplayName));- }- }-- public string Port- {- get => _port;- set- {- if (SetProperty(ref _port, value))- OnPropertyChanged(nameof(DisplayName));- }- }-- public string Username- {- get => _username;- set => SetProperty(ref _username, value);- }-- public string Password- {- get => _password;- set => SetProperty(ref _password, value);- }-- public string DisplayName => $"{_type} {_host}:{_port}";-}diff --git a/Windows/gui/ViewModels/ProfileDialogViewModel.cs b/Windows/gui/ViewModels/ProfileDialogViewModel.csdeleted file mode 100644index e92d20e..0000000--- a/Windows/gui/ViewModels/ProfileDialogViewModel.cs+++ /dev/null@@ -1,35 +0,0 @@-using System;-using System.Windows.Input;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class ProfileDialogViewModel : ViewModelBase-{- private string _inputValue;- private readonly Action<string> _onConfirm;-- public string Message { get; }- public bool IsInputMode { get; }-- public string InputValue- {- get => _inputValue;- set => SetProperty(ref _inputValue, value);- }-- public ICommand ConfirmCommand { get; }- public ICommand CancelCommand { get; }-- public ProfileDialogViewModel(string message, bool isInputMode, string defaultValue,- Action<string> onConfirm, Action onCancel)- {- Message = message;- IsInputMode = isInputMode;- _inputValue = defaultValue;- _onConfirm = onConfirm;-- ConfirmCommand = new RelayCommand(() => _onConfirm(_inputValue));- CancelCommand = new RelayCommand(onCancel);- }-}diff --git a/Windows/gui/ViewModels/ProxyRulesViewModel.cs b/Windows/gui/ViewModels/ProxyRulesViewModel.csdeleted file mode 100644index 8234262..0000000--- a/Windows/gui/ViewModels/ProxyRulesViewModel.cs+++ /dev/null@@ -1,517 +0,0 @@-using System;-using System.Collections.ObjectModel;-using System.Linq;-using System.Windows.Input;-using Avalonia.Controls;-using ProxyBridge.GUI.Services;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class ProxyRulesViewModel : ViewModelBase-{- private static readonly System.Text.RegularExpressions.Regex _processNameRegex =- new(@"^[\w\s._\-*;""\\:()+\u4E00-\u9FFF\u3400-\u4DBF\uF900-\uFAFF]+$",- System.Text.RegularExpressions.RegexOptions.Compiled,- TimeSpan.FromSeconds(1));-- private readonly Loc _loc = Loc.Instance;- public Loc Loc => _loc;-- private bool _isAddRuleViewOpen;- private bool _isEditMode;- private uint _currentEditingRuleId;- private string _newProcessName = "*";- private string _newTargetHosts = "*";- private string _newTargetPorts = "*";- private string _newTargetDomains = "*";- private string _newProtocol = "TCP"; // TCP, UDP, or BOTH- private RuleActionItem? _selectedRuleAction;- private string _processNameError = "";- private Action<ProxyRule>? _onAddRule;- private Action? _onClose;- private Action? _onConfigChanged;- private ProxyBridgeService? _proxyService;- private Window? _window;-- public ObservableCollection<ProxyRule> ProxyRules { get; }- public ObservableCollection<RuleActionItem> AvailableActions { get; } = new();-- public bool IsAddRuleViewOpen- {- get => _isAddRuleViewOpen;- set => SetProperty(ref _isAddRuleViewOpen, value);- }-- public string NewProcessName- {- get => _newProcessName;- set- {- SetProperty(ref _newProcessName, value);- ProcessNameError = "";- }- }-- public string NewTargetHosts- {- get => _newTargetHosts;- set => SetProperty(ref _newTargetHosts, value);- }-- public string NewTargetPorts- {- get => _newTargetPorts;- set => SetProperty(ref _newTargetPorts, value);- }-- public string NewTargetDomains- {- get => _newTargetDomains;- set => SetProperty(ref _newTargetDomains, value);- }-- public string NewProtocol- {- get => _newProtocol;- set => SetProperty(ref _newProtocol, value);- }-- public RuleActionItem? SelectedRuleAction- {- get => _selectedRuleAction;- set => SetProperty(ref _selectedRuleAction, value);- }-- public string ProcessNameError- {- get => _processNameError;- set => SetProperty(ref _processNameError, value);- }-- public ICommand AddRuleCommand { get; }- public ICommand SaveNewRuleCommand { get; }- public ICommand CancelAddRuleCommand { get; }- public ICommand CloseCommand { get; }- public ICommand BrowseProcessCommand { get; }- public ICommand DeleteRuleCommand { get; }- public ICommand EditRuleCommand { get; }- public ICommand ToggleSelectAllCommand { get; }- public ICommand DeleteSelectedRulesCommand { get; }-- public bool HasSelectedRules => ProxyRules.Any(r => r.IsSelected);- public bool AllRulesSelected => ProxyRules.Any() && ProxyRules.All(r => r.IsSelected);-- public void SetWindow(Window window)- {- _window = window;- window.Closed += (_, _) => Cleanup();- }-- public void Cleanup()- {- foreach (var rule in ProxyRules)- rule.PropertyChanged -= Rule_PropertyChanged;- }-- public bool MoveRuleToPosition(uint ruleId, uint newPosition)- {- if (_proxyService == null)- return false;-- return _proxyService.MoveRuleToPosition(ruleId, newPosition);- }-- private void ResetRuleForm()- {- NewProcessName = "*";- NewTargetHosts = "*";- NewTargetPorts = "*";- NewTargetDomains = "*";- NewProtocol = "TCP";- SelectedRuleAction = AvailableActions.FirstOrDefault();- ProcessNameError = "";- }-- public ProxyRulesViewModel(ObservableCollection<ProxyRule> proxyRules, ObservableCollection<ProxyConfig> availableProxyConfigs, Action<ProxyRule> onAddRule, Action onClose, ProxyBridgeService? proxyService = null, Action? onConfigChanged = null)- {- ProxyRules = proxyRules;- _onAddRule = onAddRule;- _onClose = onClose;- _proxyService = proxyService;- _onConfigChanged = onConfigChanged;-- // proxy configs first, then direct/block at end- foreach (var pc in availableProxyConfigs)- AvailableActions.Add(new RuleActionItem(pc.DisplayName, "PROXY", pc.Id));- AvailableActions.Add(new RuleActionItem("Direct", "DIRECT", 0));- AvailableActions.Add(new RuleActionItem("Block", "BLOCK", 0));- _selectedRuleAction = AvailableActions.FirstOrDefault();-- foreach (var rule in ProxyRules)- {- rule.PropertyChanged += Rule_PropertyChanged;- }-- AddRuleCommand = new RelayCommand(() =>- {- ResetRuleForm();- IsAddRuleViewOpen = true;- });-- SaveNewRuleCommand = new RelayCommand(() =>- {- NewProcessName = ValidationHelper.DefaultIfEmpty(NewProcessName);- NewTargetHosts = ValidationHelper.DefaultIfEmpty(NewTargetHosts);- NewTargetPorts = ValidationHelper.DefaultIfEmpty(NewTargetPorts);- NewTargetDomains = ValidationHelper.DefaultIfEmpty(NewTargetDomains);-- if (!_processNameRegex.IsMatch(NewProcessName))- {- ProcessNameError = "Invalid characters in process name. Only letters, numbers, spaces, dots, dashes, underscores, semicolons, quotes, parentheses, plus signs, and * are allowed";- return;- }-- if (NewProcessName != "*" && !NewProcessName.Equals("*", StringComparison.OrdinalIgnoreCase))- {- if (!NewProcessName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) &&- !NewProcessName.Contains(".exe ", StringComparison.OrdinalIgnoreCase) &&- !NewProcessName.Contains(";", StringComparison.OrdinalIgnoreCase))- {- NewProcessName += ".exe";- }- }-- if (_isEditMode && _proxyService != null)- {- var existRule = ProxyRules.FirstOrDefault(r => r.RuleId == _currentEditingRuleId);- string action = SelectedRuleAction?.Action ?? "PROXY";- uint pcId = SelectedRuleAction?.ProxyConfigId ?? 0;-- if (_proxyService.EditRule(_currentEditingRuleId, NewProcessName, NewTargetHosts, NewTargetPorts, NewTargetDomains, NewProtocol, action, pcId))- {- if (existRule != null)- {- existRule.ProcessName = NewProcessName;- existRule.TargetHosts = NewTargetHosts;- existRule.TargetPorts = NewTargetPorts;- existRule.TargetDomains = NewTargetDomains;- existRule.Protocol = NewProtocol;- existRule.Action = action;- existRule.ProxyConfigId = pcId;- existRule.ProxyConfigDisplay = action == "PROXY" ? (SelectedRuleAction?.Label ?? "") : "";- }- _onConfigChanged?.Invoke();- }-- _isEditMode = false;- _currentEditingRuleId = 0;- }- else- {- string action = SelectedRuleAction?.Action ?? "PROXY";- uint pcId = SelectedRuleAction?.ProxyConfigId ?? 0;- var newRule = new ProxyRule- {- ProcessName = NewProcessName,- TargetHosts = NewTargetHosts,- TargetPorts = NewTargetPorts,- TargetDomains = NewTargetDomains,- Protocol = NewProtocol,- Action = action,- IsEnabled = true,- ProxyConfigId = pcId,- ProxyConfigDisplay = action == "PROXY" ? (SelectedRuleAction?.Label ?? "") : ""- };-- newRule.PropertyChanged += Rule_PropertyChanged;- _onAddRule?.Invoke(newRule);- }-- IsAddRuleViewOpen = false;- ResetRuleForm();- }); CancelAddRuleCommand = new RelayCommand(() =>- {- ResetRuleForm();- IsAddRuleViewOpen = false;- });-- CloseCommand = new RelayCommand(() =>- {- _onClose?.Invoke();- });-- BrowseProcessCommand = new RelayCommand(async () =>- {- if (_window == null)- return;-- var dialog = new Avalonia.Platform.Storage.FilePickerOpenOptions- {- Title = "Select Process Executable",- AllowMultiple = false,- FileTypeFilter = new[]- {- new Avalonia.Platform.Storage.FilePickerFileType("Executable Files")- {- Patterns = new[] { "*.exe" }- },- new Avalonia.Platform.Storage.FilePickerFileType("All Files")- {- Patterns = new[] { "*.*" }- }- }- };-- var result = await _window.StorageProvider.OpenFilePickerAsync(dialog);-- if (result != null && result.Count > 0)- {- string filename = System.IO.Path.GetFileName(result[0].Path.LocalPath);- if (string.IsNullOrWhiteSpace(NewProcessName) || NewProcessName == "*")- {- NewProcessName = filename;- }- else- {- if (!NewProcessName.EndsWith(";"))- NewProcessName += "; ";- else- NewProcessName += " ";-- NewProcessName += filename;- }- }- });-- DeleteRuleCommand = new RelayCommandWithParameter<ProxyRule>(async (rule) =>- {- if (rule == null || _proxyService == null || _window == null)- return;-- var result = await ShowConfirmDialogAsync("Delete Rule",- $"Are you sure you want to delete the rule for process '{rule.ProcessName}'?");-- if (result)- {- if (_proxyService.DeleteRule(rule.RuleId))- {- ProxyRules.Remove(rule);- _onConfigChanged?.Invoke();- }- }- });-- EditRuleCommand = new RelayCommandWithParameter<ProxyRule>((rule) =>- {- if (rule == null)- return;-- _isEditMode = true;- _currentEditingRuleId = rule.RuleId;- NewProcessName = rule.ProcessName;- NewTargetHosts = rule.TargetHosts;- NewTargetPorts = rule.TargetPorts;- NewTargetDomains = rule.TargetDomains;- NewProtocol = rule.Protocol;- SelectedRuleAction = AvailableActions.FirstOrDefault(a =>- a.Action == rule.Action && (a.Action != "PROXY" || a.ProxyConfigId == rule.ProxyConfigId))- ?? AvailableActions.FirstOrDefault();- ProcessNameError = "";- IsAddRuleViewOpen = true;- });-- ToggleSelectAllCommand = new RelayCommand(() =>- {- bool selectAll = !AllRulesSelected;- foreach (var rule in ProxyRules)- {- rule.IsSelected = selectAll;- }- OnPropertyChanged(nameof(HasSelectedRules));- OnPropertyChanged(nameof(AllRulesSelected));- });-- DeleteSelectedRulesCommand = new RelayCommand(async () =>- {- var selectedRules = ProxyRules.Where(r => r.IsSelected).ToList();- if (selectedRules.Count == 0)- return;-- var confirmMsg = selectedRules.Count == 1- ? $"Delete 1 selected rule?"- : $"Delete {selectedRules.Count} selected rules?";-- var confirmed = await ShowConfirmDialogAsync("Delete Selected Rules", confirmMsg);- if (!confirmed)- return;-- foreach (var rule in selectedRules)- {- if (_proxyService != null && _proxyService.DeleteRule(rule.RuleId))- {- ProxyRules.Remove(rule);- }- }-- _onConfigChanged?.Invoke();- OnPropertyChanged(nameof(HasSelectedRules));- OnPropertyChanged(nameof(AllRulesSelected));- });- }-- private async System.Threading.Tasks.Task<bool> ShowConfirmDialogAsync(string title, string message)- {- if (_window == null)- return false;-- var messageBox = new Window- {- Title = title,- Width = 400,- Height = 150,- WindowStartupLocation = WindowStartupLocation.CenterOwner,- CanResize = false- };-- bool result = false;-- var stackPanel = new StackPanel- {- Margin = new Avalonia.Thickness(20),- Spacing = 10- };-- stackPanel.Children.Add(new Avalonia.Controls.TextBlock- {- Text = message,- TextWrapping = Avalonia.Media.TextWrapping.Wrap- });-- var buttonPanel = new StackPanel- {- Orientation = Avalonia.Layout.Orientation.Horizontal,- HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,- Spacing = 10- };-- var yesButton = new Button- {- Content = "Yes",- Width = 80- };- yesButton.Click += (s, e) =>- {- result = true;- messageBox.Close();- };-- var noButton = new Button- {- Content = "No",- Width = 80- };- noButton.Click += (s, e) =>- {- result = false;- messageBox.Close();- };-- buttonPanel.Children.Add(yesButton);- buttonPanel.Children.Add(noButton);- stackPanel.Children.Add(buttonPanel);-- messageBox.Content = stackPanel;-- await messageBox.ShowDialog(_window);- return result;- }-- private void Rule_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)- {- if (e.PropertyName == nameof(ProxyRule.IsEnabled) && sender is ProxyRule rule && _proxyService != null)- {- if (rule.IsEnabled)- {- _proxyService.EnableRule(rule.RuleId);- }- else- {- _proxyService.DisableRule(rule.RuleId);- }- _onConfigChanged?.Invoke();- }- else if (e.PropertyName == nameof(ProxyRule.IsSelected))- {- OnPropertyChanged(nameof(HasSelectedRules));- OnPropertyChanged(nameof(AllRulesSelected));- }- }-- private async System.Threading.Tasks.Task ShowMessageAsync(string title, string message)- {- if (_window == null)- return;-- var messageBox = new Window- {- Title = title,- Width = 450,- Height = 180,- WindowStartupLocation = WindowStartupLocation.CenterOwner,- CanResize = false,- Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.Parse("#FF2D2D30"))- };-- var stackPanel = new StackPanel- {- Margin = new Avalonia.Thickness(20),- Spacing = 15- };-- stackPanel.Children.Add(new Avalonia.Controls.TextBlock- {- Text = message,- TextWrapping = Avalonia.Media.TextWrapping.Wrap,- Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.White),- FontSize = 13- });-- var buttonPanel = new StackPanel- {- Orientation = Avalonia.Layout.Orientation.Horizontal,- HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,- Spacing = 10- };-- var okButton = new Button- {- Content = "OK",- Width = 80,- Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.Parse("#FF0E639C")),- Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.White)- };- okButton.Click += (s, e) => messageBox.Close();-- buttonPanel.Children.Add(okButton);- stackPanel.Children.Add(buttonPanel);-- messageBox.Content = stackPanel;-- await messageBox.ShowDialog(_window);- }-}--public class RuleActionItem-{- public string Label { get; }- public string Action { get; } // "PROXY", "DIRECT", "BLOCK"- public uint ProxyConfigId { get; }-- public RuleActionItem(string label, string action, uint proxyConfigId)- {- Label = label;- Action = action;- ProxyConfigId = proxyConfigId;- }-}diff --git a/Windows/gui/ViewModels/ProxySettingsViewModel.cs b/Windows/gui/ViewModels/ProxySettingsViewModel.csdeleted file mode 100644index 3e6bfa3..0000000--- a/Windows/gui/ViewModels/ProxySettingsViewModel.cs+++ /dev/null@@ -1,391 +0,0 @@-using System;-using System.Collections.ObjectModel;-using System.Linq;-using System.Net;-using System.Text.RegularExpressions;-using System.Windows.Input;-using Avalonia.Controls;-using ProxyBridge.GUI.Services;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class ProxySettingsViewModel : ViewModelBase-{- private static readonly Regex _domainRegex =- new(@"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9](?:[a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$",- RegexOptions.Compiled,- TimeSpan.FromSeconds(1));-- private readonly Loc _loc = Loc.Instance;- public Loc Loc => _loc;-- private readonly ObservableCollection<ProxyConfig> _proxyConfigs;- private readonly ProxyBridgeService? _proxyService;- private readonly Action? _onConfigsChanged;- private readonly Action? _onClose;-- // edit panel state- private bool _isEditPanelOpen;- private uint _editingConfigId;- private Window? _window;- private readonly Func<uint, int>? _countRulesUsingConfig;- private readonly Action<uint>? _deleteRulesForConfig;-- private string _newType = "SOCKS5";- private string _newHost = "";- private string _newPort = "";- private string _newUsername = "";- private string _newPassword = "";- private string _hostError = "";- private string _portError = "";-- // test panel state- private bool _isTestViewOpen;- private string _testTargetHost = "google.com";- private string _testTargetPort = "80";- private string _testOutput = "";- private bool _isTesting;- private uint _testingConfigId;-- public ObservableCollection<ProxyConfig> ProxyConfigs => _proxyConfigs;-- public bool IsEditPanelOpen- {- get => _isEditPanelOpen;- set => SetProperty(ref _isEditPanelOpen, value);- }-- public string EditPanelTitle => _editingConfigId > 0 ? "Edit Proxy Config" : "Add Proxy Config";-- public string NewType- {- get => _newType;- set => SetProperty(ref _newType, value);- }-- public string NewHost- {- get => _newHost;- set { SetProperty(ref _newHost, value); HostError = ""; }- }-- public string NewPort- {- get => _newPort;- set { SetProperty(ref _newPort, value); PortError = ""; }- }-- public string NewUsername- {- get => _newUsername;- set => SetProperty(ref _newUsername, value);- }-- public string NewPassword- {- get => _newPassword;- set => SetProperty(ref _newPassword, value);- }-- public string HostError- {- get => _hostError;- set => SetProperty(ref _hostError, value);- }-- public string PortError- {- get => _portError;- set => SetProperty(ref _portError, value);- }-- public bool IsTestViewOpen- {- get => _isTestViewOpen;- set => SetProperty(ref _isTestViewOpen, value);- }-- public string TestTargetHost- {- get => _testTargetHost;- set => SetProperty(ref _testTargetHost, value);- }-- public string TestTargetPort- {- get => _testTargetPort;- set => SetProperty(ref _testTargetPort, value);- }-- public string TestOutput- {- get => _testOutput;- set => SetProperty(ref _testOutput, value);- }-- public bool IsTesting- {- get => _isTesting;- set => SetProperty(ref _isTesting, value);- }-- public ICommand OpenAddPanelCommand { get; }- public ICommand SaveConfigCommand { get; }- public ICommand CancelEditCommand { get; }- public ICommand EditConfigCommand { get; }- public ICommand DeleteConfigCommand { get; }- public ICommand OpenTestPanelCommand { get; }- public ICommand CloseTestPanelCommand { get; }- public ICommand StartTestCommand { get; }- public ICommand CloseCommand { get; }-- public void SetWindow(Window window) => _window = window;-- public ProxySettingsViewModel(- ObservableCollection<ProxyConfig> proxyConfigs,- ProxyBridgeService? proxyService,- Action? onConfigsChanged,- Action? onClose,- Func<uint, int>? countRulesUsingConfig = null,- Action<uint>? deleteRulesForConfig = null)- {- _proxyConfigs = proxyConfigs;- _proxyService = proxyService;- _onConfigsChanged = onConfigsChanged;- _onClose = onClose;- _countRulesUsingConfig = countRulesUsingConfig;- _deleteRulesForConfig = deleteRulesForConfig;-- OpenAddPanelCommand = new RelayCommand(() =>- {- _editingConfigId = 0;- OnPropertyChanged(nameof(EditPanelTitle));- NewType = "SOCKS5";- NewHost = "";- NewPort = "";- NewUsername = "";- NewPassword = "";- HostError = "";- PortError = "";- IsEditPanelOpen = true;- });-- SaveConfigCommand = new RelayCommand(() =>- {- bool valid = ValidationHelper.ValidateIpOrDomain(NewHost, IsValidIpOrDomain, msg => HostError = msg)- && ValidationHelper.ValidatePort(NewPort, msg => PortError = msg);- if (!valid) return;-- if (!ushort.TryParse(NewPort, out ushort portNum)) return;-- if (_editingConfigId > 0)- {- if (_proxyService != null)- _proxyService.EditProxyConfig(_editingConfigId, NewType, NewHost, portNum, NewUsername, NewPassword);-- var existing = FindConfig(_editingConfigId);- if (existing != null)- {- existing.Type = NewType;- existing.Host = NewHost;- existing.Port = NewPort;- existing.Username = NewUsername;- existing.Password = NewPassword;- }- }- else- {- uint newId = 0;- if (_proxyService != null)- newId = _proxyService.AddProxyConfig(NewType, NewHost, portNum, NewUsername, NewPassword);-- if (newId == 0) newId = (uint)(DateTime.Now.Ticks & 0xFFFFFFFF);-- _proxyConfigs.Add(new ProxyConfig- {- Id = newId,- Type = NewType,- Host = NewHost,- Port = NewPort,- Username = NewUsername,- Password = NewPassword- });- }-- IsEditPanelOpen = false;- _onConfigsChanged?.Invoke();- });-- CancelEditCommand = new RelayCommand(() =>- {- IsEditPanelOpen = false;- });-- EditConfigCommand = new RelayCommandWithParameter<ProxyConfig>(config =>- {- if (config == null) return;- _editingConfigId = config.Id;- OnPropertyChanged(nameof(EditPanelTitle));- NewType = config.Type;- NewHost = config.Host;- NewPort = config.Port;- NewUsername = config.Username;- NewPassword = config.Password;- HostError = "";- PortError = "";- IsEditPanelOpen = true;- });-- DeleteConfigCommand = new RelayCommandWithParameter<ProxyConfig>(config =>- {- if (config == null) return;- _ = DeleteConfigAsync(config);- });-- // ---------------------------------------------------------------- // Helpers- // ---------------------------------------------------------------- OpenTestPanelCommand = new RelayCommandWithParameter<ProxyConfig>(config =>- {- if (config == null) return;- _testingConfigId = config.Id;- TestOutput = "";- IsTestViewOpen = true;- });-- CloseTestPanelCommand = new RelayCommand(() =>- {- IsTestViewOpen = false;- });-- StartTestCommand = new RelayCommand(async () =>- {- if (IsTesting) return;- if (string.IsNullOrWhiteSpace(TestTargetHost)) { TestOutput = "ERROR: Enter target host"; return; }- if (!ushort.TryParse(TestTargetPort, out ushort targetPortNum)) { TestOutput = "ERROR: Invalid target port"; return; }-- IsTesting = true;- TestOutput = "Testing...\n";- try- {- if (_proxyService != null)- {- await System.Threading.Tasks.Task.Run(() =>- {- TestOutput = _proxyService.TestProxyConfig(_testingConfigId, TestTargetHost, targetPortNum);- });- }- else- {- TestOutput = "ERROR: Proxy service not available";- }- }- catch (Exception ex)- {- TestOutput += $"\nERROR: {ex.Message}";- }- finally- {- IsTesting = false;- }- });-- CloseCommand = new RelayCommand(() => _onClose?.Invoke());- }-- private ProxyConfig? FindConfig(uint configId)- {- return _proxyConfigs.FirstOrDefault(c => c.Id == configId);- }-- private async System.Threading.Tasks.Task DeleteConfigAsync(ProxyConfig config)- {- int affectedCount = _countRulesUsingConfig?.Invoke(config.Id) ?? 0;-- if (affectedCount > 0)- {- string ruleWord = affectedCount == 1 ? "rule" : "rules";- bool confirmed = await ShowConfirmAsync(- "Delete Proxy Config",- $"{affectedCount} {ruleWord} using this proxy config will also be deleted.\n\nContinue?");- if (!confirmed)- return;- }-- _deleteRulesForConfig?.Invoke(config.Id);-- if (_proxyService != null)- _proxyService.DeleteProxyConfig(config.Id);-- _proxyConfigs.Remove(config);- _onConfigsChanged?.Invoke();- }-- private async System.Threading.Tasks.Task<bool> ShowConfirmAsync(string title, string message)- {- if (_window == null)- return true;-- bool result = false;-- var dialog = new Window- {- Title = title,- Width = 420,- Height = 190,- WindowStartupLocation = WindowStartupLocation.CenterOwner,- CanResize = false,- Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.Parse("#FF2D2D30"))- };-- var stack = new StackPanel { Margin = new Avalonia.Thickness(20), Spacing = 16 };-- stack.Children.Add(new Avalonia.Controls.TextBlock- {- Text = message,- TextWrapping = Avalonia.Media.TextWrapping.Wrap,- Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.White),- FontSize = 13- });-- var buttons = new StackPanel- {- Orientation = Avalonia.Layout.Orientation.Horizontal,- HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,- Spacing = 10- };-- var deleteBtn = new Button- {- Content = "Delete",- Width = 80,- Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.Parse("#FFCC3333")),- Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.White)- };- deleteBtn.Click += (s, e) => { result = true; dialog.Close(); };-- var cancelBtn = new Button- {- Content = "Cancel",- Width = 80,- Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Color.Parse("#FF3C3C3C")),- Foreground = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.White)- };- cancelBtn.Click += (s, e) => dialog.Close();-- buttons.Children.Add(deleteBtn);- buttons.Children.Add(cancelBtn);- stack.Children.Add(buttons);- dialog.Content = stack;-- await dialog.ShowDialog(_window);- return result;- }-- private static bool IsValidIpOrDomain(string input)- {- if (IPAddress.TryParse(input, out _)) return true;- return _domainRegex.IsMatch(input);- }-}diff --git a/Windows/gui/ViewModels/UpdateCheckViewModel.cs b/Windows/gui/ViewModels/UpdateCheckViewModel.csdeleted file mode 100644index f77477b..0000000--- a/Windows/gui/ViewModels/UpdateCheckViewModel.cs+++ /dev/null@@ -1,226 +0,0 @@-using System;-using System.Windows.Input;-using System.Threading.Tasks;-using ProxyBridge.GUI.Services;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class UpdateCheckViewModel : ViewModelBase-{- private readonly UpdateService _updateService;- private readonly Action _onClose;- private string _currentVersion = "";- private string _latestVersion = "";- private string _statusMessage = "";- private string _statusColor = "#FFB0B0B0";- private string _latestVersionColor = "#FFB0B0B0";- private string _errorMessage = "";- private bool _isChecking = false;- private bool _hasError = false;- private bool _isUpdateAvailable = false;- private bool _isDownloading = false;- private int _downloadProgress = 0;- private string _downloadStatus = "";- private VersionInfo? _currentVersionInfo;-- public UpdateCheckViewModel() : this(() => { })- {- }-- public UpdateCheckViewModel(Action onClose)- {- _updateService = new UpdateService();- _onClose = onClose;-- CheckUpdatesCommand = new RelayCommand(async () => await CheckForUpdatesAsync());- DownloadNowCommand = new RelayCommand(async () => await DownloadAndInstallAsync(), () => IsUpdateAvailable && !IsDownloading);- CloseCommand = new RelayCommand(onClose);-- _ = CheckForUpdatesAsync();- }-- public string CurrentVersion- {- get => _currentVersion;- set => SetProperty(ref _currentVersion, value);- }-- public string LatestVersion- {- get => _latestVersion;- set => SetProperty(ref _latestVersion, value);- }-- public string StatusMessage- {- get => _statusMessage;- set => SetProperty(ref _statusMessage, value);- }-- public string StatusColor- {- get => _statusColor;- set => SetProperty(ref _statusColor, value);- }-- public string LatestVersionColor- {- get => _latestVersionColor;- set => SetProperty(ref _latestVersionColor, value);- }-- public string ErrorMessage- {- get => _errorMessage;- set => SetProperty(ref _errorMessage, value);- }-- public bool IsChecking- {- get => _isChecking;- set => SetProperty(ref _isChecking, value);- }-- public bool HasError- {- get => _hasError;- set => SetProperty(ref _hasError, value);- }-- public bool IsUpdateAvailable- {- get => _isUpdateAvailable;- set => SetProperty(ref _isUpdateAvailable, value);- }-- public bool IsDownloading- {- get => _isDownloading;- set => SetProperty(ref _isDownloading, value);- }-- public int DownloadProgress- {- get => _downloadProgress;- set => SetProperty(ref _downloadProgress, value);- }-- public string DownloadStatus- {- get => _downloadStatus;- set => SetProperty(ref _downloadStatus, value);- }-- public ICommand CheckUpdatesCommand { get; }- public ICommand DownloadNowCommand { get; }- public ICommand CloseCommand { get; }-- private async Task CheckForUpdatesAsync()- {- IsChecking = true;- HasError = false;- StatusMessage = "";- ErrorMessage = "";-- try- {- var versionInfo = await _updateService.CheckForUpdatesAsync();- _currentVersionInfo = versionInfo;-- CurrentVersion = versionInfo.CurrentVersionString;- LatestVersion = versionInfo.LatestVersionString;- IsUpdateAvailable = versionInfo.IsUpdateAvailable;-- if (!string.IsNullOrEmpty(versionInfo.Error))- {- HasError = true;- ErrorMessage = $"Error checking for updates: {versionInfo.Error}";- StatusMessage = "Unable to check for updates";- StatusColor = "#FFFF6B6B";- LatestVersionColor = "#FFFF6B6B";- }- else if (versionInfo.IsUpdateAvailable)- {- StatusMessage = "New version available!";- StatusColor = "#FF4CAF50";- LatestVersionColor = "#FF4CAF50";- }- else- {- StatusMessage = "You have the latest version";- StatusColor = "#FF4CAF50";- LatestVersionColor = "#FF007ACC";- }-- (DownloadNowCommand as RelayCommand)?.RaiseCanExecuteChanged();- }- catch (Exception ex)- {- HasError = true;- ErrorMessage = $"Error checking for updates: {ex.Message}";- StatusMessage = "Unable to check for updates";- StatusColor = "#FFFF6B6B";- LatestVersionColor = "#FFFF6B6B";- }- finally- {- IsChecking = false;- }- }-- private async Task DownloadAndInstallAsync()- {- if (_currentVersionInfo?.DownloadUrl == null || _currentVersionInfo?.SetupFileName == null)- {- ErrorMessage = "Download URL not available";- HasError = true;- return;- }-- IsDownloading = true;- DownloadProgress = 0;- DownloadStatus = "Starting download...";- HasError = false;- ErrorMessage = "";-- try- {- var progress = new Progress<int>(percent =>- {- DownloadProgress = percent;- DownloadStatus = $"Downloading... {percent}%";- });-- var installerPath = await _updateService.DownloadUpdateAsync(- _currentVersionInfo.DownloadUrl,- _currentVersionInfo.SetupFileName,- progress);-- if (installerPath != null)- {- DownloadStatus = "Download complete. Starting installer...";- await Task.Delay(1000);-- _updateService.InstallUpdateAndExit(installerPath);- }- else- {- HasError = true;- ErrorMessage = "Failed to download the update";- DownloadStatus = "Download failed";- }- }- catch (Exception ex)- {- HasError = true;- ErrorMessage = $"Download error: {ex.Message}";- DownloadStatus = "Download failed";- }- finally- {- IsDownloading = false;- (DownloadNowCommand as RelayCommand)?.RaiseCanExecuteChanged();- }- }-}\ No newline at end of filediff --git a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs b/Windows/gui/ViewModels/UpdateNotificationViewModel.csdeleted file mode 100644index 98f34cf..0000000--- a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs+++ /dev/null@@ -1,171 +0,0 @@-using System;-using System.Windows.Input;-using System.Threading.Tasks;-using System.Diagnostics;-using System.IO;-using System.Net.Http;-using ProxyBridge.GUI.Services;-using ProxyBridge.GUI.Common;--namespace ProxyBridge.GUI.ViewModels;--public class UpdateNotificationViewModel : ViewModelBase-{- private readonly UpdateService _updateService;- private readonly SettingsService _settingsService;- private readonly Action _onClose;- private readonly VersionInfo _versionInfo;-- private string _currentVersion = "";- private string _latestVersion = "";- private string _downloadStatus = "";- private string _errorMessage = "";- private double _downloadProgress = 0;- private bool _isDownloading = false;- private bool _hasError = false;-- public UpdateNotificationViewModel() : this(() => { }, new VersionInfo())- {- }-- public UpdateNotificationViewModel(Action onClose, VersionInfo versionInfo)- {- _updateService = new UpdateService();- _settingsService = new SettingsService();- _onClose = onClose;- _versionInfo = versionInfo;-- CurrentVersion = versionInfo.CurrentVersionString;- LatestVersion = versionInfo.LatestVersionString;-- UpdateNowCommand = new RelayCommand(async () => await DownloadAndInstallAsync());- DontAskAgainCommand = new RelayCommand(DontAskAgain);- LaterCommand = new RelayCommand(_onClose);- }-- public string CurrentVersion- {- get => _currentVersion;- set => SetProperty(ref _currentVersion, value);- }-- public string LatestVersion- {- get => _latestVersion;- set => SetProperty(ref _latestVersion, value);- }-- public string DownloadStatus- {- get => _downloadStatus;- set => SetProperty(ref _downloadStatus, value);- }-- public string ErrorMessage- {- get => _errorMessage;- set => SetProperty(ref _errorMessage, value);- }-- public double DownloadProgress- {- get => _downloadProgress;- set => SetProperty(ref _downloadProgress, value);- }-- public bool IsDownloading- {- get => _isDownloading;- set => SetProperty(ref _isDownloading, value);- }-- public bool HasError- {- get => _hasError;- set => SetProperty(ref _hasError, value);- }-- public ICommand UpdateNowCommand { get; }- public ICommand DontAskAgainCommand { get; }- public ICommand LaterCommand { get; }-- private async Task DownloadAndInstallAsync()- {- IsDownloading = true;- HasError = false;- ErrorMessage = "";- DownloadProgress = 0;- DownloadStatus = "Starting download...";-- try- {- if (string.IsNullOrEmpty(_versionInfo.DownloadUrl))- {- throw new Exception("Could not find download URL for the latest version");- }-- var tempPath = Path.GetTempPath();- var fileName = _versionInfo.SetupFileName ?? "ProxyBridge-Setup.exe";- var filePath = Path.Combine(tempPath, fileName);-- DownloadStatus = "Downloading update...";-- using var httpClient = new HttpClient();- using var response = await httpClient.GetAsync(_versionInfo.DownloadUrl, HttpCompletionOption.ResponseHeadersRead);- response.EnsureSuccessStatusCode();-- var totalBytes = response.Content.Headers.ContentLength ?? -1L;- using var contentStream = await response.Content.ReadAsStreamAsync();- using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true);-- var buffer = new byte[8192];- long totalBytesRead = 0;- int bytesRead;-- while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)- {- await fileStream.WriteAsync(buffer, 0, bytesRead);- totalBytesRead += bytesRead;-- if (totalBytes > 0)- {- DownloadProgress = (double)totalBytesRead / totalBytes * 100;- DownloadStatus = $"Downloaded {totalBytesRead / 1024 / 1024:F1} MB of {totalBytes / 1024 / 1024:F1} MB";- }- else- {- DownloadStatus = $"Downloaded {totalBytesRead / 1024 / 1024:F1} MB";- }- }-- DownloadStatus = "Download complete. Starting installation...";- DownloadProgress = 100;-- Process.Start(new ProcessStartInfo- {- FileName = filePath,- UseShellExecute = true- });-- Environment.Exit(0);- }- catch (Exception ex)- {- HasError = true;- ErrorMessage = $"Error downloading update: {ex.Message}";- DownloadStatus = "Download failed";- }- finally- {- IsDownloading = false;- }- }-- private void DontAskAgain()- {- var settings = _settingsService.LoadSettings();- settings.CheckForUpdatesOnStartup = false;- _settingsService.SaveSettings(settings);- _onClose();- }-}\ No newline at end of filediff --git a/Windows/gui/ViewModels/ViewModelBase.cs b/Windows/gui/ViewModels/ViewModelBase.csdeleted file mode 100644index 8e55ad6..0000000--- a/Windows/gui/ViewModels/ViewModelBase.cs+++ /dev/null@@ -1,25 +0,0 @@-using System.Collections.Generic;-using System.ComponentModel;-using System.Runtime.CompilerServices;--namespace ProxyBridge.GUI.ViewModels;--public class ViewModelBase : INotifyPropertyChanged-{- public event PropertyChangedEventHandler? PropertyChanged;-- protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)- {- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));- }-- protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? propertyName = null)- {- // EqualityComparer<T>.Default avoids the boxing that object.Equals(field, value)- // incurs for value-typed properties (bool/int/enum) — this runs on every setter.- if (EqualityComparer<T>.Default.Equals(field, value)) return false;- field = value;- OnPropertyChanged(propertyName);- return true;- }-}diff --git a/Windows/gui/Views/AboutWindow.axaml b/Windows/gui/Views/AboutWindow.axamldeleted file mode 100644index 522ca01..0000000--- a/Windows/gui/Views/AboutWindow.axaml+++ /dev/null@@ -1,86 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- x:Class="ProxyBridge.GUI.Views.AboutWindow"- x:DataType="vm:AboutViewModel"- x:CompileBindings="True"- Title="About ProxyBridge"- Icon="/Assets/logo.ico"- Width="500" Height="400"- CanResize="False"- WindowStartupLocation="CenterOwner"- Background="#FF1E1E1E">-- <Design.DataContext>- <vm:AboutViewModel/>- </Design.DataContext>-- <Grid RowDefinitions="Auto,*">- <!-- Header -->- <Border Grid.Row="0" Background="#FF252526" BorderBrush="#FF007ACC" BorderThickness="0,0,0,1" Padding="20,16">- <StackPanel Orientation="Horizontal" Spacing="12">- <TextBlock Text="ℹ" FontSize="24" Foreground="#FF007ACC" VerticalAlignment="Center"/>- <TextBlock Text="About ProxyBridge"- FontSize="18"- FontWeight="SemiBold"- VerticalAlignment="Center"/>- </StackPanel>- </Border>-- <!-- Content -->- <StackPanel Grid.Row="1" Margin="32,24" Spacing="16">- <TextBlock Text="ProxyBridge"- FontSize="28"- FontWeight="Bold"- HorizontalAlignment="Center"- Foreground="#FF007ACC"/>-- <TextBlock Text="{Binding Version}"- FontSize="14"- HorizontalAlignment="Center"- Foreground="#FFB0B0B0"/>-- <TextBlock Text="Universal proxy client for Windows applications"- FontSize="14"- HorizontalAlignment="Center"- Foreground="#FFB0B0B0"- TextWrapping="Wrap"- Margin="0,0,0,8"/>--- <TextBlock Text="Author: Sourav Kalal / InterceptSuite"- FontSize="13"- HorizontalAlignment="Center"- Foreground="#FFB0B0B0"- Margin="0,4,0,0"/>-- <!-- Clickable Links -->- <StackPanel Spacing="12">- <TextBlock HorizontalAlignment="Center">- <Run Text="Website: " Foreground="#FFB0B0B0"/>- <TextBlock Text="interceptsuite.com"- Foreground="#FF007ACC"- TextDecorations="Underline"- Cursor="Hand"- PointerPressed="OnWebsiteClick"/>- </TextBlock>-- <TextBlock HorizontalAlignment="Center">- <Run Text="GitHub: " Foreground="#FFB0B0B0"/>- <TextBlock Text="github.com/InterceptSuite/ProxyBridge"- Foreground="#FF007ACC"- TextDecorations="Underline"- Cursor="Hand"- PointerPressed="OnGitHubClick"/>- </TextBlock>- </StackPanel>-- <TextBlock Text="License: MIT"- FontSize="13"- HorizontalAlignment="Center"- Foreground="#FFB0B0B0"- Margin="0,8,0,0"/>-- </StackPanel>- </Grid>-</Window>diff --git a/Windows/gui/Views/AboutWindow.axaml.cs b/Windows/gui/Views/AboutWindow.axaml.csdeleted file mode 100644index 7d9afed..0000000--- a/Windows/gui/Views/AboutWindow.axaml.cs+++ /dev/null@@ -1,40 +0,0 @@-using Avalonia.Controls;-using System.Diagnostics;-using Avalonia.Input;--namespace ProxyBridge.GUI.Views;--public partial class AboutWindow : Window-{- public AboutWindow()- {- InitializeComponent();- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };- }-- private void OnWebsiteClick(object? sender, PointerPressedEventArgs e)- {- OpenUrl("https://interceptsuite.com");- }-- private void OnGitHubClick(object? sender, PointerPressedEventArgs e)- {- OpenUrl("https://github.com/InterceptSuite/ProxyBridge");- }-- private void OpenUrl(string url)- {- try- {- Process.Start(new ProcessStartInfo- {- FileName = url,- UseShellExecute = true- });- }- catch- {- // Silently fail if browser can't be opened- }- }-}diff --git a/Windows/gui/Views/LogFiltersWindow.axaml b/Windows/gui/Views/LogFiltersWindow.axamldeleted file mode 100644index c4729e6..0000000--- a/Windows/gui/Views/LogFiltersWindow.axaml+++ /dev/null@@ -1,169 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- mc:Ignorable="d" d:DesignWidth="700" d:DesignHeight="480"- x:Class="ProxyBridge.GUI.Views.LogFiltersWindow"- x:DataType="vm:LogFiltersViewModel"- x:CompileBindings="True"- Title="Log Filters"- Icon="/Assets/logo.ico"- Width="700" Height="460"- MinWidth="560" MinHeight="300"- Background="#FF2D2D30"- WindowStartupLocation="CenterOwner">-- <DockPanel>- <!-- Header -->- <Border DockPanel.Dock="Top" Background="#FF1E1E1E" Padding="20,16"- BorderBrush="#FF3F3F46" BorderThickness="0,0,0,1">- <StackPanel Spacing="6">- <StackPanel Orientation="Horizontal" Spacing="10">- <TextBlock Text="🔽" FontSize="20" VerticalAlignment="Center"/>- <TextBlock Text="Log Filters"- FontSize="18"- FontWeight="SemiBold"- Foreground="#FFE0E0E0"- VerticalAlignment="Center"/>- </StackPanel>- <TextBlock Text="{Binding Loc.LogFiltersDesc1}"- FontSize="12"- Foreground="#FF9E9E9E"- TextWrapping="Wrap"/>- <TextBlock Text="{Binding Loc.LogFiltersDesc2}"- FontSize="12"- Foreground="#FF9E9E9E"- TextWrapping="Wrap"/>- </StackPanel>- </Border>-- <!-- Footer -->- <Border DockPanel.Dock="Bottom" Background="#FF1E1E1E" Padding="16,12"- BorderBrush="#FF3F3F46" BorderThickness="0,1,0,0">- <Grid ColumnDefinitions="*,Auto,8,Auto,8,Auto">- <Button Grid.Column="1"- Content="Clear All"- Command="{Binding ClearAllCommand}"- Classes="secondary"- Padding="12,8"/>- <Button Grid.Column="3"- Content="Cancel"- Command="{Binding CloseCommand}"- Classes="secondary"- Padding="12,8"/>- <Button Grid.Column="5"- Content="Save"- Command="{Binding SaveCommand}"- Padding="24,8"/>- </Grid>- </Border>-- <!-- Body -->- <DockPanel>- <!-- Add Rule button -->- <Border DockPanel.Dock="Top" Background="#FF252526" Padding="16,10"- BorderBrush="#FF3F3F46" BorderThickness="0,0,0,1">- <Button Content="+ Add Rule"- Command="{Binding AddRuleCommand}"- Classes="secondary"- Padding="12,6"- HorizontalAlignment="Left"/>- </Border>-- <!-- Rule cards -->- <ScrollViewer VerticalScrollBarVisibility="Auto">- <ItemsControl ItemsSource="{Binding Rules}" Margin="12,8">- <ItemsControl.ItemTemplate>- <DataTemplate x:DataType="vm:LogFilterRuleViewModel">- <Border Background="#FF1E1E1E"- BorderBrush="#FF4A4A50"- BorderThickness="1"- CornerRadius="4"- Margin="0,0,0,8">- <StackPanel>-- <!-- Rule header: Mode + remove button -->- <Border Background="#FF252526" Padding="12,8">- <Grid ColumnDefinitions="Auto,*,Auto">- <ComboBox Grid.Column="0"- ItemsSource="{Binding ModeList}"- SelectedItem="{Binding Mode}"- MinWidth="110"- Padding="8,5"/>- <Button Grid.Column="2"- Content="🗑"- Command="{Binding $parent[ItemsControl].((vm:LogFiltersViewModel)DataContext).RemoveRuleCommand}"- CommandParameter="{Binding}"- Classes="secondary"- Padding="4"- Width="32" Height="32"- VerticalAlignment="Center"/>- </Grid>- </Border>-- <!-- Fields -->- <Border Padding="12,10">- <Grid ColumnDefinitions="80,*,20,80,*"- RowDefinitions="Auto,Auto,Auto">-- <!-- Row 0: Process | Action -->- <TextBlock Grid.Row="0" Grid.Column="0"- Text="Process"- Foreground="#FF9E9E9E" FontSize="12"- VerticalAlignment="Center" Margin="0,0,8,6"/>- <TextBox Grid.Row="0" Grid.Column="1"- Text="{Binding ProcessName}"- Watermark="any (e.g. curl, chrome*, *.exe)"- Padding="8,5" Margin="0,0,0,6"/>- <TextBlock Grid.Row="0" Grid.Column="3"- Text="Action"- Foreground="#FF9E9E9E" FontSize="12"- VerticalAlignment="Center" Margin="0,0,8,6"/>- <ComboBox Grid.Row="0" Grid.Column="4"- ItemsSource="{Binding ActionList}"- SelectedItem="{Binding Action}"- HorizontalAlignment="Stretch"- Padding="8,5" Margin="0,0,0,6"/>-- <!-- Row 1: IP | Protocol -->- <TextBlock Grid.Row="1" Grid.Column="0"- Text="IP"- Foreground="#FF9E9E9E" FontSize="12"- VerticalAlignment="Center" Margin="0,0,8,6"/>- <TextBox Grid.Row="1" Grid.Column="1"- Text="{Binding Ip}"- Watermark="any (e.g. 8.8.*, 192.168.*)"- Padding="8,5" Margin="0,0,0,6"/>- <TextBlock Grid.Row="1" Grid.Column="3"- Text="Protocol"- Foreground="#FF9E9E9E" FontSize="12"- VerticalAlignment="Center" Margin="0,0,8,6"/>- <ComboBox Grid.Row="1" Grid.Column="4"- ItemsSource="{Binding ProtocolList}"- SelectedItem="{Binding Protocol}"- HorizontalAlignment="Stretch"- Padding="8,5" Margin="0,0,0,6"/>-- <!-- Row 2: Port -->- <TextBlock Grid.Row="2" Grid.Column="0"- Text="Port"- Foreground="#FF9E9E9E" FontSize="12"- VerticalAlignment="Center" Margin="0,0,8,0"/>- <TextBox Grid.Row="2" Grid.Column="1"- Text="{Binding Port}"- Watermark="any (e.g. 443, 8080)"- Padding="8,5"/>-- </Grid>- </Border>-- </StackPanel>- </Border>- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </ScrollViewer>- </DockPanel>- </DockPanel>-</Window>diff --git a/Windows/gui/Views/LogFiltersWindow.axaml.cs b/Windows/gui/Views/LogFiltersWindow.axaml.csdeleted file mode 100644index 2317c6e..0000000--- a/Windows/gui/Views/LogFiltersWindow.axaml.cs+++ /dev/null@@ -1,13 +0,0 @@-using Avalonia.Controls;-using Avalonia.Input;--namespace ProxyBridge.GUI.Views;--public partial class LogFiltersWindow : Window-{- public LogFiltersWindow()- {- InitializeComponent();- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };- }-}diff --git a/Windows/gui/Views/MainWindow.axaml b/Windows/gui/Views/MainWindow.axamldeleted file mode 100644index ed5e5de..0000000--- a/Windows/gui/Views/MainWindow.axaml+++ /dev/null@@ -1,403 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- xmlns:services="using:ProxyBridge.GUI.Services"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- mc:Ignorable="d" d:DesignWidth="1100" d:DesignHeight="650"- x:Class="ProxyBridge.GUI.Views.MainWindow"- x:DataType="vm:MainWindowViewModel"- x:CompileBindings="True"- Title="{Binding Title}"- Icon="/Assets/logo.ico"- Width="1100" Height="650"- MinWidth="900" MinHeight="600"- Background="#1E1E1E"- TransparencyLevelHint="AcrylicBlur"- ExtendClientAreaToDecorationsHint="True">-- <Design.DataContext>- <vm:MainWindowViewModel/>- </Design.DataContext>-- <Window.Styles>- <!-- Modern Dark Theme -->- <Style Selector="Window">- <Setter Property="Background" Value="#FF1E1E1E"/>- </Style>-- <!-- Menu Styling -->- <Style Selector="Menu">- <Setter Property="Background" Value="#FF2D2D30"/>- <Setter Property="Foreground" Value="#FFE0E0E0"/>- <Setter Property="Height" Value="30"/>- </Style>-- <Style Selector="MenuItem">- <Setter Property="Foreground" Value="#FFE0E0E0"/>- <Setter Property="Padding" Value="12,6"/>- <Setter Property="Height" Value="30"/>- </Style>-- <Style Selector="MenuItem:pointerover /template/ Border#PART_LayoutRoot">- <Setter Property="Background" Value="#FF3E3E42"/>- </Style>-- <Style Selector="MenuItem:selected /template/ Border#PART_LayoutRoot">- <Setter Property="Background" Value="#FF094771"/>- </Style>-- <!-- Tab Control -->- <Style Selector="TabControl">- <Setter Property="Background" Value="Transparent"/>- </Style>-- <Style Selector="TabItem">- <Setter Property="Foreground" Value="#FF9E9E9E"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="Padding" Value="16,8"/>- <Setter Property="MinHeight" Value="36"/>- </Style>-- <Style Selector="TabItem:selected">- <Setter Property="Foreground" Value="#FFFFFFFF"/>- <Setter Property="Background" Value="#FF2D2D30"/>- </Style>-- <Style Selector="TabItem:pointerover">- <Setter Property="Foreground" Value="#FFCCCCCC"/>- </Style>-- <!-- TextBox Styling -->- <Style Selector="TextBox">- <Setter Property="Background" Value="#FF1E1E1E"/>- <Setter Property="Foreground" Value="#FFD4D4D4"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="BorderThickness" Value="1"/>- <Setter Property="Padding" Value="8"/>- <Setter Property="FontFamily" Value="Consolas,Courier New"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="SelectionBrush" Value="#FF264F78"/>- <Setter Property="SelectionForegroundBrush" Value="#FFFFFFFF"/>- </Style>-- <Style Selector="TextBox:focus /template/ Border#PART_BorderElement">- <Setter Property="BorderBrush" Value="#FF007ACC"/>- <Setter Property="BorderThickness" Value="1"/>- </Style>-- <Style Selector="TextBox:pointerover /template/ Border#PART_BorderElement">- <Setter Property="BorderBrush" Value="#FF555555"/>- </Style>-- <!-- Button Styling -->- <Style Selector="Button">- <Setter Property="Background" Value="#FF0E639C"/>- <Setter Property="Foreground" Value="#FFFFFFFF"/>- <Setter Property="BorderThickness" Value="0"/>- <Setter Property="Padding" Value="16,8"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="CornerRadius" Value="3"/>- <Setter Property="Cursor" Value="Hand"/>- </Style>-- <Style Selector="Button:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF1177BB"/>- </Style>-- <Style Selector="Button:pressed /template/ ContentPresenter">- <Setter Property="Background" Value="#FF005A9E"/>- </Style>-- <Style Selector="Button.secondary">- <Setter Property="Background" Value="#FF3E3E42"/>- </Style>-- <Style Selector="Button.secondary:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF505050"/>- </Style>-- <Style Selector="Button.close">- <Setter Property="Background" Value="Transparent"/>- <Setter Property="Padding" Value="8"/>- <Setter Property="FontSize" Value="14"/>- <Setter Property="Width" Value="36"/>- <Setter Property="Height" Value="36"/>- </Style>-- <Style Selector="Button.close:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FFE81123"/>- </Style>-- <!-- CheckBox -->- <Style Selector="CheckBox">- <Setter Property="Foreground" Value="#FFD4D4D4"/>- </Style>-- <!-- ListBox -->- <Style Selector="ListBox">- <Setter Property="Background" Value="#FF252526"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="BorderThickness" Value="1"/>- </Style>-- <Style Selector="ListBoxItem">- <Setter Property="Padding" Value="12"/>- <Setter Property="MinHeight" Value="48"/>- </Style>-- <Style Selector="ListBoxItem:selected /template/ ContentPresenter">- <Setter Property="Background" Value="#FF094771"/>- </Style>-- <Style Selector="ListBoxItem:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF2A2D2E"/>- </Style>-- <!-- ComboBox -->- <Style Selector="ComboBox">- <Setter Property="Background" Value="#FF3C3C3C"/>- <Setter Property="Foreground" Value="#FFD4D4D4"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="Padding" Value="8"/>- </Style>-- <Style Selector="ComboBox:pointerover /template/ Border#Background">- <Setter Property="BorderBrush" Value="#FF555555"/>- </Style>-- <Style Selector="ComboBox:focus /template/ Border#Background">- <Setter Property="BorderBrush" Value="#FF007ACC"/>- </Style>-- <!-- TextBlock -->- <Style Selector="TextBlock">- <Setter Property="Foreground" Value="#FFD4D4D4"/>- </Style>-- <Style Selector="TextBlock.label">- <Setter Property="FontWeight" Value="Medium"/>- <Setter Property="Margin" Value="0,0,0,4"/>- </Style>-- <Style Selector="TextBlock.secondary">- <Setter Property="Foreground" Value="#FF9E9E9E"/>- </Style>- </Window.Styles>-- <Grid>- <!-- Main Content -->- <DockPanel>- <!-- Title Bar (Custom) -->- <Border DockPanel.Dock="Top" Background="#FF2D2D30" Height="32" IsHitTestVisible="False">- <Grid>- <TextBlock Text="{Binding Title}"- Foreground="#FFE0E0E0"- FontSize="12"- VerticalAlignment="Center"- Margin="12,0,0,0"/>- </Grid>- </Border>-- <!-- Menu Bar -->- <Grid DockPanel.Dock="Top" Background="#FF2D2D30" Height="30">- <Grid.ColumnDefinitions>- <ColumnDefinition Width="Auto"/>- <ColumnDefinition Width="Auto"/>- <ColumnDefinition Width="*"/>- </Grid.ColumnDefinitions>- <Menu Grid.Column="0" Background="Transparent" VerticalAlignment="Center">- <MenuItem Header="{Binding Loc.MenuProxy}">- <MenuItem Header="{Binding Loc.MenuProxySettings}" Command="{Binding ShowProxySettingsCommand}"/>- <MenuItem Header="{Binding Loc.MenuProxyRules}" Command="{Binding ShowProxyRulesCommand}"/>- <Separator/>- <MenuItem Header="{Binding Loc.MenuEnableTrafficLogging}"- Command="{Binding ToggleTrafficLoggingCommand}">- <MenuItem.Icon>- <CheckBox IsChecked="{Binding IsTrafficLoggingEnabled}"- IsHitTestVisible="False"- Margin="0"/>- </MenuItem.Icon>- </MenuItem>- <MenuItem Header="{Binding Loc.MenuLocalhostViaProxy}"- Command="{Binding ToggleLocalhostViaProxyCommand}">- <MenuItem.Icon>- <CheckBox IsChecked="{Binding LocalhostViaProxy}"- IsHitTestVisible="False"- Margin="0"/>- </MenuItem.Icon>- </MenuItem>- </MenuItem>- <MenuItem Header="{Binding Loc.MenuSettings}">- <MenuItem Header="{Binding Loc.MenuCloseToTray}"- Command="{Binding ToggleCloseToTrayCommand}">- <MenuItem.Icon>- <CheckBox IsChecked="{Binding CloseToTray}"- IsHitTestVisible="False"- Margin="0"/>- </MenuItem.Icon>- </MenuItem>- <MenuItem Header="{Binding Loc.MenuRunAtStartup}"- Command="{Binding ToggleStartWithWindowsCommand}">- <MenuItem.Icon>- <CheckBox IsChecked="{Binding StartWithWindows}"- IsHitTestVisible="False"- Margin="0"/>- </MenuItem.Icon>- </MenuItem>- <Separator/>- <MenuItem Header="{Binding Loc.MenuLogFilters}"- Command="{Binding ShowLogFiltersCommand}"/>- <MenuItem Header="{Binding Loc.MenuAutoClearLogs}"- Command="{Binding ToggleAutoClearConnectionLogsCommand}">- <MenuItem.Icon>- <CheckBox IsChecked="{Binding AutoClearConnectionLogs}"- IsHitTestVisible="False"- Margin="0"/>- </MenuItem.Icon>- </MenuItem>- <Separator/>- <MenuItem Header="{Binding Loc.MenuLanguage}">- <MenuItem Header="English" Click="OnChangeLanguageEnglish">- <MenuItem.Icon>- <TextBlock Text="{Binding EnglishCheckmark}" FontSize="14"/>- </MenuItem.Icon>- </MenuItem>- <MenuItem Header="中文 (Chinese)" Click="OnChangeLanguageChinese">- <MenuItem.Icon>- <TextBlock Text="{Binding ChineseCheckmark}" FontSize="14"/>- </MenuItem.Icon>- </MenuItem>- </MenuItem>- </MenuItem>- <MenuItem Header="{Binding Loc.MenuProfile}">- <MenuItem Header="{Binding Loc.MenuNewProfile}" Command="{Binding NewProfileCommand}"/>- <MenuItem Header="{Binding Loc.MenuRenameProfile}" Command="{Binding RenameProfileCommand}"/>- <MenuItem Header="{Binding Loc.MenuDeleteProfile}" Command="{Binding DeleteProfileCommand}"/>- <Separator/>- <MenuItem x:Name="SwitchProfileMenuItem" Header="{Binding Loc.MenuSwitchProfile}"/>- <Separator/>- <MenuItem Header="{Binding Loc.MenuImportProfile}" Command="{Binding ImportProfileCommand}"/>- <MenuItem Header="{Binding Loc.MenuExportProfile}" Command="{Binding ExportProfileCommand}"/>- </MenuItem>- <MenuItem Header="{Binding Loc.MenuAbout}">- <MenuItem Header="{Binding Loc.MenuAboutProxyBridge}" Command="{Binding ShowAboutCommand}"/>- <MenuItem Header="{Binding Loc.MenuCheckUpdates}" Command="{Binding CheckForUpdatesCommand}"/>- </MenuItem>- </Menu>- <!-- Quick-access buttons: right next to menu items -->- <StackPanel Grid.Column="1" Orientation="Horizontal" Spacing="2"- VerticalAlignment="Center" Margin="4,0">- <Button Command="{Binding ShowProxySettingsCommand}"- Classes="secondary"- ToolTip.Tip="{Binding Loc.MenuProxySettings}"- Padding="6,2" FontSize="16" Height="26"- Content="⚙"/>- <Button Command="{Binding ShowProxyRulesCommand}"- Classes="secondary"- ToolTip.Tip="{Binding Loc.MenuProxyRules}"- Padding="6,2" FontSize="16" Height="26"- Content="📋"/>- </StackPanel>- </Grid>-- <!-- Tab Control -->- <TabControl SelectedIndex="{Binding SelectedTabIndex}" Background="#FF1E1E1E" Padding="0">- <TabItem Header="{Binding Loc.TabConnections}">- <Border Background="#FF252526" Margin="8" CornerRadius="4" BorderBrush="#FF3F3F46" BorderThickness="1">- <DockPanel>- <!-- Search and Clear Bar -->- <Border DockPanel.Dock="Top" Background="#FF1E1E1E" Padding="8" BorderBrush="#FF3F3F46" BorderThickness="0,0,0,1">- <Grid ColumnDefinitions="*,Auto">- <TextBox Grid.Column="0"- Text="{Binding ConnectionsSearchText}"- Watermark="Search connections (press Enter)..."- Margin="0,0,8,0">- <TextBox.KeyBindings>- <KeyBinding Gesture="Enter" Command="{Binding SearchConnectionsCommand}"/>- </TextBox.KeyBindings>- </TextBox>- <Button Grid.Column="1"- Content="{Binding Loc.ButtonClearAllConnections}"- Classes="secondary"- Command="{Binding ClearConnectionsLogCommand}"- Padding="12,6"/>- </Grid>- </Border>-- <!-- Connections Log (read-only display: SelectableTextBlock is far- lighter than an editable TextBox — no undo buffer/caret/input- machinery — while still allowing text selection + copy) -->- <ScrollViewer>- <Panel MinHeight="500">- <SelectableTextBlock Text="{Binding FilteredConnectionsLog, Mode=OneWay}"- FontFamily="Consolas,Courier New"- FontSize="13"- Foreground="#FFD4D4D4"- SelectionBrush="#FF264F78"- TextWrapping="Wrap"- Padding="8"- VerticalAlignment="Top"/>- <TextBlock Text="No active connections..."- Foreground="#FF6A6A6A"- FontFamily="Consolas,Courier New"- FontSize="13"- Padding="8"- VerticalAlignment="Top"- IsHitTestVisible="False"- IsVisible="{Binding FilteredConnectionsLog, Converter={x:Static StringConverters.IsNullOrEmpty}}"/>- </Panel>- </ScrollViewer>- </DockPanel>- </Border>- </TabItem>- <TabItem Header="{Binding Loc.TabActivity}">- <Border Background="#FF252526" Margin="8" CornerRadius="4" BorderBrush="#FF3F3F46" BorderThickness="1">- <DockPanel>- <!-- Search and Clear Bar -->- <Border DockPanel.Dock="Top" Background="#FF1E1E1E" Padding="8" BorderBrush="#FF3F3F46" BorderThickness="0,0,0,1">- <Grid ColumnDefinitions="*,Auto">- <TextBox Grid.Column="0"- Text="{Binding ActivitySearchText}"- Watermark="Search activity (press Enter)..."- Margin="0,0,8,0">- <TextBox.KeyBindings>- <KeyBinding Gesture="Enter" Command="{Binding SearchActivityCommand}"/>- </TextBox.KeyBindings>- </TextBox>- <Button Grid.Column="1"- Content="{Binding Loc.ButtonClearAllLogs}"- Classes="secondary"- Command="{Binding ClearActivityLogCommand}"- Padding="12,6"/>- </Grid>- </Border>-- <!-- Activity Log (read-only: SelectableTextBlock, see connections log) -->- <ScrollViewer>- <Panel MinHeight="500">- <SelectableTextBlock Text="{Binding FilteredActivityLog, Mode=OneWay}"- FontFamily="Consolas,Courier New"- FontSize="13"- Foreground="#FFD4D4D4"- SelectionBrush="#FF264F78"- TextWrapping="Wrap"- Padding="8"- VerticalAlignment="Top"/>- <TextBlock Text="No activity yet..."- Foreground="#FF6A6A6A"- FontFamily="Consolas,Courier New"- FontSize="13"- Padding="8"- VerticalAlignment="Top"- IsHitTestVisible="False"- IsVisible="{Binding FilteredActivityLog, Converter={x:Static StringConverters.IsNullOrEmpty}}"/>- </Panel>- </ScrollViewer>- </DockPanel>- </Border>- </TabItem>- </TabControl>- </DockPanel>- </Grid>-</Window>diff --git a/Windows/gui/Views/MainWindow.axaml.cs b/Windows/gui/Views/MainWindow.axaml.csdeleted file mode 100644index ed38983..0000000--- a/Windows/gui/Views/MainWindow.axaml.cs+++ /dev/null@@ -1,98 +0,0 @@-using System.Collections.Specialized;-using System.Linq;-using Avalonia.Controls;-using ProxyBridge.GUI.ViewModels;-using System;-using System.ComponentModel;-using Avalonia.Interactivity;--namespace ProxyBridge.GUI.Views;--public partial class MainWindow : Window-{- public MainWindow()- {- InitializeComponent();-- this.Opened += (s, e) =>- {- if (DataContext is MainWindowViewModel vm)- {- vm.SetMainWindow(this);- SetupSwitchProfileMenu(vm);- }- };- }-- private void SetupSwitchProfileMenu(MainWindowViewModel vm)- {- var switchMenu = this.FindControl<MenuItem>("SwitchProfileMenuItem");- if (switchMenu == null) return;-- void Rebuild()- {- var items = vm.SwitchProfileItems.Select(name =>- {- var item = new MenuItem { Header = name };- item.Click += (_, _) => vm.SwitchProfileCommand.Execute(name);- return item;- }).Cast<object>().ToList();- switchMenu.ItemsSource = items;- }-- Rebuild();- vm.SwitchProfileItems.CollectionChanged += (_, _) => Rebuild();- }-- private void OnChangeLanguageEnglish(object? sender, RoutedEventArgs e)- {- if (DataContext is MainWindowViewModel vm)- {- vm.ChangeLanguage("en");- }- }-- private void OnChangeLanguageChinese(object? sender, RoutedEventArgs e)- {- if (DataContext is MainWindowViewModel vm)- {- vm.ChangeLanguage("zh");- }- }-- protected override void OnClosing(WindowClosingEventArgs e)- {- if (e.CloseReason == WindowCloseReason.ApplicationShutdown)- {- if (DataContext is MainWindowViewModel vm)- {- vm.Cleanup();- }- base.OnClosing(e);- return;- }-- // verify if user cclose app or minimize to tray- if (DataContext is MainWindowViewModel viewModel)- {- if (viewModel.CloseToTray)- {- // minimize to tray- e.Cancel = true;- this.Hide();- }- else- {- // exit the app if not tray- viewModel.Cleanup();- base.OnClosing(e);- }- }- else- {- // fallback to tray- e.Cancel = true;- this.Hide();- }- }-}diff --git a/Windows/gui/Views/ProfileDialogWindow.axaml b/Windows/gui/Views/ProfileDialogWindow.axamldeleted file mode 100644index faf400b..0000000--- a/Windows/gui/Views/ProfileDialogWindow.axaml+++ /dev/null@@ -1,87 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- x:Class="ProxyBridge.GUI.Views.ProfileDialogWindow"- x:DataType="vm:ProfileDialogViewModel"- x:CompileBindings="True"- Title="Profile"- Width="440" Height="185"- CanResize="False"- WindowStartupLocation="CenterOwner"- Background="#FF1E1E1E"- SizeToContent="Height">-- <Window.Styles>- <Style Selector="Button">- <Setter Property="Background" Value="#FF0E639C"/>- <Setter Property="Foreground" Value="#FFFFFFFF"/>- <Setter Property="BorderThickness" Value="0"/>- <Setter Property="Padding" Value="16,8"/>- <Setter Property="FontSize" Value="13"/>- <Setter Property="CornerRadius" Value="3"/>- <Setter Property="Cursor" Value="Hand"/>- </Style>- <Style Selector="Button:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF1177BB"/>- </Style>- <Style Selector="Button.secondary">- <Setter Property="Background" Value="#FF3E3E42"/>- </Style>- <Style Selector="Button.secondary:pointerover /template/ ContentPresenter">- <Setter Property="Background" Value="#FF505050"/>- </Style>- <Style Selector="TextBox">- <Setter Property="Background" Value="#FF2D2D30"/>- <Setter Property="Foreground" Value="#FFD4D4D4"/>- <Setter Property="BorderBrush" Value="#FF3F3F46"/>- <Setter Property="BorderThickness" Value="1"/>- <Setter Property="Padding" Value="8"/>- <Setter Property="FontSize" Value="13"/>- </Style>- <Style Selector="TextBox:focus /template/ Border#PART_BorderElement">- <Setter Property="BorderBrush" Value="#FF007ACC"/>- </Style>- <Style Selector="TextBlock">- <Setter Property="Foreground" Value="#FFD4D4D4"/>- </Style>- </Window.Styles>-- <Grid Margin="24,20,24,20">- <Grid.RowDefinitions>- <RowDefinition Height="Auto"/>- <RowDefinition Height="Auto"/>- <RowDefinition Height="16"/>- <RowDefinition Height="Auto"/>- </Grid.RowDefinitions>-- <TextBlock Grid.Row="0"- Text="{Binding Message}"- TextWrapping="Wrap"- Foreground="#FFD4D4D4"- FontSize="13"- Margin="0,0,0,12"/>-- <TextBox Grid.Row="1"- Text="{Binding InputValue}"- IsVisible="{Binding IsInputMode}"- x:Name="InputBox">- <TextBox.KeyBindings>- <KeyBinding Gesture="Enter" Command="{Binding ConfirmCommand}"/>- <KeyBinding Gesture="Escape" Command="{Binding CancelCommand}"/>- </TextBox.KeyBindings>- </TextBox>-- <StackPanel Grid.Row="3"- Orientation="Horizontal"- HorizontalAlignment="Right"- Spacing="8">- <Button Content="OK"- Command="{Binding ConfirmCommand}"- Width="80"/>- <Button Content="Cancel"- Command="{Binding CancelCommand}"- Classes="secondary"- Width="80"/>- </StackPanel>- </Grid>-</Window>diff --git a/Windows/gui/Views/ProfileDialogWindow.axaml.cs b/Windows/gui/Views/ProfileDialogWindow.axaml.csdeleted file mode 100644index 64e01d6..0000000--- a/Windows/gui/Views/ProfileDialogWindow.axaml.cs+++ /dev/null@@ -1,38 +0,0 @@-using System;-using Avalonia.Controls;-using Avalonia.Input;--namespace ProxyBridge.GUI.Views;--public partial class ProfileDialogWindow : Window-{- public bool Confirmed { get; private set; }- public string InputValue { get; private set; } = "";-- public ProfileDialogWindow()- {- InitializeComponent();- }-- public ProfileDialogWindow(string title, string message, bool isInputMode, string defaultValue = "")- {- InitializeComponent();- Title = title;- DataContext = new ViewModels.ProfileDialogViewModel(- message, isInputMode, defaultValue,- value => { Confirmed = true; InputValue = value?.Trim() ?? ""; Close(); },- () => { Confirmed = false; Close(); }- );- KeyDown += (_, e) => { if (e.Key == Key.Escape) { Confirmed = false; Close(); } };- }-- protected override void OnOpened(EventArgs e)- {- base.OnOpened(e);- if (this.FindControl<TextBox>("InputBox") is { } box)- {- box.Focus();- box.SelectAll();- }- }-}diff --git a/Windows/gui/Views/ProxyRulesWindow.axaml b/Windows/gui/Views/ProxyRulesWindow.axamldeleted file mode 100644index b88696a..0000000--- a/Windows/gui/Views/ProxyRulesWindow.axaml+++ /dev/null@@ -1,356 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- xmlns:views="using:ProxyBridge.GUI.Views"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- mc:Ignorable="d" d:DesignWidth="1100" d:DesignHeight="550"- x:Class="ProxyBridge.GUI.Views.ProxyRulesWindow"- x:DataType="vm:ProxyRulesViewModel"- x:CompileBindings="True"- Title="{Binding Loc.ProxyRulesTitle}"- Icon="/Assets/logo.ico"- Width="1100" Height="550"- MinWidth="980" MinHeight="400"- Background="#FF2D2D30"- WindowStartupLocation="CenterOwner">-- <Window.Resources>- <views:SelectAllTextConverter x:Key="SelectAllTextConverter"/>- <views:SelectAllIconConverter x:Key="SelectAllIconConverter"/>- </Window.Resources>-- <DockPanel>- <!-- Header -->- <Border DockPanel.Dock="Top" Background="#FF1E1E1E" Padding="20,16">- <Grid ColumnDefinitions="*,Auto">- <StackPanel Orientation="Horizontal" Spacing="10">- <TextBlock Text="⚙" FontSize="22" VerticalAlignment="Center"/>- <TextBlock Text="{Binding Loc.ProxyRulesTitle}"- FontSize="18"- FontWeight="SemiBold"- Foreground="#FFE0E0E0"- VerticalAlignment="Center"/>- </StackPanel>- <StackPanel Grid.Column="1"- Orientation="Horizontal"- Spacing="8"- IsVisible="{Binding !IsAddRuleViewOpen}">- <Button Content="{Binding AllRulesSelected, Converter={StaticResource SelectAllTextConverter}}"- Command="{Binding ToggleSelectAllCommand}"- Classes="secondary"- Padding="12,8"- IsEnabled="{Binding ProxyRules.Count}">- <Button.Content>- <StackPanel Orientation="Horizontal" Spacing="6">- <TextBlock Text="{Binding AllRulesSelected, Converter={StaticResource SelectAllIconConverter}}" FontSize="14"/>- <TextBlock Text="{Binding AllRulesSelected, Converter={StaticResource SelectAllTextConverter}}"/>- </StackPanel>- </Button.Content>- </Button>- <Button Command="{Binding DeleteSelectedRulesCommand}"- Classes="secondary"- Padding="12,8"- IsEnabled="{Binding HasSelectedRules}">- <StackPanel Orientation="Horizontal" Spacing="6">- <TextBlock Text="🗑" FontSize="14"/>- <TextBlock Text="Delete Selected"/>- </StackPanel>- </Button>- <Button Content="{Binding Loc.ButtonAdd}"- Command="{Binding AddRuleCommand}"/>- </StackPanel>- </Grid>- </Border>-- <!-- Rules List View -->- <Grid IsVisible="{Binding !IsAddRuleViewOpen}">- <Grid.RowDefinitions>- <RowDefinition Height="Auto"/>- <RowDefinition Height="*"/>- </Grid.RowDefinitions>-- <!-- Table Header -->- <Border Grid.Row="0"- Background="#FF1E1E1E"- BorderBrush="#FF3F3F46"- BorderThickness="0,1,0,1"- Padding="20,12">- <Grid ColumnDefinitions="60,80,140,60,200,150,120,150,80,*">- <TextBlock Grid.Column="0"- Text="Select"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="1"- Text="{Binding Loc.EnabledLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="2"- Text="{Binding Loc.ActionsLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="3"- Text="{Binding Loc.SRLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="4"- Text="{Binding Loc.ProcessLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="5"- Text="{Binding Loc.TargetHostsLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="6"- Text="{Binding Loc.TargetPortsLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="7"- Text="{Binding Loc.TargetDomainsLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="8"- Text="{Binding Loc.ProtocolLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="9"- Text="{Binding Loc.ActionLabel}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFB0B0B0"/>- </Grid>- </Border>-- <!-- Table Body -->- <ScrollViewer Grid.Row="1"- HorizontalScrollBarVisibility="Auto"- VerticalScrollBarVisibility="Auto">- <ItemsControl ItemsSource="{Binding ProxyRules}" x:Name="RulesItemsControl">- <ItemsControl.ItemTemplate>- <DataTemplate>- <Border Background="#FF252526"- BorderBrush="#FF3F3F46"- BorderThickness="0,0,0,1"- Padding="20,16"- PointerPressed="Rule_PointerPressed"- DragDrop.AllowDrop="True">- <Grid ColumnDefinitions="60,80,140,60,200,150,120,150,80,*">- <CheckBox Grid.Column="0"- IsChecked="{Binding IsSelected}"- VerticalAlignment="Center"- Margin="0,0,10,0"/>- <CheckBox Grid.Column="1"- IsChecked="{Binding IsEnabled}"- VerticalAlignment="Center"- Margin="0,0,10,0"/>- <StackPanel Grid.Column="2"- Orientation="Horizontal"- Spacing="8"- VerticalAlignment="Center"- Margin="0,0,10,0">- <Button Content="{Binding $parent[ItemsControl].((vm:ProxyRulesViewModel)DataContext).Loc.ButtonEdit, StringFormat='✏ {0}'}"- Command="{Binding $parent[ItemsControl].((vm:ProxyRulesViewModel)DataContext).EditRuleCommand}"- CommandParameter="{Binding}"- Padding="8,4"- MinWidth="60"- FontSize="12"/>- <Button Content="{Binding $parent[ItemsControl].((vm:ProxyRulesViewModel)DataContext).Loc.ButtonDelete, StringFormat='🗑 {0}'}"- Command="{Binding $parent[ItemsControl].((vm:ProxyRulesViewModel)DataContext).DeleteRuleCommand}"- CommandParameter="{Binding}"- Padding="8,4"- MinWidth="60"- FontSize="12"- Classes="secondary"/>- </StackPanel>- <TextBlock Grid.Column="3"- Text="{Binding Index}"- FontSize="14"- Foreground="#FF999999"- VerticalAlignment="Center"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="4"- Text="{Binding ProcessName}"- FontSize="14"- FontWeight="Medium"- Foreground="#FFE0E0E0"- VerticalAlignment="Center"- TextTrimming="CharacterEllipsis"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="5"- Text="{Binding TargetHosts}"- FontSize="13"- Foreground="#FF999999"- VerticalAlignment="Center"- TextTrimming="CharacterEllipsis"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="6"- Text="{Binding TargetPorts}"- FontSize="13"- Foreground="#FF999999"- VerticalAlignment="Center"- TextTrimming="CharacterEllipsis"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="7"- Text="{Binding TargetDomains}"- FontSize="13"- Foreground="#FF999999"- VerticalAlignment="Center"- TextTrimming="CharacterEllipsis"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="8"- Text="{Binding Protocol}"- FontSize="13"- Foreground="#FF999999"- VerticalAlignment="Center"- Margin="0,0,10,0"/>- <TextBlock Grid.Column="9"- Text="{Binding ActionDisplay}"- FontSize="14"- FontWeight="SemiBold"- Foreground="#FF4EC9B0"- VerticalAlignment="Center"- TextTrimming="CharacterEllipsis"/>- </Grid>- </Border>- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </ScrollViewer>- </Grid>-- <!-- Add Rule Form View -->- <ScrollViewer VerticalScrollBarVisibility="Auto"- HorizontalScrollBarVisibility="Disabled"- IsVisible="{Binding IsAddRuleViewOpen}">- <StackPanel Margin="24,20"- Spacing="20">- <!-- Applications Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ApplicationsLabel}" Classes="label"/>- <Grid ColumnDefinitions="*,Auto">- <TextBox Grid.Column="0"- Text="{Binding NewProcessName}"- Watermark="Any"- Margin="0,0,8,0"/>- <Button Grid.Column="1"- Content="{Binding Loc.BrowseButton}"- Command="{Binding BrowseProcessCommand}"- Padding="12,8"- MinWidth="100"/>- </Grid>- <TextBlock Text="{Binding Loc.ExampleApplications}"- FontSize="11"- Foreground="#FF999999"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <!-- Target Hosts Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.TargetHostsLabel}" Classes="label"/>- <TextBox Text="{Binding NewTargetHosts}"- Watermark="Any"/>- <TextBlock Text="{Binding Loc.ExampleTargetHosts}"- FontSize="11"- Foreground="#FF999999"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <!-- Target Ports Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.TargetPortsLabel}" Classes="label"/>- <TextBox Text="{Binding NewTargetPorts}"- Watermark="Any"/>- <TextBlock Text="{Binding Loc.ExampleTargetPorts}"- FontSize="11"- Foreground="#FF999999"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <!-- Target Domains Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.TargetDomainsLabel}" Classes="label"/>- <TextBox Text="{Binding NewTargetDomains}"- Watermark="Any"/>- <TextBlock Text="{Binding Loc.ExampleTargetDomains}"- FontSize="11"- Foreground="#FF999999"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <!-- Protocol Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ProtocolLabel}" Classes="label"/>- <ComboBox HorizontalAlignment="Stretch"- x:Name="ProtocolComboBox">- <ComboBoxItem Content="{Binding Loc.ProtocolTCP}" Tag="TCP"/>- <ComboBoxItem Content="{Binding Loc.ProtocolUDP}" Tag="UDP"/>- <ComboBoxItem Content="{Binding Loc.ProtocolBoth}" Tag="BOTH"/>- </ComboBox>- <TextBlock Text="{Binding Loc.UDPProxyNote}"- FontSize="11"- Foreground="#FFCC9900"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <!-- Action Section -->- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ActionLabel}" Classes="label"/>- <ComboBox HorizontalAlignment="Stretch"- x:Name="ActionComboBox"- ItemsSource="{Binding AvailableActions}"- SelectedItem="{Binding SelectedRuleAction}">- <ComboBox.ItemTemplate>- <DataTemplate x:DataType="vm:RuleActionItem">- <TextBlock Text="{Binding Label}"/>- </DataTemplate>- </ComboBox.ItemTemplate>- </ComboBox>- </StackPanel>-- <!-- Validation Error -->- <TextBlock Text="{Binding ProcessNameError}"- IsVisible="{Binding ProcessNameError, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"- Foreground="#FFFF6B6B"- FontSize="12"- Margin="0,4,0,0"/>-- <!-- Action Buttons -->- <StackPanel Orientation="Horizontal"- HorizontalAlignment="Right"- Spacing="12"- Margin="0,16,0,0">- <Button Content="{Binding Loc.ButtonCancel}"- Classes="secondary"- Command="{Binding CancelAddRuleCommand}"- Width="100"/>- <Button Content="{Binding Loc.SaveRuleButton}"- Command="{Binding SaveNewRuleCommand}"- Width="130"/>- </StackPanel>- </StackPanel>- </ScrollViewer>- </DockPanel>-</Window>diff --git a/Windows/gui/Views/ProxyRulesWindow.axaml.cs b/Windows/gui/Views/ProxyRulesWindow.axaml.csdeleted file mode 100644index 41211f7..0000000--- a/Windows/gui/Views/ProxyRulesWindow.axaml.cs+++ /dev/null@@ -1,206 +0,0 @@-using System;-using System.ComponentModel;-using System.Globalization;-using Avalonia.Controls;-using Avalonia.Data.Converters;-using Avalonia.Interactivity;-using Avalonia.Input;-using ProxyBridge.GUI.ViewModels;--namespace ProxyBridge.GUI.Views;--public class SelectAllTextConverter : IValueConverter-{- public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)- {- return value is bool allSelected && allSelected ? "Deselect All" : "Select All";- }-- public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)- {- throw new NotImplementedException();- }-}--public class SelectAllIconConverter : IValueConverter-{- public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)- {- return value is bool allSelected && allSelected ? "☑" : "☐";- }-- public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)- {- throw new NotImplementedException();- }-}--public partial class ProxyRulesWindow : Window-{- private bool _isUpdatingFromViewModel = false;-- public ProxyRulesWindow()- {- InitializeComponent();-- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };-- if (this.FindControl<ComboBox>("ProtocolComboBox") is ComboBox protocolComboBox)- {- protocolComboBox.SelectionChanged += ProtocolComboBox_SelectionChanged;- }-- this.DataContextChanged += ProxyRulesWindow_DataContextChanged;-- if (this.FindControl<ItemsControl>("RulesItemsControl") is ItemsControl itemsControl)- {- itemsControl.AddHandler(DragDrop.DropEvent, Rules_Drop);- itemsControl.AddHandler(DragDrop.DragOverEvent, Rules_DragOver);- }- }-- private ProxyRulesViewModel? _boundViewModel;-- private void ProxyRulesWindow_DataContextChanged(object? sender, EventArgs e)- {- if (_boundViewModel != null)- _boundViewModel.PropertyChanged -= ViewModel_PropertyChanged;-- _boundViewModel = DataContext as ProxyRulesViewModel;-- if (_boundViewModel != null)- {- _boundViewModel.PropertyChanged += ViewModel_PropertyChanged;- UpdateComboBoxSelections(_boundViewModel);- }- }-- private void ViewModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)- {- if (sender is ProxyRulesViewModel vm && e.PropertyName == nameof(ProxyRulesViewModel.NewProtocol))- {- UpdateProtocolComboBox(vm.NewProtocol);- }- }-- private void UpdateComboBoxSelections(ProxyRulesViewModel vm)- {- UpdateProtocolComboBox(vm.NewProtocol);- }-- private void UpdateProtocolComboBox(string protocol)- {- if (this.FindControl<ComboBox>("ProtocolComboBox") is ComboBox protocolComboBox)- {- _isUpdatingFromViewModel = true;-- foreach (var item in protocolComboBox.Items)- {- if (item is ComboBoxItem comboBoxItem &&- comboBoxItem.Tag is string tag &&- tag.Equals(protocol, StringComparison.OrdinalIgnoreCase))- {- protocolComboBox.SelectedItem = comboBoxItem;- break;- }- }-- _isUpdatingFromViewModel = false;- }- }-- private void ProtocolComboBox_SelectionChanged(object? sender, SelectionChangedEventArgs e)- {- if (_isUpdatingFromViewModel)- return;-- if (sender is ComboBox comboBox &&- comboBox.SelectedItem is ComboBoxItem item &&- item.Tag is string tag &&- DataContext is ProxyRulesViewModel vm)- {- vm.NewProtocol = tag;- }- }-- // Holds the rule being dragged. This is an in-process, single-window reorder, so we- // keep the object in a field rather than serializing it into the drag payload —- // Avalonia 12's DataTransfer/DataFormat model is format-oriented (text/bytes/files)- // and doesn't carry arbitrary .NET objects. The DataTransfer below just initiates the- // drag; the actual payload is _draggedRule.- private ProxyRule? _draggedRule;-- private async void Rule_PointerPressed(object? sender, PointerPressedEventArgs e)- {- if (sender is not Border border || border.DataContext is not ProxyRule rule)- return;-- _draggedRule = rule;- try- {- var dragData = new DataTransfer();- dragData.Add(DataTransferItem.Create(DataFormat.Text, "rule"));-- var result = await DragDrop.DoDragDropAsync(e, dragData, DragDropEffects.Move);-- if (result == DragDropEffects.Move && DataContext is ProxyRulesViewModel vm)- {- // refsh indices after drag completes- for (int i = 0; i < vm.ProxyRules.Count; i++)- {- vm.ProxyRules[i].Index = i + 1;- }- }- }- finally- {- _draggedRule = null;- }- }-- private void Rules_DragOver(object? sender, DragEventArgs e)- {- e.DragEffects = _draggedRule != null ? DragDropEffects.Move : DragDropEffects.None;- }-- private void Rules_Drop(object? sender, DragEventArgs e)- {- if (DataContext is not ProxyRulesViewModel vm)- return;-- if (_draggedRule is not ProxyRule draggedRule)- return;-- if (e.Source is Control control)- {- var current = control;- while (current != null && current is not Border)- {- current = current.Parent as Control;- }-- if (current is Border border && border.DataContext is ProxyRule targetRule)- {- if (draggedRule.RuleId == targetRule.RuleId)- return;-- int draggedIndex = vm.ProxyRules.IndexOf(draggedRule);- int targetIndex = vm.ProxyRules.IndexOf(targetRule);-- if (draggedIndex == -1 || targetIndex == -1 || draggedIndex == targetIndex)- return;-- uint newPosition = (uint)(targetIndex + 1);- if (vm.MoveRuleToPosition(draggedRule.RuleId, newPosition))- {- vm.ProxyRules.Move(draggedIndex, targetIndex);-- for (int i = 0; i < vm.ProxyRules.Count; i++)- {- vm.ProxyRules[i].Index = i + 1;- }- }- }- }- }-}\ No newline at end of filediff --git a/Windows/gui/Views/ProxySettingsWindow.axaml b/Windows/gui/Views/ProxySettingsWindow.axamldeleted file mode 100644index 6e03f26..0000000--- a/Windows/gui/Views/ProxySettingsWindow.axaml+++ /dev/null@@ -1,257 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"- mc:Ignorable="d" d:DesignWidth="560" d:DesignHeight="600"- x:Class="ProxyBridge.GUI.Views.ProxySettingsWindow"- x:DataType="vm:ProxySettingsViewModel"- x:CompileBindings="True"- Title="{Binding Loc.ProxySettingsTitle}"- Icon="/Assets/logo.ico"- Width="560" Height="520"- MinWidth="440" MinHeight="300"- MaxHeight="700"- SizeToContent="Height"- CanResize="True"- Background="#FF2D2D30"- WindowStartupLocation="CenterOwner">-- <DockPanel>- <!-- Header -->- <Border DockPanel.Dock="Top" Background="#FF1E1E1E" Padding="20,16">- <Grid ColumnDefinitions="*,Auto">- <StackPanel Orientation="Horizontal" Spacing="10">- <TextBlock Text="🔧" FontSize="22" VerticalAlignment="Center"/>- <TextBlock Text="{Binding Loc.ProxySettingsTitle}"- FontSize="18"- FontWeight="SemiBold"- Foreground="#FFE0E0E0"- VerticalAlignment="Center"/>- </StackPanel>- <StackPanel Grid.Column="1"- Orientation="Horizontal"- Spacing="8"- IsVisible="{Binding !IsEditPanelOpen}">- <Button Content="{Binding Loc.ButtonAdd}"- Command="{Binding OpenAddPanelCommand}"/>- </StackPanel>- </Grid>- </Border>-- <!-- Proxy List View -->- <Grid IsVisible="{Binding !IsEditPanelOpen}">- <Grid.RowDefinitions>- <RowDefinition Height="Auto"/>- <RowDefinition Height="*"/>- <!-- Test panel at bottom -->- <RowDefinition Height="Auto"/>- </Grid.RowDefinitions>-- <!-- Table Header -->- <Border Grid.Row="0"- Background="#FF1E1E1E"- BorderBrush="#FF3F3F46"- BorderThickness="0,1,0,1"- Padding="20,10">- <Grid ColumnDefinitions="90,*,80,80,90,90,90">- <TextBlock Grid.Column="0" Text="Type" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- <TextBlock Grid.Column="1" Text="Host" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- <TextBlock Grid.Column="2" Text="Port" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- <TextBlock Grid.Column="3" Text="Test" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- <TextBlock Grid.Column="4" Text="Edit" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- <TextBlock Grid.Column="5" Text="Delete" FontSize="13" FontWeight="SemiBold" Foreground="#FF999999"/>- </Grid>- </Border>-- <!-- Proxy Config Items -->- <ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto">- <ItemsControl ItemsSource="{Binding ProxyConfigs}">- <ItemsControl.ItemTemplate>- <DataTemplate x:DataType="vm:ProxyConfig">- <Border BorderBrush="#FF3F3F46"- BorderThickness="0,0,0,1"- Padding="20,12">- <Grid ColumnDefinitions="90,*,80,80,90,90">- <TextBlock Grid.Column="0"- Text="{Binding Type}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FF4EC9B0"- VerticalAlignment="Center"/>- <StackPanel Grid.Column="1" VerticalAlignment="Center">- <TextBlock Text="{Binding Host}"- FontSize="14"- Foreground="#FFE0E0E0"- TextTrimming="CharacterEllipsis"/>- </StackPanel>- <TextBlock Grid.Column="2"- Text="{Binding Port}"- FontSize="13"- Foreground="#FF999999"- VerticalAlignment="Center"/>- <Button Grid.Column="3"- Content="🔗 Test"- Command="{Binding $parent[ItemsControl].((vm:ProxySettingsViewModel)DataContext).OpenTestPanelCommand}"- CommandParameter="{Binding}"- Padding="6,4"- FontSize="12"- Classes="secondary"/>- <Button Grid.Column="4"- Content="✏ Edit"- Command="{Binding $parent[ItemsControl].((vm:ProxySettingsViewModel)DataContext).EditConfigCommand}"- CommandParameter="{Binding}"- Padding="6,4"- FontSize="12"/>- <Button Grid.Column="5"- Content="🗑 Del"- Command="{Binding $parent[ItemsControl].((vm:ProxySettingsViewModel)DataContext).DeleteConfigCommand}"- CommandParameter="{Binding}"- Padding="6,4"- FontSize="12"- Classes="secondary"/>- </Grid>- </Border>- </DataTemplate>- </ItemsControl.ItemTemplate>- </ItemsControl>- </ScrollViewer>-- <!-- Test Panel at bottom (shared) -->- <Border Grid.Row="2"- Background="#FF1E1E1E"- BorderBrush="#FF007ACC"- BorderThickness="0,2,0,0"- IsVisible="{Binding IsTestViewOpen}">- <!-- Header bar -->- <StackPanel>- <Grid ColumnDefinitions="Auto,*,Auto"- Background="#FF252526"- Margin="0">- <TextBlock Grid.Column="0"- Text="🔗"- FontSize="14"- VerticalAlignment="Center"- Margin="16,10,8,10"/>- <TextBlock Grid.Column="1"- Text="{Binding Loc.TestConnectionTitle}"- FontSize="13"- FontWeight="SemiBold"- Foreground="#FFE0E0E0"- VerticalAlignment="Center"/>- <Button Grid.Column="2"- Content="✕ Close"- Classes="secondary"- Command="{Binding CloseTestPanelCommand}"- FontSize="12"- Padding="10,6"- Margin="8,6"/>- </Grid>- <StackPanel Spacing="8" Margin="16,10,16,14">- <Grid ColumnDefinitions="3*,120,Auto">- <TextBox Grid.Column="0"- Text="{Binding TestTargetHost}"- Watermark="Target host (e.g. google.com)"- Margin="0,0,8,0"/>- <TextBox Grid.Column="1"- Text="{Binding TestTargetPort}"- Watermark="Port"- Margin="0,0,8,0"/>- <Button Grid.Column="2"- Content="{Binding Loc.StartTestButton}"- Command="{Binding StartTestCommand}"- IsEnabled="{Binding !IsTesting}"- MinWidth="100"/>- </Grid>- <Border Background="#FF2D2D30"- BorderBrush="#FF3F3F46"- BorderThickness="1"- CornerRadius="3"- Padding="10,8"- MinHeight="60"- MaxHeight="130"- IsVisible="{Binding TestOutput, Converter={x:Static StringConverters.IsNotNullOrEmpty}}">- <ScrollViewer VerticalScrollBarVisibility="Auto">- <TextBlock Text="{Binding TestOutput}"- FontFamily="Consolas,monospace"- FontSize="12"- Foreground="#FFD4D4D4"- TextWrapping="Wrap"/>- </ScrollViewer>- </Border>- </StackPanel>- </StackPanel>- </Border>- </Grid>-- <!-- Add/Edit Form -->- <ScrollViewer VerticalScrollBarVisibility="Auto"- HorizontalScrollBarVisibility="Disabled"- IsVisible="{Binding IsEditPanelOpen}">- <StackPanel Margin="24,20" Spacing="16">- <TextBlock Text="{Binding EditPanelTitle}"- FontSize="16"- FontWeight="SemiBold"- Foreground="#FFE0E0E0"/>-- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ProxyTypeLabel}" Classes="label"/>- <ComboBox HorizontalAlignment="Stretch"- x:Name="EditTypeComboBox">- <ComboBoxItem Content="SOCKS5" Tag="SOCKS5"/>- <ComboBoxItem Content="HTTP" Tag="HTTP"/>- </ComboBox>- <TextBlock Text="{Binding Loc.UDPProxyNote}"- FontSize="11"- Foreground="#FFCC9900"- TextWrapping="Wrap"- Margin="0,4,0,0"/>- </StackPanel>-- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ProxyIpLabel}" Classes="label"/>- <TextBox Text="{Binding NewHost}"- Watermark="{Binding Loc.ProxyIpPlaceholder}"/>- <TextBlock Text="{Binding HostError}"- Classes="error"- IsVisible="{Binding HostError, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"/>- </StackPanel>-- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.ProxyPortLabel}" Classes="label"/>- <TextBox Text="{Binding NewPort}"- Watermark="{Binding Loc.ProxyPortPlaceholder}"/>- <TextBlock Text="{Binding PortError}"- Classes="error"- IsVisible="{Binding PortError, Converter={x:Static StringConverters.IsNotNullOrEmpty}}"/>- </StackPanel>-- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.UsernameLabel}" Classes="label"/>- <TextBox Text="{Binding NewUsername}"- Watermark="{Binding Loc.UsernamePlaceholder}"/>- </StackPanel>-- <StackPanel Spacing="6">- <TextBlock Text="{Binding Loc.PasswordLabel}" Classes="label"/>- <TextBox Text="{Binding NewPassword}"- Watermark="{Binding Loc.PasswordPlaceholder}"- PasswordChar="●"/>- </StackPanel>-- <StackPanel Orientation="Horizontal"- HorizontalAlignment="Right"- Spacing="12"- Margin="0,16,0,20">- <Button Content="{Binding Loc.ButtonCancel}"- Classes="secondary"- Command="{Binding CancelEditCommand}"- Width="100"/>- <Button Content="{Binding Loc.SaveChangesButton}"- Command="{Binding SaveConfigCommand}"- Width="130"/>- </StackPanel>- </StackPanel>- </ScrollViewer>- </DockPanel>-</Window>diff --git a/Windows/gui/Views/ProxySettingsWindow.axaml.cs b/Windows/gui/Views/ProxySettingsWindow.axaml.csdeleted file mode 100644index da62de7..0000000--- a/Windows/gui/Views/ProxySettingsWindow.axaml.cs+++ /dev/null@@ -1,88 +0,0 @@-using System.ComponentModel;-using System.Linq;-using Avalonia.Controls;-using Avalonia.Input;-using Avalonia.Interactivity;-using ProxyBridge.GUI.ViewModels;--namespace ProxyBridge.GUI.Views;--public partial class ProxySettingsWindow : Window-{- private bool _isUpdatingFromViewModel = false;- private ProxySettingsViewModel? _boundViewModel;-- public ProxySettingsWindow()- {- InitializeComponent();-- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };-- this.DataContextChanged += OnDataContextChanged;- this.Closed += (_, _) =>- {- if (_boundViewModel != null)- _boundViewModel.PropertyChanged -= ViewModel_PropertyChanged;- };-- this.Opened += (s, e) =>- {- if (DataContext is ProxySettingsViewModel vm)- UpdateEditTypeComboBox(vm.NewType);- };- }-- private void OnDataContextChanged(object? sender, System.EventArgs e)- {- if (_boundViewModel != null)- _boundViewModel.PropertyChanged -= ViewModel_PropertyChanged;-- _boundViewModel = DataContext as ProxySettingsViewModel;-- if (_boundViewModel != null)- {- _boundViewModel.PropertyChanged += ViewModel_PropertyChanged;-- var editComboBox = this.FindControl<ComboBox>("EditTypeComboBox");- if (editComboBox != null)- {- editComboBox.SelectionChanged -= EditTypeComboBox_SelectionChanged;- editComboBox.SelectionChanged += EditTypeComboBox_SelectionChanged;- }- }- }-- private void ViewModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)- {- if (sender is ProxySettingsViewModel vm && e.PropertyName == nameof(ProxySettingsViewModel.NewType))- {- UpdateEditTypeComboBox(vm.NewType);- }- }-- private void UpdateEditTypeComboBox(string typeTag)- {- var comboBox = this.FindControl<ComboBox>("EditTypeComboBox");- if (comboBox == null) return;-- _isUpdatingFromViewModel = true;- comboBox.SelectedItem = comboBox.Items- .OfType<ComboBoxItem>()- .FirstOrDefault(item => item.Tag is string tag &&- tag.Equals(typeTag, System.StringComparison.OrdinalIgnoreCase));- _isUpdatingFromViewModel = false;- }-- private void EditTypeComboBox_SelectionChanged(object? sender, SelectionChangedEventArgs e)- {- if (_isUpdatingFromViewModel) return;-- if (sender is ComboBox comboBox &&- comboBox.SelectedItem is ComboBoxItem item &&- item.Tag is string tag &&- DataContext is ProxySettingsViewModel vm)- {- vm.NewType = tag;- }- }-}diff --git a/Windows/gui/Views/UpdateCheckWindow.axaml b/Windows/gui/Views/UpdateCheckWindow.axamldeleted file mode 100644index ca06c66..0000000--- a/Windows/gui/Views/UpdateCheckWindow.axaml+++ /dev/null@@ -1,114 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- x:Class="ProxyBridge.GUI.Views.UpdateCheckWindow"- x:DataType="vm:UpdateCheckViewModel"- x:CompileBindings="True"- Title="Check for Updates"- Icon="/Assets/logo.ico"- Width="500" Height="300"- CanResize="False"- WindowStartupLocation="CenterOwner"- Background="#FF1E1E1E">-- <Design.DataContext>- <vm:UpdateCheckViewModel/>- </Design.DataContext>-- <Grid RowDefinitions="Auto,*,Auto">- <!-- Header -->- <Border Grid.Row="0" Background="#FF252526" BorderBrush="#FF007ACC" BorderThickness="0,0,0,1" Padding="16,12">- <StackPanel Orientation="Horizontal" Spacing="10">- <TextBlock Text="Update Check"- FontSize="16"- FontWeight="SemiBold"- VerticalAlignment="Center"/>- </StackPanel>- </Border>-- <!-- Content -->- <StackPanel Grid.Row="1" Margin="32,24" Spacing="16" VerticalAlignment="Center">- <!-- Current Version -->- <StackPanel Orientation="Horizontal" Spacing="8">- <TextBlock Text="Current Version:"- FontWeight="Medium"- Foreground="#FFB0B0B0"- Width="120"/>- <TextBlock Text="{Binding CurrentVersion}"- Foreground="#FF007ACC"/>- </StackPanel>-- <!-- Latest Version -->- <StackPanel Orientation="Horizontal" Spacing="8">- <TextBlock Text="Latest Version:"- FontWeight="Medium"- Foreground="#FFB0B0B0"- Width="120"/>- <TextBlock Text="{Binding LatestVersion}"- Foreground="{Binding LatestVersionColor}"/>- </StackPanel>-- <!-- Status Message -->- <TextBlock Text="{Binding StatusMessage}"- FontWeight="Medium"- Foreground="{Binding StatusColor}"- HorizontalAlignment="Center"- TextWrapping="Wrap"- Margin="0,8,0,0"/>-- <!-- Loading indicator -->- <TextBlock Text="Checking for updates..."- Foreground="#FFB0B0B0"- HorizontalAlignment="Center"- IsVisible="{Binding IsChecking}"/>-- <!-- Download Progress -->- <StackPanel Spacing="8" IsVisible="{Binding IsDownloading}">- <TextBlock Text="{Binding DownloadStatus}"- Foreground="#FF007ACC"- HorizontalAlignment="Center"/>- <ProgressBar Value="{Binding DownloadProgress}"- Minimum="0"- Maximum="100"- Height="6"- Background="#FF3C3C3C"- Foreground="#FF007ACC"/>- </StackPanel>-- <!-- Error message -->- <TextBlock Text="{Binding ErrorMessage}"- Foreground="#FFFF6B6B"- HorizontalAlignment="Center"- TextWrapping="Wrap"- IsVisible="{Binding HasError}"/>- </StackPanel>-- <!-- Buttons -->- <Border Grid.Row="2" Background="#FF252526" BorderBrush="#FF007ACC" BorderThickness="0,1,0,0" Padding="16,12">- <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10">- <!-- Download Now Button (only visible when update is available) -->- <Button Content="Download Now"- Command="{Binding DownloadNowCommand}"- IsVisible="{Binding IsUpdateAvailable}"- IsEnabled="{Binding !IsDownloading}"- Background="#FF4CAF50"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- <Button Content="Check Again"- Command="{Binding CheckUpdatesCommand}"- IsEnabled="{Binding !IsChecking}"- Background="#FF007ACC"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- <Button Content="Close"- Command="{Binding CloseCommand}"- Background="#FF3C3C3C"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- </StackPanel>- </Border>- </Grid>-</Window>\ No newline at end of filediff --git a/Windows/gui/Views/UpdateCheckWindow.axaml.cs b/Windows/gui/Views/UpdateCheckWindow.axaml.csdeleted file mode 100644index e76b223..0000000--- a/Windows/gui/Views/UpdateCheckWindow.axaml.cs+++ /dev/null@@ -1,13 +0,0 @@-using Avalonia.Controls;-using Avalonia.Input;--namespace ProxyBridge.GUI.Views;--public partial class UpdateCheckWindow : Window-{- public UpdateCheckWindow()- {- InitializeComponent();- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };- }-}\ No newline at end of filediff --git a/Windows/gui/Views/UpdateNotificationWindow.axaml b/Windows/gui/Views/UpdateNotificationWindow.axamldeleted file mode 100644index 7383227..0000000--- a/Windows/gui/Views/UpdateNotificationWindow.axaml+++ /dev/null@@ -1,106 +0,0 @@-<Window xmlns="https://github.com/avaloniaui"- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"- xmlns:vm="using:ProxyBridge.GUI.ViewModels"- x:Class="ProxyBridge.GUI.Views.UpdateNotificationWindow"- x:DataType="vm:UpdateNotificationViewModel"- x:CompileBindings="True"- Title="Update Available"- Icon="/Assets/logo.ico"- Width="450" Height="250"- CanResize="False"- WindowStartupLocation="CenterOwner"- Background="#FF1E1E1E">-- <Design.DataContext>- <vm:UpdateNotificationViewModel/>- </Design.DataContext>-- <Grid RowDefinitions="Auto,*,Auto">- <!-- Header -->- <Border Grid.Row="0" Background="#FF252526" BorderBrush="#FF007ACC" BorderThickness="0,0,0,1" Padding="16,12">- <StackPanel Orientation="Horizontal" Spacing="10">- <TextBlock Text="Update Available"- FontSize="16"- FontWeight="SemiBold"- VerticalAlignment="Center"/>- </StackPanel>- </Border>-- <!-- Content -->- <StackPanel Grid.Row="1" Margin="32,24" Spacing="16" VerticalAlignment="Center">- <!-- Version Info -->- <StackPanel Spacing="12">- <StackPanel Orientation="Horizontal" Spacing="8">- <TextBlock Text="Current Version:"- FontWeight="Medium"- Foreground="#FFB0B0B0"- Width="120"/>- <TextBlock Text="{Binding CurrentVersion}"- Foreground="#FF007ACC"/>- </StackPanel>-- <StackPanel Orientation="Horizontal" Spacing="8">- <TextBlock Text="New Version:"- FontWeight="Medium"- Foreground="#FFB0B0B0"- Width="120"/>- <TextBlock Text="{Binding LatestVersion}"- Foreground="#FF4CAF50"/>- </StackPanel>- </StackPanel>-- <!-- Update Message -->- <TextBlock Text="A new version of ProxyBridge is available. Would you like to download and install it now?"- TextWrapping="Wrap"- HorizontalAlignment="Center"- Foreground="#FFB0B0B0"- Margin="0,8,0,8"/>-- <!-- Download Progress -->- <StackPanel IsVisible="{Binding IsDownloading}" Spacing="8">- <TextBlock Text="{Binding DownloadStatus}"- HorizontalAlignment="Center"- Foreground="#FF007ACC"/>- <ProgressBar Value="{Binding DownloadProgress}"- Maximum="100"- Height="8"- Background="#FF3C3C3C"- Foreground="#FF007ACC"/>- </StackPanel>-- <!-- Error Message -->- <TextBlock Text="{Binding ErrorMessage}"- Foreground="#FFFF6B6B"- HorizontalAlignment="Center"- TextWrapping="Wrap"- IsVisible="{Binding HasError}"/>- </StackPanel>-- <!-- Buttons -->- <Border Grid.Row="2" Background="#FF252526" BorderBrush="#FF007ACC" BorderThickness="0,1,0,0" Padding="16,12">- <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10">- <Button Content="Update Now"- Command="{Binding UpdateNowCommand}"- IsEnabled="{Binding !IsDownloading}"- Background="#FF4CAF50"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- <Button Content="Don't Ask Again"- Command="{Binding DontAskAgainCommand}"- IsEnabled="{Binding !IsDownloading}"- Background="#FFFF6B6B"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- <Button Content="Later"- Command="{Binding LaterCommand}"- IsEnabled="{Binding !IsDownloading}"- Background="#FF3C3C3C"- Foreground="White"- Padding="16,6"- CornerRadius="3"/>- </StackPanel>- </Border>- </Grid>-</Window>\ No newline at end of filediff --git a/Windows/gui/Views/UpdateNotificationWindow.axaml.cs b/Windows/gui/Views/UpdateNotificationWindow.axaml.csdeleted file mode 100644index c91b177..0000000--- a/Windows/gui/Views/UpdateNotificationWindow.axaml.cs+++ /dev/null@@ -1,13 +0,0 @@-using Avalonia.Controls;-using Avalonia.Input;--namespace ProxyBridge.GUI.Views;--public partial class UpdateNotificationWindow : Window-{- public UpdateNotificationWindow()- {- InitializeComponent();- KeyDown += (_, e) => { if (e.Key == Key.Escape) Close(); };- }-}\ No newline at end of filediff --git a/Windows/gui/api/pb_api.h b/Windows/gui/api/pb_api.hnew file mode 100644index 0000000..8385471--- /dev/null+++ b/Windows/gui/api/pb_api.h@@ -0,0 +1,113 @@+// pb_api.h - thin loader for ProxyBridgeCore.dll.+//+// Mirrors the exported C API in ../src/ProxyBridge.h. The DLL is loaded dynamically+// (LoadLibrary + GetProcAddress) by name, so the+// GUI has no import-lib link dependency and fails gracefully if the DLL is missing.+#ifndef PB_API_H+#define PB_API_H++#include <windows.h>++// enums (must match ProxyBridge.h)+typedef enum { PB_PROXY_HTTP = 0, PB_PROXY_SOCKS5 = 1 } PBProxyType;+typedef enum { PB_ACTION_PROXY = 0, PB_ACTION_DIRECT = 1, PB_ACTION_BLOCK = 2 } PBRuleAction;+typedef enum { PB_PROTO_TCP = 0, PB_PROTO_UDP = 1, PB_PROTO_BOTH = 2 } PBRuleProtocol;++// callbacks (native thread - never touch UI directly from these)+typedef void (*PBLogCallback)(const char* message);+typedef void (*PBConnectionCallback)(const char* process_name, DWORD pid,+ const char* dest_ip, unsigned short dest_port,+ const char* proxy_info);++// exported function pointer typedefs+typedef UINT32 (*PFN_AddProxyConfig)(PBProxyType, const char*, unsigned short, const char*, const char*);+typedef BOOL (*PFN_EditProxyConfig)(UINT32, PBProxyType, const char*, unsigned short, const char*, const char*);+typedef BOOL (*PFN_DeleteProxyConfig)(UINT32);+typedef int (*PFN_TestProxyConfig)(UINT32, const char*, unsigned short, char*, size_t);+typedef void (*PBTestLogCallback)(const char* line, void* user);+typedef int (*PFN_TestProxyConfigEx)(UINT32, const char*, unsigned short, PBTestLogCallback, void*);+typedef UINT32 (*PFN_AddRule)(const char*, const char*, const char*, const char*, PBRuleProtocol, PBRuleAction, UINT32);+typedef BOOL (*PFN_EnableRule)(UINT32);+typedef BOOL (*PFN_DisableRule)(UINT32);+typedef BOOL (*PFN_DeleteRule)(UINT32);+typedef BOOL (*PFN_EditRule)(UINT32, const char*, const char*, const char*, const char*, PBRuleProtocol, PBRuleAction, UINT32);+typedef BOOL (*PFN_MoveRuleToPosition)(UINT32, UINT32);+typedef UINT32 (*PFN_GetRulePosition)(UINT32);+typedef void (*PFN_SetLocalhostViaProxy)(BOOL);+typedef void (*PFN_SetLogCallback)(PBLogCallback);+typedef void (*PFN_SetConnectionCallback)(PBConnectionCallback);+typedef void (*PFN_SetTrafficLoggingEnabled)(BOOL);+typedef void (*PFN_ClearConnectionLogs)(void);+typedef BOOL (*PFN_Start)(void);+typedef BOOL (*PFN_Stop)(void);++// resolved API table+typedef struct {+ HMODULE dll;+ PFN_AddProxyConfig AddProxyConfig;+ PFN_EditProxyConfig EditProxyConfig;+ PFN_DeleteProxyConfig DeleteProxyConfig;+ PFN_TestProxyConfig TestProxyConfig;+ PFN_TestProxyConfigEx TestProxyConfigEx;+ PFN_AddRule AddRule;+ PFN_EnableRule EnableRule;+ PFN_DisableRule DisableRule;+ PFN_DeleteRule DeleteRule;+ PFN_EditRule EditRule;+ PFN_MoveRuleToPosition MoveRuleToPosition;+ PFN_GetRulePosition GetRulePosition;+ PFN_SetLocalhostViaProxy SetLocalhostViaProxy;+ PFN_SetLogCallback SetLogCallback;+ PFN_SetConnectionCallback SetConnectionCallback;+ PFN_SetTrafficLoggingEnabled SetTrafficLoggingEnabled;+ PFN_ClearConnectionLogs ClearConnectionLogs;+ PFN_Start Start;+ PFN_Stop Stop;+} PBApi;++// Loads ProxyBridgeCore.dll (from the exe's directory) and resolves every export.+// Returns TRUE only if the DLL and all required functions were found.+static BOOL PB_Load(PBApi* api)+{+ ZeroMemory(api, sizeof(*api));++ // Load from the executable's own directory so we don't depend on CWD/PATH.+ wchar_t path[MAX_PATH];+ DWORD n = GetModuleFileNameW(NULL, path, MAX_PATH);+ if (n == 0 || n >= MAX_PATH) return FALSE;+ for (DWORD i = n; i > 0; i--) { if (path[i - 1] == L'\\') { path[i] = 0; break; } }+ lstrcatW(path, L"ProxyBridgeCore.dll");++ api->dll = LoadLibraryW(path);+ if (!api->dll) api->dll = LoadLibraryW(L"ProxyBridgeCore.dll"); // fallback to search path+ if (!api->dll) return FALSE;++ #define PB_BIND(field, name) \+ api->field = (PFN_##field)(void*)GetProcAddress(api->dll, "ProxyBridge_" name); \+ if (!api->field) return FALSE;++ PB_BIND(AddProxyConfig, "AddProxyConfig");+ PB_BIND(EditProxyConfig, "EditProxyConfig");+ PB_BIND(DeleteProxyConfig, "DeleteProxyConfig");+ PB_BIND(TestProxyConfig, "TestProxyConfig");+ PB_BIND(TestProxyConfigEx, "TestProxyConfigEx");+ PB_BIND(AddRule, "AddRule");+ PB_BIND(EnableRule, "EnableRule");+ PB_BIND(DisableRule, "DisableRule");+ PB_BIND(DeleteRule, "DeleteRule");+ PB_BIND(EditRule, "EditRule");+ PB_BIND(MoveRuleToPosition, "MoveRuleToPosition");+ PB_BIND(GetRulePosition, "GetRulePosition");+ PB_BIND(SetLocalhostViaProxy, "SetLocalhostViaProxy");+ PB_BIND(SetLogCallback, "SetLogCallback");+ PB_BIND(SetConnectionCallback, "SetConnectionCallback");+ PB_BIND(SetTrafficLoggingEnabled, "SetTrafficLoggingEnabled");+ PB_BIND(ClearConnectionLogs, "ClearConnectionLogs");+ PB_BIND(Start, "Start");+ PB_BIND(Stop, "Stop");+ #undef PB_BIND++ return TRUE;+}++#endif // PB_API_Hdiff --git a/Windows/gui/app.manifest b/Windows/gui/app.manifestdeleted file mode 100644index ed2c595..0000000--- a/Windows/gui/app.manifest+++ /dev/null@@ -1,23 +0,0 @@-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>-<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">- <assemblyIdentity- version="4.0.0.0"- processorArchitecture="*"- name="ProxyBridge"- type="win32"- />- <description>ProxyBridge - Network Traffic Proxy Control</description>- <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">- <security>- <requestedPrivileges>- <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>- </requestedPrivileges>- </security>- </trustInfo>- <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">- <application>- <!-- Windows 10 and Windows 11 -->- <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>- </application>- </compatibility>-</assembly>diff --git a/Windows/gui/loc/loc.h b/Windows/gui/loc/loc.hnew file mode 100644index 0000000..ce42c32--- /dev/null+++ b/Windows/gui/loc/loc.h@@ -0,0 +1,197 @@+// loc.h - EN/ZH string table for the GUI.+//+// Win32 is natively UTF-16, so Chinese renders without any special handling. T(id) returns+// the current-language string; g_lang is 0=en, 1=zh. The .c source is saved UTF-8, so the+// wide literals below must be produced by the compiler treating the file as UTF-8 - the+// build passes /utf-8 so L"中文" is encoded correctly.+#ifndef PB_LOC_H+#define PB_LOC_H++#define APP_VERSION PB_VER_STRW // defined in res/resource.h (single source of truth)++enum {+ S_M_PROXY, S_M_PROXY_SETTINGS, S_M_PROXY_RULES,+ S_M_PROFILE, S_M_NEWPROFILE, S_M_DELPROFILE, S_M_IMPORT, S_M_EXPORT, S_M_SWITCH,+ S_M_SETTINGS, S_M_LOCALHOST, S_M_TRAFFIC, S_M_TRAY, S_M_LANG, S_M_LANG_EN, S_M_LANG_ZH,+ S_M_CLEARCONN, S_M_CLEARACT, S_M_HELP, S_M_ABOUT, S_M_DOCS, S_M_STARTUP,+ S_BTN_CLEARLOGS, S_SEARCH_CUE,+ S_TAB_CONN, S_TAB_ACT, S_TRAY_SHOW, S_TRAY_EXIT,+ S_DLG_SETTINGS, S_L_TYPE, S_L_HOST, S_L_PORT, S_L_USER, S_L_PASS, S_L_CFGLIST,+ S_BTN_ADD, S_BTN_UPDATE, S_BTN_DELETE, S_BTN_CLOSE,+ S_DLG_RULES, S_L_APPS, S_L_HOSTS, S_L_PORTS, S_L_DOMAINS, S_L_PROTO, S_L_ACTION, S_L_CFGID,+ S_BTN_ADDRULE, S_BTN_TOGGLE,+ S_COL_ON, S_COL_APPS, S_COL_HOSTS, S_COL_PORTS, S_COL_DOMAINS, S_COL_PROTO, S_COL_ACTION, S_COL_CFG,+ S_DLG_NEWPROFILE, S_L_PROFNAME, S_BTN_OK, S_BTN_CANCEL,+ S_ABOUT_TITLE, S_ABOUT_BODY, S_STARTED, S_STARTFAIL,+ S_ERR_HOST, S_ERR_ADDCFG, S_ERR_ADDRULE, S_INFO_NODELDEFAULT, S_ERR_IMPORT, S_ERR_EXPORT,+ S_DLG_SERVERS, S_DLG_SERVER, S_G_SERVER, S_G_AUTH, S_L_ADDR, S_CHK_ENABLE, S_CHK_ENABLED,+ S_DLG_RULE, S_BTN_ADDDOTS, S_BTN_EDITDOTS, S_BTN_REMOVE, S_BTN_CLONE, S_BTN_UP, S_BTN_DOWN,+ S_COL_ADDR, S_COL_TYPE, S_RULES_HINT,+ S_BTN_CHECK, S_TEST_OK, S_TEST_FAIL, S_TEST_TITLE,+ S_DLG_CHECKER, S_BTN_RETEST, S_TEST_RUNNING, S_CK_HOST, S_BTN_BROWSE,+ S_EX_APPS, S_EX_HOSTS, S_EX_PORTS, S_EX_DOMAINS, S_UDP_NOTE,+ S_M_AUTOCLEAR, S_M_RENAME, S_M_LOGFILTERS, S_DLG_RENAME,+ S_DLG_FILTERS, S_DLG_FILTER, S_FL_DESC, S_L_MODE, S_L_PROC, S_L_IP,+ S_COL_MODE, S_COL_PROC, S_COL_IP, S_INFO_NORENAMEDEFAULT, S_ERR_RUNNING,+ S_AB_VERSION, S_AB_DESC, S_AB_AUTHOR, S_AB_WEB, S_AB_GITHUB, S_AB_LICENSE,+ S_M_UPDATE, S_UPD_TITLE, S_UPD_AVAIL, S_UPD_NOTES, S_UPD_NOW, S_UPD_LATER,+ S_UPD_DONTASK, S_UPD_LATEST, S_UPD_ERR, S_UPD_DLING, S_UPD_DLFAIL,+ S_COUNT+};++static int g_lang = 0; // 0 = en, 1 = zh++static const wchar_t* const g_strings[S_COUNT][2] = {+ /* S_M_PROXY */ { L"&Proxy", L"代理(&P)" },+ /* S_M_PROXY_SETTINGS */ { L"Proxy &Settings...", L"代理设置(&S)..." },+ /* S_M_PROXY_RULES */ { L"Proxy &Rules...", L"代理规则(&R)..." },+ /* S_M_PROFILE */ { L"P&rofile", L"配置文件(&R)" },+ /* S_M_NEWPROFILE */ { L"&New Profile...", L"新建配置(&N)..." },+ /* S_M_DELPROFILE */ { L"&Delete Current Profile", L"删除当前配置(&D)" },+ /* S_M_IMPORT */ { L"&Import Profile...", L"导入配置(&I)..." },+ /* S_M_EXPORT */ { L"&Export Profile...", L"导出配置(&E)..." },+ /* S_M_SWITCH */ { L"&Switch Profile", L"切换配置(&S)" },+ /* S_M_SETTINGS */ { L"&Settings", L"设置(&S)" },+ /* S_M_LOCALHOST */ { L"Localhost via Proxy", L"本地主机通过代理" },+ /* S_M_TRAFFIC */ { L"Enable Traffic Logging", L"启用流量日志" },+ /* S_M_TRAY */ { L"Close to Tray", L"关闭到系统托盘" },+ /* S_M_LANG */ { L"Language", L"语言" },+ /* S_M_LANG_EN */ { L"English", L"English" },+ /* S_M_LANG_ZH */ { L"中文 (Chinese)", L"中文" },+ /* S_M_CLEARCONN */ { L"Clear Connections Log", L"清除连接日志" },+ /* S_M_CLEARACT */ { L"Clear Activity Log", L"清除活动日志" },+ /* S_M_HELP */ { L"&Help", L"帮助(&H)" },+ /* S_M_ABOUT */ { L"&About", L"关于(&A)" },+ /* S_M_DOCS */ { L"&Documentation", L"文档(&D)" },+ /* S_M_STARTUP */ { L"Run at Startup", L"开机时运行" },+ /* S_BTN_CLEARLOGS */ { L"Clear All Logs", L"清除所有日志" },+ /* S_SEARCH_CUE */ { L"Search (press Enter)...", L"搜索 (按回车)..." },+ /* S_TAB_CONN */ { L"Connections", L"网络连接" },+ /* S_TAB_ACT */ { L"Activity Log", L"活动日志" },+ /* S_TRAY_SHOW */ { L"Show ProxyBridge", L"显示 ProxyBridge" },+ /* S_TRAY_EXIT */ { L"Exit", L"退出" },+ /* S_DLG_SETTINGS */ { L"Proxy Settings", L"代理设置" },+ /* S_L_TYPE */ { L"Type:", L"类型:" },+ /* S_L_HOST */ { L"Host / IP:", L"主机 / IP:" },+ /* S_L_PORT */ { L"Port:", L"端口:" },+ /* S_L_USER */ { L"Username:", L"用户名:" },+ /* S_L_PASS */ { L"Password:", L"密码:" },+ /* S_L_CFGLIST */ { L"Configured proxies (select to edit):", L"已配置的代理 (选择以编辑):" },+ /* S_BTN_ADD */ { L"Add", L"添加" },+ /* S_BTN_UPDATE */ { L"Update", L"更新" },+ /* S_BTN_DELETE */ { L"Delete", L"删除" },+ /* S_BTN_CLOSE */ { L"Close", L"关闭" },+ /* S_DLG_RULES */ { L"Proxy Rules", L"代理规则" },+ /* S_L_APPS */ { L"Applications:", L"应用程序:" },+ /* S_L_HOSTS */ { L"Target Hosts:", L"目标主机:" },+ /* S_L_PORTS */ { L"Target Ports:", L"目标端口:" },+ /* S_L_DOMAINS */ { L"Target Domains:", L"目标域名:" },+ /* S_L_PROTO */ { L"Protocol:", L"协议:" },+ /* S_L_ACTION */ { L"Action:", L"操作:" },+ /* S_L_CFGID */ { L"Proxy Config Id:", L"代理配置 ID:" },+ /* S_BTN_ADDRULE */ { L"Add Rule", L"添加规则" },+ /* S_BTN_TOGGLE */ { L"Enable/Disable", L"启用/禁用" },+ /* S_COL_ON */ { L"On", L"启用" },+ /* S_COL_APPS */ { L"Applications", L"应用程序" },+ /* S_COL_HOSTS */ { L"Hosts", L"主机" },+ /* S_COL_PORTS */ { L"Ports", L"端口" },+ /* S_COL_DOMAINS */ { L"Domains", L"域名" },+ /* S_COL_PROTO */ { L"Proto", L"协议" },+ /* S_COL_ACTION */ { L"Action", L"操作" },+ /* S_COL_CFG */ { L"Proxy", L"代理" },+ /* S_DLG_NEWPROFILE */ { L"New Profile", L"新建配置" },+ /* S_L_PROFNAME */ { L"Profile name:", L"配置名称:" },+ /* S_BTN_OK */ { L"OK", L"确定" },+ /* S_BTN_CANCEL */ { L"Cancel", L"取消" },+ /* S_ABOUT_TITLE */ { L"About ProxyBridge", L"关于 ProxyBridge" },+ /* S_ABOUT_BODY */ { L"ProxyBridge\nUniversal proxy client for Windows.\n\n© InterceptSuite",+ L"ProxyBridge\nWindows 通用代理客户端。\n\n© InterceptSuite" },+ /* S_STARTED */ { L"ProxyBridge service started.\r\n", L"ProxyBridge 服务已启动。\r\n" },+ /* S_STARTFAIL */ { L"[error] Failed to start ProxyBridge service. Run as Administrator and ensure WinDivert64.sys is present.\r\n",+ L"[错误] 无法启动 ProxyBridge 服务。请以管理员身份运行,并确保 WinDivert64.sys 存在。\r\n" },+ /* S_ERR_HOST */ { L"Host is required.", L"必须填写主机。" },+ /* S_ERR_ADDCFG */ { L"Failed to add proxy config.", L"添加代理配置失败。" },+ /* S_ERR_ADDRULE */ { L"Failed to add rule.", L"添加规则失败。" },+ /* S_INFO_NODELDEFAULT */ { L"The Default profile cannot be deleted.", L"无法删除默认配置。" },+ /* S_ERR_IMPORT */ { L"Failed to import profile.", L"导入配置失败。" },+ /* S_ERR_EXPORT */ { L"Failed to export profile.", L"导出配置失败。" },+ /* S_DLG_SERVERS */ { L"Proxy Servers", L"代理服务器" },+ /* S_DLG_SERVER */ { L"Proxy Server", L"代理服务器" },+ /* S_G_SERVER */ { L"Server", L"服务器" },+ /* S_G_AUTH */ { L"Authentication", L"身份验证" },+ /* S_L_ADDR */ { L"Address:", L"地址:" },+ /* S_CHK_ENABLE */ { L"Enable", L"启用" },+ /* S_CHK_ENABLED */ { L"Enabled", L"已启用" },+ /* S_DLG_RULE */ { L"Proxy Rule", L"代理规则" },+ /* S_BTN_ADDDOTS */ { L"Add...", L"添加..." },+ /* S_BTN_EDITDOTS */ { L"Edit...", L"编辑..." },+ /* S_BTN_REMOVE */ { L"Remove", L"移除" },+ /* S_BTN_CLONE */ { L"Clone", L"克隆" },+ /* S_BTN_UP */ { L"\x25B2", L"\x25B2" },+ /* S_BTN_DOWN */ { L"\x25BC", L"\x25BC" },+ /* S_COL_ADDR */ { L"Address", L"地址" },+ /* S_COL_TYPE */ { L"Type", L"类型" },+ /* S_RULES_HINT */ { L"Rules are checked top to bottom; use the check box to enable/disable a rule.",+ L"规则从上到下依次匹配;使用复选框启用/禁用规则。" },+ /* S_BTN_CHECK */ { L"Proxy Test", L"代理测试" },+ /* S_TEST_OK */ { L"Proxy is reachable.\n\n%s", L"代理可访问。\n\n%s" },+ /* S_TEST_FAIL */ { L"Proxy test failed.\n\n%s", L"代理测试失败。\n\n%s" },+ /* S_TEST_TITLE */ { L"Proxy Check", L"代理测试" },+ /* S_DLG_CHECKER */ { L"Proxy Checker", L"代理检查器" },+ /* S_BTN_RETEST */ { L"Retest", L"重新测试" },+ /* S_TEST_RUNNING */ { L"Testing, please wait...", L"正在测试,请稍候..." },+ /* S_CK_HOST */ { L"Host:", L"主机:" },+ /* S_BTN_BROWSE */ { L"Browse...", L"浏览..." },+ /* S_EX_APPS */ { L"Example: iexplore.exe; \"C:\\some app.exe\"; fire*.exe; *.bin",+ L"示例: iexplore.exe; \"C:\\某个应用.exe\"; fire*.exe; *.bin" },+ /* S_EX_HOSTS */ { L"Example: 127.0.0.1; 192.168.1.*; 10.1.0.0-10.5.255.255; ::1; 2001:db8::/32; fe80::1-fe80::ff",+ L"示例: 127.0.0.1; 192.168.1.*; 10.1.0.0-10.5.255.255; ::1; 2001:db8::/32; fe80::1-fe80::ff" },+ /* S_EX_PORTS */ { L"Example: 80; 8000-9000; 3128", L"示例: 80; 8000-9000; 3128" },+ /* S_EX_DOMAINS */ { L"Example: google.com; *.google.com; *.gstatic.com (requires unencrypted DNS)",+ L"示例: google.com; *.google.com; *.gstatic.com (需要未加密的 DNS)" },+ /* S_UDP_NOTE */ { L"\x26A0 UDP only works with SOCKS5 proxy. Not all SOCKS5 proxies support UDP by default. "+ L"SOCKS5 UDP support does not guarantee QUIC or HTTP/3 support, verify your proxy supports these protocols separately.",+ L"\x26A0 UDP 仅支持 SOCKS5 代理。并非所有 SOCKS5 代理默认支持 UDP。SOCKS5 UDP 支持并不保证支持 QUIC 或 HTTP/3 -- 请单独确认您的代理是否支持这些协议。" },+ /* S_M_AUTOCLEAR */ { L"Auto Clear Logs", L"自动清除日志" },+ /* S_M_RENAME */ { L"Rename Profile", L"重命名配置" },+ /* S_M_LOGFILTERS */ { L"Log Filters...", L"日志过滤器..." },+ /* S_DLG_RENAME */ { L"Rename Profile", L"重命名配置" },+ /* S_DLG_FILTERS */ { L"Log Filters", L"日志过滤器" },+ /* S_DLG_FILTER */ { L"Log Filter Rule", L"日志过滤规则" },+ /* S_FL_DESC */ { L"Include rules show only matching connections; Exclude rules hide matching connections (excludes run first). "+ L"Leave a field empty or \"All\" to ignore it. Wildcards: chrome* / *.exe / *ch*.",+ L"Include 规则只显示匹配的连接;Exclude 规则隐藏匹配的连接(排除优先)。留空或选\"全部\"表示忽略该字段。通配符:chrome* / *.exe / *ch*。" },+ /* S_L_MODE */ { L"Mode:", L"模式:" },+ /* S_L_PROC */ { L"Process:", L"进程:" },+ /* S_L_IP */ { L"IP:", L"IP:" },+ /* S_COL_MODE */ { L"Mode", L"模式" },+ /* S_COL_PROC */ { L"Process", L"进程" },+ /* S_COL_IP */ { L"IP", L"IP" },+ /* S_INFO_NORENAMEDEFAULT*/{ L"The Default profile cannot be renamed.", L"无法重命名默认配置。" },+ /* S_ERR_RUNNING */ { L"ProxyBridge is already running (GUI or CLI).\nPlease close the other instance first.",+ L"ProxyBridge 已在运行 (GUI 或 CLI)。\n请先关闭另一个实例。" },+ /* S_AB_VERSION */ { L"Version " APP_VERSION, L"版本 " APP_VERSION },+ /* S_AB_DESC */ { L"Universal proxy client for Windows applications",+ L"适用于 Windows 应用程序的通用代理客户端" },+ /* S_AB_AUTHOR */ { L"Author: Sourav Kalal / InterceptSuite", L"作者: Sourav Kalal / InterceptSuite" },+ /* S_AB_WEB */ { L"Website: <a href=\"https://interceptsuite.com\">interceptsuite.com</a>",+ L"网站: <a href=\"https://interceptsuite.com\">interceptsuite.com</a>" },+ /* S_AB_GITHUB */ { L"GitHub: <a href=\"https://github.com/InterceptSuite/ProxyBridge\">github.com/InterceptSuite/ProxyBridge</a>",+ L"GitHub: <a href=\"https://github.com/InterceptSuite/ProxyBridge\">github.com/InterceptSuite/ProxyBridge</a>" },+ /* S_AB_LICENSE */ { L"License: MIT", L"许可证: MIT" },+ /* S_M_UPDATE */ { L"Check for &Updates...", L"检查更新(&U)..." },+ /* S_UPD_TITLE */ { L"Software Update", L"软件更新" },+ /* S_UPD_AVAIL */ { L"A new version of ProxyBridge is available.", L"ProxyBridge 有新版本可用。" },+ /* S_UPD_NOTES */ { L"Release notes", L"发行说明" },+ /* S_UPD_NOW */ { L"Update Now", L"立即更新" },+ /* S_UPD_LATER */ { L"Later", L"稍后" },+ /* S_UPD_DONTASK */ { L"Don't Ask Again", L"不再提示" },+ /* S_UPD_LATEST */ { L"You are running the latest version.", L"您正在使用最新版本。" },+ /* S_UPD_ERR */ { L"Could not check for updates. Please try again later.", L"无法检查更新,请稍后重试。" },+ /* S_UPD_DLING */ { L"Downloading update...", L"正在下载更新..." },+ /* S_UPD_DLFAIL */ { L"Download failed.", L"下载失败。" },+};++static const wchar_t* T(int id) { return g_strings[id][g_lang ? 1 : 0]; }++#endif // PB_LOC_Hdiff --git a/Windows/gui/main.c b/Windows/gui/main.cnew file mode 100644index 0000000..89156fd--- /dev/null+++ b/Windows/gui/main.c@@ -0,0 +1,855 @@+// ProxyBridge GUI.+//+// Drives ProxyBridgeCore.dll and reads/writes %APPDATA%\ProxyBridge settings.json ++// *.pbprofile files.+//+// Threading: DLL log/connection callbacks fire on native threads; each formats a line and+// PostMessage()s a heap wide-string to the UI thread, which appends it and frees it.++#ifndef UNICODE+#define UNICODE+#endif+#ifndef _UNICODE+#define _UNICODE+#endif++#include <windows.h>+#include <windowsx.h>+#include <tlhelp32.h>+#include <commctrl.h>+#include <commdlg.h>+#include <dwmapi.h>+#include <uxtheme.h>+#include <stdio.h>+#include <stdlib.h>+#include "res/resource.h"+#include "api/pb_api.h"+#include "profile/profile.h"+#include "loc/loc.h"++#pragma comment(lib, "comctl32.lib")+#pragma comment(lib, "user32.lib")+#pragma comment(lib, "gdi32.lib")+#pragma comment(lib, "shell32.lib")+#pragma comment(lib, "comdlg32.lib")+#pragma comment(lib, "dwmapi.lib")+#pragma comment(lib, "uxtheme.lib")++// dark theme+#define C_BG RGB(0x1E, 0x1E, 0x1E) // window / edit background+#define C_PANEL RGB(0x25, 0x25, 0x26) // strip background+#define C_TEXT RGB(0xD4, 0xD4, 0xD4)+#define C_DIM RGB(0x8A, 0x8A, 0x8A)+#define C_TAB RGB(0x2D, 0x2D, 0x30) // inactive tab+#define C_TABSEL RGB(0x1E, 0x1E, 0x1E) // active tab (matches content)+#define C_TABHOT RGB(0x3E, 0x3E, 0x42) // hovered tab+#define C_ACCENT RGB(0x00, 0x7A, 0xCC) // active-tab top strip+#define C_MENU RGB(0x2D, 0x2D, 0x30)+#define C_MENUHOT RGB(0x3E, 0x3E, 0x46)+#define C_LINE RGB(0x3F, 0x3F, 0x46)+#define C_WARN RGB(0xD7, 0xA5, 0x22) // amber hint for the UDP note++static HBRUSH g_brBg, g_brPanel, g_brTab, g_brTabSel, g_brTabHot, g_brAccent, g_brMenu, g_brMenuHot;+static int g_tabHot = -1; // hovered tab index (owner-draw)++// Undocumented immersive-menu messages (as used by Windows Terminal's dark-mode shim).+#define WM_UAHDRAWMENU 0x0091+#define WM_UAHDRAWMENUITEM 0x0092+typedef union { struct { DWORD cx, cy; } rgsizeBar[2]; struct { DWORD cx, cy; } rgsizePopup[4]; } UAHMENUITEMMETRICS;+typedef struct { DWORD rgcx[4]; DWORD fUpdateMaxWidths : 2; } UAHMENUPOPUPMETRICS;+typedef struct { HMENU hmenu; HDC hdc; DWORD dwFlags; } UAHMENU;+typedef struct { int iPosition; UAHMENUITEMMETRICS umim; UAHMENUPOPUPMETRICS umpm; } UAHMENUITEM;+typedef struct { DRAWITEMSTRUCT dis; UAHMENU um; UAHMENUITEM umi; } UAHDRAWMENUITEM;++// uxtheme.dll dark-mode ordinals (1903+). Loaded dynamically.+typedef enum { APPMODE_DEFAULT, APPMODE_ALLOWDARK, APPMODE_FORCEDARK, APPMODE_FORCELIGHT, APPMODE_MAX } PreferredAppMode;+typedef PreferredAppMode (WINAPI *fnSetPreferredAppMode)(PreferredAppMode);+typedef BOOL (WINAPI *fnAllowDarkModeForWindow)(HWND, BOOL);+typedef void (WINAPI *fnFlushMenuThemes)(void);++#define WM_APP_LOG (WM_APP + 1)+#define WM_APP_CONN (WM_APP + 2)+#define WM_APP_TRAY (WM_APP + 3)+#define WM_APP_TESTLINE (WM_APP + 4) // proxy-checker worker -> one log line+#define WM_APP_TESTDONE (WM_APP + 5) // proxy-checker worker -> testing finished++#define APP_TITLE L"ProxyBridge"+#define WND_CLASS L"ProxyBridgeNativeMainWnd"+#define MAX_LOG_CHARS 60000++// globals+static PBApi g_api;+static HWND g_hMain, g_hTab, g_hConnLog, g_hActLog;+static HWND g_hConnSearch, g_hConnClear, g_hActSearch, g_hActClear;+#define IDC_CONN_SEARCH 3001+#define IDC_CONN_CLEAR 3002+#define IDC_ACT_SEARCH 3003+#define IDC_ACT_CLEAR 3004++// Per-log line store so the search box can filter without losing lines. New lines append to+// the edit only when they match the active filter; changing the filter re-renders from here.+#define LOG_MAX_LINES 4000+typedef struct {+ HWND edit;+ wchar_t* lines[LOG_MAX_LINES];+ int count;+ wchar_t filter[128];+} LogStore;+static LogStore g_connStore, g_actStore;+static HFONT g_hMono, g_hUi;+static HINSTANCE g_hInst;+static NOTIFYICONDATAW g_tray;+static BOOL g_trayAdded = FALSE;+static BOOL g_reallyExit = FALSE;+static BOOL g_started = FALSE;++static PBProfile g_profile;+static wchar_t g_activeProfile[PB_NAME_MAX] = L"Default";+static BOOL g_localhost = FALSE, g_trafficLog = TRUE, g_closeToTray = TRUE;+static BOOL g_startup = FALSE; // "Run at Startup" (schtasks logon task)+static BOOL g_autoClear = TRUE; // auto-clear logs past a line threshold to save memory+#define AUTO_CLEAR_LINES 500+static PBFilter g_flt[PB_MAX_FILTER]; // connection-log filter snapshot (read by native cb)+static int g_fltCount = 0;++static wchar_t g_profNames[64][PB_NAME_MAX];+static int g_profCount = 0;+static wchar_t g_nameResult[PB_NAME_MAX];+static HMENU g_switchMenu = NULL; // the Profile > Switch submenu (rebuilt on demand)++// small helpers+static void W2Ux(const wchar_t* w, char* out, int cch)+{ WideCharToMultiByte(CP_UTF8, 0, w ? w : L"", -1, out, cch, NULL, NULL); }++static wchar_t* U2Wdup(const char* s)+{+ if (!s) s = "";+ int n = MultiByteToWideChar(CP_UTF8, 0, s, -1, NULL, 0);+ wchar_t* w = (wchar_t*)malloc((size_t)n * sizeof(wchar_t));+ if (w) MultiByteToWideChar(CP_UTF8, 0, s, -1, w, n);+ return w;+}++static int ProtoIdx(const wchar_t* s) { if (!_wcsicmp(s, L"UDP")) return 1; if (!_wcsicmp(s, L"BOTH")) return 2; return 0; }+static int ActionIdx(const wchar_t* s) { if (!_wcsicmp(s, L"DIRECT")) return 1; if (!_wcsicmp(s, L"BLOCK")) return 2; return 0; }+static const wchar_t* ProtoName(int i) { return i == 1 ? L"UDP" : i == 2 ? L"BOTH" : L"TCP"; }++// log panel + connection filters (split out)+#include "ui/logview.h"++// forward decls+static void SaveActive(void);+static UINT32 ResolveNativeCfg(UINT32 storedId);+static void ApplyConfigs(void);+static void ApplyRules(void);+static void UnapplyProfile(void);+static void SwitchToProfile(const wchar_t* name);+static void RebuildProfileMenu(HWND hwnd);+static void UpdateTitle(void);+static void SyncMenuChecks(HWND hwnd);+static void BuildMainMenu(HWND hwnd);+static void RelocalizeUI(HWND hwnd);+static UINT32 EngineAddRule(PBRule* r);+static void EngineEditRule(PBRule* r);+INT_PTR CALLBACK ServersDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK ServerEditDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK RulesDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK RuleEditDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK FiltersDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK FilterEditDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK NameDlgProc(HWND, UINT, WPARAM, LPARAM);+INT_PTR CALLBACK AboutDlgProc(HWND, UINT, WPARAM, LPARAM);++// DLL callbacks (native thread)+static void PBLogCb(const char* message)+{+ if (!g_hMain) return;+ wchar_t* body = U2Wdup(message);+ if (!body) return;+ wchar_t ts[16]; GetTimePrefix(ts, 16);+ size_t n = wcslen(ts) + wcslen(body) + 3;+ wchar_t* line = (wchar_t*)malloc(n * sizeof(wchar_t));+ if (line) { _snwprintf_s(line, n, _TRUNCATE, L"%s%s\r\n", ts, body); PostMessageW(g_hMain, WM_APP_LOG, 0, (LPARAM)line); }+ free(body);+}++static void PBConnCb(const char* proc, DWORD pid, const char* ip, unsigned short port, const char* info)+{+ if (!g_hMain || !g_trafficLog) return;+ wchar_t *wp = U2Wdup(proc), *wi = U2Wdup(ip), *wf = U2Wdup(info);+ // Connection-log filters: derive protocol/action from the proxy_info and drop non-matches.+ if (g_fltCount > 0)+ {+ wchar_t wport[16]; _snwprintf_s(wport, 16, _TRUNCATE, L"%u", port);+ const wchar_t* proto = (info && strstr(info, "(UDP)")) ? L"UDP" : L"TCP";+ const wchar_t* action = (info && _strnicmp(info, "Direct", 6) == 0) ? L"Direct"+ : (info && _strnicmp(info, "Block", 5) == 0) ? L"Blocked" : L"Proxy";+ if (!PassesLogFilters(wp ? wp : L"", wi ? wi : L"", wport, proto, action))+ { free(wp); free(wi); free(wf); return; }+ }+ wchar_t ts[16]; GetTimePrefix(ts, 16);+ size_t n = 64 + (wp ? wcslen(wp) : 0) + (wi ? wcslen(wi) : 0) + (wf ? wcslen(wf) : 0);+ wchar_t* line = (wchar_t*)malloc(n * sizeof(wchar_t));+ if (line)+ {+ _snwprintf_s(line, n, _TRUNCATE, L"%s%s (PID:%lu) -> %s:%u via %s\r\n",+ ts, wp ? wp : L"?", pid, wi ? wi : L"?", port, wf ? wf : L"?");+ PostMessageW(g_hMain, WM_APP_CONN, 0, (LPARAM)line);+ }+ free(wp); free(wi); free(wf);+}++// profile apply / persist+static void SaveActive(void) { PB_ProfileSave(g_activeProfile, &g_profile); }++static UINT32 ResolveNativeCfg(UINT32 storedId)+{+ for (int i = 0; i < g_profile.cfgCount; i++)+ if (g_profile.cfg[i].storedId == storedId) return g_profile.cfg[i].nativeId;+ return 0; // 0 => DLL uses first available config+}++static void ApplyConfigs(void)+{+ for (int i = 0; i < g_profile.cfgCount; i++)+ {+ PBConfig* c = &g_profile.cfg[i];+ int type = (_wcsicmp(c->type, L"HTTP") == 0) ? PB_PROXY_HTTP : PB_PROXY_SOCKS5;+ char h[256], u[256], p[256];+ W2Ux(c->host, h, sizeof(h)); W2Ux(c->user, u, sizeof(u)); W2Ux(c->pass, p, sizeof(p));+ c->nativeId = g_api.AddProxyConfig((PBProxyType)type, h, (unsigned short)_wtoi(c->port), u, p);+ if (c->storedId == 0) c->storedId = c->nativeId;+ }+}++static void ApplyRules(void)+{+ for (int i = 0; i < g_profile.ruleCount; i++)+ {+ PBRule* r = &g_profile.rule[i];+ char proc[512], hosts[512], ports[256], domains[512];+ W2Ux(r->proc, proc, sizeof(proc)); W2Ux(r->hosts, hosts, sizeof(hosts));+ W2Ux(r->ports, ports, sizeof(ports)); W2Ux(r->domains, domains, sizeof(domains));+ r->nativeId = g_api.AddRule(proc, hosts, ports, domains,+ (PBRuleProtocol)ProtoIdx(r->proto), (PBRuleAction)ActionIdx(r->action),+ ResolveNativeCfg(r->cfgStoredId));+ if (r->nativeId && !r->enabled) g_api.DisableRule(r->nativeId);+ }+}++// Add one rule to the engine, returning its (stable) native id. Enable state applied too.+static UINT32 EngineAddRule(PBRule* r)+{+ char proc[512], hosts[512], ports[256], domains[512];+ W2Ux(r->proc, proc, sizeof(proc)); W2Ux(r->hosts, hosts, sizeof(hosts));+ W2Ux(r->ports, ports, sizeof(ports)); W2Ux(r->domains, domains, sizeof(domains));+ UINT32 id = g_api.AddRule(proc, hosts, ports, domains,+ (PBRuleProtocol)ProtoIdx(r->proto), (PBRuleAction)ActionIdx(r->action),+ ResolveNativeCfg(r->cfgStoredId));+ if (id && !r->enabled) g_api.DisableRule(id);+ return id;+}+// Edit an existing rule in place - keeps the same native id and list position.+static void EngineEditRule(PBRule* r)+{+ char proc[512], hosts[512], ports[256], domains[512];+ W2Ux(r->proc, proc, sizeof(proc)); W2Ux(r->hosts, hosts, sizeof(hosts));+ W2Ux(r->ports, ports, sizeof(ports)); W2Ux(r->domains, domains, sizeof(domains));+ g_api.EditRule(r->nativeId, proc, hosts, ports, domains,+ (PBRuleProtocol)ProtoIdx(r->proto), (PBRuleAction)ActionIdx(r->action),+ ResolveNativeCfg(r->cfgStoredId));+ if (r->enabled) g_api.EnableRule(r->nativeId); else g_api.DisableRule(r->nativeId);+}++static void UnapplyProfile(void)+{+ for (int i = 0; i < g_profile.ruleCount; i++) if (g_profile.rule[i].nativeId) g_api.DeleteRule(g_profile.rule[i].nativeId);+ for (int i = 0; i < g_profile.cfgCount; i++) if (g_profile.cfg[i].nativeId) g_api.DeleteProxyConfig(g_profile.cfg[i].nativeId);+}++static void SwitchToProfile(const wchar_t* name)+{+ UnapplyProfile();+ PB_SetActiveProfile(name);+ lstrcpynW(g_activeProfile, name, PB_NAME_MAX);+ PB_ProfileLoad(name, &g_profile);+ g_localhost = g_profile.localhostViaProxy;+ g_trafficLog = g_profile.trafficLogging;+ g_closeToTray = g_profile.closeToTray;+ g_autoClear = g_profile.autoClearLogs;+ ApplyFilterSnapshot();+ g_api.SetLocalhostViaProxy(g_localhost);+ g_api.SetTrafficLoggingEnabled(g_trafficLog);+ ApplyConfigs();+ ApplyRules();+ SyncMenuChecks(g_hMain);+ RebuildProfileMenu(g_hMain);+ UpdateTitle();+}++static void UpdateTitle(void)+{+ wchar_t t[128]; _snwprintf_s(t, 128, _TRUNCATE, L"%s - %s", APP_TITLE, g_activeProfile);+ SetWindowTextW(g_hMain, t);+}++// Builds the whole menu bar from the string table so a language switch can rebuild it live.+static void BuildMainMenu(HWND hwnd)+{+ HMENU bar = CreateMenu();++ HMENU proxy = CreatePopupMenu();+ AppendMenuW(proxy, MF_STRING, IDM_PROXY_SETTINGS, T(S_M_PROXY_SETTINGS));+ AppendMenuW(proxy, MF_STRING, IDM_PROXY_RULES, T(S_M_PROXY_RULES));+ AppendMenuW(proxy, MF_STRING, IDM_LOG_FILTERS, T(S_M_LOGFILTERS));+ AppendMenuW(bar, MF_POPUP, (UINT_PTR)proxy, T(S_M_PROXY));++ HMENU profile = CreatePopupMenu();+ AppendMenuW(profile, MF_STRING, IDM_PROFILE_NEW, T(S_M_NEWPROFILE));+ AppendMenuW(profile, MF_STRING, IDM_PROFILE_RENAME, T(S_M_RENAME));+ AppendMenuW(profile, MF_STRING, IDM_PROFILE_DELETE, T(S_M_DELPROFILE));+ AppendMenuW(profile, MF_SEPARATOR, 0, NULL);+ AppendMenuW(profile, MF_STRING, IDM_PROFILE_IMPORT, T(S_M_IMPORT));+ AppendMenuW(profile, MF_STRING, IDM_PROFILE_EXPORT, T(S_M_EXPORT));+ AppendMenuW(profile, MF_SEPARATOR, 0, NULL);+ g_switchMenu = CreatePopupMenu();+ AppendMenuW(profile, MF_POPUP, (UINT_PTR)g_switchMenu, T(S_M_SWITCH));+ AppendMenuW(bar, MF_POPUP, (UINT_PTR)profile, T(S_M_PROFILE));++ HMENU settings = CreatePopupMenu();+ AppendMenuW(settings, MF_STRING, IDM_SET_LOCALHOST, T(S_M_LOCALHOST));+ AppendMenuW(settings, MF_STRING, IDM_SET_TRAFFICLOG, T(S_M_TRAFFIC));+ AppendMenuW(settings, MF_STRING, IDM_SET_CLOSETOTRAY, T(S_M_TRAY));+ AppendMenuW(settings, MF_STRING, IDM_SET_STARTUP, T(S_M_STARTUP));+ AppendMenuW(settings, MF_STRING, IDM_SET_AUTOCLEAR, T(S_M_AUTOCLEAR));+ AppendMenuW(settings, MF_SEPARATOR, 0, NULL);+ HMENU lang = CreatePopupMenu();+ AppendMenuW(lang, MF_STRING, IDM_LANG_EN, T(S_M_LANG_EN));+ AppendMenuW(lang, MF_STRING, IDM_LANG_ZH, T(S_M_LANG_ZH));+ AppendMenuW(settings, MF_POPUP, (UINT_PTR)lang, T(S_M_LANG));+ AppendMenuW(bar, MF_POPUP, (UINT_PTR)settings, T(S_M_SETTINGS));++ HMENU help = CreatePopupMenu();+ AppendMenuW(help, MF_STRING, IDM_HELP_DOCS, T(S_M_DOCS));+ AppendMenuW(help, MF_STRING, IDM_HELP_UPDATE, T(S_M_UPDATE));+ AppendMenuW(help, MF_SEPARATOR, 0, NULL);+ AppendMenuW(help, MF_STRING, IDM_HELP_ABOUT, T(S_M_ABOUT));+ AppendMenuW(bar, MF_POPUP, (UINT_PTR)help, T(S_M_HELP));++ HMENU old = GetMenu(hwnd);+ SetMenu(hwnd, bar);+ if (old) DestroyMenu(old);+}++static void RebuildProfileMenu(HWND hwnd)+{+ if (!g_switchMenu) return;+ while (GetMenuItemCount(g_switchMenu) > 0) DeleteMenu(g_switchMenu, 0, MF_BYPOSITION);+ g_profCount = PB_ProfileList(g_profNames, 64);+ for (int i = 0; i < g_profCount; i++)+ {+ UINT flags = MF_STRING | (_wcsicmp(g_profNames[i], g_activeProfile) == 0 ? MF_CHECKED : 0);+ AppendMenuW(g_switchMenu, flags, (UINT_PTR)(IDM_PROFILE_SWITCH_BASE + i), g_profNames[i]);+ }+ if (g_profCount == 0) AppendMenuW(g_switchMenu, MF_STRING | MF_GRAYED, IDM_PROFILE_SWITCH_BASE, L"-");+ DrawMenuBar(hwnd);+}++// Rebuild everything that carries text after a language change.+static void RelocalizeUI(HWND hwnd)+{+ BuildMainMenu(hwnd);+ RebuildProfileMenu(hwnd);+ SyncMenuChecks(hwnd);+ TCITEMW ti; ti.mask = TCIF_TEXT;+ ti.pszText = (LPWSTR)T(S_TAB_CONN); TabCtrl_SetItem(g_hTab, 0, &ti);+ ti.pszText = (LPWSTR)T(S_TAB_ACT); TabCtrl_SetItem(g_hTab, 1, &ti);+ UpdateTitle();+ DrawMenuBar(hwnd);+}++// single-instance + Run at Startup (split out)+#include "ui/startup.h"++// tray / layout / menu-checks+static void TrayAdd(HWND hwnd)+{+ ZeroMemory(&g_tray, sizeof(g_tray));+ g_tray.cbSize = sizeof(g_tray);+ g_tray.hWnd = hwnd; g_tray.uID = 1;+ g_tray.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;+ g_tray.uCallbackMessage = WM_APP_TRAY;+ g_tray.hIcon = (HICON)LoadImageW(g_hInst, MAKEINTRESOURCEW(IDI_APPICON), IMAGE_ICON,+ GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);+ lstrcpynW(g_tray.szTip, APP_TITLE, ARRAYSIZE(g_tray.szTip));+ Shell_NotifyIconW(NIM_ADD, &g_tray);+ g_trayAdded = TRUE;+}+static void TrayRemove(void) { if (g_trayAdded) { Shell_NotifyIconW(NIM_DELETE, &g_tray); g_trayAdded = FALSE; } }+static void ShowMainWindow(HWND hwnd) { ShowWindow(hwnd, SW_SHOW); ShowWindow(hwnd, SW_RESTORE); SetForegroundWindow(hwnd); }++static void LayoutMain(HWND hwnd)+{+ RECT rc; GetClientRect(hwnd, &rc);+ int tabTop = 6, tabH = 32; // small gap below the menu bar+ MoveWindow(g_hTab, 0, tabTop, rc.right, tabH, TRUE);+ int top = tabTop + tabH + 6;+ int barH = 30, clearW = 130, gap = 6;+ int searchW = rc.right - 4 - clearW - gap - 4;+ int logTop = top + barH + 4;+ int logH = rc.bottom - logTop - 4; if (logH < 0) logH = 0;+ // search box + Clear button row, then the log below (both tabs share the same rect)+ MoveWindow(g_hConnSearch, 4, top, searchW, barH - 6, TRUE);+ MoveWindow(g_hActSearch, 4, top, searchW, barH - 6, TRUE);+ MoveWindow(g_hConnClear, 4 + searchW + gap, top - 1, clearW, barH - 2, TRUE);+ MoveWindow(g_hActClear, 4 + searchW + gap, top - 1, clearW, barH - 2, TRUE);+ MoveWindow(g_hConnLog, 2, logTop, rc.right - 4, logH, TRUE);+ MoveWindow(g_hActLog, 2, logTop, rc.right - 4, logH, TRUE);+}+static void SelectTab(int idx)+{+ int c = (idx == 0) ? SW_SHOW : SW_HIDE;+ int a = (idx == 1) ? SW_SHOW : SW_HIDE;+ ShowWindow(g_hConnLog, c); ShowWindow(g_hConnSearch, c); ShowWindow(g_hConnClear, c);+ ShowWindow(g_hActLog, a); ShowWindow(g_hActSearch, a); ShowWindow(g_hActClear, a);+}+static void SyncMenuChecks(HWND hwnd)+{+ HMENU m = GetMenu(hwnd);+ CheckMenuItem(m, IDM_SET_LOCALHOST, MF_BYCOMMAND | (g_localhost ? MF_CHECKED : MF_UNCHECKED));+ CheckMenuItem(m, IDM_SET_TRAFFICLOG, MF_BYCOMMAND | (g_trafficLog ? MF_CHECKED : MF_UNCHECKED));+ CheckMenuItem(m, IDM_SET_CLOSETOTRAY, MF_BYCOMMAND | (g_closeToTray? MF_CHECKED : MF_UNCHECKED));+ CheckMenuItem(m, IDM_SET_STARTUP, MF_BYCOMMAND | (g_startup ? MF_CHECKED : MF_UNCHECKED));+ CheckMenuItem(m, IDM_SET_AUTOCLEAR, MF_BYCOMMAND | (g_autoClear ? MF_CHECKED : MF_UNCHECKED));+ int zh = (_wcsicmp(g_profile.language, L"zh") == 0);+ CheckMenuItem(m, IDM_LANG_EN, MF_BYCOMMAND | (zh ? MF_UNCHECKED : MF_CHECKED));+ CheckMenuItem(m, IDM_LANG_ZH, MF_BYCOMMAND | (zh ? MF_CHECKED : MF_UNCHECKED));+}++// file dialogs+static BOOL PickFile(HWND owner, BOOL save, wchar_t* path, int cch)+{+ OPENFILENAMEW ofn; ZeroMemory(&ofn, sizeof(ofn));+ path[0] = 0;+ ofn.lStructSize = sizeof(ofn);+ ofn.hwndOwner = owner;+ ofn.lpstrFilter = L"ProxyBridge Profile (*.pbprofile)\0*.pbprofile\0All Files\0*.*\0";+ ofn.lpstrFile = path; ofn.nMaxFile = cch;+ ofn.lpstrDefExt = L"pbprofile";+ ofn.Flags = save ? (OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST)+ : (OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST);+ return save ? GetSaveFileNameW(&ofn) : GetOpenFileNameW(&ofn);+}++// dark theme helpers (split out)+#include "ui/theme.h"+// update checker (split out)+#include "ui/update.h"++// main window proc+static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_CREATE:+ {+ g_hUi = CreateFontW(-19, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,+ DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI");+ g_hMono = CreateFontW(-19, 0, 0, 0, FW_NORMAL, 0, 0, 0, DEFAULT_CHARSET,+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,+ FIXED_PITCH | FF_MODERN, L"Consolas");+ g_hTab = CreateWindowExW(0, WC_TABCONTROLW, NULL,+ WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | TCS_OWNERDRAWFIXED,+ 0, 0, 0, 0, hwnd, NULL, g_hInst, NULL);+ SendMessageW(g_hTab, WM_SETFONT, (WPARAM)g_hUi, TRUE);+ TCITEMW ti; ti.mask = TCIF_TEXT;+ ti.pszText = (LPWSTR)T(S_TAB_CONN); TabCtrl_InsertItem(g_hTab, 0, &ti);+ ti.pszText = (LPWSTR)T(S_TAB_ACT); TabCtrl_InsertItem(g_hTab, 1, &ti);++ DWORD es = WS_CHILD | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_BORDER;+ g_hConnLog = CreateWindowExW(0, L"EDIT", NULL, es | WS_VISIBLE, 0, 0, 0, 0, hwnd, NULL, g_hInst, NULL);+ g_hActLog = CreateWindowExW(0, L"EDIT", NULL, es, 0, 0, 0, 0, hwnd, NULL, g_hInst, NULL);+ SendMessageW(g_hConnLog, WM_SETFONT, (WPARAM)g_hMono, TRUE);+ SendMessageW(g_hActLog, WM_SETFONT, (WPARAM)g_hMono, TRUE);+ SendMessageW(g_hConnLog, EM_SETLIMITTEXT, MAX_LOG_CHARS * 2, 0);+ SendMessageW(g_hActLog, EM_SETLIMITTEXT, MAX_LOG_CHARS * 2, 0);++ // Per-tab search box + Clear button, one set per log.+ DWORD ss = WS_CHILD | ES_AUTOHSCROLL;+ g_hConnSearch = CreateWindowExW(0, L"EDIT", NULL, ss, 0,0,0,0, hwnd, (HMENU)IDC_CONN_SEARCH, g_hInst, NULL);+ g_hActSearch = CreateWindowExW(0, L"EDIT", NULL, ss, 0,0,0,0, hwnd, (HMENU)IDC_ACT_SEARCH, g_hInst, NULL);+ g_hConnClear = CreateWindowExW(0, L"BUTTON", T(S_BTN_CLEARLOGS), WS_CHILD | BS_PUSHBUTTON | WS_TABSTOP, 0,0,0,0, hwnd, (HMENU)IDC_CONN_CLEAR, g_hInst, NULL);+ g_hActClear = CreateWindowExW(0, L"BUTTON", T(S_BTN_CLEARLOGS), WS_CHILD | BS_PUSHBUTTON | WS_TABSTOP, 0,0,0,0, hwnd, (HMENU)IDC_ACT_CLEAR, g_hInst, NULL);+ SendMessageW(g_hConnSearch, WM_SETFONT, (WPARAM)g_hUi, TRUE);+ SendMessageW(g_hActSearch, WM_SETFONT, (WPARAM)g_hUi, TRUE);+ SendMessageW(g_hConnClear, WM_SETFONT, (WPARAM)g_hUi, TRUE);+ SendMessageW(g_hActClear, WM_SETFONT, (WPARAM)g_hUi, TRUE);+ SendMessageW(g_hConnSearch, EM_SETCUEBANNER, TRUE, (LPARAM)T(S_SEARCH_CUE));+ SendMessageW(g_hActSearch, EM_SETCUEBANNER, TRUE, (LPARAM)T(S_SEARCH_CUE));+ g_connStore.edit = g_hConnLog;+ g_actStore.edit = g_hActLog;++ // Dark theme: elevate to immersive dark mode, dark scrollbars on the log edits,+ // and hover tracking for the owner-drawn tabs.+ InitDarkMode(hwnd);+ SetWindowTheme(g_hConnLog, L"DarkMode_Explorer", NULL);+ SetWindowTheme(g_hActLog, L"DarkMode_Explorer", NULL);+ SetWindowTheme(g_hTab, L"DarkMode_Explorer", NULL);+ SetWindowSubclass(g_hTab, TabSubProc, 1, 0);++ LayoutMain(hwnd); SelectTab(0);+ return 0;+ }+ case WM_SIZE: LayoutMain(hwnd); return 0;+ case WM_CTLCOLOREDIT:+ case WM_CTLCOLORLISTBOX:+ case WM_CTLCOLORBTN:+ case WM_CTLCOLORSTATIC:+ {+ HDC dc = (HDC)wp;+ SetTextColor(dc, C_TEXT);+ SetBkColor(dc, C_BG);+ return (LRESULT)g_brBg;+ }+ case WM_DRAWITEM:+ {+ LPDRAWITEMSTRUCT d = (LPDRAWITEMSTRUCT)lp;+ if (d->CtlType == ODT_TAB || d->hwndItem == g_hTab)+ {+ BOOL sel = (d->itemState & ODS_SELECTED) != 0;+ BOOL hot = ((int)d->itemID == g_tabHot);+ FillRect(d->hDC, &d->rcItem, sel ? g_brTabSel : (hot ? g_brTabHot : g_brTab));+ if (sel)+ {+ RECT top = d->rcItem; top.bottom = top.top + 2;+ FillRect(d->hDC, &top, g_brAccent);+ }+ wchar_t txt[64] = {0};+ TCITEMW ti; ti.mask = TCIF_TEXT; ti.pszText = txt; ti.cchTextMax = 64;+ TabCtrl_GetItem(g_hTab, d->itemID, &ti);+ SetBkMode(d->hDC, TRANSPARENT);+ SetTextColor(d->hDC, sel ? C_TEXT : C_DIM);+ DrawTextW(d->hDC, txt, -1, &d->rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ return TRUE;+ }+ return 0;+ }+ case WM_UAHDRAWMENU:+ {+ UAHMENU* pum = (UAHMENU*)lp;+ MENUBARINFO mbi; mbi.cbSize = sizeof(mbi);+ GetMenuBarInfo(hwnd, OBJID_MENU, 0, &mbi);+ RECT wr; GetWindowRect(hwnd, &wr);+ RECT r = mbi.rcBar; OffsetRect(&r, -wr.left, -wr.top);+ FillRect(pum->hdc, &r, g_brMenu);+ return TRUE;+ }+ case WM_UAHDRAWMENUITEM:+ {+ UAHDRAWMENUITEM* pmi = (UAHDRAWMENUITEM*)lp;+ wchar_t txt[128] = {0};+ MENUITEMINFOW mii; mii.cbSize = sizeof(mii);+ mii.fMask = MIIM_STRING; mii.dwTypeData = txt; mii.cch = 128;+ GetMenuItemInfoW(pmi->um.hmenu, (UINT)pmi->umi.iPosition, TRUE, &mii);+ BOOL hot = (pmi->dis.itemState & (ODS_HOTLIGHT | ODS_SELECTED)) != 0;+ FillRect(pmi->um.hdc, &pmi->dis.rcItem, hot ? g_brMenuHot : g_brMenu);+ SetBkMode(pmi->um.hdc, TRANSPARENT);+ SetTextColor(pmi->um.hdc,+ (pmi->dis.itemState & (ODS_GRAYED | ODS_DISABLED)) ? C_DIM : C_TEXT);+ DrawTextW(pmi->um.hdc, txt, -1, &pmi->dis.rcItem, DT_CENTER | DT_VCENTER | DT_SINGLELINE);+ return TRUE;+ }+ case WM_NCACTIVATE:+ case WM_NCPAINT:+ {+ LRESULT r = DefWindowProcW(hwnd, msg, wp, lp);+ PaintMenuBottomLine(hwnd);+ return r;+ }+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ if (nh->hwndFrom == g_hTab && nh->code == TCN_SELCHANGE) SelectTab(TabCtrl_GetCurSel(g_hTab));+ return 0;+ }+ case WM_APP_LOG: { wchar_t* s = (wchar_t*)lp; if (s) { LogStoreAdd(&g_actStore, s); free(s); } return 0; }+ case WM_APP_CONN: { wchar_t* s = (wchar_t*)lp; if (s) { LogStoreAdd(&g_connStore, s); free(s); } return 0; }+ case WM_APP_UPDATE:+ {+ UpdInfo* info = (UpdInfo*)lp;+ BOOL ok = (wp & 1) != 0, manual = (wp & 2) != 0;+ if (info)+ {+ if (ok && info->available)+ DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_UPDATE), hwnd, UpdateDlgProc, (LPARAM)info);+ else if (manual)+ MessageBoxW(hwnd, ok ? T(S_UPD_LATEST) : T(S_UPD_ERR), T(S_UPD_TITLE), MB_OK | MB_ICONINFORMATION);+ free(info);+ }+ return 0;+ }+ case WM_APP_TRAY:+ if (LOWORD(lp) == WM_LBUTTONDBLCLK) ShowMainWindow(hwnd);+ else if (LOWORD(lp) == WM_RBUTTONUP)+ {+ POINT pt; GetCursorPos(&pt);+ HMENU pm = CreatePopupMenu();+ AppendMenuW(pm, MF_STRING, IDM_TRAY_SHOW, T(S_TRAY_SHOW));+ AppendMenuW(pm, MF_SEPARATOR, 0, NULL);+ AppendMenuW(pm, MF_STRING, IDM_TRAY_EXIT, T(S_TRAY_EXIT));+ SetForegroundWindow(hwnd);+ TrackPopupMenu(pm, TPM_RIGHTBUTTON, pt.x, pt.y, 0, hwnd, NULL);+ DestroyMenu(pm);+ }+ return 0;++ case WM_COMMAND:+ {+ WORD id = LOWORD(wp);+ if (id >= IDM_PROFILE_SWITCH_BASE && id < IDM_PROFILE_SWITCH_BASE + g_profCount)+ {+ int i = id - IDM_PROFILE_SWITCH_BASE;+ if (_wcsicmp(g_profNames[i], g_activeProfile) != 0) SwitchToProfile(g_profNames[i]);+ return 0;+ }+ switch (id)+ {+ case IDM_PROXY_SETTINGS: DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_SERVERS), hwnd, ServersDlgProc); return 0;+ case IDM_PROXY_RULES: DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_RULES), hwnd, RulesDlgProc); return 0;+ case IDM_SET_LOCALHOST:+ g_localhost = !g_localhost; g_profile.localhostViaProxy = g_localhost;+ g_api.SetLocalhostViaProxy(g_localhost); SaveActive(); SyncMenuChecks(hwnd); return 0;+ case IDM_SET_TRAFFICLOG:+ g_trafficLog = !g_trafficLog; g_profile.trafficLogging = g_trafficLog;+ g_api.SetTrafficLoggingEnabled(g_trafficLog); SaveActive(); SyncMenuChecks(hwnd); return 0;+ case IDM_SET_CLOSETOTRAY:+ g_closeToTray = !g_closeToTray; g_profile.closeToTray = g_closeToTray;+ SaveActive(); SyncMenuChecks(hwnd); return 0;+ case IDM_SET_STARTUP:+ g_startup = !g_startup; StartupSet(g_startup);+ g_startup = StartupIsEnabled(); // reflect the real state+ SyncMenuChecks(hwnd); return 0;+ case IDM_SET_AUTOCLEAR:+ g_autoClear = !g_autoClear; g_profile.autoClearLogs = g_autoClear;+ SaveActive(); SyncMenuChecks(hwnd); return 0;+ case IDM_LOG_FILTERS:+ if (DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_FILTERS), hwnd, FiltersDlgProc))+ {+ ApplyFilterSnapshot(); SaveActive();+ LogStoreClear(&g_connStore); // re-populate under the new filter set+ }+ return 0;+ case IDM_PROFILE_RENAME:+ if (_wcsicmp(g_activeProfile, L"Default") == 0)+ { MessageBoxW(hwnd, T(S_INFO_NORENAMEDEFAULT), APP_TITLE, MB_OK | MB_ICONINFORMATION); return 0; }+ if (DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_NAME), hwnd, NameDlgProc) && g_nameResult[0])+ {+ for (wchar_t* q = g_nameResult; *q; q++) if (wcschr(L"<>:\"/\\|?*", *q)) *q = L'_';+ if (_wcsicmp(g_nameResult, g_activeProfile) != 0)+ {+ if (PB_ProfileRename(g_activeProfile, g_nameResult))+ { lstrcpynW(g_activeProfile, g_nameResult, PB_NAME_MAX); RebuildProfileMenu(hwnd); UpdateTitle(); }+ else MessageBoxW(hwnd, T(S_ERR_IMPORT), APP_TITLE, MB_OK | MB_ICONERROR);+ }+ }+ return 0;+ case IDM_LANG_EN: g_lang = 0; lstrcpynW(g_profile.language, L"en", 8); SaveActive(); RelocalizeUI(hwnd); return 0;+ case IDM_LANG_ZH: g_lang = 1; lstrcpynW(g_profile.language, L"zh", 8); SaveActive(); RelocalizeUI(hwnd); return 0;+ case IDC_CONN_CLEAR: LogStoreClear(&g_connStore); if (g_api.ClearConnectionLogs) g_api.ClearConnectionLogs(); return 0;+ case IDC_ACT_CLEAR: LogStoreClear(&g_actStore); return 0;+ case IDC_CONN_SEARCH:+ if (HIWORD(wp) == EN_CHANGE)+ { GetWindowTextW(g_hConnSearch, g_connStore.filter, 128); LogStoreRebuild(&g_connStore); }+ return 0;+ case IDC_ACT_SEARCH:+ if (HIWORD(wp) == EN_CHANGE)+ { GetWindowTextW(g_hActSearch, g_actStore.filter, 128); LogStoreRebuild(&g_actStore); }+ return 0;+ case IDM_PROFILE_NEW:+ if (DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_NAME), hwnd, NameDlgProc) && g_nameResult[0])+ {+ for (wchar_t* q = g_nameResult; *q; q++) if (wcschr(L"<>:\"/\\|?*", *q)) *q = L'_';+ PBProfile* np = (PBProfile*)malloc(sizeof(PBProfile)); // too big for the stack+ if (np) { PB_ProfileDefaults(np, g_nameResult); PB_ProfileSave(g_nameResult, np); free(np); }+ SwitchToProfile(g_nameResult);+ }+ return 0;+ case IDM_PROFILE_DELETE:+ if (_wcsicmp(g_activeProfile, L"Default") == 0)+ { MessageBoxW(hwnd, T(S_INFO_NODELDEFAULT), APP_TITLE, MB_OK | MB_ICONINFORMATION); return 0; }+ {+ wchar_t toDel[PB_NAME_MAX]; lstrcpynW(toDel, g_activeProfile, PB_NAME_MAX);+ SwitchToProfile(L"Default");+ PB_ProfileDelete(toDel);+ RebuildProfileMenu(hwnd);+ }+ return 0;+ case IDM_PROFILE_IMPORT:+ {+ wchar_t src[MAX_PATH];+ if (PickFile(hwnd, FALSE, src, MAX_PATH))+ {+ wchar_t assigned[PB_NAME_MAX];+ if (PB_ProfileImport(src, assigned, PB_NAME_MAX)) SwitchToProfile(assigned);+ else MessageBoxW(hwnd, T(S_ERR_IMPORT), APP_TITLE, MB_OK | MB_ICONERROR);+ }+ return 0;+ }+ case IDM_PROFILE_EXPORT:+ {+ wchar_t dst[MAX_PATH];+ if (PickFile(hwnd, TRUE, dst, MAX_PATH))+ {+ if (!PB_ProfileExport(g_activeProfile, dst))+ MessageBoxW(hwnd, T(S_ERR_EXPORT), APP_TITLE, MB_OK | MB_ICONERROR);+ }+ return 0;+ }+ case IDM_HELP_DOCS:+ ShellExecuteW(hwnd, L"open", L"https://interceptsuite.com/docs/proxybridge/", NULL, NULL, SW_SHOWNORMAL);+ return 0;+ case IDM_HELP_UPDATE:+ UpdStartCheck(hwnd, TRUE); // manual: also reports "up to date" / errors+ return 0;+ case IDM_HELP_ABOUT:+ DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_ABOUT), hwnd, AboutDlgProc);+ return 0;+ case IDM_TRAY_SHOW: ShowMainWindow(hwnd); return 0;+ case IDM_TRAY_EXIT: g_reallyExit = TRUE; DestroyWindow(hwnd); return 0;+ }+ return 0;+ }++ case WM_CLOSE:+ if (g_closeToTray && !g_reallyExit) { ShowWindow(hwnd, SW_HIDE); return 0; }+ DestroyWindow(hwnd);+ return 0;+ case WM_DESTROY:+ if (g_api.Stop) g_api.Stop();+ TrayRemove();+ LogStoreClear(&g_connStore); // release the buffered log lines+ LogStoreClear(&g_actStore);+ if (g_hMono) DeleteObject(g_hMono);+ if (g_hUi) DeleteObject(g_hUi);+ if (g_brBg) DeleteObject(g_brBg);+ if (g_brPanel) DeleteObject(g_brPanel);+ if (g_brTab) DeleteObject(g_brTab);+ if (g_brTabSel) DeleteObject(g_brTabSel);+ if (g_brTabHot) DeleteObject(g_brTabHot);+ if (g_brAccent) DeleteObject(g_brAccent);+ if (g_brMenu) DeleteObject(g_brMenu);+ if (g_brMenuHot)DeleteObject(g_brMenuHot);+ PostQuitMessage(0);+ return 0;+ }+ return DefWindowProcW(hwnd, msg, wp, lp);+}+// all dialogs (split out)+#include "ui/dialogs.h"+++// entry point+int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)+{+ (void)hPrev;+ g_hInst = hInst;+ BOOL startMinimized = (cmd && wcsstr(cmd, L"--minimized") != NULL);++ INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_TAB_CLASSES | ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES | ICC_STANDARD_CLASSES | ICC_LINK_CLASS | ICC_PROGRESS_CLASS };+ InitCommonControlsEx(&icc);++ if (!PB_Load(&g_api))+ {+ MessageBoxW(NULL, L"Could not load ProxyBridgeCore.dll.\n"+ L"Make sure it is in the same folder as this executable.",+ APP_TITLE, MB_OK | MB_ICONERROR);+ return 1;+ }++ // Load the active profile.+ PB_GetActiveProfile(g_activeProfile, PB_NAME_MAX);+ PB_ProfileLoad(g_activeProfile, &g_profile);+ g_localhost = g_profile.localhostViaProxy;+ g_trafficLog = g_profile.trafficLogging;+ g_closeToTray = g_profile.closeToTray;+ g_lang = (_wcsicmp(g_profile.language, L"zh") == 0) ? 1 : 0;++ // Refuse to start if another GUI or the CLI is already running - they'd both grab the+ // WinDivert driver and the same relay ports.+ if (AnotherInstanceRunning())+ {+ MessageBoxW(NULL, T(S_ERR_RUNNING), APP_TITLE, MB_OK | MB_ICONWARNING);+ return 0;+ }++ g_autoClear = g_profile.autoClearLogs;+ g_startup = StartupIsEnabled();+ ApplyFilterSnapshot();++ CreateDarkBrushes(); // needed for the window class background below++ WNDCLASSEXW wc; ZeroMemory(&wc, sizeof(wc));+ wc.cbSize = sizeof(wc);+ wc.lpfnWndProc = WndProc;+ wc.hInstance = hInst;+ wc.hIcon = (HICON)LoadImageW(hInst, MAKEINTRESOURCEW(IDI_APPICON), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE);+ wc.hIconSm = wc.hIcon;+ wc.hCursor = LoadCursorW(NULL, IDC_ARROW);+ wc.hbrBackground = g_brBg;+ wc.lpszClassName = WND_CLASS;+ wc.lpszMenuName = NULL; // menu is built programmatically (localizable)+ if (!RegisterClassExW(&wc)) return 1;++ g_hMain = CreateWindowExW(0, WND_CLASS, APP_TITLE, WS_OVERLAPPEDWINDOW,+ CW_USEDEFAULT, CW_USEDEFAULT, 1200, 820, NULL, NULL, hInst, NULL);+ if (!g_hMain) return 1;++ // Center on the working area of the monitor the window landed on (CW_USEDEFAULT places+ // it top-left otherwise).+ {+ RECT wr; GetWindowRect(g_hMain, &wr);+ int ww = wr.right - wr.left, wh = wr.bottom - wr.top;+ HMONITOR mon = MonitorFromWindow(g_hMain, MONITOR_DEFAULTTONEAREST);+ MONITORINFO mi; mi.cbSize = sizeof(mi);+ if (GetMonitorInfoW(mon, &mi))+ {+ int x = mi.rcWork.left + (mi.rcWork.right - mi.rcWork.left - ww) / 2;+ int y = mi.rcWork.top + (mi.rcWork.bottom - mi.rcWork.top - wh) / 2;+ SetWindowPos(g_hMain, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);+ }+ }++ BuildMainMenu(g_hMain);+ DrawMenuBar(g_hMain);+ TrayAdd(g_hMain);+ SyncMenuChecks(g_hMain);+ RebuildProfileMenu(g_hMain);+ UpdateTitle();++ // Wire callbacks + toggles, add configs (before Start so the UDP relay starts), start,+ // then add rules - mirroring the C# startup order.+ g_api.SetLocalhostViaProxy(g_localhost);+ g_api.SetTrafficLoggingEnabled(g_trafficLog);+ g_api.SetLogCallback(PBLogCb);+ g_api.SetConnectionCallback(PBConnCb);+ ApplyConfigs();+ g_started = g_api.Start();+ if (g_started) { ApplyRules(); LogStoreAdd(&g_actStore, T(S_STARTED)); }+ else LogStoreAdd(&g_actStore, T(S_STARTFAIL));++ if (startMinimized) ShowWindow(g_hMain, SW_HIDE); // launched by the logon task+ else { ShowWindow(g_hMain, show); UpdateWindow(g_hMain); }++ // Silent update check on startup (opt-out via the notification's "Don't Ask Again").+ if (PB_GetCheckUpdates()) UpdStartCheck(g_hMain, FALSE);++ MSG msg;+ while (GetMessageW(&msg, NULL, 0, 0) > 0)+ {+ if (IsDialogMessageW(g_hMain, &msg)) continue;+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }+ return (int)msg.wParam;+}diff --git a/Windows/gui/profile/json.h b/Windows/gui/profile/json.hnew file mode 100644index 0000000..4e7bf3a--- /dev/null+++ b/Windows/gui/profile/json.h@@ -0,0 +1,256 @@+// json.h - a compact, dependency-free JSON parser + writer for the GUI.+//+// Just enough to round-trip ProxyBridge's settings.json and *.pbprofile files+// (PascalCase keys). Parser builds a small DOM; writer is a growable UTF-8 string+// buffer with correct escaping. Whitespace/formatting is insignificant, so we emit+// compact-ish indented JSON.+#ifndef PB_JSON_H+#define PB_JSON_H++#include <stdlib.h>+#include <string.h>+#include <stdio.h>++// DOM+typedef enum { J_NULL, J_BOOL, J_NUM, J_STR, J_ARR, J_OBJ } JType;++typedef struct JVal {+ JType type;+ char* key; // member key (owned) - set only for object members+ int bval; // J_BOOL+ double nval; // J_NUM+ char* sval; // J_STR (owned, decoded UTF-8)+ struct JVal* child; // first child (J_ARR / J_OBJ)+ struct JVal* next; // next sibling+} JVal;++// parser+typedef struct { const char* p; const char* end; } JParser;++static JVal* j_new(JType t)+{+ JVal* v = (JVal*)calloc(1, sizeof(JVal));+ if (v) v->type = t;+ return v;+}++static void json_free(JVal* v)+{+ while (v)+ {+ JVal* nx = v->next;+ if (v->child) json_free(v->child);+ free(v->key);+ free(v->sval);+ free(v);+ v = nx;+ }+}++static void j_skip_ws(JParser* s)+{+ while (s->p < s->end)+ {+ char c = *s->p;+ if (c == ' ' || c == '\t' || c == '\r' || c == '\n') s->p++;+ else break;+ }+}++// Decode a JSON string (assumes *s->p == '"'). Returns malloc'd UTF-8, advances past it.+static char* j_parse_string(JParser* s)+{+ if (s->p >= s->end || *s->p != '"') return NULL;+ s->p++;+ size_t cap = 16, len = 0;+ char* out = (char*)malloc(cap);+ if (!out) return NULL;+ while (s->p < s->end && *s->p != '"')+ {+ char c = *s->p++;+ if (c == '\\' && s->p < s->end)+ {+ char e = *s->p++;+ switch (e)+ {+ case '"': c = '"'; break;+ case '\\': c = '\\'; break;+ case '/': c = '/'; break;+ case 'b': c = '\b'; break;+ case 'f': c = '\f'; break;+ case 'n': c = '\n'; break;+ case 'r': c = '\r'; break;+ case 't': c = '\t'; break;+ case 'u':+ {+ if (s->end - s->p < 4) { free(out); return NULL; }+ unsigned cp = 0;+ for (int i = 0; i < 4; i++)+ {+ char h = *s->p++;+ cp <<= 4;+ if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');+ else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);+ else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);+ else { free(out); return NULL; }+ }+ // Encode code point as UTF-8 (BMP only; surrogate pairs are rare in our files).+ char buf[4]; int n = 0;+ if (cp < 0x80) buf[n++] = (char)cp;+ else if (cp < 0x800) { buf[n++] = (char)(0xC0 | (cp >> 6)); buf[n++] = (char)(0x80 | (cp & 0x3F)); }+ else { buf[n++] = (char)(0xE0 | (cp >> 12)); buf[n++] = (char)(0x80 | ((cp >> 6) & 0x3F)); buf[n++] = (char)(0x80 | (cp & 0x3F)); }+ for (int i = 0; i < n; i++)+ {+ if (len + 1 >= cap) { cap *= 2; char* t = (char*)realloc(out, cap); if (!t) { free(out); return NULL; } out = t; }+ out[len++] = buf[i];+ }+ continue;+ }+ default: c = e; break;+ }+ }+ if (len + 1 >= cap) { cap *= 2; char* t = (char*)realloc(out, cap); if (!t) { free(out); return NULL; } out = t; }+ out[len++] = c;+ }+ if (s->p < s->end && *s->p == '"') s->p++;+ out[len] = 0;+ return out;+}++static JVal* j_parse_value(JParser* s);++static JVal* j_parse_container(JParser* s, char open, char close, JType type)+{+ s->p++; // consume open+ JVal* node = j_new(type);+ if (!node) return NULL;+ JVal* tail = NULL;+ j_skip_ws(s);+ if (s->p < s->end && *s->p == close) { s->p++; return node; }+ while (s->p < s->end)+ {+ j_skip_ws(s);+ char* key = NULL;+ if (type == J_OBJ)+ {+ key = j_parse_string(s);+ j_skip_ws(s);+ if (s->p < s->end && *s->p == ':') s->p++;+ }+ JVal* val = j_parse_value(s);+ if (!val) { free(key); json_free(node); return NULL; }+ val->key = key;+ if (tail) tail->next = val; else node->child = val;+ tail = val;+ j_skip_ws(s);+ if (s->p < s->end && *s->p == ',') { s->p++; continue; }+ if (s->p < s->end && *s->p == close) { s->p++; break; }+ break;+ }+ (void)open;+ return node;+}++static JVal* j_parse_value(JParser* s)+{+ j_skip_ws(s);+ if (s->p >= s->end) return NULL;+ char c = *s->p;+ if (c == '{') return j_parse_container(s, '{', '}', J_OBJ);+ if (c == '[') return j_parse_container(s, '[', ']', J_ARR);+ if (c == '"') { char* str = j_parse_string(s); JVal* v = j_new(J_STR); if (v) v->sval = str; else free(str); return v; }+ if (c == 't') { if (s->end - s->p >= 4 && strncmp(s->p, "true", 4) == 0) { s->p += 4; JVal* v = j_new(J_BOOL); if (v) v->bval = 1; return v; } return NULL; }+ if (c == 'f') { if (s->end - s->p >= 5 && strncmp(s->p, "false", 5) == 0) { s->p += 5; JVal* v = j_new(J_BOOL); if (v) v->bval = 0; return v; } return NULL; }+ if (c == 'n') { if (s->end - s->p >= 4 && strncmp(s->p, "null", 4) == 0) { s->p += 4; return j_new(J_NULL); } return NULL; }+ // number+ {+ char numbuf[64]; int n = 0;+ while (s->p < s->end && n < 63)+ {+ char d = *s->p;+ if ((d >= '0' && d <= '9') || d == '-' || d == '+' || d == '.' || d == 'e' || d == 'E') { numbuf[n++] = d; s->p++; }+ else break;+ }+ numbuf[n] = 0;+ if (n == 0) return NULL;+ JVal* v = j_new(J_NUM);+ if (v) v->nval = atof(numbuf);+ return v;+ }+}++// Parse a whole document. Returns root (owned) or NULL.+static JVal* json_parse(const char* text, size_t length)+{+ JParser s; s.p = text; s.end = text + length;+ return j_parse_value(&s);+}++// DOM accessors+static JVal* json_get(const JVal* obj, const char* key)+{+ if (!obj || obj->type != J_OBJ) return NULL;+ for (JVal* c = obj->child; c; c = c->next)+ if (c->key && strcmp(c->key, key) == 0) return c;+ return NULL;+}++static const char* json_str(const JVal* obj, const char* key, const char* def)+{+ JVal* v = json_get(obj, key);+ return (v && v->type == J_STR && v->sval) ? v->sval : def;+}++static int json_bool(const JVal* obj, const char* key, int def)+{+ JVal* v = json_get(obj, key);+ return (v && v->type == J_BOOL) ? v->bval : def;+}++static long json_long(const JVal* obj, const char* key, long def)+{+ JVal* v = json_get(obj, key);+ return (v && v->type == J_NUM) ? (long)v->nval : def;+}++// writer (growable UTF-8 buffer)+typedef struct { char* buf; size_t len, cap; } StrBuf;++static void sb_init(StrBuf* b) { b->cap = 256; b->len = 0; b->buf = (char*)malloc(b->cap); if (b->buf) b->buf[0] = 0; }+static void sb_free(StrBuf* b) { free(b->buf); b->buf = NULL; }+static void sb_putn(StrBuf* b, const char* s, size_t n)+{+ if (!b->buf) return;+ if (b->len + n + 1 > b->cap) { while (b->len + n + 1 > b->cap) b->cap *= 2; char* t = (char*)realloc(b->buf, b->cap); if (!t) return; b->buf = t; }+ memcpy(b->buf + b->len, s, n); b->len += n; b->buf[b->len] = 0;+}+static void sb_put(StrBuf* b, const char* s) { sb_putn(b, s, strlen(s)); }++// Append a JSON-escaped string literal (with surrounding quotes).+static void sb_json_str(StrBuf* b, const char* s)+{+ sb_put(b, "\"");+ if (s)+ {+ for (const unsigned char* p = (const unsigned char*)s; *p; p++)+ {+ unsigned char c = *p;+ switch (c)+ {+ case '"': sb_put(b, "\\\""); break;+ case '\\': sb_put(b, "\\\\"); break;+ case '\b': sb_put(b, "\\b"); break;+ case '\f': sb_put(b, "\\f"); break;+ case '\n': sb_put(b, "\\n"); break;+ case '\r': sb_put(b, "\\r"); break;+ case '\t': sb_put(b, "\\t"); break;+ default:+ if (c < 0x20) { char u[8]; snprintf(u, sizeof(u), "\\u%04x", c); sb_put(b, u); }+ else { char ch = (char)c; sb_putn(b, &ch, 1); } // pass UTF-8 bytes through+ }+ }+ }+ sb_put(b, "\"");+}++#endif // PB_JSON_Hdiff --git a/Windows/gui/profile/profile.c b/Windows/gui/profile/profile.cnew file mode 100644index 0000000..fec3d1d--- /dev/null+++ b/Windows/gui/profile/profile.c@@ -0,0 +1,364 @@+// profile.c - settings.json + *.pbprofile I/O (see profile.h).+#ifndef UNICODE+#define UNICODE+#endif+#include <windows.h>+#include <stdio.h>+#include <string.h>+#include "profile.h"+#include "json.h"++// UTF-8 <-> UTF-16+static void u2w(const char* s, wchar_t* out, int cch)+{+ if (!s) { if (cch) out[0] = 0; return; }+ MultiByteToWideChar(CP_UTF8, 0, s, -1, out, cch);+}+static void w2u(const wchar_t* w, char* out, int cch)+{+ if (!w) { if (cch) out[0] = 0; return; }+ WideCharToMultiByte(CP_UTF8, 0, w, -1, out, cch, NULL, NULL);+}++// paths+static void base_dir(wchar_t* out, int cch)+{+ wchar_t appdata[MAX_PATH];+ if (!GetEnvironmentVariableW(L"APPDATA", appdata, MAX_PATH)) appdata[0] = 0;+ _snwprintf_s(out, cch, _TRUNCATE, L"%s\\ProxyBridge", appdata);+}+static void settings_path(wchar_t* out, int cch)+{ wchar_t b[MAX_PATH]; base_dir(b, MAX_PATH); _snwprintf_s(out, cch, _TRUNCATE, L"%s\\settings.json", b); }+static void profiles_dir(wchar_t* out, int cch)+{ wchar_t b[MAX_PATH]; base_dir(b, MAX_PATH); _snwprintf_s(out, cch, _TRUNCATE, L"%s\\profiles", b); }+static void profile_path(const wchar_t* name, wchar_t* out, int cch)+{ wchar_t d[MAX_PATH]; profiles_dir(d, MAX_PATH); _snwprintf_s(out, cch, _TRUNCATE, L"%s\\%s.pbprofile", d, name); }+static void ensure_dirs(void)+{+ wchar_t b[MAX_PATH], d[MAX_PATH];+ base_dir(b, MAX_PATH); CreateDirectoryW(b, NULL);+ profiles_dir(d, MAX_PATH); CreateDirectoryW(d, NULL);+}++// file helpers+static char* read_file(const wchar_t* path, DWORD* outLen)+{+ HANDLE h = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);+ if (h == INVALID_HANDLE_VALUE) return NULL;+ DWORD sz = GetFileSize(h, NULL);+ if (sz == INVALID_FILE_SIZE || sz > (64u * 1024u * 1024u)) { CloseHandle(h); return NULL; }+ char* buf = (char*)malloc(sz + 1);+ if (!buf) { CloseHandle(h); return NULL; }+ DWORD rd = 0;+ BOOL ok = ReadFile(h, buf, sz, &rd, NULL);+ CloseHandle(h);+ if (!ok) { free(buf); return NULL; }+ buf[rd] = 0;+ if (rd >= 3 && (unsigned char)buf[0] == 0xEF && (unsigned char)buf[1] == 0xBB && (unsigned char)buf[2] == 0xBF)+ { memmove(buf, buf + 3, rd - 3 + 1); rd -= 3; }+ if (outLen) *outLen = rd;+ return buf;+}++static BOOL write_file_atomic(const wchar_t* path, const char* data, size_t len)+{+ wchar_t tmp[MAX_PATH]; _snwprintf_s(tmp, MAX_PATH, _TRUNCATE, L"%s.tmp", path);+ HANDLE h = CreateFileW(tmp, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);+ if (h == INVALID_HANDLE_VALUE) return FALSE;+ DWORD wr = 0;+ BOOL ok = WriteFile(h, data, (DWORD)len, &wr, NULL) && wr == (DWORD)len;+ CloseHandle(h);+ if (!ok) { DeleteFileW(tmp); return FALSE; }+ if (!MoveFileExW(tmp, path, MOVEFILE_REPLACE_EXISTING)) { DeleteFileW(tmp); return FALSE; }+ return TRUE;+}++// settings.json - all fields loaded/saved together so each public accessor only touches+// the one it cares about while preserving the rest.+typedef struct { int checkUpd, startWin; char lastCheck[64]; char activeName[256]; } Settings;++static void settings_load(Settings* s)+{+ s->checkUpd = 1; s->startWin = 0;+ strcpy_s(s->lastCheck, sizeof(s->lastCheck), "0001-01-01T00:00:00");+ strcpy_s(s->activeName, sizeof(s->activeName), "Default");+ wchar_t sp[MAX_PATH]; settings_path(sp, MAX_PATH);+ DWORD len = 0; char* txt = read_file(sp, &len);+ if (!txt) return;+ JVal* root = json_parse(txt, len);+ if (root)+ {+ s->checkUpd = json_bool(root, "CheckForUpdatesOnStartup", 1);+ s->startWin = json_bool(root, "StartWithWindows", 0);+ const char* lc = json_str(root, "LastUpdateCheck", NULL);+ if (lc) strncpy_s(s->lastCheck, sizeof(s->lastCheck), lc, _TRUNCATE);+ const char* an = json_str(root, "ActiveProfileName", NULL);+ if (an) strncpy_s(s->activeName, sizeof(s->activeName), an, _TRUNCATE);+ json_free(root);+ }+ free(txt);+}++static void settings_save(const Settings* s)+{+ ensure_dirs();+ wchar_t sp[MAX_PATH]; settings_path(sp, MAX_PATH);+ StrBuf b; sb_init(&b);+ sb_put(&b, "{\n");+ sb_put(&b, " \"CheckForUpdatesOnStartup\": "); sb_put(&b, s->checkUpd ? "true" : "false"); sb_put(&b, ",\n");+ sb_put(&b, " \"LastUpdateCheck\": "); sb_json_str(&b, s->lastCheck); sb_put(&b, ",\n");+ sb_put(&b, " \"StartWithWindows\": "); sb_put(&b, s->startWin ? "true" : "false"); sb_put(&b, ",\n");+ sb_put(&b, " \"ActiveProfileName\": "); sb_json_str(&b, s->activeName); sb_put(&b, "\n}\n");+ write_file_atomic(sp, b.buf, b.len);+ sb_free(&b);+}++void PB_GetActiveProfile(wchar_t* out, int cch)+{+ Settings s; settings_load(&s);+ u2w(s.activeName, out, cch);+}++void PB_SetActiveProfile(const wchar_t* name)+{+ Settings s; settings_load(&s);+ w2u(name, s.activeName, sizeof(s.activeName));+ settings_save(&s);+}++BOOL PB_GetCheckUpdates(void)+{+ Settings s; settings_load(&s);+ return s.checkUpd ? TRUE : FALSE;+}++void PB_SetCheckUpdates(BOOL enable)+{+ Settings s; settings_load(&s);+ s.checkUpd = enable ? 1 : 0;+ settings_save(&s);+}++// *.pbprofile+void PB_ProfileDefaults(PBProfile* p, const wchar_t* name)+{+ (void)name;+ ZeroMemory(p, sizeof(*p));+ p->localhostViaProxy = 0;+ p->trafficLogging = 1;+ p->autoClearLogs = 1;+ p->closeToTray = 1;+ lstrcpynW(p->language, L"en", 8);+}++void PB_ProfileLoad(const wchar_t* name, PBProfile* p)+{+ PB_ProfileDefaults(p, name);+ wchar_t pp[MAX_PATH]; profile_path(name, pp, MAX_PATH);+ DWORD len = 0; char* txt = read_file(pp, &len);+ if (!txt) return;+ JVal* root = json_parse(txt, len);+ if (root && root->type == J_OBJ)+ {+ p->localhostViaProxy = json_bool(root, "LocalhostViaProxy", 0);+ p->trafficLogging = json_bool(root, "IsTrafficLoggingEnabled", 1);+ p->autoClearLogs = json_bool(root, "AutoClearConnectionLogs", 1);+ p->closeToTray = json_bool(root, "CloseToTray", 1);+ u2w(json_str(root, "Language", "en"), p->language, 8);++ JVal* cfgs = json_get(root, "ProxyConfigs");+ if (cfgs && cfgs->type == J_ARR)+ for (JVal* c = cfgs->child; c && p->cfgCount < PB_MAX_CFG; c = c->next)+ {+ if (c->type != J_OBJ) continue;+ PBConfig* cf = &p->cfg[p->cfgCount++];+ cf->storedId = (UINT32)json_long(c, "Id", 0);+ u2w(json_str(c, "Type", "SOCKS5"), cf->type, 16);+ u2w(json_str(c, "Host", ""), cf->host, 128);+ u2w(json_str(c, "Port", ""), cf->port, 16);+ u2w(json_str(c, "Username", ""), cf->user, 128);+ u2w(json_str(c, "Password", ""), cf->pass, 128);+ }++ JVal* rules = json_get(root, "ProxyRules");+ if (rules && rules->type == J_ARR)+ for (JVal* r = rules->child; r && p->ruleCount < PB_MAX_RULE; r = r->next)+ {+ if (r->type != J_OBJ) continue;+ PBRule* ru = &p->rule[p->ruleCount++];+ u2w(json_str(r, "ProcessName", "*"), ru->proc, 256);+ u2w(json_str(r, "TargetHosts", "*"), ru->hosts, 256);+ u2w(json_str(r, "TargetPorts", "*"), ru->ports, 128);+ u2w(json_str(r, "TargetDomains", "*"), ru->domains, 256);+ u2w(json_str(r, "Protocol", "TCP"), ru->proto, 8);+ u2w(json_str(r, "Action", "PROXY"), ru->action, 16);+ ru->enabled = json_bool(r, "IsEnabled", 1);+ ru->cfgStoredId = (UINT32)json_long(r, "ProxyConfigId", 0);+ }++ JVal* filters = json_get(root, "LogFilters");+ if (filters && filters->type == J_ARR)+ for (JVal* f = filters->child; f && p->filterCount < PB_MAX_FILTER; f = f->next)+ {+ if (f->type != J_OBJ) continue;+ PBFilter* fi = &p->filter[p->filterCount++];+ u2w(json_str(f, "Mode", "Include"), fi->mode, 16);+ u2w(json_str(f, "ProcessName", ""), fi->proc, 256);+ u2w(json_str(f, "Ip", ""), fi->ip, 64);+ u2w(json_str(f, "Port", ""), fi->port, 16);+ u2w(json_str(f, "Protocol", "All"), fi->proto, 8);+ u2w(json_str(f, "Action", "All"), fi->action, 16);+ }+ }+ if (root) json_free(root);+ free(txt);+}++static void put_kv_str(StrBuf* b, const char* indent, const char* key, const wchar_t* wval, const char* trail)+{+ char tmp[1024]; w2u(wval, tmp, sizeof(tmp));+ sb_put(b, indent); sb_put(b, "\""); sb_put(b, key); sb_put(b, "\": ");+ sb_json_str(b, tmp); sb_put(b, trail);+}++BOOL PB_ProfileSave(const wchar_t* name, const PBProfile* p)+{+ ensure_dirs();+ char tmp[1024];+ StrBuf b; sb_init(&b);+ sb_put(&b, "{\n");+ sb_put(&b, " \"Version\": \"1.0\",\n");+ put_kv_str(&b, " ", "Name", name, ",\n");+ sb_put(&b, " \"LocalhostViaProxy\": "); sb_put(&b, p->localhostViaProxy ? "true" : "false"); sb_put(&b, ",\n");+ sb_put(&b, " \"IsTrafficLoggingEnabled\": "); sb_put(&b, p->trafficLogging ? "true" : "false"); sb_put(&b, ",\n");+ sb_put(&b, " \"AutoClearConnectionLogs\": "); sb_put(&b, p->autoClearLogs ? "true" : "false"); sb_put(&b, ",\n");+ put_kv_str(&b, " ", "Language", p->language, ",\n");+ sb_put(&b, " \"CloseToTray\": "); sb_put(&b, p->closeToTray ? "true" : "false"); sb_put(&b, ",\n");++ sb_put(&b, " \"ProxyConfigs\": [");+ for (int i = 0; i < p->cfgCount; i++)+ {+ const PBConfig* c = &p->cfg[i];+ sb_put(&b, i ? ",\n" : "\n"); sb_put(&b, " {\n");+ snprintf(tmp, sizeof(tmp), "%u", c->storedId);+ sb_put(&b, " \"Id\": "); sb_put(&b, tmp); sb_put(&b, ",\n");+ put_kv_str(&b, " ", "Type", c->type, ",\n");+ put_kv_str(&b, " ", "Host", c->host, ",\n");+ put_kv_str(&b, " ", "Port", c->port, ",\n");+ put_kv_str(&b, " ", "Username", c->user, ",\n");+ put_kv_str(&b, " ", "Password", c->pass, "\n");+ sb_put(&b, " }");+ }+ sb_put(&b, p->cfgCount ? "\n ],\n" : "],\n");++ sb_put(&b, " \"ProxyRules\": [");+ for (int i = 0; i < p->ruleCount; i++)+ {+ const PBRule* r = &p->rule[i];+ sb_put(&b, i ? ",\n" : "\n"); sb_put(&b, " {\n");+ put_kv_str(&b, " ", "ProcessName", r->proc, ",\n");+ put_kv_str(&b, " ", "TargetHosts", r->hosts, ",\n");+ put_kv_str(&b, " ", "TargetPorts", r->ports, ",\n");+ put_kv_str(&b, " ", "TargetDomains", r->domains, ",\n");+ put_kv_str(&b, " ", "Protocol", r->proto, ",\n");+ put_kv_str(&b, " ", "Action", r->action, ",\n");+ sb_put(&b, " \"IsEnabled\": "); sb_put(&b, r->enabled ? "true" : "false"); sb_put(&b, ",\n");+ snprintf(tmp, sizeof(tmp), "%u", r->cfgStoredId);+ sb_put(&b, " \"ProxyConfigId\": "); sb_put(&b, tmp); sb_put(&b, "\n");+ sb_put(&b, " }");+ }+ sb_put(&b, p->ruleCount ? "\n ],\n" : "],\n");++ sb_put(&b, " \"LogFilters\": [");+ for (int i = 0; i < p->filterCount; i++)+ {+ const PBFilter* f = &p->filter[i];+ sb_put(&b, i ? ",\n" : "\n"); sb_put(&b, " {\n");+ put_kv_str(&b, " ", "Mode", f->mode, ",\n");+ put_kv_str(&b, " ", "ProcessName", f->proc, ",\n");+ put_kv_str(&b, " ", "Ip", f->ip, ",\n");+ put_kv_str(&b, " ", "Port", f->port, ",\n");+ put_kv_str(&b, " ", "Protocol", f->proto, ",\n");+ put_kv_str(&b, " ", "Action", f->action, "\n");+ sb_put(&b, " }");+ }+ sb_put(&b, p->filterCount ? "\n ]\n" : "]\n");+ sb_put(&b, "}\n");++ wchar_t pp[MAX_PATH]; profile_path(name, pp, MAX_PATH);+ BOOL ok = write_file_atomic(pp, b.buf, b.len);+ sb_free(&b);+ return ok;+}++// management+int PB_ProfileList(wchar_t names[][PB_NAME_MAX], int maxNames)+{+ ensure_dirs();+ wchar_t dir[MAX_PATH], pat[MAX_PATH];+ profiles_dir(dir, MAX_PATH);+ _snwprintf_s(pat, MAX_PATH, _TRUNCATE, L"%s\\*.pbprofile", dir);+ WIN32_FIND_DATAW fd; HANDLE h = FindFirstFileW(pat, &fd);+ int n = 0;+ if (h != INVALID_HANDLE_VALUE)+ {+ do {+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;+ wchar_t nm[PB_NAME_MAX]; lstrcpynW(nm, fd.cFileName, PB_NAME_MAX);+ size_t l = wcslen(nm);+ if (l > 10 && _wcsicmp(nm + l - 10, L".pbprofile") == 0) nm[l - 10] = 0;+ if (n < maxNames) lstrcpynW(names[n++], nm, PB_NAME_MAX);+ } while (FindNextFileW(h, &fd));+ FindClose(h);+ }+ return n;+}++BOOL PB_ProfileDelete(const wchar_t* name)+{+ wchar_t pp[MAX_PATH]; profile_path(name, pp, MAX_PATH);+ return DeleteFileW(pp);+}++BOOL PB_ProfileRename(const wchar_t* oldName, const wchar_t* newName)+{+ if (!newName || !newName[0]) return FALSE;+ wchar_t src[MAX_PATH], dst[MAX_PATH];+ profile_path(oldName, src, MAX_PATH);+ profile_path(newName, dst, MAX_PATH);+ if (GetFileAttributesW(dst) != INVALID_FILE_ATTRIBUTES) return FALSE; // target exists+ if (!MoveFileW(src, dst)) return FALSE;+ // Repoint the active-profile setting if we just renamed the active one.+ wchar_t active[PB_NAME_MAX]; PB_GetActiveProfile(active, PB_NAME_MAX);+ if (_wcsicmp(active, oldName) == 0) PB_SetActiveProfile(newName);+ return TRUE;+}++BOOL PB_ProfileExport(const wchar_t* name, const wchar_t* destPath)+{+ wchar_t pp[MAX_PATH]; profile_path(name, pp, MAX_PATH);+ return CopyFileW(pp, destPath, FALSE);+}++BOOL PB_ProfileImport(const wchar_t* srcPath, wchar_t* assignedName, int cch)+{+ const wchar_t* fn = wcsrchr(srcPath, L'\\'); fn = fn ? fn + 1 : srcPath;+ wchar_t base[PB_NAME_MAX]; lstrcpynW(base, fn, PB_NAME_MAX);+ size_t l = wcslen(base);+ if (l > 10 && _wcsicmp(base + l - 10, L".pbprofile") == 0) base[l - 10] = 0;+ if (!base[0]) lstrcpynW(base, L"Imported", PB_NAME_MAX);+ for (wchar_t* q = base; *q; q++) if (wcschr(L"<>:\"/\\|?*", *q)) *q = L'_';++ wchar_t name[PB_NAME_MAX]; lstrcpynW(name, base, PB_NAME_MAX);+ for (int i = 2; i <= 99; i++)+ {+ wchar_t pp[MAX_PATH]; profile_path(name, pp, MAX_PATH);+ if (GetFileAttributesW(pp) == INVALID_FILE_ATTRIBUTES) break;+ _snwprintf_s(name, PB_NAME_MAX, _TRUNCATE, L"%s (%d)", base, i);+ }+ ensure_dirs();+ wchar_t dpp[MAX_PATH]; profile_path(name, dpp, MAX_PATH);+ if (!CopyFileW(srcPath, dpp, FALSE)) return FALSE;+ lstrcpynW(assignedName, name, cch);+ return TRUE;+}diff --git a/Windows/gui/profile/profile.h b/Windows/gui/profile/profile.hnew file mode 100644index 0000000..444bfb1--- /dev/null+++ b/Windows/gui/profile/profile.h@@ -0,0 +1,76 @@+// profile.h - read/write settings.json + *.pbprofile.+//+// Storage:+// %APPDATA%\ProxyBridge\settings.json -> { ActiveProfileName, ... }+// %APPDATA%\ProxyBridge\profiles\<name>.pbprofile -> ProxyProfile (PascalCase JSON)+//+// The in-memory struct holds every profile field - including LogFilters, which have no+// editor yet but are round-tripped verbatim so nothing is lost on save.+#ifndef PB_PROFILE_H+#define PB_PROFILE_H++#include <windows.h>++#define PB_MAX_CFG 32+#define PB_MAX_RULE 128+#define PB_MAX_FILTER 64+#define PB_NAME_MAX 64++typedef struct {+ UINT32 storedId; // Id as written in the profile+ UINT32 nativeId; // id returned by AddProxyConfig after apply+ wchar_t type[16]; // "SOCKS5" | "HTTP"+ wchar_t host[128];+ wchar_t port[16];+ wchar_t user[128];+ wchar_t pass[128];+} PBConfig;++typedef struct {+ UINT32 nativeId; // id returned by AddRule after apply+ wchar_t proc[256];+ wchar_t hosts[256];+ wchar_t ports[128];+ wchar_t domains[256];+ wchar_t proto[8]; // "TCP" | "UDP" | "BOTH"+ wchar_t action[16]; // "PROXY" | "DIRECT" | "BLOCK"+ int enabled;+ UINT32 cfgStoredId; // ProxyConfigId as written in the profile+} PBRule;++typedef struct {+ wchar_t mode[16], proc[256], ip[64], port[16], proto[8], action[16];+} PBFilter;++typedef struct {+ int localhostViaProxy;+ int trafficLogging;+ int autoClearLogs;+ int closeToTray;+ wchar_t language[8]; // "en" | "zh"+ PBConfig cfg[PB_MAX_CFG]; int cfgCount;+ PBRule rule[PB_MAX_RULE]; int ruleCount;+ PBFilter filter[PB_MAX_FILTER]; int filterCount;+} PBProfile;++// settings.json (active profile pointer). Other settings fields are preserved on write.+void PB_GetActiveProfile(wchar_t* out, int cch);+void PB_SetActiveProfile(const wchar_t* name);++// settings.json - "check for updates on startup" flag (preserves the other fields).+BOOL PB_GetCheckUpdates(void);+void PB_SetCheckUpdates(BOOL enable);++// *.pbprofile. Load fills defaults if the file is missing/invalid.+void PB_ProfileDefaults(PBProfile* p, const wchar_t* name);+void PB_ProfileLoad(const wchar_t* name, PBProfile* p);+BOOL PB_ProfileSave(const wchar_t* name, const PBProfile* p);++// Management.+int PB_ProfileList(wchar_t names[][PB_NAME_MAX], int maxNames); // returns count+BOOL PB_ProfileDelete(const wchar_t* name);+BOOL PB_ProfileRename(const wchar_t* oldName, const wchar_t* newName);+BOOL PB_ProfileImport(const wchar_t* srcPath, wchar_t* assignedName, int cch);+BOOL PB_ProfileExport(const wchar_t* name, const wchar_t* destPath);++#endif // PB_PROFILE_Hdiff --git a/Windows/gui/res/app.manifest b/Windows/gui/res/app.manifestnew file mode 100644index 0000000..4a8e4ac--- /dev/null+++ b/Windows/gui/res/app.manifest@@ -0,0 +1,31 @@+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">+ <assemblyIdentity version="4.0.9.0" processorArchitecture="*" name="InterceptSuite.ProxyBridge.NativeGUI" type="win32"/>+ <!-- Require administrator: WinDivert needs elevation to load its kernel driver. -->+ <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">+ <security>+ <requestedPrivileges>+ <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>+ </requestedPrivileges>+ </security>+ </trustInfo>+ <!-- Common Controls v6 for themed tabs / listview / buttons. -->+ <dependency>+ <dependentAssembly>+ <assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls"+ version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>+ </dependentAssembly>+ </dependency>+ <!-- Per-monitor DPI awareness + modern Windows compatibility. -->+ <application xmlns="urn:schemas-microsoft-com:asm.v3">+ <windowsSettings>+ <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>+ </windowsSettings>+ </application>+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">+ <application>+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/> <!-- Windows 10/11 -->+ </application>+ </compatibility>+</assembly>diff --git a/Windows/gui/res/app.rc b/Windows/gui/res/app.rcnew file mode 100644index 0000000..9d77429--- /dev/null+++ b/Windows/gui/res/app.rc@@ -0,0 +1,234 @@+#include <windows.h>+#include "resource.h"++// Application icon (reuse the shared logo)+IDI_APPICON ICON "logo.ico"++// Embedded manifest (admin + Common Controls v6 + DPI)+1 24 "app.manifest"++// Version info (exe Properties → Details); numbers come from resource.h+VS_VERSION_INFO VERSIONINFO+ FILEVERSION PB_VER_MAJOR,PB_VER_MINOR,PB_VER_PATCH,PB_VER_BUILD+ PRODUCTVERSION PB_VER_MAJOR,PB_VER_MINOR,PB_VER_PATCH,PB_VER_BUILD+ FILEFLAGSMASK 0x3fL+ FILEFLAGS 0x0L+ FILEOS VOS_NT_WINDOWS32+ FILETYPE VFT_APP+ FILESUBTYPE 0x0L+BEGIN+ BLOCK "StringFileInfo"+ BEGIN+ BLOCK "040904b0"+ BEGIN+ VALUE "CompanyName", "InterceptSuite"+ VALUE "FileDescription", "Universal proxy client for Windows applications"+ VALUE "FileVersion", PB_VER_STR+ VALUE "InternalName", "ProxyBridge"+ VALUE "OriginalFilename", "ProxyBridge.exe"+ VALUE "ProductName", "ProxyBridge"+ VALUE "ProductVersion", PB_VER_STR+ VALUE "LegalCopyright", "Copyright (c) 2026 InterceptSuite"+ END+ END+ BLOCK "VarFileInfo"+ BEGIN+ VALUE "Translation", 0x409, 1200+ END+END++// Note: the menu is built programmatically in main.c (from loc.h) so it can be localized+// at runtime - there is no menu resource here on purpose.++// Proxy Servers (list) dialog+IDD_SERVERS DIALOGEX 0, 0, 340, 176+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Proxy Servers"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ CONTROL "", IDC_SV_LIST, "SysListView32",+ LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SINGLESEL | WS_BORDER | WS_TABSTOP,+ 8, 8, 258, 138+ PUSHBUTTON "Add...", IDC_SV_ADD, 274, 8, 58, 15+ PUSHBUTTON "Edit...", IDC_SV_EDIT, 274, 28, 58, 15+ PUSHBUTTON "Remove", IDC_SV_REMOVE, 274, 48, 58, 15+ PUSHBUTTON "Proxy Test", IDC_SV_CHECK, 274, 72, 58, 15+ DEFPUSHBUTTON "Close", IDCANCEL, 274, 155, 58, 15+END++// Proxy Server (edit) sub-dialog+IDD_SERVER DIALOGEX 0, 0, 244, 176+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Proxy Server"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ GROUPBOX "Server", IDC_SE_G_SERVER, 8, 6, 228, 66+ LTEXT "Address:", IDC_SE_L_ADDR, 18, 24, 44, 10+ EDITTEXT IDC_SE_ADDR, 66, 22, 108, 12, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "Port:", IDC_SE_L_PORT, 182, 24, 20, 10+ EDITTEXT IDC_SE_PORT, 204, 22, 24, 12, ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP+ LTEXT "Protocol:", IDC_SE_L_PROTO, 18, 48, 44, 10+ COMBOBOX IDC_SE_PROTO, 66, 46, 108, 80, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP+ GROUPBOX "Authentication", IDC_SE_G_AUTH, 8, 80, 228, 66+ AUTOCHECKBOX "Enable", IDC_SE_AUTH, 18, 96, 60, 10+ LTEXT "Username:", IDC_SE_L_USER, 18, 114, 44, 10+ EDITTEXT IDC_SE_USER, 66, 112, 162, 12, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "Password:", IDC_SE_L_PASS, 18, 130, 44, 10+ EDITTEXT IDC_SE_PASS, 66, 128, 162, 12, ES_AUTOHSCROLL | ES_PASSWORD | WS_TABSTOP+ DEFPUSHBUTTON "OK", IDOK, 128, 156, 50, 14+ PUSHBUTTON "Cancel", IDCANCEL, 186, 156, 50, 14+END++// Proxy Checker dialog+IDD_CHECKER DIALOGEX 0, 0, 360, 236+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Proxy Checker"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ LTEXT "Host:", IDC_CK_L_HOST, 8, 10, 20, 10+ EDITTEXT IDC_CK_HOST, 30, 8, 118, 12, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "Port:", IDC_CK_L_PORT, 154, 10, 18, 10+ EDITTEXT IDC_CK_PORT, 174, 8, 32, 12, ES_AUTOHSCROLL | ES_NUMBER | WS_TABSTOP+ PUSHBUTTON "Retest", IDC_CK_RETEST, 240, 7, 52, 14+ DEFPUSHBUTTON "Close", IDCANCEL, 300, 7, 52, 14+ EDITTEXT IDC_CK_LOG, 8, 28, 344, 200,+ ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_BORDER | NOT WS_TABSTOP+END++// Proxification Rules (list) dialog+IDD_RULES DIALOGEX 0, 0, 540, 300+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Proxy Rules"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ PUSHBUTTON "Add...", IDC_RL_ADD, 8, 8, 60, 16+ PUSHBUTTON "Clone", IDC_RL_CLONE, 72, 8, 60, 16+ PUSHBUTTON "Edit...", IDC_RL_EDIT, 136, 8, 60, 16+ PUSHBUTTON "Remove", IDC_RL_REMOVE,200, 8, 60, 16+ CONTROL "", IDC_RL_LIST, "SysListView32",+ LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SINGLESEL | WS_BORDER | WS_TABSTOP,+ 8, 30, 500, 232+ PUSHBUTTON "Move Up", IDC_RL_UP, 516, 30, 18, 16+ PUSHBUTTON "Move Down", IDC_RL_DOWN, 516, 52, 18, 16+ LTEXT "Rules are checked top to bottom; use the check box to enable/disable a rule.",+ IDC_RL_HINT, 8, 270, 400, 11+ DEFPUSHBUTTON "Close", IDCANCEL, 456, 278, 60, 16+END++// Proxification Rule (edit) sub-dialog+IDD_RULE DIALOGEX 0, 0, 400, 272+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Proxy Rule"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ AUTOCHECKBOX "Enabled", IDC_RE_ENABLED, 330, 10, 62, 10+ LTEXT "Applications:", IDC_RE_L_APPS, 8, 10, 80, 10+ EDITTEXT IDC_RE_APPS, 92, 8, 176, 13, ES_AUTOHSCROLL | WS_TABSTOP+ PUSHBUTTON "Browse...", IDC_RE_BROWSE, 272, 7, 50, 14+ LTEXT "", IDC_RE_EX_APPS, 92, 24, 300, 9++ LTEXT "Target Hosts:", IDC_RE_L_HOSTS, 8, 40, 80, 10+ EDITTEXT IDC_RE_HOSTS, 92, 38, 300, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "", IDC_RE_EX_HOSTS, 92, 54, 300, 9++ LTEXT "Target Ports:", IDC_RE_L_PORTS, 8, 70, 80, 10+ EDITTEXT IDC_RE_PORTS, 92, 68, 300, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "", IDC_RE_EX_PORTS, 92, 84, 300, 9++ LTEXT "Target Domains:", IDC_RE_L_DOMAINS, 8, 100, 80, 10+ EDITTEXT IDC_RE_DOMAINS, 92, 98, 300, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "", IDC_RE_EX_DOMAINS,92, 114, 300, 9++ LTEXT "Protocol:", IDC_RE_L_PROTO, 8, 130, 80, 10+ COMBOBOX IDC_RE_PROTO, 92, 128, 110, 80, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP+ LTEXT "", IDC_RE_UDPNOTE, 92, 146, 300, 40++ LTEXT "Action:", IDC_RE_L_ACTION, 8, 192, 80, 10+ COMBOBOX IDC_RE_ACTION, 92, 190, 300,160, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP++ DEFPUSHBUTTON "OK", IDOK, 282, 250, 52, 14+ PUSHBUTTON "Cancel", IDCANCEL, 338, 250, 52, 14+END++// Log Filters (list) dialog+IDD_FILTERS DIALOGEX 0, 0, 460, 260+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Log Filters"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ LTEXT "", IDC_FL_DESC, 8, 6, 444, 40+ PUSHBUTTON "Add...", IDC_FL_ADD, 8, 50, 60, 16+ PUSHBUTTON "Edit...", IDC_FL_EDIT, 72, 50, 60, 16+ PUSHBUTTON "Remove", IDC_FL_REMOVE, 136, 50, 60, 16+ CONTROL "", IDC_FL_LIST, "SysListView32",+ LVS_REPORT | LVS_SHOWSELALWAYS | LVS_SINGLESEL | WS_BORDER | WS_TABSTOP,+ 8, 72, 444, 158+ DEFPUSHBUTTON "Close", IDCANCEL, 392, 238, 60, 16+END++// Log Filter (edit) sub-dialog+IDD_FILTER DIALOGEX 0, 0, 280, 178+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Log Filter Rule"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ LTEXT "Mode:", IDC_FE_L_MODE, 8, 12, 60, 10+ COMBOBOX IDC_FE_MODE, 80, 10, 120, 80, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP+ LTEXT "Process:", IDC_FE_L_PROC, 8, 34, 60, 10+ EDITTEXT IDC_FE_PROC, 80, 32, 190, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "IP:", IDC_FE_L_IP, 8, 56, 60, 10+ EDITTEXT IDC_FE_IP, 80, 54, 190, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "Port:", IDC_FE_L_PORT, 8, 78, 60, 10+ EDITTEXT IDC_FE_PORT, 80, 76, 190, 13, ES_AUTOHSCROLL | WS_TABSTOP+ LTEXT "Protocol:", IDC_FE_L_PROTO, 8, 100, 60, 10+ COMBOBOX IDC_FE_PROTO, 80, 98, 120, 80, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP+ LTEXT "Action:", IDC_FE_L_ACTION, 8, 122, 60, 10+ COMBOBOX IDC_FE_ACTION,80, 120, 120, 90, CBS_DROPDOWNLIST | WS_VSCROLL | WS_TABSTOP+ DEFPUSHBUTTON "OK", IDOK, 164, 152, 52, 14+ PUSHBUTTON "Cancel", IDCANCEL, 220, 152, 52, 14+END++// Update notification dialog+IDD_UPDATE DIALOGEX 0, 0, 300, 176+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "Software Update"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ CTEXT "", IDC_UP_TEXT, 10, 12, 280, 22+ CTEXT "", IDC_UP_VERS, 10, 42, 280, 12+ CTEXT "", IDC_UP_DATE, 10, 58, 280, 11+ CONTROL "", IDC_UP_NOTES, "SysLink", WS_TABSTOP, 10, 76, 280, 12+ CONTROL "", IDC_UP_PROGRESS, "msctls_progress32", WS_BORDER, 10, 98, 280, 10+ CTEXT "", IDC_UP_STATUS, 10, 112, 280, 11+ PUSHBUTTON "Update Now", IDC_UP_NOW, 14, 150, 84, 18+ PUSHBUTTON "Later", IDCANCEL, 108, 150, 60, 18+ PUSHBUTTON "Don't Ask Again", IDC_UP_DONTASK,178, 150, 108, 18+END++// Name input dialog (new profile)+IDD_NAME DIALOGEX 0, 0, 220, 80+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "New Profile"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ LTEXT "Profile name:", IDC_NAME_PROMPT, 10, 12, 200, 10+ EDITTEXT IDC_NAME_EDIT, 10, 28, 200, 13, ES_AUTOHSCROLL | WS_TABSTOP+ DEFPUSHBUTTON "OK", IDOK, 100, 54, 50, 14+ PUSHBUTTON "Cancel", IDCANCEL, 158, 54, 50, 14+END++// About dialog+IDD_ABOUT DIALOGEX 0, 0, 250, 170+STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU+CAPTION "About ProxyBridge"+FONT 11, "Segoe UI", 400, 0, 0x0+BEGIN+ CTEXT "ProxyBridge", IDC_AB_TITLE, 0, 12, 250, 18+ CTEXT "", IDC_AB_VER, 0, 33, 250, 11+ CTEXT "", IDC_AB_DESC, 6, 50, 238, 11+ CTEXT "", IDC_AB_AUTHOR, 0, 67, 250, 11+ CONTROL "", IDC_AB_WEB, "SysLink", WS_TABSTOP, 0, 86, 250, 12+ CONTROL "", IDC_AB_GITHUB, "SysLink", WS_TABSTOP, 0, 103, 250, 12+ CTEXT "", IDC_AB_LICENSE, 0, 122, 250, 11+ DEFPUSHBUTTON "Close", IDCANCEL, 99, 146, 52, 16+ENDdiff --git a/Windows/gui/Assets/logo.ico b/Windows/gui/res/logo.icosimilarity index 100%rename from Windows/gui/Assets/logo.icorename to Windows/gui/res/logo.icodiff --git a/Windows/gui/res/resource.h b/Windows/gui/res/resource.hnew file mode 100644index 0000000..b05213b--- /dev/null+++ b/Windows/gui/res/resource.h@@ -0,0 +1,156 @@+#ifndef RESOURCE_H+#define RESOURCE_H++// App version - single source of truth+// Feeds the About dialog (via loc.h APP_VERSION) and the VS_VERSION_INFO resource+// (exe Properties → Details). Also mirror the numeric form in res\app.manifest's+// <assemblyIdentity version="..."> when bumping.+#define PB_VER_MAJOR 4+#define PB_VER_MINOR 0+#define PB_VER_PATCH 9+#define PB_VER_BUILD 0+#define PB_VER_STR "4.0.9-Beta" // narrow, for the .rc VERSIONINFO strings+#define PB_VER_STRW L"4.0.9-Beta" // wide, for the C/About UI++#define IDI_APPICON 101++// Menu+#define IDR_MAINMENU 200+#define IDM_PROXY_SETTINGS 201+#define IDM_PROXY_RULES 202+#define IDM_SET_LOCALHOST 210+#define IDM_SET_TRAFFICLOG 211+#define IDM_SET_CLOSETOTRAY 212+#define IDM_SET_STARTUP 215+#define IDM_SET_AUTOCLEAR 216+#define IDM_LOG_FILTERS 217+#define IDM_PROFILE_RENAME 244++// Log Filters (list) dialog+#define IDD_FILTERS 600+#define IDC_FL_LIST 601+#define IDC_FL_ADD 602+#define IDC_FL_EDIT 603+#define IDC_FL_REMOVE 604+#define IDC_FL_DESC 605++// Log Filter (edit) sub-dialog+#define IDD_FILTER 620+#define IDC_FE_MODE 621+#define IDC_FE_PROC 622+#define IDC_FE_IP 623+#define IDC_FE_PORT 624+#define IDC_FE_PROTO 625+#define IDC_FE_ACTION 626+#define IDC_FE_L_MODE 630+#define IDC_FE_L_PROC 631+#define IDC_FE_L_IP 632+#define IDC_FE_L_PORT 633+#define IDC_FE_L_PROTO 634+#define IDC_FE_L_ACTION 635+#define IDM_HELP_ABOUT 220+#define IDM_HELP_DOCS 221+#define IDM_HELP_UPDATE 222+#define IDM_TRAY_SHOW 230+#define IDM_TRAY_EXIT 231+#define IDM_PROFILE_NEW 240+#define IDM_PROFILE_DELETE 241+#define IDM_PROFILE_IMPORT 242+#define IDM_PROFILE_EXPORT 243+#define IDM_LANG_EN 250+#define IDM_LANG_ZH 251+#define IDM_PROFILE_SWITCH_BASE 2000 // switch items: base + index++// Proxy Servers (list) dialog+#define IDD_SERVERS 300+#define IDC_SV_LIST 301+#define IDC_SV_ADD 302+#define IDC_SV_EDIT 303+#define IDC_SV_REMOVE 304+#define IDC_SV_CHECK 305++// Proxy Server (edit) sub-dialog+#define IDD_SERVER 320+#define IDC_SE_ADDR 321+#define IDC_SE_PORT 322+#define IDC_SE_PROTO 323+#define IDC_SE_AUTH 324 // "Enable" authentication checkbox+#define IDC_SE_USER 325+#define IDC_SE_PASS 326+#define IDC_SE_L_ADDR 330+#define IDC_SE_L_PORT 331+#define IDC_SE_L_PROTO 332+#define IDC_SE_L_USER 333+#define IDC_SE_L_PASS 334+#define IDC_SE_G_SERVER 335 // "Server" group box+#define IDC_SE_G_AUTH 336 // "Authentication" group box++// Proxy Checker dialog+#define IDD_CHECKER 340+#define IDC_CK_LOG 341+#define IDC_CK_RETEST 342+#define IDC_CK_HOST 343+#define IDC_CK_PORT 344+#define IDC_CK_L_HOST 345+#define IDC_CK_L_PORT 346++// Proxification Rules (list) dialog+#define IDD_RULES 400+#define IDC_RL_LIST 401+#define IDC_RL_ADD 402+#define IDC_RL_CLONE 403+#define IDC_RL_EDIT 404+#define IDC_RL_REMOVE 405+#define IDC_RL_UP 406+#define IDC_RL_DOWN 407+#define IDC_RL_HINT 408++// Proxification Rule (edit) sub-dialog+#define IDD_RULE 420+#define IDC_RE_ENABLED 421+#define IDC_RE_APPS 422+#define IDC_RE_HOSTS 423+#define IDC_RE_PORTS 424+#define IDC_RE_DOMAINS 425+#define IDC_RE_PROTO 426+#define IDC_RE_ACTION 427+#define IDC_RE_L_APPS 430+#define IDC_RE_L_HOSTS 431+#define IDC_RE_L_PORTS 432+#define IDC_RE_L_DOMAINS 433+#define IDC_RE_L_PROTO 434+#define IDC_RE_L_ACTION 435+#define IDC_RE_BROWSE 436+#define IDC_RE_EX_APPS 437+#define IDC_RE_EX_HOSTS 438+#define IDC_RE_EX_PORTS 439+#define IDC_RE_EX_DOMAINS 440+#define IDC_RE_UDPNOTE 441++// Name-input dialog (new profile)+#define IDD_NAME 500+#define IDC_NAME_EDIT 501+#define IDC_NAME_PROMPT 502++// Update notification dialog+#define IDD_UPDATE 720+#define IDC_UP_TEXT 721+#define IDC_UP_VERS 722+#define IDC_UP_DATE 723+#define IDC_UP_NOTES 724+#define IDC_UP_PROGRESS 725+#define IDC_UP_STATUS 726+#define IDC_UP_NOW 727+#define IDC_UP_DONTASK 728++// About dialog+#define IDD_ABOUT 700+#define IDC_AB_TITLE 701+#define IDC_AB_VER 702+#define IDC_AB_DESC 703+#define IDC_AB_AUTHOR 704+#define IDC_AB_WEB 705+#define IDC_AB_GITHUB 706+#define IDC_AB_LICENSE 707++#endif // RESOURCE_Hdiff --git a/Windows/gui/ui/dialogs.h b/Windows/gui/ui/dialogs.hnew file mode 100644index 0000000..a69843d--- /dev/null+++ b/Windows/gui/ui/dialogs.h@@ -0,0 +1,897 @@+// ui/dialogs.h - all modal dialogs (Proxy Servers, Proxy Checker,+// Proxy Rules, Log Filters, and their edit sub-dialogs, plus the new-profile prompt).+//+// Unity-build include: pulled into main.c after the globals, theme helpers, log store,+// filter helpers and the profile/engine helpers it calls. Not a standalone header.+#ifndef PB_UI_DIALOGS_H+#define PB_UI_DIALOGS_H++// Subclass a ListView to (a) dark-theme its header via custom draw - it stays light+// otherwise - and (b) the header's empty right-hand area gets filled dark too.+static LRESULT CALLBACK ListDarkSubProc(HWND h, UINT m, WPARAM w, LPARAM l, UINT_PTR id, DWORD_PTR ref)+{+ (void)id; (void)ref;+ if (m == WM_NOTIFY)+ {+ NMHDR* nh = (NMHDR*)l;+ if (nh->code == NM_CUSTOMDRAW && nh->hwndFrom == ListView_GetHeader(h))+ {+ NMCUSTOMDRAW* cd = (NMCUSTOMDRAW*)l;+ switch (cd->dwDrawStage)+ {+ case CDDS_PREPAINT:+ FillRect(cd->hdc, &cd->rc, g_brPanel);+ return CDRF_NOTIFYITEMDRAW;+ case CDDS_ITEMPREPAINT:+ {+ wchar_t txt[64] = {0};+ HDITEMW hi; hi.mask = HDI_TEXT; hi.pszText = txt; hi.cchTextMax = 64;+ Header_GetItem(nh->hwndFrom, (int)cd->dwItemSpec, &hi);+ FillRect(cd->hdc, &cd->rc, g_brPanel);+ SetBkMode(cd->hdc, TRANSPARENT);+ SetTextColor(cd->hdc, C_TEXT);+ RECT tr = cd->rc; tr.left += 6; tr.right -= 4;+ DrawTextW(cd->hdc, txt, -1, &tr, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);+ RECT ln = { cd->rc.right - 1, cd->rc.top, cd->rc.right, cd->rc.bottom };+ FillRect(cd->hdc, &ln, g_brBg); // subtle column divider+ return CDRF_SKIPDEFAULT;+ }+ }+ }+ }+ return DefSubclassProc(h, m, w, l);+}++// Stretch the last column so the list uses its full width (no dead space on the right).+static void FillLastColumn(HWND lv, int count)+{+ RECT rc; GetClientRect(lv, &rc);+ int used = 0;+ for (int i = 0; i < count - 1; i++) used += ListView_GetColumnWidth(lv, i);+ int w = rc.right - used - 2;+ if (w > 80) ListView_SetColumnWidth(lv, count - 1, w);+}++// Dark-theme a report ListView: full-row select + double buffer (+ any extra ex-styles),+// dark colours, dark-drawn header. Columns/FillLastColumn are added by the caller.+static void DarkListView(HWND lv, DWORD extraExStyle)+{+ ListView_SetExtendedListViewStyle(lv, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | extraExStyle);+ SetWindowTheme(lv, L"DarkMode_Explorer", NULL);+ ListView_SetBkColor(lv, C_PANEL);+ ListView_SetTextBkColor(lv, C_PANEL);+ ListView_SetTextColor(lv, C_TEXT);+ SetWindowSubclass(lv, ListDarkSubProc, 3, 0);+}++// Proxy Servers+// A Proxifier-style list of proxy servers with Add.../Edit.../Remove; the actual+// address/port/protocol/auth fields live in the IDD_SERVER sub-dialog.++static void InitServerList(HWND lv)+{+ DarkListView(lv, 0);+ struct { int s; int w; } cols[] = { {S_COL_ADDR, 190}, {S_COL_PORTS, 70}, {S_COL_TYPE, 90} };+ LVCOLUMNW c; c.mask = LVCF_TEXT | LVCF_WIDTH;+ for (int i = 0; i < 3; i++) { c.pszText = (LPWSTR)T(cols[i].s); c.cx = cols[i].w; ListView_InsertColumn(lv, i, &c); }+ FillLastColumn(lv, 3);+}+static void RefreshServerList(HWND lv)+{+ ListView_DeleteAllItems(lv);+ for (int i = 0; i < g_profile.cfgCount; i++)+ {+ PBConfig* c = &g_profile.cfg[i];+ LVITEMW it; ZeroMemory(&it, sizeof(it));+ it.mask = LVIF_TEXT; it.iItem = i; it.pszText = c->host;+ ListView_InsertItem(lv, &it);+ ListView_SetItemText(lv, i, 1, c->port);+ ListView_SetItemText(lv, i, 2, c->type);+ }+}++// Edit sub-dialog. lParam is a PBConfig* seeded with current values (or zeroed for a new one);+// on OK it is written back and the dialog returns 1.+INT_PTR CALLBACK ServerEditDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ {+ SetWindowLongPtrW(dlg, GWLP_USERDATA, (LONG_PTR)lp);+ PBConfig* c = (PBConfig*)lp;+ SetWindowTextW(dlg, T(S_DLG_SERVER));+ SetDlgItemTextW(dlg, IDC_SE_G_SERVER, T(S_G_SERVER));+ SetDlgItemTextW(dlg, IDC_SE_G_AUTH, T(S_G_AUTH));+ SetDlgItemTextW(dlg, IDC_SE_L_ADDR, T(S_L_ADDR));+ SetDlgItemTextW(dlg, IDC_SE_L_PORT, T(S_L_PORT));+ SetDlgItemTextW(dlg, IDC_SE_L_PROTO, T(S_L_PROTO));+ SetDlgItemTextW(dlg, IDC_SE_AUTH, T(S_CHK_ENABLE));+ SetDlgItemTextW(dlg, IDC_SE_L_USER, T(S_L_USER));+ SetDlgItemTextW(dlg, IDC_SE_L_PASS, T(S_L_PASS));+ SetDlgItemTextW(dlg, IDOK, T(S_BTN_OK));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CANCEL));+ HWND pr = GetDlgItem(dlg, IDC_SE_PROTO);+ SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)L"SOCKS5");+ SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)L"HTTP");+ SendMessageW(pr, CB_SETCURSEL, (_wcsicmp(c->type, L"HTTP") == 0) ? 1 : 0, 0);+ SetDlgItemTextW(dlg, IDC_SE_ADDR, c->host);+ if (c->port[0]) SetDlgItemTextW(dlg, IDC_SE_PORT, c->port); else SetDlgItemInt(dlg, IDC_SE_PORT, 1080, FALSE);+ SetDlgItemTextW(dlg, IDC_SE_USER, c->user);+ SetDlgItemTextW(dlg, IDC_SE_PASS, c->pass);+ BOOL hasAuth = c->user[0] != 0;+ CheckDlgButton(dlg, IDC_SE_AUTH, hasAuth ? BST_CHECKED : BST_UNCHECKED);+ EnableWindow(GetDlgItem(dlg, IDC_SE_USER), hasAuth);+ EnableWindow(GetDlgItem(dlg, IDC_SE_PASS), hasAuth);+ InitDarkMode(dlg);+ return TRUE;+ }+ PB_DARK_CTLCOLORS;+ case WM_COMMAND:+ switch (LOWORD(wp))+ {+ case IDC_SE_AUTH:+ {+ BOOL on = IsDlgButtonChecked(dlg, IDC_SE_AUTH) == BST_CHECKED;+ EnableWindow(GetDlgItem(dlg, IDC_SE_USER), on);+ EnableWindow(GetDlgItem(dlg, IDC_SE_PASS), on);+ return TRUE;+ }+ case IDOK:+ {+ PBConfig* c = (PBConfig*)GetWindowLongPtrW(dlg, GWLP_USERDATA);+ int isHttp = (int)SendMessageW(GetDlgItem(dlg, IDC_SE_PROTO), CB_GETCURSEL, 0, 0) == 1;+ lstrcpynW(c->type, isHttp ? L"HTTP" : L"SOCKS5", 16);+ GetDlgItemTextW(dlg, IDC_SE_ADDR, c->host, 128);+ GetDlgItemTextW(dlg, IDC_SE_PORT, c->port, 16);+ if (IsDlgButtonChecked(dlg, IDC_SE_AUTH) == BST_CHECKED)+ {+ GetDlgItemTextW(dlg, IDC_SE_USER, c->user, 128);+ GetDlgItemTextW(dlg, IDC_SE_PASS, c->pass, 128);+ }+ else { c->user[0] = 0; c->pass[0] = 0; }+ if (!c->host[0]) { MessageBoxW(dlg, T(S_ERR_HOST), APP_TITLE, MB_OK | MB_ICONWARNING); return TRUE; }+ EndDialog(dlg, 1);+ return TRUE;+ }+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ return FALSE;+}++// Proxy Checker+// A Proxifier-style multi-step check. The DLL streams log lines through a callback on a+// worker thread (it can block up to 10s on an unreachable proxy); each line is posted to+// the dialog which appends it to a read-only log - no blocking, no popup.+INT_PTR CALLBACK CheckerDlgProc(HWND, UINT, WPARAM, LPARAM);++static void CheckerLogCb(const char* line, void* user)+{+ HWND dlg = (HWND)user;+ int wn = MultiByteToWideChar(CP_ACP, 0, line, -1, NULL, 0);+ if (wn <= 0) return;+ wchar_t* w = (wchar_t*)malloc((size_t)wn * sizeof(wchar_t));+ if (!w) return;+ MultiByteToWideChar(CP_ACP, 0, line, -1, w, wn);+ PostMessageW(dlg, WM_APP_TESTLINE, 0, (LPARAM)w); // dialog frees it+}+typedef struct { HWND dlg; UINT32 id; char host[256]; unsigned short port; } CheckerJob;+static DWORD WINAPI CheckerThread(LPVOID p)+{+ CheckerJob* j = (CheckerJob*)p;+ g_api.TestProxyConfigEx(j->id, j->host, j->port, CheckerLogCb, j->dlg);+ PostMessageW(j->dlg, WM_APP_TESTDONE, 0, 0);+ free(j);+ return 0;+}+static void CheckerStart(HWND dlg)+{+ CheckerJob* j = (CheckerJob*)calloc(1, sizeof(CheckerJob));+ if (!j) return;+ j->dlg = dlg;+ j->id = (UINT32)(UINT_PTR)GetWindowLongPtrW(dlg, GWLP_USERDATA);+ wchar_t wh[256]; GetDlgItemTextW(dlg, IDC_CK_HOST, wh, 256);+ if (!wh[0]) lstrcpynW(wh, L"www.google.com", 256);+ WideCharToMultiByte(CP_ACP, 0, wh, -1, j->host, sizeof(j->host), NULL, NULL);+ UINT port = GetDlgItemInt(dlg, IDC_CK_PORT, NULL, FALSE);+ if (port == 0 || port > 65535) port = 80;+ j->port = (unsigned short)port;++ SetWindowTextW(GetDlgItem(dlg, IDC_CK_LOG), L"");+ EnableWindow(GetDlgItem(dlg, IDC_CK_RETEST), FALSE);+ HANDLE t = CreateThread(NULL, 0, CheckerThread, j, 0, NULL);+ if (t) CloseHandle(t);+ else { free(j); EnableWindow(GetDlgItem(dlg, IDC_CK_RETEST), TRUE); }+}++INT_PTR CALLBACK CheckerDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ SetWindowLongPtrW(dlg, GWLP_USERDATA, (LONG_PTR)lp); // lParam = config nativeId+ SetWindowTextW(dlg, T(S_DLG_CHECKER));+ SetDlgItemTextW(dlg, IDC_CK_L_HOST, T(S_CK_HOST));+ SetDlgItemTextW(dlg, IDC_CK_L_PORT, T(S_L_PORT));+ SetDlgItemTextW(dlg, IDC_CK_RETEST, T(S_BTN_RETEST));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CLOSE));+ SetDlgItemTextW(dlg, IDC_CK_HOST, L"www.google.com");+ SetDlgItemInt(dlg, IDC_CK_PORT, 80, FALSE);+ SendDlgItemMessageW(dlg, IDC_CK_LOG, WM_SETFONT,+ (WPARAM)(g_hMono ? g_hMono : (HFONT)GetStockObject(ANSI_FIXED_FONT)), TRUE);+ InitDarkMode(dlg);+ CheckerStart(dlg);+ return TRUE;+ PB_DARK_CTLCOLORS;+ case WM_APP_TESTLINE:+ {+ wchar_t* w = (wchar_t*)lp;+ if (w)+ {+ HWND e = GetDlgItem(dlg, IDC_CK_LOG);+ int len = GetWindowTextLengthW(e);+ SendMessageW(e, EM_SETSEL, len, len);+ SendMessageW(e, EM_REPLACESEL, FALSE, (LPARAM)w);+ SendMessageW(e, EM_REPLACESEL, FALSE, (LPARAM)L"\r\n");+ free(w);+ }+ return TRUE;+ }+ case WM_APP_TESTDONE:+ EnableWindow(GetDlgItem(dlg, IDC_CK_RETEST), TRUE);+ return TRUE;+ case WM_COMMAND:+ if (LOWORD(wp) == IDC_CK_RETEST) { CheckerStart(dlg); return TRUE; }+ if (LOWORD(wp) == IDCANCEL) { EndDialog(dlg, 0); return TRUE; }+ return FALSE;+ }+ return FALSE;+}++INT_PTR CALLBACK ServersDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ SetWindowTextW(dlg, T(S_DLG_SERVERS));+ SetDlgItemTextW(dlg, IDC_SV_ADD, T(S_BTN_ADDDOTS));+ SetDlgItemTextW(dlg, IDC_SV_EDIT, T(S_BTN_EDITDOTS));+ SetDlgItemTextW(dlg, IDC_SV_REMOVE, T(S_BTN_REMOVE));+ SetDlgItemTextW(dlg, IDC_SV_CHECK, T(S_BTN_CHECK));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CLOSE));+ InitDarkMode(dlg);+ InitServerList(GetDlgItem(dlg, IDC_SV_LIST));+ RefreshServerList(GetDlgItem(dlg, IDC_SV_LIST));+ return TRUE;+ case WM_SIZE:+ FillLastColumn(GetDlgItem(dlg, IDC_SV_LIST), 3);+ return FALSE;+ PB_DARK_CTLCOLORS;+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ if (nh->idFrom == IDC_SV_LIST && nh->code == NM_DBLCLK)+ PostMessageW(dlg, WM_COMMAND, IDC_SV_EDIT, 0);+ return TRUE;+ }+ case WM_COMMAND:+ {+ HWND lv = GetDlgItem(dlg, IDC_SV_LIST);+ switch (LOWORD(wp))+ {+ case IDC_SV_ADD:+ {+ if (g_profile.cfgCount >= PB_MAX_CFG) { MessageBoxW(dlg, L"Config limit reached.", APP_TITLE, MB_OK); return TRUE; }+ PBConfig c; ZeroMemory(&c, sizeof(c));+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_SERVER), dlg, ServerEditDlgProc, (LPARAM)&c) == 1)+ {+ char h[256], u[256], p[256]; W2Ux(c.host, h, sizeof(h)); W2Ux(c.user, u, sizeof(u)); W2Ux(c.pass, p, sizeof(p));+ UINT32 id = g_api.AddProxyConfig((_wcsicmp(c.type, L"HTTP") == 0) ? PB_PROXY_HTTP : PB_PROXY_SOCKS5,+ h, (unsigned short)_wtoi(c.port), u, p);+ if (id > 0) { c.nativeId = id; c.storedId = id; g_profile.cfg[g_profile.cfgCount++] = c; SaveActive(); RefreshServerList(lv); }+ else MessageBoxW(dlg, T(S_ERR_ADDCFG), APP_TITLE, MB_OK | MB_ICONERROR);+ }+ return TRUE;+ }+ case IDC_SV_EDIT:+ {+ int sel = ListView_GetNextItem(lv, -1, LVNI_SELECTED);+ if (sel < 0 || sel >= g_profile.cfgCount) return TRUE;+ PBConfig c = g_profile.cfg[sel];+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_SERVER), dlg, ServerEditDlgProc, (LPARAM)&c) == 1)+ {+ g_profile.cfg[sel] = c;+ char h[256], u[256], p[256]; W2Ux(c.host, h, sizeof(h)); W2Ux(c.user, u, sizeof(u)); W2Ux(c.pass, p, sizeof(p));+ g_api.EditProxyConfig(c.nativeId, (_wcsicmp(c.type, L"HTTP") == 0) ? PB_PROXY_HTTP : PB_PROXY_SOCKS5,+ h, (unsigned short)_wtoi(c.port), u, p);+ SaveActive(); RefreshServerList(lv);+ ListView_SetItemState(lv, sel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);+ }+ return TRUE;+ }+ case IDC_SV_CHECK:+ {+ int sel = ListView_GetNextItem(lv, -1, LVNI_SELECTED);+ if (sel < 0 || sel >= g_profile.cfgCount) return TRUE;+ DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_CHECKER), dlg, CheckerDlgProc,+ (LPARAM)(UINT_PTR)g_profile.cfg[sel].nativeId);+ return TRUE;+ }+ case IDC_SV_REMOVE:+ {+ int sel = ListView_GetNextItem(lv, -1, LVNI_SELECTED);+ if (sel < 0 || sel >= g_profile.cfgCount) return TRUE;+ g_api.DeleteProxyConfig(g_profile.cfg[sel].nativeId);+ for (int i = sel; i < g_profile.cfgCount - 1; i++) g_profile.cfg[i] = g_profile.cfg[i + 1];+ g_profile.cfgCount--;+ SaveActive(); RefreshServerList(lv);+ return TRUE;+ }+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ }+ return FALSE;+}++// Proxification Rules+// List of rules with check-box enable/disable, Add.../Clone/Edit.../Remove and+// Move Up / Move Down ordering. The rule fields live in the IDD_RULE sub-dialog.++static BOOL g_rulesRefreshing = FALSE; // guards the checkbox-change notification during refill++static void InitRulesList(HWND lv)+{+ // Checkboxes give the enable/disable toggle in the first column.+ DarkListView(lv, LVS_EX_CHECKBOXES);+ struct { int s; int w; } cols[] = {+ {S_COL_ON, 36}, {S_COL_APPS, 180}, {S_COL_HOSTS, 70}, {S_COL_PORTS, 60},+ {S_COL_DOMAINS, 100}, {S_COL_PROTO, 60}, {S_COL_ACTION, 70}, {S_COL_CFG, 200}+ };+ LVCOLUMNW c; c.mask = LVCF_TEXT | LVCF_WIDTH;+ for (int i = 0; i < 8; i++) { c.pszText = (LPWSTR)T(cols[i].s); c.cx = cols[i].w; ListView_InsertColumn(lv, i, &c); }+ SetWindowSubclass(lv, ListDarkSubProc, 3, 0);+ FillLastColumn(lv, 8);+}+static void RefreshRulesList(HWND lv)+{+ g_rulesRefreshing = TRUE;+ ListView_DeleteAllItems(lv);+ for (int i = 0; i < g_profile.ruleCount; i++)+ {+ PBRule* r = &g_profile.rule[i];+ LVITEMW it; ZeroMemory(&it, sizeof(it));+ it.mask = LVIF_TEXT; it.iItem = i; it.pszText = (LPWSTR)L"";+ ListView_InsertItem(lv, &it);+ ListView_SetItemText(lv, i, 1, r->proc);+ ListView_SetItemText(lv, i, 2, r->hosts);+ ListView_SetItemText(lv, i, 3, r->ports);+ ListView_SetItemText(lv, i, 4, r->domains);+ ListView_SetItemText(lv, i, 5, r->proto);+ ListView_SetItemText(lv, i, 6, r->action);+ wchar_t cfg[160];+ if (_wcsicmp(r->action, L"PROXY") == 0)+ {+ const PBConfig* c = NULL;+ for (int k = 0; k < g_profile.cfgCount; k++)+ if (g_profile.cfg[k].storedId == r->cfgStoredId) { c = &g_profile.cfg[k]; break; }+ if (c) _snwprintf_s(cfg, 160, _TRUNCATE, L"%s %s:%s", c->type, c->host, c->port);+ else _snwprintf_s(cfg, 160, _TRUNCATE, L"#%u (missing)", r->cfgStoredId);+ cfg[159] = 0;+ }+ else lstrcpynW(cfg, L"\x2014", 160); // em dash for Direct/Block+ ListView_SetItemText(lv, i, 7, cfg);+ ListView_SetCheckState(lv, i, r->enabled ? TRUE : FALSE);+ }+ g_rulesRefreshing = FALSE;+}++// Edit sub-dialog. lParam is a PBRule* seeded with current values; on OK it is written back+// (proc/hosts/ports/domains/proto/action/cfgStoredId/enabled) and the dialog returns 1.+INT_PTR CALLBACK RuleEditDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ {+ SetWindowLongPtrW(dlg, GWLP_USERDATA, (LONG_PTR)lp);+ PBRule* r = (PBRule*)lp;+ SetWindowTextW(dlg, T(S_DLG_RULE));+ SetDlgItemTextW(dlg, IDC_RE_ENABLED, T(S_CHK_ENABLED));+ SetDlgItemTextW(dlg, IDC_RE_L_APPS, T(S_L_APPS));+ SetDlgItemTextW(dlg, IDC_RE_L_HOSTS, T(S_L_HOSTS));+ SetDlgItemTextW(dlg, IDC_RE_L_PORTS, T(S_L_PORTS));+ SetDlgItemTextW(dlg, IDC_RE_L_DOMAINS,T(S_L_DOMAINS));+ SetDlgItemTextW(dlg, IDC_RE_L_PROTO, T(S_L_PROTO));+ SetDlgItemTextW(dlg, IDC_RE_L_ACTION, T(S_L_ACTION));+ SetDlgItemTextW(dlg, IDC_RE_BROWSE, T(S_BTN_BROWSE));+ SetDlgItemTextW(dlg, IDC_RE_EX_APPS, T(S_EX_APPS));+ SetDlgItemTextW(dlg, IDC_RE_EX_HOSTS, T(S_EX_HOSTS));+ SetDlgItemTextW(dlg, IDC_RE_EX_PORTS, T(S_EX_PORTS));+ SetDlgItemTextW(dlg, IDC_RE_EX_DOMAINS, T(S_EX_DOMAINS));+ SetDlgItemTextW(dlg, IDC_RE_UDPNOTE, T(S_UDP_NOTE));+ SetDlgItemTextW(dlg, IDOK, T(S_BTN_OK));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CANCEL));+ HWND pr = GetDlgItem(dlg, IDC_RE_PROTO);+ SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)L"TCP");+ SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)L"UDP");+ SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)L"BOTH");+ // Action combo: Direct, Block, then one entry per configured proxy (item data = storedId).+ HWND ac = GetDlgItem(dlg, IDC_RE_ACTION);+ SendMessageW(ac, CB_SETITEMDATA, SendMessageW(ac, CB_ADDSTRING, 0, (LPARAM)L"Direct"), 0);+ SendMessageW(ac, CB_SETITEMDATA, SendMessageW(ac, CB_ADDSTRING, 0, (LPARAM)L"Block"), 0);+ for (int i = 0; i < g_profile.cfgCount; i++)+ {+ PBConfig* c = &g_profile.cfg[i];+ wchar_t label[320];+ _snwprintf_s(label, 320, _TRUNCATE, L"%s %s:%s (#%u)", c->type, c->host, c->port, c->storedId);+ label[319] = 0;+ LRESULT idx = SendMessageW(ac, CB_ADDSTRING, 0, (LPARAM)label);+ SendMessageW(ac, CB_SETITEMDATA, idx, c->storedId);+ }+ SendMessageW(ac, CB_SETDROPPEDWIDTH, 280, 0);+ // Seed fields from the rule.+ SetDlgItemTextW(dlg, IDC_RE_APPS, r->proc[0] ? r->proc : L"*");+ SetDlgItemTextW(dlg, IDC_RE_HOSTS, r->hosts[0] ? r->hosts : L"*");+ SetDlgItemTextW(dlg, IDC_RE_PORTS, r->ports[0] ? r->ports : L"*");+ SetDlgItemTextW(dlg, IDC_RE_DOMAINS, r->domains[0] ? r->domains : L"*");+ SendMessageW(pr, CB_SETCURSEL, ProtoIdx(r->proto[0] ? r->proto : L"BOTH"), 0);+ int target = 0;+ if (!_wcsicmp(r->action, L"BLOCK")) target = 1;+ else if (!_wcsicmp(r->action, L"DIRECT")) target = 0;+ else if (!_wcsicmp(r->action, L"PROXY"))+ {+ int n = (int)SendMessageW(ac, CB_GETCOUNT, 0, 0);+ for (int k = 2; k < n; k++)+ if ((UINT32)SendMessageW(ac, CB_GETITEMDATA, k, 0) == r->cfgStoredId) { target = k; break; }+ }+ SendMessageW(ac, CB_SETCURSEL, target, 0);+ CheckDlgButton(dlg, IDC_RE_ENABLED, r->enabled ? BST_CHECKED : BST_UNCHECKED);+ InitDarkMode(dlg);+ return TRUE;+ }+ case WM_CTLCOLORDLG:+ case WM_CTLCOLOREDIT:+ case WM_CTLCOLORLISTBOX:+ case WM_CTLCOLORBTN:+ return DlgCtlColor(wp);+ case WM_CTLCOLORSTATIC:+ {+ HDC dc = (HDC)wp;+ int id = GetDlgCtrlID((HWND)lp);+ SetBkColor(dc, C_BG);+ if (id == IDC_RE_UDPNOTE) SetTextColor(dc, C_WARN);+ else if (id == IDC_RE_EX_APPS || id == IDC_RE_EX_HOSTS ||+ id == IDC_RE_EX_PORTS || id == IDC_RE_EX_DOMAINS) SetTextColor(dc, C_DIM);+ else SetTextColor(dc, C_TEXT);+ return (INT_PTR)g_brBg;+ }+ case WM_COMMAND:+ switch (LOWORD(wp))+ {+ case IDC_RE_BROWSE:+ {+ // Pick an .exe and append just its file name.+ wchar_t path[MAX_PATH] = L"";+ OPENFILENAMEW ofn; ZeroMemory(&ofn, sizeof(ofn));+ ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = dlg;+ ofn.lpstrFilter = L"Executables\0*.exe\0All Files\0*.*\0";+ ofn.lpstrFile = path; ofn.nMaxFile = MAX_PATH;+ ofn.lpstrTitle = L"Select Process Executable";+ ofn.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_PATHMUSTEXIST;+ if (GetOpenFileNameW(&ofn))+ {+ const wchar_t* base = path;+ for (const wchar_t* p = path; *p; p++) if (*p == L'\\' || *p == L'/') base = p + 1;+ wchar_t cur[256]; GetDlgItemTextW(dlg, IDC_RE_APPS, cur, 256);+ wchar_t out[256];+ if (!cur[0] || (cur[0] == L'*' && cur[1] == 0))+ lstrcpynW(out, base, 256);+ else+ {+ size_t n = wcslen(cur);+ _snwprintf_s(out, 256, _TRUNCATE, L"%s%s%s", cur, (n && cur[n - 1] == L';') ? L" " : L"; ", base);+ out[255] = 0;+ }+ SetDlgItemTextW(dlg, IDC_RE_APPS, out);+ }+ return TRUE;+ }+ case IDOK:+ {+ PBRule* r = (PBRule*)GetWindowLongPtrW(dlg, GWLP_USERDATA);+ GetDlgItemTextW(dlg, IDC_RE_APPS, r->proc, 256);+ GetDlgItemTextW(dlg, IDC_RE_HOSTS, r->hosts, 256);+ GetDlgItemTextW(dlg, IDC_RE_PORTS, r->ports, 128);+ GetDlgItemTextW(dlg, IDC_RE_DOMAINS, r->domains, 256);+ if (!r->proc[0]) lstrcpynW(r->proc, L"*", 256);+ if (!r->hosts[0]) lstrcpynW(r->hosts, L"*", 256);+ if (!r->ports[0]) lstrcpynW(r->ports, L"*", 128);+ if (!r->domains[0]) lstrcpynW(r->domains, L"*", 256);+ lstrcpynW(r->proto, ProtoName((int)SendMessageW(GetDlgItem(dlg, IDC_RE_PROTO), CB_GETCURSEL, 0, 0)), 8);+ HWND ac = GetDlgItem(dlg, IDC_RE_ACTION);+ int asel = (int)SendMessageW(ac, CB_GETCURSEL, 0, 0);+ if (asel == 0) { lstrcpynW(r->action, L"DIRECT", 16); r->cfgStoredId = 0; }+ else if (asel == 1) { lstrcpynW(r->action, L"BLOCK", 16); r->cfgStoredId = 0; }+ else { lstrcpynW(r->action, L"PROXY", 16);+ r->cfgStoredId = (UINT32)SendMessageW(ac, CB_GETITEMDATA, asel, 0); }+ r->enabled = (IsDlgButtonChecked(dlg, IDC_RE_ENABLED) == BST_CHECKED) ? 1 : 0;+ EndDialog(dlg, 1);+ return TRUE;+ }+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ return FALSE;+}++static void SwapRules(HWND lv, int a, int b)+{+ if (a < 0 || b < 0 || a >= g_profile.ruleCount || b >= g_profile.ruleCount) return;+ PBRule t = g_profile.rule[a]; g_profile.rule[a] = g_profile.rule[b]; g_profile.rule[b] = t;+ // Reorder inside the engine without recreating rules - the rule keeps its native id.+ // MoveRuleToPosition takes a 1-based position; the moved rule now sits at array index b.+ if (g_profile.rule[b].nativeId)+ g_api.MoveRuleToPosition(g_profile.rule[b].nativeId, (UINT32)(b + 1));+ SaveActive();+ RefreshRulesList(lv);+ ListView_SetItemState(lv, b, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);+ ListView_EnsureVisible(lv, b, FALSE);+}++INT_PTR CALLBACK RulesDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ SetWindowTextW(dlg, T(S_DLG_RULES));+ SetDlgItemTextW(dlg, IDC_RL_ADD, T(S_BTN_ADDDOTS));+ SetDlgItemTextW(dlg, IDC_RL_CLONE, T(S_BTN_CLONE));+ SetDlgItemTextW(dlg, IDC_RL_EDIT, T(S_BTN_EDITDOTS));+ SetDlgItemTextW(dlg, IDC_RL_REMOVE, T(S_BTN_REMOVE));+ SetDlgItemTextW(dlg, IDC_RL_UP, T(S_BTN_UP));+ SetDlgItemTextW(dlg, IDC_RL_DOWN, T(S_BTN_DOWN));+ SetDlgItemTextW(dlg, IDC_RL_HINT, T(S_RULES_HINT));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CLOSE));+ InitDarkMode(dlg);+ InitRulesList(GetDlgItem(dlg, IDC_RL_LIST));+ RefreshRulesList(GetDlgItem(dlg, IDC_RL_LIST));+ return TRUE;+ case WM_SIZE:+ FillLastColumn(GetDlgItem(dlg, IDC_RL_LIST), 8);+ return FALSE;+ PB_DARK_CTLCOLORS;+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ HWND lv = GetDlgItem(dlg, IDC_RL_LIST);+ if (nh->idFrom == IDC_RL_LIST && nh->code == NM_DBLCLK)+ {+ PostMessageW(dlg, WM_COMMAND, IDC_RL_EDIT, 0);+ }+ else if (nh->idFrom == IDC_RL_LIST && nh->code == LVN_ITEMCHANGED && !g_rulesRefreshing)+ {+ NMLISTVIEW* nlv = (NMLISTVIEW*)lp;+ if ((nlv->uChanged & LVIF_STATE) && (nlv->uNewState & LVIS_STATEIMAGEMASK) &&+ nlv->iItem >= 0 && nlv->iItem < g_profile.ruleCount)+ {+ BOOL checked = ListView_GetCheckState(lv, nlv->iItem);+ PBRule* r = &g_profile.rule[nlv->iItem];+ if ((BOOL)r->enabled != checked)+ {+ r->enabled = checked ? 1 : 0;+ if (r->enabled) g_api.EnableRule(r->nativeId); else g_api.DisableRule(r->nativeId);+ SaveActive();+ }+ }+ }+ return TRUE;+ }+ case WM_COMMAND:+ {+ HWND lv = GetDlgItem(dlg, IDC_RL_LIST);+ int sel = ListView_GetNextItem(lv, -1, LVNI_SELECTED);+ switch (LOWORD(wp))+ {+ case IDC_RL_ADD:+ {+ if (g_profile.ruleCount >= PB_MAX_RULE) { MessageBoxW(dlg, L"Rule limit reached.", APP_TITLE, MB_OK); return TRUE; }+ PBRule r; ZeroMemory(&r, sizeof(r));+ lstrcpynW(r.proc, L"*", 256); lstrcpynW(r.hosts, L"*", 256);+ lstrcpynW(r.ports, L"*", 128); lstrcpynW(r.domains, L"*", 256);+ lstrcpynW(r.proto, L"BOTH", 8); lstrcpynW(r.action, L"DIRECT", 16); r.enabled = 1;+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_RULE), dlg, RuleEditDlgProc, (LPARAM)&r) == 1)+ {+ UINT32 id = EngineAddRule(&r); // appended at the end of the engine list+ if (id) { r.nativeId = id; g_profile.rule[g_profile.ruleCount++] = r; SaveActive(); RefreshRulesList(lv); }+ else MessageBoxW(dlg, T(S_ERR_ADDRULE), APP_TITLE, MB_OK | MB_ICONERROR);+ }+ return TRUE;+ }+ case IDC_RL_CLONE:+ {+ if (sel < 0 || sel >= g_profile.ruleCount) return TRUE;+ if (g_profile.ruleCount >= PB_MAX_RULE) { MessageBoxW(dlg, L"Rule limit reached.", APP_TITLE, MB_OK); return TRUE; }+ PBRule r = g_profile.rule[sel]; r.nativeId = 0;+ UINT32 id = EngineAddRule(&r); // new engine rule (its own id), added at the end+ if (!id) { MessageBoxW(dlg, T(S_ERR_ADDRULE), APP_TITLE, MB_OK | MB_ICONERROR); return TRUE; }+ r.nativeId = id;+ for (int i = g_profile.ruleCount; i > sel + 1; i--) g_profile.rule[i] = g_profile.rule[i - 1];+ g_profile.rule[sel + 1] = r; g_profile.ruleCount++;+ g_api.MoveRuleToPosition(id, (UINT32)(sel + 2)); // slot it right after the source+ SaveActive(); RefreshRulesList(lv);+ ListView_SetItemState(lv, sel + 1, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);+ return TRUE;+ }+ case IDC_RL_EDIT:+ {+ if (sel < 0 || sel >= g_profile.ruleCount) return TRUE;+ PBRule r = g_profile.rule[sel]; // keeps nativeId - edited in place+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_RULE), dlg, RuleEditDlgProc, (LPARAM)&r) == 1)+ {+ g_profile.rule[sel] = r;+ EngineEditRule(&r);+ SaveActive(); RefreshRulesList(lv);+ ListView_SetItemState(lv, sel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);+ }+ return TRUE;+ }+ case IDC_RL_REMOVE:+ {+ if (sel < 0 || sel >= g_profile.ruleCount) return TRUE;+ if (g_profile.rule[sel].nativeId) g_api.DeleteRule(g_profile.rule[sel].nativeId);+ for (int i = sel; i < g_profile.ruleCount - 1; i++) g_profile.rule[i] = g_profile.rule[i + 1];+ g_profile.ruleCount--;+ SaveActive(); RefreshRulesList(lv);+ return TRUE;+ }+ case IDC_RL_UP: if (sel > 0) SwapRules(lv, sel, sel - 1); return TRUE;+ case IDC_RL_DOWN: if (sel >= 0 && sel < g_profile.ruleCount - 1) SwapRules(lv, sel, sel + 1); return TRUE;+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ }+ return FALSE;+}++// Log Filters+INT_PTR CALLBACK FilterEditDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ static const wchar_t* kProto[] = { L"All", L"TCP", L"UDP" };+ static const wchar_t* kAction[] = { L"All", L"Direct", L"Proxy", L"Blocked" };+ switch (msg)+ {+ case WM_INITDIALOG:+ {+ SetWindowLongPtrW(dlg, GWLP_USERDATA, (LONG_PTR)lp);+ PBFilter* f = (PBFilter*)lp;+ SetWindowTextW(dlg, T(S_DLG_FILTER));+ SetDlgItemTextW(dlg, IDC_FE_L_MODE, T(S_L_MODE));+ SetDlgItemTextW(dlg, IDC_FE_L_PROC, T(S_L_PROC));+ SetDlgItemTextW(dlg, IDC_FE_L_IP, T(S_L_IP));+ SetDlgItemTextW(dlg, IDC_FE_L_PORT, T(S_L_PORT));+ SetDlgItemTextW(dlg, IDC_FE_L_PROTO, T(S_L_PROTO));+ SetDlgItemTextW(dlg, IDC_FE_L_ACTION, T(S_L_ACTION));+ SetDlgItemTextW(dlg, IDOK, T(S_BTN_OK)); SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CANCEL));+ HWND mode = GetDlgItem(dlg, IDC_FE_MODE), pr = GetDlgItem(dlg, IDC_FE_PROTO), ac = GetDlgItem(dlg, IDC_FE_ACTION);+ SendMessageW(mode, CB_ADDSTRING, 0, (LPARAM)L"Include");+ SendMessageW(mode, CB_ADDSTRING, 0, (LPARAM)L"Exclude");+ for (int i = 0; i < 3; i++) SendMessageW(pr, CB_ADDSTRING, 0, (LPARAM)kProto[i]);+ for (int i = 0; i < 4; i++) SendMessageW(ac, CB_ADDSTRING, 0, (LPARAM)kAction[i]);+ SendMessageW(mode, CB_SETCURSEL, (_wcsicmp(f->mode, L"Exclude") == 0) ? 1 : 0, 0);+ SetDlgItemTextW(dlg, IDC_FE_PROC, f->proc);+ SetDlgItemTextW(dlg, IDC_FE_IP, f->ip);+ SetDlgItemTextW(dlg, IDC_FE_PORT, f->port);+ int pi = 0; if (!_wcsicmp(f->proto, L"TCP")) pi = 1; else if (!_wcsicmp(f->proto, L"UDP")) pi = 2;+ int ai = 0; if (!_wcsicmp(f->action, L"Direct")) ai = 1; else if (!_wcsicmp(f->action, L"Proxy")) ai = 2; else if (!_wcsicmp(f->action, L"Blocked")) ai = 3;+ SendMessageW(pr, CB_SETCURSEL, pi, 0);+ SendMessageW(ac, CB_SETCURSEL, ai, 0);+ InitDarkMode(dlg);+ return TRUE;+ }+ PB_DARK_CTLCOLORS;+ case WM_COMMAND:+ switch (LOWORD(wp))+ {+ case IDOK:+ {+ PBFilter* f = (PBFilter*)GetWindowLongPtrW(dlg, GWLP_USERDATA);+ int m = (int)SendMessageW(GetDlgItem(dlg, IDC_FE_MODE), CB_GETCURSEL, 0, 0);+ lstrcpynW(f->mode, m == 1 ? L"Exclude" : L"Include", 16);+ GetDlgItemTextW(dlg, IDC_FE_PROC, f->proc, 256);+ GetDlgItemTextW(dlg, IDC_FE_IP, f->ip, 64);+ GetDlgItemTextW(dlg, IDC_FE_PORT, f->port, 16);+ int pi = (int)SendMessageW(GetDlgItem(dlg, IDC_FE_PROTO), CB_GETCURSEL, 0, 0); if (pi < 0) pi = 0;+ int ai = (int)SendMessageW(GetDlgItem(dlg, IDC_FE_ACTION), CB_GETCURSEL, 0, 0); if (ai < 0) ai = 0;+ lstrcpynW(f->proto, kProto[pi], 8);+ lstrcpynW(f->action, kAction[ai], 16);+ EndDialog(dlg, 1);+ return TRUE;+ }+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ return FALSE;+}++static void InitFilterList(HWND lv)+{+ DarkListView(lv, 0);+ struct { int s; int w; } cols[] = {+ {S_COL_MODE, 70}, {S_COL_PROC, 150}, {S_COL_IP, 110}, {S_COL_PORTS, 70}, {S_COL_PROTO, 70}, {S_COL_ACTION, 90}+ };+ LVCOLUMNW c; c.mask = LVCF_TEXT | LVCF_WIDTH;+ for (int i = 0; i < 6; i++) { c.pszText = (LPWSTR)T(cols[i].s); c.cx = cols[i].w; ListView_InsertColumn(lv, i, &c); }+ SetWindowSubclass(lv, ListDarkSubProc, 3, 0);+ FillLastColumn(lv, 6);+}+static void RefreshFilterList(HWND lv)+{+ ListView_DeleteAllItems(lv);+ for (int i = 0; i < g_profile.filterCount; i++)+ {+ PBFilter* f = &g_profile.filter[i];+ LVITEMW it; ZeroMemory(&it, sizeof(it));+ it.mask = LVIF_TEXT; it.iItem = i; it.pszText = f->mode[0] ? f->mode : (LPWSTR)L"Include";+ ListView_InsertItem(lv, &it);+ ListView_SetItemText(lv, i, 1, f->proc[0] ? f->proc : (LPWSTR)L"*");+ ListView_SetItemText(lv, i, 2, f->ip[0] ? f->ip : (LPWSTR)L"*");+ ListView_SetItemText(lv, i, 3, f->port[0] ? f->port : (LPWSTR)L"*");+ ListView_SetItemText(lv, i, 4, f->proto[0] ? f->proto : (LPWSTR)L"All");+ ListView_SetItemText(lv, i, 5, f->action[0] ? f->action : (LPWSTR)L"All");+ }+}+INT_PTR CALLBACK FiltersDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ SetWindowTextW(dlg, T(S_DLG_FILTERS));+ SetDlgItemTextW(dlg, IDC_FL_DESC, T(S_FL_DESC));+ SetDlgItemTextW(dlg, IDC_FL_ADD, T(S_BTN_ADDDOTS));+ SetDlgItemTextW(dlg, IDC_FL_EDIT, T(S_BTN_EDITDOTS));+ SetDlgItemTextW(dlg, IDC_FL_REMOVE, T(S_BTN_REMOVE));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CLOSE));+ InitDarkMode(dlg);+ InitFilterList(GetDlgItem(dlg, IDC_FL_LIST));+ RefreshFilterList(GetDlgItem(dlg, IDC_FL_LIST));+ return TRUE;+ PB_DARK_CTLCOLORS;+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ if (nh->idFrom == IDC_FL_LIST && nh->code == NM_DBLCLK) PostMessageW(dlg, WM_COMMAND, IDC_FL_EDIT, 0);+ return TRUE;+ }+ case WM_COMMAND:+ {+ HWND lv = GetDlgItem(dlg, IDC_FL_LIST);+ int sel = ListView_GetNextItem(lv, -1, LVNI_SELECTED);+ switch (LOWORD(wp))+ {+ case IDC_FL_ADD:+ {+ if (g_profile.filterCount >= PB_MAX_FILTER) { MessageBoxW(dlg, L"Filter limit reached.", APP_TITLE, MB_OK); return TRUE; }+ PBFilter f; ZeroMemory(&f, sizeof(f));+ lstrcpynW(f.mode, L"Include", 16); lstrcpynW(f.proto, L"All", 8); lstrcpynW(f.action, L"All", 16);+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_FILTER), dlg, FilterEditDlgProc, (LPARAM)&f) == 1)+ { g_profile.filter[g_profile.filterCount++] = f; RefreshFilterList(lv); }+ return TRUE;+ }+ case IDC_FL_EDIT:+ {+ if (sel < 0 || sel >= g_profile.filterCount) return TRUE;+ PBFilter f = g_profile.filter[sel];+ if (DialogBoxParamW(g_hInst, MAKEINTRESOURCEW(IDD_FILTER), dlg, FilterEditDlgProc, (LPARAM)&f) == 1)+ { g_profile.filter[sel] = f; RefreshFilterList(lv);+ ListView_SetItemState(lv, sel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); }+ return TRUE;+ }+ case IDC_FL_REMOVE:+ if (sel < 0 || sel >= g_profile.filterCount) return TRUE;+ for (int i = sel; i < g_profile.filterCount - 1; i++) g_profile.filter[i] = g_profile.filter[i + 1];+ g_profile.filterCount--;+ RefreshFilterList(lv);+ return TRUE;+ case IDCANCEL: EndDialog(dlg, 1); return TRUE; // nonzero => caller re-applies + saves+ }+ return FALSE;+ }+ }+ return FALSE;+}++// Name input dialog+INT_PTR CALLBACK NameDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ (void)lp;+ switch (msg)+ {+ case WM_INITDIALOG:+ g_nameResult[0] = 0;+ SetWindowTextW(dlg, T(S_DLG_NEWPROFILE));+ SetDlgItemTextW(dlg, IDC_NAME_PROMPT, T(S_L_PROFNAME));+ SetDlgItemTextW(dlg, IDOK, T(S_BTN_OK));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CANCEL));+ InitDarkMode(dlg);+ SetFocus(GetDlgItem(dlg, IDC_NAME_EDIT));+ return FALSE;+ PB_DARK_CTLCOLORS;+ case WM_COMMAND:+ if (LOWORD(wp) == IDOK) { GetDlgItemTextW(dlg, IDC_NAME_EDIT, g_nameResult, PB_NAME_MAX); EndDialog(dlg, 1); return TRUE; }+ if (LOWORD(wp) == IDCANCEL) { g_nameResult[0] = 0; EndDialog(dlg, 0); return TRUE; }+ return FALSE;+ }+ return FALSE;+}++// About dialog+static void AboutCenterLink(HWND dlg, int id)+{+ HWND h = GetDlgItem(dlg, id);+ SIZE sz = {0};+ SendMessageW(h, LM_GETIDEALSIZE, 0, (LPARAM)&sz);+ RECT cr; GetClientRect(dlg, &cr);+ RECT wr; GetWindowRect(h, &wr);+ POINT p = { wr.left, wr.top }; ScreenToClient(dlg, &p);+ MoveWindow(h, (cr.right - sz.cx) / 2, p.y, sz.cx, sz.cy, TRUE);+}+INT_PTR CALLBACK AboutDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ static HFONT s_titleFont = NULL;+ switch (msg)+ {+ case WM_INITDIALOG:+ SetWindowTextW(dlg, T(S_ABOUT_TITLE));+ SetDlgItemTextW(dlg, IDC_AB_TITLE, APP_TITLE);+ SetDlgItemTextW(dlg, IDC_AB_VER, T(S_AB_VERSION));+ SetDlgItemTextW(dlg, IDC_AB_DESC, T(S_AB_DESC));+ SetDlgItemTextW(dlg, IDC_AB_AUTHOR, T(S_AB_AUTHOR));+ SetDlgItemTextW(dlg, IDC_AB_WEB, T(S_AB_WEB));+ SetDlgItemTextW(dlg, IDC_AB_GITHUB, T(S_AB_GITHUB));+ SetDlgItemTextW(dlg, IDC_AB_LICENSE, T(S_AB_LICENSE));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_BTN_CLOSE));+ if (!s_titleFont)+ s_titleFont = CreateFontW(-34, 0, 0, 0, FW_BOLD, 0, 0, 0, DEFAULT_CHARSET,+ OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY,+ DEFAULT_PITCH | FF_DONTCARE, L"Segoe UI");+ SendDlgItemMessageW(dlg, IDC_AB_TITLE, WM_SETFONT, (WPARAM)s_titleFont, TRUE);+ InitDarkMode(dlg);+ AboutCenterLink(dlg, IDC_AB_WEB);+ AboutCenterLink(dlg, IDC_AB_GITHUB);+ return TRUE;+ case WM_CTLCOLORDLG:+ case WM_CTLCOLORBTN:+ case WM_CTLCOLORSTATIC:+ {+ HDC dc = (HDC)wp;+ int id = GetDlgCtrlID((HWND)lp);+ SetBkColor(dc, C_BG);+ SetTextColor(dc, id == IDC_AB_TITLE ? C_ACCENT : (id == IDC_AB_DESC || id == 0 ? C_TEXT : C_DIM));+ return (INT_PTR)g_brBg;+ }+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ if ((nh->code == NM_CLICK || nh->code == NM_RETURN) &&+ (nh->idFrom == IDC_AB_WEB || nh->idFrom == IDC_AB_GITHUB))+ {+ PNMLINK link = (PNMLINK)lp;+ ShellExecuteW(dlg, L"open", link->item.szUrl, NULL, NULL, SW_SHOWNORMAL);+ }+ return TRUE;+ }+ case WM_COMMAND:+ if (LOWORD(wp) == IDCANCEL || LOWORD(wp) == IDOK) { EndDialog(dlg, 0); return TRUE; }+ return FALSE;+ }+ return FALSE;+}++#endif // PB_UI_DIALOGS_Hdiff --git a/Windows/gui/ui/logview.h b/Windows/gui/ui/logview.hnew file mode 100644index 0000000..eb762ce--- /dev/null+++ b/Windows/gui/ui/logview.h@@ -0,0 +1,136 @@+// ui/logview.h - log panel storage + connection-log filtering.+//+// Unity-build include: pulled into main.c after the globals (LogStore, g_connStore/+// g_actStore, g_autoClear, g_flt/g_fltCount, g_profile) it operates on. Not standalone.+#ifndef PB_UI_LOGVIEW_H+#define PB_UI_LOGVIEW_H++static void GetTimePrefix(wchar_t* buf, int cch)+{+ SYSTEMTIME st; GetLocalTime(&st);+ _snwprintf_s(buf, cch, _TRUNCATE, L"[%02d:%02d:%02d] ", st.wHour, st.wMinute, st.wSecond);+}++static void AppendToEdit(HWND edit, const wchar_t* line)+{+ int len = GetWindowTextLengthW(edit);+ if (len > MAX_LOG_CHARS)+ {+ SendMessageW(edit, EM_SETSEL, 0, len / 2);+ SendMessageW(edit, EM_REPLACESEL, FALSE, (LPARAM)L"");+ len = GetWindowTextLengthW(edit);+ }+ SendMessageW(edit, EM_SETSEL, len, len);+ SendMessageW(edit, EM_REPLACESEL, FALSE, (LPARAM)line);+}++// Case-insensitive substring test (avoids a shlwapi dependency).+static BOOL ContainsCI(const wchar_t* hay, const wchar_t* needle)+{+ if (!needle || !needle[0]) return TRUE;+ size_t nl = wcslen(needle);+ for (const wchar_t* p = hay; *p; p++)+ if (_wcsnicmp(p, needle, nl) == 0) return TRUE;+ return FALSE;+}+static BOOL LogLineMatches(const LogStore* s, const wchar_t* line)+{+ return s->filter[0] ? ContainsCI(line, s->filter) : TRUE;+}++// connection-log filters (include/exclude rules)+static const wchar_t* StrStrCI(const wchar_t* hay, const wchar_t* needle, size_t nlen)+{+ for (; *hay; hay++) if (_wcsnicmp(hay, needle, nlen) == 0) return hay;+ return NULL;+}+static BOOL GlobMatch(const wchar_t* text, const wchar_t* pattern)+{+ if (!pattern[0] || wcscmp(pattern, L"*") == 0) return TRUE;+ if (!wcschr(pattern, L'*')) return ContainsCI(text, pattern); // non-glob = contains+ size_t tlen = wcslen(text), plen = wcslen(pattern);+ BOOL leadStar = (pattern[0] == L'*'), trailStar = (pattern[plen - 1] == L'*');+ const wchar_t* tpos = text; const wchar_t* p = pattern;+ BOOL firstPart = TRUE; const wchar_t* lastPtr = NULL; size_t lastLen = 0;+ while (*p)+ {+ if (*p == L'*') { p++; continue; }+ const wchar_t* e = p; while (*e && *e != L'*') e++;+ size_t len = (size_t)(e - p);+ const wchar_t* found = StrStrCI(tpos, p, len);+ if (!found) return FALSE;+ if (firstPart && !leadStar && found != text) return FALSE; // must start with first part+ lastPtr = p; lastLen = len; tpos = found + len; firstPart = FALSE; p = e;+ }+ if (!trailStar && lastLen > 0)+ if (tlen < lastLen || _wcsnicmp(text + tlen - lastLen, lastPtr, lastLen) != 0) return FALSE;+ return TRUE;+}+static BOOL FTextMatch(const wchar_t* actual, const wchar_t* pattern)+{+ if (!pattern[0] || _wcsicmp(pattern, L"*") == 0 || _wcsicmp(pattern, L"All") == 0) return TRUE;+ return GlobMatch(actual, pattern);+}+static BOOL FilterEq(const wchar_t* field, const wchar_t* actual) // combo fields (proto/action)+{+ return (!field[0] || _wcsicmp(field, L"All") == 0) ? TRUE : (_wcsicmp(field, actual) == 0);+}+static BOOL FilterRuleMatches(const PBFilter* f, const wchar_t* proc, const wchar_t* ip,+ const wchar_t* port, const wchar_t* proto, const wchar_t* action)+{+ return FTextMatch(proc, f->proc) && FTextMatch(ip, f->ip) && FTextMatch(port, f->port) &&+ FilterEq(f->proto, proto) && FilterEq(f->action, action);+}+// Excludes run first (any match hides). Then includes: if any exist, at least one must match.+static BOOL PassesLogFilters(const wchar_t* proc, const wchar_t* ip, const wchar_t* port,+ const wchar_t* proto, const wchar_t* action)+{+ if (g_fltCount == 0) return TRUE;+ for (int i = 0; i < g_fltCount; i++)+ if (_wcsicmp(g_flt[i].mode, L"Exclude") == 0 &&+ FilterRuleMatches(&g_flt[i], proc, ip, port, proto, action)) return FALSE;+ BOOL hasInc = FALSE;+ for (int i = 0; i < g_fltCount; i++)+ if (_wcsicmp(g_flt[i].mode, L"Include") == 0)+ { hasInc = TRUE; if (FilterRuleMatches(&g_flt[i], proc, ip, port, proto, action)) return TRUE; }+ return !hasInc;+}+static void ApplyFilterSnapshot(void)+{+ g_fltCount = g_profile.filterCount;+ for (int i = 0; i < g_fltCount; i++) g_flt[i] = g_profile.filter[i];+}+static void LogStoreAdd(LogStore* s, const wchar_t* line)+{+ wchar_t* copy = _wcsdup(line);+ if (!copy) return;+ if (s->count >= LOG_MAX_LINES) // drop the oldest to stay bounded+ {+ free(s->lines[0]);+ memmove(&s->lines[0], &s->lines[1], (LOG_MAX_LINES - 1) * sizeof(wchar_t*));+ s->count--;+ }+ s->lines[s->count++] = copy;+ if (LogLineMatches(s, line)) AppendToEdit(s->edit, line);+ // Auto Clear: once a log grows past the threshold, wipe it to keep memory bounded.+ if (g_autoClear && s->count > AUTO_CLEAR_LINES)+ {+ for (int i = 0; i < s->count; i++) free(s->lines[i]);+ s->count = 0;+ SetWindowTextW(s->edit, L"");+ }+}+static void LogStoreRebuild(LogStore* s) // re-render the edit for the current filter+{+ SetWindowTextW(s->edit, L"");+ for (int i = 0; i < s->count; i++)+ if (LogLineMatches(s, s->lines[i])) AppendToEdit(s->edit, s->lines[i]);+}+static void LogStoreClear(LogStore* s)+{+ for (int i = 0; i < s->count; i++) free(s->lines[i]);+ s->count = 0;+ SetWindowTextW(s->edit, L"");+}++#endif // PB_UI_LOGVIEW_Hdiff --git a/Windows/gui/ui/startup.h b/Windows/gui/ui/startup.hnew file mode 100644index 0000000..6ba48ab--- /dev/null+++ b/Windows/gui/ui/startup.h@@ -0,0 +1,65 @@+// ui/startup.h - single-instance guard + "Run at Startup" logon task (schtasks).+//+// Unity-build include: pulled into main.c (uses only Win32 + APP-independent state).+#ifndef PB_UI_STARTUP_H+#define PB_UI_STARTUP_H++// TRUE if another ProxyBridge GUI or CLI process (not us) is already running. Two instances+// would fight over the WinDivert driver and the local relay ports.+static BOOL AnotherInstanceRunning(void)+{+ DWORD self = GetCurrentProcessId();+ HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);+ if (snap == INVALID_HANDLE_VALUE) return FALSE;+ PROCESSENTRY32W pe; pe.dwSize = sizeof(pe);+ BOOL found = FALSE;+ if (Process32FirstW(snap, &pe))+ {+ do {+ if (pe.th32ProcessID == self) continue;+ if (_wcsicmp(pe.szExeFile, L"ProxyBridge.exe") == 0 ||+ _wcsicmp(pe.szExeFile, L"ProxyBridge_CLI.exe") == 0)+ { found = TRUE; break; }+ } while (Process32NextW(snap, &pe));+ }+ CloseHandle(snap);+ return found;+}++// Run at Startup (schtasks logon task)+// Runs schtasks.exe hidden and returns its exit code (0 = success / task exists).+static DWORD RunSchtasks(const wchar_t* args)+{+ wchar_t cmd[1024];+ _snwprintf_s(cmd, 1024, _TRUNCATE, L"schtasks.exe %s", args); cmd[1023] = 0;+ STARTUPINFOW si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si);+ si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE;+ PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi));+ if (!CreateProcessW(NULL, cmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi))+ return (DWORD)-1;+ WaitForSingleObject(pi.hProcess, 15000);+ DWORD code = (DWORD)-1; GetExitCodeProcess(pi.hProcess, &code);+ CloseHandle(pi.hThread); CloseHandle(pi.hProcess);+ return code;+}+static BOOL StartupIsEnabled(void)+{+ return RunSchtasks(L"/Query /TN \"ProxyBridge\"") == 0;+}+static void StartupSet(BOOL enable)+{+ if (enable)+ {+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(NULL, exe, MAX_PATH);+ wchar_t args[1200];+ // ONLOGON task launching the exe minimized, highest run level.+ _snwprintf_s(args, 1200, _TRUNCATE,+ L"/Create /F /TN \"ProxyBridge\" /TR \"\\\"%s\\\" --minimized\" /SC ONLOGON /RL HIGHEST",+ exe);+ args[1199] = 0;+ RunSchtasks(args);+ }+ else RunSchtasks(L"/Delete /F /TN \"ProxyBridge\"");+}++#endif // PB_UI_STARTUP_Hdiff --git a/Windows/gui/ui/theme.h b/Windows/gui/ui/theme.hnew file mode 100644index 0000000..a75e2e6--- /dev/null+++ b/Windows/gui/ui/theme.h@@ -0,0 +1,153 @@+// ui/theme.h - dark-theme helpers for the GUI.+//+// Unity-build include: pulled into main.c after the colour macros (C_*), brush globals+// (g_br*), the UAH menu structs and the uxtheme ordinal typedefs are declared, so this+// file relies on those already being visible. Not a standalone header.+#ifndef PB_UI_THEME_H+#define PB_UI_THEME_H++static void CreateDarkBrushes(void)+{+ g_brBg = CreateSolidBrush(C_BG);+ g_brPanel = CreateSolidBrush(C_PANEL);+ g_brTab = CreateSolidBrush(C_TAB);+ g_brTabSel = CreateSolidBrush(C_TABSEL);+ g_brTabHot = CreateSolidBrush(C_TABHOT);+ g_brAccent = CreateSolidBrush(C_ACCENT);+ g_brMenu = CreateSolidBrush(C_MENU);+ g_brMenuHot= CreateSolidBrush(C_MENUHOT);+}++// Group boxes (BS_GROUPBOX) draw their own caption; the themed button keeps it black on+// dark. Owner-paint the frame + caption in light so they match the rest of the dialog.+static LRESULT CALLBACK GroupSubProc(HWND h, UINT m, WPARAM w, LPARAM l, UINT_PTR id, DWORD_PTR ref)+{+ (void)id; (void)ref;+ if (m == WM_PAINT)+ {+ PAINTSTRUCT ps; HDC dc = BeginPaint(h, &ps);+ RECT rc; GetClientRect(h, &rc);+ wchar_t txt[64] = {0}; GetWindowTextW(h, txt, 64);+ FillRect(dc, &rc, g_brBg);+ HFONT f = (HFONT)SendMessageW(h, WM_GETFONT, 0, 0);+ HFONT of = f ? (HFONT)SelectObject(dc, f) : NULL;+ SIZE ts; GetTextExtentPoint32W(dc, txt, lstrlenW(txt), &ts);+ HPEN pen = CreatePen(PS_SOLID, 1, C_LINE), op = (HPEN)SelectObject(dc, pen);+ HBRUSH ob = (HBRUSH)SelectObject(dc, GetStockObject(NULL_BRUSH));+ RoundRect(dc, rc.left, rc.top + ts.cy / 2, rc.right - 1, rc.bottom - 1, 6, 6);+ SelectObject(dc, ob); SelectObject(dc, op); DeleteObject(pen);+ RECT tr = { rc.left + 8, rc.top, rc.left + 14 + ts.cx, rc.top + ts.cy };+ FillRect(dc, &tr, g_brBg); // break the frame line behind the caption+ SetBkMode(dc, TRANSPARENT); SetTextColor(dc, C_TEXT);+ TextOutW(dc, rc.left + 11, rc.top, txt, lstrlenW(txt));+ if (of) SelectObject(dc, of);+ EndPaint(h, &ps);+ return 0;+ }+ return DefSubclassProc(h, m, w, l);+}++// Apply the matching dark theme to a child control by class. Immersive dark mode only+// themes the top-level window; edits/combos/buttons stay light until themed individually.+static BOOL CALLBACK DarkThemeChild(HWND h, LPARAM lp)+{+ (void)lp;+ wchar_t cls[48]; GetClassNameW(h, cls, 48);+ if (!_wcsicmp(cls, L"Edit") || !_wcsicmp(cls, L"ComboBox"))+ SetWindowTheme(h, L"DarkMode_CFD", NULL); // dark edit/combo field+ else if (!_wcsicmp(cls, L"Button"))+ {+ if ((GetWindowLongW(h, GWL_STYLE) & BS_TYPEMASK) == BS_GROUPBOX)+ SetWindowSubclass(h, GroupSubProc, 7, 0); // owner-paint the caption/frame+ else+ SetWindowTheme(h, L"DarkMode_Explorer", NULL);+ }+ else if (!_wcsicmp(cls, L"ListBox"))+ SetWindowTheme(h, L"DarkMode_Explorer", NULL);+ else if (!_wcsicmp(cls, L"SysListView32") || !_wcsicmp(cls, WC_TABCONTROLW))+ SetWindowTheme(h, L"DarkMode_Explorer", NULL);+ return TRUE;+}++static void InitDarkMode(HWND hwnd)+{+ // Enable the OS immersive dark mode so popup menus, scrollbars and combo dropdowns+ // render dark (undocumented uxtheme ordinals - stable on Win10 1903+ / Win11).+ HMODULE ux = LoadLibraryExW(L"uxtheme.dll", NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);+ if (ux)+ {+ fnSetPreferredAppMode setMode = (fnSetPreferredAppMode)(void*)GetProcAddress(ux, MAKEINTRESOURCEA(135));+ fnAllowDarkModeForWindow allow = (fnAllowDarkModeForWindow)(void*)GetProcAddress(ux, MAKEINTRESOURCEA(133));+ fnFlushMenuThemes flush = (fnFlushMenuThemes)(void*)GetProcAddress(ux, MAKEINTRESOURCEA(136));+ if (setMode) setMode(APPMODE_FORCEDARK);+ if (allow) allow(hwnd, TRUE);+ if (flush) flush();+ FreeLibrary(ux); // ordinals were called; release our loader ref (called per dialog)+ }+ BOOL dark = TRUE;+ DwmSetWindowAttribute(hwnd, 20 /* DWMWA_USE_IMMERSIVE_DARK_MODE */, &dark, sizeof(dark));+ // Theme every child control so edits/combos/buttons aren't left glaring white.+ EnumChildWindows(hwnd, DarkThemeChild, 0);+}++// Paint over the light 1px line the OS draws under the menu bar.+static void PaintMenuBottomLine(HWND hwnd)+{+ MENUBARINFO mbi; mbi.cbSize = sizeof(mbi);+ if (!GetMenuBarInfo(hwnd, OBJID_MENU, 0, &mbi)) return;+ RECT wr; GetWindowRect(hwnd, &wr);+ RECT r = mbi.rcBar; OffsetRect(&r, -wr.left, -wr.top);+ r.top = r.bottom; r.bottom += 1;+ HDC dc = GetWindowDC(hwnd);+ FillRect(dc, &r, g_brMenu);+ ReleaseDC(hwnd, dc);+}++// Shared dark colouring for dialog controls (dialog procs return the brush directly).+static INT_PTR DlgCtlColor(WPARAM wp)+{+ HDC dc = (HDC)wp;+ SetTextColor(dc, C_TEXT);+ SetBkColor(dc, C_BG);+ return (INT_PTR)g_brBg;+}++// Drop-in dark handling for every WM_CTLCOLOR* a dialog gets. Use inside a dialog proc's+// switch for the common case; dialogs that need per-control colours handle them explicitly.+#define PB_DARK_CTLCOLORS \+ case WM_CTLCOLORDLG: case WM_CTLCOLOREDIT: case WM_CTLCOLORLISTBOX: \+ case WM_CTLCOLORBTN: case WM_CTLCOLORSTATIC: return DlgCtlColor(wp)++// Subclass the tab control: dark background fill + hovered-tab tracking (owner-draw needs it).+static LRESULT CALLBACK TabSubProc(HWND h, UINT m, WPARAM w, LPARAM l, UINT_PTR id, DWORD_PTR ref)+{+ (void)id; (void)ref;+ switch (m)+ {+ case WM_ERASEBKGND:+ {+ RECT rc; GetClientRect(h, &rc);+ FillRect((HDC)w, &rc, g_brPanel);+ return 1;+ }+ case WM_MOUSEMOVE:+ {+ TCHITTESTINFO ht; ht.pt.x = GET_X_LPARAM(l); ht.pt.y = GET_Y_LPARAM(l); ht.flags = 0;+ int hit = TabCtrl_HitTest(h, &ht);+ if (hit != g_tabHot)+ {+ g_tabHot = hit;+ InvalidateRect(h, NULL, FALSE);+ TRACKMOUSEEVENT tme = { sizeof(tme), TME_LEAVE, h, 0 };+ TrackMouseEvent(&tme);+ }+ break;+ }+ case WM_MOUSELEAVE:+ if (g_tabHot != -1) { g_tabHot = -1; InvalidateRect(h, NULL, FALSE); }+ break;+ }+ return DefSubclassProc(h, m, w, l);+}++#endif // PB_UI_THEME_Hdiff --git a/Windows/gui/ui/update.h b/Windows/gui/ui/update.hnew file mode 100644index 0000000..1596b07--- /dev/null+++ b/Windows/gui/ui/update.h@@ -0,0 +1,283 @@+// ui/update.h - update checker (startup + manual): reads a+// custom JSON feed. Notification offers Update Now / Later /+// Don't Ask Again. Unity-build include: pulled into main.c after the theme helpers and the+// globals it uses (g_hInst, g_hMain, g_reallyExit).+#ifndef PB_UI_UPDATE_H+#define PB_UI_UPDATE_H++#include <winhttp.h>+#include "../profile/json.h"+#pragma comment(lib, "winhttp.lib")++#define UPD_FEED_URL L"https://download.interceptsuite.com/proxybridge.json"++#define WM_APP_UPDATE (WM_APP + 6) // check worker -> main window (result)+#define WM_APP_DLPROG (WM_APP + 7) // download worker -> dialog (percent)+#define WM_APP_DLDONE (WM_APP + 8) // download worker -> dialog (success + job)++typedef struct {+ BOOL available;+ wchar_t latest[32];+ wchar_t download[512];+ wchar_t notes[512];+ wchar_t date[32];+} UpdInfo;++static void U8W(const char* s, wchar_t* out, int cch)+{+ MultiByteToWideChar(CP_UTF8, 0, s ? s : "", -1, out, cch);+}++// Parse the first three dot-separated integers, ignoring a leading 'v' and any suffix ("-Beta").+static void UpdParseVer(const wchar_t* s, int out[3])+{+ out[0] = out[1] = out[2] = 0;+ int i = 0;+ while (*s && (*s < L'0' || *s > L'9')) s++; // skip 'v' / leading junk+ while (*s && i < 3)+ {+ if (*s >= L'0' && *s <= L'9') { int n = 0; while (*s >= L'0' && *s <= L'9') { n = n * 10 + (*s - L'0'); s++; } out[i++] = n; }+ else if (*s == L'.') s++;+ else break; // stop at '-Beta' etc.+ }+}+static int UpdVerCmp(const int a[3], const int b[3])+{+ for (int i = 0; i < 3; i++) if (a[i] != b[i]) return a[i] < b[i] ? -1 : 1;+ return 0;+}++// Open a GET request and read the response headers. On success returns the request handle+// and hands back the session/connection handles for cleanup; NULL on any failure.+static HINTERNET UpdOpenGet(const wchar_t* url, HINTERNET* sOut, HINTERNET* cOut)+{+ *sOut = *cOut = NULL;+ URL_COMPONENTS uc; wchar_t host[256] = {0}, path[2048] = {0};+ ZeroMemory(&uc, sizeof(uc)); uc.dwStructSize = sizeof(uc);+ uc.lpszHostName = host; uc.dwHostNameLength = 255;+ uc.lpszUrlPath = path; uc.dwUrlPathLength = 2047;+ if (!WinHttpCrackUrl(url, 0, 0, &uc)) return NULL;+ BOOL https = (uc.nScheme == INTERNET_SCHEME_HTTPS);+ HINTERNET s = WinHttpOpen(L"ProxyBridge-UpdateChecker", WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,+ WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0);+ if (!s) return NULL;+ HINTERNET c = WinHttpConnect(s, host, uc.nPort, 0);+ if (!c) { WinHttpCloseHandle(s); return NULL; }+ HINTERNET r = WinHttpOpenRequest(c, L"GET", path, NULL, WINHTTP_NO_REFERER,+ WINHTTP_DEFAULT_ACCEPT_TYPES, https ? WINHTTP_FLAG_SECURE : 0);+ if (!r ||+ !WinHttpSendRequest(r, WINHTTP_NO_ADDITIONAL_HEADERS, 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0) ||+ !WinHttpReceiveResponse(r, NULL))+ {+ if (r) WinHttpCloseHandle(r);+ WinHttpCloseHandle(c); WinHttpCloseHandle(s);+ return NULL;+ }+ *sOut = s; *cOut = c;+ return r;+}+static void UpdCloseGet(HINTERNET s, HINTERNET c, HINTERNET r)+{+ if (r) WinHttpCloseHandle(r);+ if (c) WinHttpCloseHandle(c);+ if (s) WinHttpCloseHandle(s);+}++// GET a URL into a malloc'd NUL-terminated buffer (caller frees). Follows redirects.+static char* UpdHttpGet(const wchar_t* url, DWORD* outLen)+{+ HINTERNET s, c, r = UpdOpenGet(url, &s, &c);+ if (!r) return NULL;+ char* buf = NULL; DWORD cap = 0, len = 0, avail;+ for (;;)+ {+ if (!WinHttpQueryDataAvailable(r, &avail) || avail == 0) break;+ if (len + avail + 1 > cap)+ {+ DWORD ncap = (len + avail + 1) * 2;+ char* nb = (char*)realloc(buf, ncap);+ if (!nb) { free(buf); buf = NULL; break; }+ buf = nb; cap = ncap;+ }+ DWORD read = 0;+ if (!WinHttpReadData(r, buf + len, avail, &read) || read == 0) break;+ len += read;+ }+ if (buf) buf[len] = 0;+ UpdCloseGet(s, c, r);+ if (buf && outLen) *outLen = len;+ return buf;+}++// Download url -> dest file, posting percent to dlg via WM_APP_DLPROG.+static BOOL UpdDownload(const wchar_t* url, const wchar_t* dest, HWND dlg)+{+ HINTERNET s, c, r = UpdOpenGet(url, &s, &c);+ if (!r) return FALSE;+ BOOL ok = FALSE;+ DWORD total = 0, tsz = sizeof(total);+ WinHttpQueryHeaders(r, WINHTTP_QUERY_CONTENT_LENGTH | WINHTTP_QUERY_FLAG_NUMBER,+ WINHTTP_HEADER_NAME_BY_INDEX, &total, &tsz, WINHTTP_NO_HEADER_INDEX);+ HANDLE f = CreateFileW(dest, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);+ if (f != INVALID_HANDLE_VALUE)+ {+ BYTE buf[16384]; DWORD got = 0, avail; ok = TRUE;+ for (;;)+ {+ if (!WinHttpQueryDataAvailable(r, &avail)) { ok = FALSE; break; }+ if (avail == 0) break;+ DWORD toread = avail > sizeof(buf) ? sizeof(buf) : avail, read = 0;+ if (!WinHttpReadData(r, buf, toread, &read) || read == 0) { ok = FALSE; break; }+ DWORD written; WriteFile(f, buf, read, &written, NULL);+ got += read;+ if (total > 0) PostMessageW(dlg, WM_APP_DLPROG, (WPARAM)((got * 100) / total), 0);+ }+ CloseHandle(f);+ }+ UpdCloseGet(s, c, r);+ return ok;+}++// Fetch + parse the feed. Fills *out; returns FALSE only on network/parse failure.+static BOOL UpdCheck(UpdInfo* out)+{+ ZeroMemory(out, sizeof(*out));+ DWORD len = 0;+ char* body = UpdHttpGet(UPD_FEED_URL, &len);+ if (!body) return FALSE;+ JVal* root = json_parse(body, len);+ free(body);+ if (!root) return FALSE;+ BOOL ok = FALSE;+ JVal* win = json_get(root, "windows");+ if (win)+ {+ const char* ver = json_str(win, "version", NULL);+ const char* dl = json_str(win, "download", NULL);+ const char* notes = json_str(win, "release_notes", NULL);+ const char* date = json_str(win, "release_date", NULL);+ if (ver) U8W(ver, out->latest, 32);+ if (dl) U8W(dl, out->download, 512);+ if (notes) U8W(notes, out->notes, 512);+ if (date) U8W(date, out->date, 32);+ int cur[3], lat[3];+ UpdParseVer(APP_VERSION, cur);+ UpdParseVer(out->latest, lat);+ out->available = (out->download[0] != 0) && (UpdVerCmp(lat, cur) > 0);+ ok = TRUE;+ }+ json_free(root);+ return ok;+}++// notification dialog+typedef struct { HWND dlg; wchar_t url[512]; wchar_t dest[MAX_PATH]; } UpdDl;+static DWORD WINAPI UpdDlThread(LPVOID p)+{+ UpdDl* d = (UpdDl*)p;+ BOOL ok = UpdDownload(d->url, d->dest, d->dlg);+ PostMessageW(d->dlg, WM_APP_DLDONE, (WPARAM)(ok ? 1 : 0), (LPARAM)d); // handler frees d+ return 0;+}+INT_PTR CALLBACK UpdateDlgProc(HWND dlg, UINT msg, WPARAM wp, LPARAM lp)+{+ switch (msg)+ {+ case WM_INITDIALOG:+ {+ SetWindowLongPtrW(dlg, GWLP_USERDATA, (LONG_PTR)lp);+ UpdInfo* info = (UpdInfo*)lp;+ SetWindowTextW(dlg, T(S_UPD_TITLE));+ SetDlgItemTextW(dlg, IDC_UP_TEXT, T(S_UPD_AVAIL));+ wchar_t v[160]; _snwprintf_s(v, 160, _TRUNCATE, L"%s \x2192 %s", APP_VERSION, info->latest);+ SetDlgItemTextW(dlg, IDC_UP_VERS, v);+ if (info->date[0]) { wchar_t d[64]; _snwprintf_s(d, 64, _TRUNCATE, L"(%s)", info->date); SetDlgItemTextW(dlg, IDC_UP_DATE, d); }+ if (info->notes[0]) { wchar_t n[640]; _snwprintf_s(n, 640, _TRUNCATE, L"<a href=\"%s\">%s</a>", info->notes, T(S_UPD_NOTES)); SetDlgItemTextW(dlg, IDC_UP_NOTES, n); }+ else ShowWindow(GetDlgItem(dlg, IDC_UP_NOTES), SW_HIDE);+ SetDlgItemTextW(dlg, IDC_UP_NOW, T(S_UPD_NOW));+ SetDlgItemTextW(dlg, IDCANCEL, T(S_UPD_LATER));+ SetDlgItemTextW(dlg, IDC_UP_DONTASK, T(S_UPD_DONTASK));+ ShowWindow(GetDlgItem(dlg, IDC_UP_PROGRESS), SW_HIDE);+ InitDarkMode(dlg);+ return TRUE;+ }+ PB_DARK_CTLCOLORS;+ case WM_NOTIFY:+ {+ LPNMHDR nh = (LPNMHDR)lp;+ if ((nh->code == NM_CLICK || nh->code == NM_RETURN) && nh->idFrom == IDC_UP_NOTES)+ { PNMLINK link = (PNMLINK)lp; ShellExecuteW(dlg, L"open", link->item.szUrl, NULL, NULL, SW_SHOWNORMAL); }+ return TRUE;+ }+ case WM_APP_DLPROG:+ SendDlgItemMessageW(dlg, IDC_UP_PROGRESS, PBM_SETPOS, (WPARAM)wp, 0);+ return TRUE;+ case WM_APP_DLDONE:+ {+ UpdDl* d = (UpdDl*)lp;+ if (wp) // success: launch the installer and quit so it can replace files+ {+ ShellExecuteW(dlg, L"open", d->dest, NULL, NULL, SW_SHOWNORMAL);+ free(d);+ g_reallyExit = TRUE;+ DestroyWindow(g_hMain);+ return TRUE;+ }+ SetDlgItemTextW(dlg, IDC_UP_STATUS, T(S_UPD_DLFAIL));+ EnableWindow(GetDlgItem(dlg, IDC_UP_NOW), TRUE);+ free(d);+ return TRUE;+ }+ case WM_COMMAND:+ switch (LOWORD(wp))+ {+ case IDC_UP_NOW:+ {+ UpdInfo* info = (UpdInfo*)GetWindowLongPtrW(dlg, GWLP_USERDATA);+ UpdDl* d = (UpdDl*)calloc(1, sizeof(UpdDl));+ if (!d) return TRUE;+ d->dlg = dlg; lstrcpynW(d->url, info->download, 512);+ const wchar_t* fn = info->download;+ for (const wchar_t* p = info->download; *p; p++) if (*p == L'/') fn = p + 1;+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);+ _snwprintf_s(d->dest, MAX_PATH, _TRUNCATE, L"%s%s", tmp, fn[0] ? fn : L"ProxyBridge-Setup.exe");+ EnableWindow(GetDlgItem(dlg, IDC_UP_NOW), FALSE);+ ShowWindow(GetDlgItem(dlg, IDC_UP_PROGRESS), SW_SHOW);+ SendDlgItemMessageW(dlg, IDC_UP_PROGRESS, PBM_SETRANGE, 0, MAKELPARAM(0, 100));+ SetDlgItemTextW(dlg, IDC_UP_STATUS, T(S_UPD_DLING));+ HANDLE t = CreateThread(NULL, 0, UpdDlThread, d, 0, NULL);+ if (t) CloseHandle(t); else { free(d); EnableWindow(GetDlgItem(dlg, IDC_UP_NOW), TRUE); }+ return TRUE;+ }+ case IDC_UP_DONTASK: PB_SetCheckUpdates(FALSE); EndDialog(dlg, 0); return TRUE;+ case IDCANCEL: EndDialog(dlg, 0); return TRUE;+ }+ return FALSE;+ }+ return FALSE;+}++// orchestration+typedef struct { HWND owner; BOOL manual; } UpdJob;+static DWORD WINAPI UpdCheckThread(LPVOID p)+{+ UpdJob* j = (UpdJob*)p;+ UpdInfo* info = (UpdInfo*)malloc(sizeof(UpdInfo));+ BOOL ok = FALSE;+ if (info) { ok = UpdCheck(info); if (!ok) ZeroMemory(info, sizeof(*info)); }+ WPARAM flags = (ok ? 1u : 0u) | (j->manual ? 2u : 0u);+ PostMessageW(j->owner, WM_APP_UPDATE, flags, (LPARAM)info);+ free(j);+ return 0;+}+// Kick off a check on a worker thread. manual=TRUE also reports "up to date" / errors.+static void UpdStartCheck(HWND owner, BOOL manual)+{+ UpdJob* j = (UpdJob*)calloc(1, sizeof(UpdJob));+ if (!j) return;+ j->owner = owner; j->manual = manual;+ HANDLE t = CreateThread(NULL, 0, UpdCheckThread, j, 0, NULL);+ if (t) CloseHandle(t); else free(j);+}++#endif // PB_UI_UPDATE_Hdiff --git a/Windows/installer/ProxyBridge.nsi b/Windows/installer/ProxyBridge.nsiindex 46c23e7..3be3d9c 100644--- a/Windows/installer/ProxyBridge.nsi+++ b/Windows/installer/ProxyBridge.nsi@@ -29,8 +29,8 @@ InstallDirRegKey HKLM "${PRODUCT_UNINST_KEY}" "InstallLocation"RequestExecutionLevel admin!define MUI_ABORTWARNING-!define MUI_ICON "..\gui\Assets\logo.ico"-!define MUI_UNICON "..\gui\Assets\logo.ico"+!define MUI_ICON "..\gui\res\logo.ico"+!define MUI_UNICON "..\gui\res\logo.ico"!insertmacro MUI_PAGE_WELCOME!insertmacro MUI_PAGE_LICENSE "..\..\\LICENSE"@@ -64,9 +64,6 @@ Section "MainSection" SEC01File "..\output\ProxyBridgeCore.dll"File "..\output\WinDivert.dll"File "..\output\WinDivert64.sys"- File "..\output\av_libglesv2.dll"- File "..\output\libHarfBuzzSharp.dll"- File "..\output\libSkiaSharp.dll"CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\ProxyBridge.exe"@@ -98,9 +95,6 @@ Section UninstallDelete "$INSTDIR\ProxyBridgeCore.dll"Delete "$INSTDIR\WinDivert.dll"Delete "$INSTDIR\WinDivert64.sys"- Delete "$INSTDIR\av_libglesv2.dll"- Delete "$INSTDIR\libHarfBuzzSharp.dll"- Delete "$INSTDIR\libSkiaSharp.dll"Delete "$INSTDIR\uninst.exe"Delete "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk"diff --git a/Windows/src/ProxyBridge.c b/Windows/src/ProxyBridge.cindex 7e3e46b..7a78ecb 100644--- a/Windows/src/ProxyBridge.c+++ b/Windows/src/ProxyBridge.c@@ -4843,6 +4843,147 @@ PROXYBRIDGE_API int ProxyBridge_TestProxyConfig(UINT32 config_id, const char* ta}}+PROXYBRIDGE_API int ProxyBridge_TestProxyConfigEx(UINT32 config_id, const char* target_host, UINT16 target_port,+ ProxyTestLogCallback cb, void* user)+{+ #define TLOG(...) do { if (cb) { char _l[300]; _snprintf_s(_l, sizeof(_l), _TRUNCATE, __VA_ARGS__); cb(_l, user); } } while (0)++ PROXY_CONFIG *cfg = find_proxy_config(config_id);+ if (cfg == NULL) { TLOG("[FAIL] No proxy config found"); return -1; }+ if (target_host == NULL || target_host[0] == '\0') target_host = "www.google.com";+ if (target_port == 0) target_port = 80;++ BOOL is_socks = (cfg->type == PROXY_TYPE_SOCKS5);+ BOOL use_auth = (cfg->username[0] != '\0');++ TLOG("Proxy: %s:%u", cfg->host, cfg->port);+ TLOG("Protocol: %s", is_socks ? "SOCKS5" : "HTTP");+ TLOG("Auth: %s", use_auth ? "yes" : "no");+ TLOG("Target: %s:%u", target_host, target_port);++ UINT32 proxy_ip = resolve_hostname(cfg->host);+ if (proxy_ip == 0) { TLOG(""); TLOG("[FAIL] Could not resolve proxy host '%s'", cfg->host); return -1; }+ struct in_addr pa; pa.s_addr = proxy_ip;+ TLOG("Proxy IP: %s", inet_ntoa(pa));++ int overall = 0;++ // ── Test 1: TCP connection to the proxy server ───────────────────────────+ TLOG("");+ TLOG("Test 1: Connection to the proxy server");+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ if (s == INVALID_SOCKET) { TLOG(" [FAIL] Failed to create socket"); return -1; }+ DWORD to = 10000;+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&to, sizeof(to));+ setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char*)&to, sizeof(to));+ struct sockaddr_in paddr; memset(&paddr, 0, sizeof(paddr));+ paddr.sin_family = AF_INET; paddr.sin_port = htons(cfg->port); paddr.sin_addr.s_addr = proxy_ip;+ ULONGLONG c0 = GetTickCount64();+ if (connect(s, (struct sockaddr*)&paddr, sizeof(paddr)) != 0)+ {+ TLOG(" [FAIL] Could not connect to the proxy server");+ closesocket(s);+ TLOG(""); TLOG("Testing finished: proxy is NOT reachable.");+ return -1;+ }+ ULONGLONG c1 = GetTickCount64();+ ULONGLONG connect_ms = c1 - c0;+ TLOG(" Connection established (%llu ms)", connect_ms);+ TLOG(" Test 1 passed");++ // ── Test 2: Connection through the proxy server ──────────────────────────+ TLOG("");+ TLOG("Test 2: Connection through the proxy server");+ UINT32 dest_ip = resolve_hostname(target_host);+ if (dest_ip == 0)+ {+ TLOG(" [FAIL] Could not resolve target host '%s'", target_host);+ closesocket(s);+ overall = -1;+ }+ else+ {+ ULONGLONG h0 = GetTickCount64();+ int rc = is_socks ? socks5_connect(s, dest_ip, target_port, cfg)+ : http_connect(s, dest_ip, target_port, cfg);+ ULONGLONG h1 = GetTickCount64();+ if (rc != 0)+ {+ TLOG(" [FAIL] Could not establish a tunnel through the proxy (code %d)", rc);+ if (use_auth) TLOG(" Hint: verify the proxy credentials");+ overall = -1;+ }+ else+ {+ if (use_auth) TLOG(" Authentication was successful");+ TLOG(" Connection to %s:%u established through the proxy (%llu ms)", target_host, target_port, h1 - h0);++ // Try to load a default web page (best-effort; needs a web server on the target).+ char req[256];+ int rn = _snprintf_s(req, sizeof(req), _TRUNCATE,+ "GET / HTTP/1.0\r\nHost: %s\r\nUser-Agent: ProxyBridge-Check\r\nConnection: close\r\n\r\n",+ target_host);+ if (rn > 0 && send(s, req, rn, 0) == rn)+ {+ char resp[512]; int got = recv(s, resp, sizeof(resp) - 1, 0);+ if (got > 0)+ {+ resp[got] = '\0';+ if (strncmp(resp, "HTTP/", 5) == 0)+ {+ char status[64] = {0};+ const char* nl = strchr(resp, '\r'); size_t sl = nl ? (size_t)(nl - resp) : 0;+ if (sl > 0 && sl < sizeof(status)) { memcpy(status, resp, sl); status[sl] = 0; }+ TLOG(" Default web page loaded: %s", status[0] ? status : "HTTP response received");+ }+ else TLOG(" Received %d bytes (non-HTTP target)", got);+ }+ else TLOG(" Note: no page data returned (target may not run a web server)");+ }+ TLOG(" Test 2 passed");+ }+ }+ closesocket(s);++ // ── Test 3: Proxy server latency ─────────────────────────────────────────+ TLOG("");+ TLOG("Test 3: Proxy server latency");+ TLOG(" Latency = %llu ms", connect_ms);+ TLOG(" Test 3 passed");++ // ── Test 4: SOCKS5 UDP ASSOCIATE support ─────────────────────────────────+ if (is_socks)+ {+ TLOG("");+ TLOG("Test 4: SOCKS5 UDP ASSOCIATE support");+ SOCKET us = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ if (us != INVALID_SOCKET)+ {+ setsockopt(us, SOL_SOCKET, SO_RCVTIMEO, (const char*)&to, sizeof(to));+ setsockopt(us, SOL_SOCKET, SO_SNDTIMEO, (const char*)&to, sizeof(to));+ if (connect(us, (struct sockaddr*)&paddr, sizeof(paddr)) == 0)+ {+ struct sockaddr_in relay; memset(&relay, 0, sizeof(relay));+ int urc = socks5_udp_associate_with_config(us, &relay, cfg);+ if (urc == 0)+ {+ TLOG(" UDP ASSOCIATE granted; relay = %s:%u", inet_ntoa(relay.sin_addr), ntohs(relay.sin_port));+ TLOG(" UDP is supported by this proxy");+ }+ else TLOG(" UDP ASSOCIATE refused — this proxy does not support UDP");+ }+ else TLOG(" Could not open a control connection for the UDP test");+ closesocket(us);+ }+ }++ TLOG("");+ TLOG(overall == 0 ? "Testing finished: proxy is ready to work." : "Testing finished with errors.");+ return overall;++ #undef TLOG+}+PROXYBRIDGE_API void ProxyBridge_SetLocalhostViaProxy(BOOL enable){g_localhost_via_proxy = enable;diff --git a/Windows/src/ProxyBridge.h b/Windows/src/ProxyBridge.hindex 9592e36..ed824ec 100644--- a/Windows/src/ProxyBridge.h+++ b/Windows/src/ProxyBridge.h@@ -41,6 +41,11 @@ PROXYBRIDGE_API UINT32 ProxyBridge_AddProxyConfig(ProxyType type, const char* prPROXYBRIDGE_API BOOL ProxyBridge_EditProxyConfig(UINT32 config_id, ProxyType type, const char* proxy_ip, UINT16 proxy_port, const char* username, const char* password);PROXYBRIDGE_API BOOL ProxyBridge_DeleteProxyConfig(UINT32 config_id);PROXYBRIDGE_API int ProxyBridge_TestProxyConfig(UINT32 config_id, const char* target_host, UINT16 target_port, char* result_buffer, size_t buffer_size);+// Detailed multi-step proxy check (like Proxifier's Proxy Checker). Streams human-readable+// log lines through the callback: TCP reach, tunnel + auth, page load, latency, and — for+// SOCKS5 — a UDP ASSOCIATE probe. Returns 0 if the critical tests passed, negative otherwise.+typedef void (*ProxyTestLogCallback)(const char* line, void* user);+PROXYBRIDGE_API int ProxyBridge_TestProxyConfigEx(UINT32 config_id, const char* target_host, UINT16 target_port, ProxyTestLogCallback callback, void* user);// Rule management - proxy_config_id selects which proxy config the rule uses (0 = first available)// target_domains: semicolon/comma separated domain patterns ("*", "google.com", "*.google.com"); NULL/"" = no domain restriction.