Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
added Profile based local storage
AnoF-Cyber29948a5a3a2b
diff --git a/Windows/gui/Resources/Resources.Designer.cs b/Windows/gui/Resources/Resources.Designer.csindex e70e39b..17fb676 100644--- a/Windows/gui/Resources/Resources.Designer.cs+++ b/Windows/gui/Resources/Resources.Designer.cs@@ -158,23 +158,13 @@ namespace ProxyBridge.GUI.Resources {}}- internal static string MenuConfig {- get {- return ResourceManager.GetString("MenuConfig", resourceCulture);- }- }-- internal static string MenuImportConfig {- get {- return ResourceManager.GetString("MenuImportConfig", resourceCulture);- }- }-- internal static string MenuExportConfig {- get {- return ResourceManager.GetString("MenuExportConfig", 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.diff --git a/Windows/gui/Resources/Resources.resx b/Windows/gui/Resources/Resources.resxindex 7215e8c..2f1270f 100644--- a/Windows/gui/Resources/Resources.resx+++ b/Windows/gui/Resources/Resources.resx@@ -53,14 +53,27 @@<data name="MenuCheckUpdates" xml:space="preserve"><value>Check for Updates</value></data>- <data name="MenuConfig" xml:space="preserve">- <value>Config</value>+ <!-- Profile Menu -->+ <data name="MenuProfile" xml:space="preserve">+ <value>Profile</value></data>- <data name="MenuImportConfig" xml:space="preserve">- <value>Import Config</value>+ <data name="MenuNewProfile" xml:space="preserve">+ <value>New Profile</value></data>- <data name="MenuExportConfig" xml:space="preserve">- <value>Export Config</value>+ <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 -->diff --git a/Windows/gui/Resources/Resources.zh.resx b/Windows/gui/Resources/Resources.zh.resxindex 788d7e7..b093a65 100644--- a/Windows/gui/Resources/Resources.zh.resx+++ b/Windows/gui/Resources/Resources.zh.resx@@ -51,13 +51,26 @@<data name="MenuCheckUpdates" xml:space="preserve"><value>检查更新</value></data>- <data name="MenuConfig" xml:space="preserve">- <value>配置</value>+ <!-- Profile Menu -->+ <data name="MenuProfile" xml:space="preserve">+ <value>配置文件</value></data>- <data name="MenuImportConfig" xml:space="preserve">+ <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="MenuExportConfig" xml:space="preserve">+ <data name="MenuExportProfile" xml:space="preserve"><value>导出配置</value></data>diff --git a/Windows/gui/Services/ConfigManager.cs b/Windows/gui/Services/ConfigManager.csdeleted file mode 100644index b67f8d9..0000000--- a/Windows/gui/Services/ConfigManager.cs+++ /dev/null@@ -1,151 +0,0 @@-using System;-using System.Collections.Generic;-using System.IO;-using System.Text.Json;-using System.Text.Json.Serialization;-using ProxyBridge.GUI.ViewModels;--namespace ProxyBridge.GUI.Services;--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 AppConfig-{- public string ConfigFileVersion { get; set; } = "2.0";- public bool DnsViaProxy { get; set; } = true;- public bool LocalhostViaProxy { get; set; } = false;- public bool IsTrafficLoggingEnabled { 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 class ProxyRuleConfig-{- public string ProcessName { get; set; } = "";- public string TargetHosts { get; set; } = "*";- public string TargetPorts { 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;-}--[JsonSerializable(typeof(AppConfig))]-[JsonSerializable(typeof(ProxyConfigEntry))]-[JsonSerializable(typeof(List<ProxyConfigEntry>))]-[JsonSerializable(typeof(ProxyRuleConfig))]-[JsonSerializable(typeof(List<ProxyRuleConfig>))]-internal partial class AppConfigJsonContext : 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 ConfigManager-{- private static readonly string ConfigDirectory = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),- "ProxyBridge"- );-- private static readonly string ConfigFilePath = Path.Combine(ConfigDirectory, "config.json");-- public static bool SaveConfig(AppConfig config)- {- var json = JsonSerializer.Serialize(config, AppConfigJsonContext.Default.AppConfig);- return AtomicFileHelper.AtomicWrite(ConfigFilePath, json);- }-- private const string CurrentVersion = "2.0";-- public static AppConfig LoadConfig()- {- var json = AtomicFileHelper.SafeReadFile(ConfigFilePath);- if (json == null)- return new AppConfig();-- try- {- var config = JsonSerializer.Deserialize(json, AppConfigJsonContext.Default.AppConfig);- if (config != null)- {- if (config.ConfigFileVersion != CurrentVersion)- {- try { File.Delete(ConfigFilePath); } catch { }- return new AppConfig();- }-- config.ProxyRules ??= new List<ProxyRuleConfig>();- config.ProxyConfigs ??= new List<ProxyConfigEntry>();- return config;- }- }- catch { }-- try { File.Delete(ConfigFilePath); } catch { }- return new AppConfig();- }-- public static bool ConfigExists()- {- return File.Exists(ConfigFilePath);- }-}diff --git a/Windows/gui/Services/Loc.cs b/Windows/gui/Services/Loc.csindex b41e535..6668da5 100644--- a/Windows/gui/Services/Loc.cs+++ b/Windows/gui/Services/Loc.cs@@ -50,9 +50,13 @@ public class Loc : INotifyPropertyChangedpublic string MenuAbout => Resources.Resources.MenuAbout;public string MenuAboutProxyBridge => Resources.Resources.MenuAboutProxyBridge;public string MenuCheckUpdates => Resources.Resources.MenuCheckUpdates;- public string MenuConfig => Resources.Resources.MenuConfig;- public string MenuImportConfig => Resources.Resources.MenuImportConfig;- public string MenuExportConfig => Resources.Resources.MenuExportConfig;+ 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;// Tabspublic string TabConnections => Resources.Resources.TabConnections;diff --git a/Windows/gui/Services/ProfileManager.cs b/Windows/gui/Services/ProfileManager.csnew file mode 100644index 0000000..66508b7--- /dev/null+++ b/Windows/gui/Services/ProfileManager.cs@@ -0,0 +1,236 @@+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 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 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 DnsViaProxy { get; set; } = true;+ public bool LocalhostViaProxy { get; set; } = false;+ public bool IsTrafficLoggingEnabled { 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();+}++[JsonSourceGenerationOptions(WriteIndented = true)]+[JsonSerializable(typeof(ProxyProfile))]+[JsonSerializable(typeof(ProxyConfigEntry))]+[JsonSerializable(typeof(List<ProxyConfigEntry>))]+[JsonSerializable(typeof(ProxyRuleConfig))]+[JsonSerializable(typeof(List<ProxyRuleConfig>))]+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 string ProfilesDirectory = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),+ "ProxyBridge",+ "profiles"+ );++ 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;+ var invalid = Path.GetInvalidFileNameChars();+ return !name.Any(c => invalid.Contains(c));+ }++ private static string GetProfilePath(string name)+ => Path.Combine(ProfilesDirectory, 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 invalid = Path.GetInvalidFileNameChars();+ var sanitized = new string(name.Select(c => invalid.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/SettingsService.cs b/Windows/gui/Services/SettingsService.csindex 9906e49..60eaba7 100644--- a/Windows/gui/Services/SettingsService.cs+++ b/Windows/gui/Services/SettingsService.cs@@ -130,4 +130,5 @@ public class AppSettingspublic 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/ViewModels/MainWindowViewModel.cs b/Windows/gui/ViewModels/MainWindowViewModel.csindex 73d5b78..a9516b5 100644--- a/Windows/gui/ViewModels/MainWindowViewModel.cs+++ b/Windows/gui/ViewModels/MainWindowViewModel.cs@@ -36,9 +36,12 @@ public class MainWindowViewModel : ViewModelBaseprivate Window? _mainWindow;private ProxyBridgeService? _proxyService;private bool _isServiceInitialized = false;- private readonly SettingsService _settingsService = new SettingsService();+ private readonly SettingsService _settingsService = new();+ private string _activeProfileName = ProfileManager.DefaultProfileName;public ObservableCollection<ProxyConfig> ProxyConfigs { get; } = new();+ public ObservableCollection<ProxyRule> ProxyRules { get; } = new();+ public ObservableCollection<ProfileSwitchItem> SwitchProfileItems { get; } = new();private readonly List<string> _pendingConnectionLogs = new(128);private readonly List<string> _pendingActivityLogs = new(64);@@ -63,9 +66,7 @@ public class MainWindowViewModel : ViewModelBase_proxyService.LogReceived += (msg) =>{lock (_activityLogLock)- {_pendingActivityLogs.Add($"[{DateTime.Now:HH:mm:ss}] {msg}\n");- }};_proxyService.ConnectionReceived += (processName, pid, destIp, destPort, proxyInfo) =>@@ -76,11 +77,8 @@ public class MainWindowViewModel : ViewModelBaseif (_connectionLogTimer?.IsEnabled == false)_connectionLogTimer.Start();- string logEntry = $"[{DateTime.Now:HH:mm:ss}] {processName} (PID:{pid}) -> {destIp}:{destPort} via {proxyInfo}\n";lock (_connectionLogLock)- {- _pendingConnectionLogs.Add(logEntry);- }+ _pendingConnectionLogs.Add($"[{DateTime.Now:HH:mm:ss}] {processName} (PID:{pid}) -> {destIp}:{destPort} via {proxyInfo}\n");};_connectionLogTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };@@ -98,10 +96,7 @@ public class MainWindowViewModel : ViewModelBasevar lines = ConnectionsLog.Split('\n');if (lines.Length > MAX_CONNECTION_LOG_LINES)- {- var linesToKeep = lines.Skip(lines.Length - MAX_CONNECTION_LOG_LINES).ToArray();- ConnectionsLog = string.Join("\n", linesToKeep);- }+ ConnectionsLog = string.Join("\n", lines.Skip(lines.Length - MAX_CONNECTION_LOG_LINES));};_activityLogTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };@@ -121,13 +116,16 @@ public class MainWindowViewModel : ViewModelBase_proxyService.SetDnsViaProxy(_dnsViaProxy);_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 pcPort))+ 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){- uint assignedId = _proxyService.AddProxyConfig(pc.Type, pc.Host, pcPort, pc.Username, pc.Password);- if (assignedId > 0)- pc.Id = assignedId;+ if (pc.Id > 0) configIdMap[pc.Id] = nativeId;+ pc.Id = nativeId;}}@@ -135,13 +133,14 @@ public class MainWindowViewModel : ViewModelBase{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.Protocol,- rule.Action,- rule.ProxyConfigId);+ rule.ProcessName, rule.TargetHosts, rule.TargetPorts,+ rule.Protocol, rule.Action, nativeProxyId);if (ruleId > 0){@@ -149,6 +148,15 @@ public class MainWindowViewModel : ViewModelBaserule.Index = ProxyRules.IndexOf(rule) + 1;}}++ foreach (var rule in ProxyRules)+ {+ if (rule.Action == "PROXY" && rule.ProxyConfigId > 0)+ {+ var pc = ProxyConfigs.FirstOrDefault(p => p.Id == rule.ProxyConfigId);+ rule.ProxyConfigDisplay = pc?.DisplayName ?? "";+ }+ }}else{@@ -169,6 +177,12 @@ public class MainWindowViewModel : ViewModelBaseset => SetProperty(ref _title, value);}+ public string ActiveProfileName+ {+ get => _activeProfileName;+ private set => SetProperty(ref _activeProfileName, value);+ }+public int SelectedTabIndex{get => _selectedTabIndex;@@ -213,8 +227,6 @@ public class MainWindowViewModel : ViewModelBase}}--public bool IsProxyRulesDialogOpen{get => _isProxyRulesDialogOpen;@@ -269,8 +281,6 @@ public class MainWindowViewModel : ViewModelBaseset => SetProperty(ref _newProxyAction, value);}- public ObservableCollection<ProxyRule> ProxyRules { get; } = new();-private bool _dnsViaProxy = true;public bool DnsViaProxy{@@ -280,13 +290,12 @@ public class MainWindowViewModel : ViewModelBaseif (SetProperty(ref _dnsViaProxy, value)){_proxyService?.SetDnsViaProxy(value);- SaveConfigurationInternal();-+ SaveCurrentProfileAsync();}}}- private bool _localhostViaProxy = false; // Default: disabled for security+ private bool _localhostViaProxy = false;public bool LocalhostViaProxy{get => _localhostViaProxy;@@ -295,7 +304,7 @@ public class MainWindowViewModel : ViewModelBaseif (SetProperty(ref _localhostViaProxy, value)){_proxyService?.SetLocalhostViaProxy(value);- SaveConfigurationInternal();+ SaveCurrentProfileAsync();}}}@@ -332,7 +341,7 @@ public class MainWindowViewModel : ViewModelBaseGC.WaitForPendingFinalizers();GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true);}- SaveConfigurationInternal();+ SaveCurrentProfileAsync();}}}@@ -386,8 +395,11 @@ public class MainWindowViewModel : ViewModelBasepublic ICommand AddRuleCommand { get; }public ICommand SaveNewRuleCommand { get; }public ICommand CancelAddRuleCommand { get; }- public ICommand ExportConfigCommand { get; }- public ICommand ImportConfigCommand { get; }+ public ICommand NewProfileCommand { get; }+ public ICommand RenameProfileCommand { get; }+ public ICommand DeleteProfileCommand { get; }+ public ICommand ImportProfileCommand { get; }+ public ICommand ExportProfileCommand { get; }public MainWindowViewModel(){@@ -398,7 +410,7 @@ public class MainWindowViewModel : ViewModelBasevar viewModel = new ProxySettingsViewModel(proxyConfigs: ProxyConfigs,proxyService: _proxyService,- onConfigsChanged: SaveConfigurationInternal,+ onConfigsChanged: SaveCurrentProfileAsync,onClose: () => window.Close(),countRulesUsingConfig: (id) =>ProxyRules.Count(r => r.Action == "PROXY" && r.ProxyConfigId == id),@@ -411,7 +423,7 @@ public class MainWindowViewModel : ViewModelBaseProxyRules.Remove(rule);}if (toDelete.Count > 0)- SaveConfigurationInternal();+ SaveCurrentProfileAsync();});@@ -419,9 +431,7 @@ public class MainWindowViewModel : ViewModelBaseviewModel.SetWindow(window);if (_mainWindow != null)- {await window.ShowDialog(_mainWindow);- }});ShowProxyRulesCommand = new RelayCommand(async () =>@@ -436,18 +446,14 @@ public class MainWindowViewModel : ViewModelBaseif (_proxyService != null){uint ruleId = _proxyService.AddRule(- rule.ProcessName,- rule.TargetHosts,- rule.TargetPorts,- rule.Protocol,- rule.Action,- rule.ProxyConfigId);+ rule.ProcessName, rule.TargetHosts, rule.TargetPorts,+ rule.Protocol, rule.Action, rule.ProxyConfigId);if (ruleId > 0){rule.RuleId = ruleId;rule.Index = ProxyRules.Count + 1;ProxyRules.Add(rule);- SaveConfigurationInternal();+ SaveCurrentProfileAsync();}else{@@ -455,36 +461,24 @@ public class MainWindowViewModel : ViewModelBase}}},- onClose: () =>- {- window.Close();- },+ onClose: () => window.Close(),proxyService: _proxyService,- onConfigChanged: SaveConfigurationInternal+ 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 Views.AboutWindow- {- DataContext = viewModel- };-+ var window = new AboutWindow { DataContext = viewModel };if (_mainWindow != null)- {await window.ShowDialog(_mainWindow);- }});CheckForUpdatesCommand = new RelayCommand(async () =>@@ -492,32 +486,18 @@ public class MainWindowViewModel : ViewModelBasevar updateWindow = new UpdateCheckWindow();var viewModel = new UpdateCheckViewModel(() => updateWindow.Close());updateWindow.DataContext = viewModel;-if (_mainWindow != null)- {await updateWindow.ShowDialog(_mainWindow);- }});- ToggleDnsViaProxyCommand = new RelayCommand(() =>- {- DnsViaProxy = !DnsViaProxy;- });-- ToggleLocalhostViaProxyCommand = new RelayCommand(() =>- {- LocalhostViaProxy = !LocalhostViaProxy;- });-- ToggleTrafficLoggingCommand = new RelayCommand(() =>- {- IsTrafficLoggingEnabled = !IsTrafficLoggingEnabled;- });+ ToggleDnsViaProxyCommand = new RelayCommand(() => { DnsViaProxy = !DnsViaProxy; });+ ToggleLocalhostViaProxyCommand = new RelayCommand(() => { LocalhostViaProxy = !LocalhostViaProxy; });+ ToggleTrafficLoggingCommand = new RelayCommand(() => { IsTrafficLoggingEnabled = !IsTrafficLoggingEnabled; });ToggleCloseToTrayCommand = new RelayCommand(() =>{CloseToTray = !CloseToTray;- SaveConfigurationInternal();+ SaveCurrentProfileAsync();});ToggleStartWithWindowsCommand = new RelayCommand(() =>@@ -587,9 +567,7 @@ public class MainWindowViewModel : ViewModelBaseSaveNewRuleCommand = new RelayCommand(() =>{if (string.IsNullOrWhiteSpace(NewProcessName))- {return;- }var rule = new ProxyRule{@@ -608,7 +586,7 @@ public class MainWindowViewModel : ViewModelBase{rule.RuleId = ruleId;ProxyRules.Add(rule);- SaveConfigurationInternal();+ SaveCurrentProfileAsync();IsAddRuleViewOpen = false;NewProcessName = "";}@@ -625,69 +603,110 @@ public class MainWindowViewModel : ViewModelBaseNewProcessName = "";});- ExportConfigCommand = new RelayCommand(async () =>+ NewProfileCommand = new RelayCommand(async () =>{if (_mainWindow == null) return;- var topLevel = TopLevel.GetTopLevel(_mainWindow);- if (topLevel == null) return;- var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions+ 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)){- Title = "Export ProxyBridge Config",- SuggestedFileName = $"ProxyBridge-Config-{DateTime.Now:yyyy-MM-dd}.json",- FileTypeChoices = new[]- {- new FilePickerFileType("JSON Files") { Patterns = new[] { "*.json" } }- }- });+ QueueActivityLog("Invalid profile name");+ return;+ }+ if (ProfileManager.ProfileExists(name))+ {+ QueueActivityLog($"Profile '{name}' already exists");+ return;+ }- if (file == null) return;+ SaveCurrentProfile();+ ProfileManager.SaveProfile(name, new ProxyProfile { Name = name });+ SwitchToProfile(name);+ QueueActivityLog($"Profile created: {name}");+ });- try+ 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)){- var config = new AppConfig- {- DnsViaProxy = _dnsViaProxy,- LocalhostViaProxy = _localhostViaProxy,- IsTrafficLoggingEnabled = _isTrafficLoggingEnabled,- Language = _currentLanguage,- CloseToTray = _closeToTray,- 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,- Protocol = r.Protocol,- Action = r.Action,- IsEnabled = r.IsEnabled,- ProxyConfigId = r.ProxyConfigId- }).ToList()- };-- var json = System.Text.Json.JsonSerializer.Serialize(config, AppConfigJsonContext.Default.AppConfig);-- await using var stream = await file.OpenWriteAsync();- await using var writer = new System.IO.StreamWriter(stream);- await writer.WriteAsync(json);-- QueueActivityLog("Configuration exported successfully");+ QueueActivityLog("Invalid profile name");+ return;}- catch (Exception ex)+ if (ProfileManager.ProfileExists(newName)){- QueueActivityLog($"Export failed: {ex.Message}");+ 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}");});- ImportConfigCommand = new RelayCommand(async () =>+ ImportProfileCommand = new RelayCommand(async () =>{if (_mainWindow == null) return;var topLevel = TopLevel.GetTopLevel(_mainWindow);@@ -695,11 +714,12 @@ public class MainWindowViewModel : ViewModelBasevar files = await topLevel.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions{- Title = "Import ProxyBridge Config",+ Title = "Import Profile",AllowMultiple = false,FileTypeFilter = new[]{- new FilePickerFileType("JSON Files") { Patterns = new[] { "*.json" } }+ new FilePickerFileType("ProxyBridge Profile") { Patterns = new[] { "*.pbprofile" } },+ new FilePickerFileType("All Files") { Patterns = new[] { "*.*" } }}});@@ -707,119 +727,66 @@ public class MainWindowViewModel : ViewModelBasetry{- string json;- await using (var stream = await files[0].OpenReadAsync())- using (var reader = new System.IO.StreamReader(stream))- json = await reader.ReadToEndAsync();-- var importedConfig = System.Text.Json.JsonSerializer.Deserialize(json, AppConfigJsonContext.Default.AppConfig);- if (importedConfig == null)+ var localPath = files[0].TryGetLocalPath();+ if (string.IsNullOrEmpty(localPath)){- QueueActivityLog("Import failed: invalid configuration file");+ QueueActivityLog("Import failed: cannot access file");return;}- // Force current version so it won't be discarded on next load- importedConfig.ConfigFileVersion = "2.0";- importedConfig.ProxyRules ??= new List<ProxyRuleConfig>();- importedConfig.ProxyConfigs ??= new List<ProxyConfigEntry>();-- // Apply scalar settings- DnsViaProxy = importedConfig.DnsViaProxy;- LocalhostViaProxy = importedConfig.LocalhostViaProxy;- IsTrafficLoggingEnabled = importedConfig.IsTrafficLoggingEnabled;- CloseToTray = importedConfig.CloseToTray;-- if (!string.IsNullOrWhiteSpace(importedConfig.Language))+ var importedName = ProfileManager.ImportProfile(localPath);+ if (importedName == null){- _currentLanguage = importedConfig.Language;- _loc.CurrentCulture = new System.Globalization.CultureInfo(importedConfig.Language);- EnglishCheckmark = importedConfig.Language == "en" ? "✓" : "";- ChineseCheckmark = importedConfig.Language == "zh" ? "✓" : "";+ QueueActivityLog("Import failed: invalid profile file");+ return;}- // Remove existing rules from DLL- foreach (var rule in ProxyRules.ToList())- _proxyService?.DeleteRule(rule.RuleId);- ProxyRules.Clear();-- // Remove existing proxy configs from DLL- foreach (var pc in ProxyConfigs.ToList())- _proxyService?.DeleteProxyConfig(pc.Id);- ProxyConfigs.Clear();-- // Add imported proxy configs; build old-id → new-id map for rule remapping- var configIdMap = new Dictionary<uint, uint>();- foreach (var pcEntry in importedConfig.ProxyConfigs)- {- if (string.IsNullOrWhiteSpace(pcEntry.Host)) continue;- if (!ushort.TryParse(pcEntry.Port, out ushort pcPort)) continue;+ RefreshProfileList();+ QueueActivityLog($"Profile imported as: {importedName}");+ }+ catch (Exception ex)+ {+ QueueActivityLog($"Import failed: {ex.Message}");+ }+ });- uint newId = _proxyService != null- ? _proxyService.AddProxyConfig(pcEntry.Type, pcEntry.Host, pcPort, pcEntry.Username ?? "", pcEntry.Password ?? "")- : pcEntry.Id;+ ExportProfileCommand = new RelayCommand(async () =>+ {+ if (_mainWindow == null) return;+ var topLevel = TopLevel.GetTopLevel(_mainWindow);+ if (topLevel == null) return;- if (newId > 0)- {- if (pcEntry.Id > 0) configIdMap[pcEntry.Id] = newId;- ProxyConfigs.Add(new ProxyConfig- {- Id = newId,- Type = pcEntry.Type,- Host = pcEntry.Host,- Port = pcEntry.Port,- Username = pcEntry.Username ?? "",- Password = pcEntry.Password ?? ""- });- }- }+ SaveCurrentProfile();- // Add imported rules with remapped config IDs- foreach (var ruleConfig in importedConfig.ProxyRules)+ var file = await topLevel.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions+ {+ Title = "Export Profile",+ SuggestedFileName = $"{_activeProfileName}.pbprofile",+ FileTypeChoices = new[]{- if (string.IsNullOrWhiteSpace(ruleConfig.ProcessName)) continue;+ new FilePickerFileType("ProxyBridge Profile") { Patterns = new[] { "*.pbprofile" } }+ }+ });- uint newProxyConfigId = 0;- if (ruleConfig.ProxyConfigId > 0)- configIdMap.TryGetValue(ruleConfig.ProxyConfigId, out newProxyConfigId);+ if (file == null) return;- if (_proxyService != null)- {- uint newRuleId = _proxyService.AddRule(- ruleConfig.ProcessName,- ValidationHelper.DefaultIfEmpty(ruleConfig.TargetHosts),- ValidationHelper.DefaultIfEmpty(ruleConfig.TargetPorts),- ValidationHelper.DefaultIfEmpty(ruleConfig.Protocol, "TCP"),- ValidationHelper.DefaultIfEmpty(ruleConfig.Action, "PROXY"),- newProxyConfigId);-- if (newRuleId > 0)- {- var pc = newProxyConfigId > 0 ? ProxyConfigs.FirstOrDefault(p => p.Id == newProxyConfigId) : null;- ProxyRules.Add(new ProxyRule- {- RuleId = newRuleId,- Index = ProxyRules.Count + 1,- ProcessName = ruleConfig.ProcessName,- TargetHosts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetHosts),- TargetPorts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetPorts),- Protocol = ValidationHelper.DefaultIfEmpty(ruleConfig.Protocol, "TCP"),- Action = ValidationHelper.DefaultIfEmpty(ruleConfig.Action, "PROXY"),- IsEnabled = ruleConfig.IsEnabled,- ProxyConfigId = newProxyConfigId,- ProxyConfigDisplay = pc?.DisplayName ?? ""- });- }- }+ try+ {+ var localPath = file.TryGetLocalPath();+ if (string.IsNullOrEmpty(localPath))+ {+ QueueActivityLog("Export failed: cannot access path");+ return;}- // Persist updated config (with remapped IDs) to disk- SaveConfigurationInternal();- QueueActivityLog("Configuration imported successfully");+ if (ProfileManager.ExportProfile(_activeProfileName, localPath))+ QueueActivityLog($"Profile exported: {_activeProfileName}");+ else+ QueueActivityLog("Export failed");}catch (Exception ex){- QueueActivityLog($"Import failed: {ex.Message}");+ QueueActivityLog($"Export failed: {ex.Message}");}});}@@ -831,16 +798,10 @@ public class MainWindowViewModel : ViewModelBase_currentLanguage = languageCode;EnglishCheckmark = languageCode == "en" ? "✓" : "";ChineseCheckmark = languageCode == "zh" ? "✓" : "";-- var config = ConfigManager.LoadConfig();- config.Language = languageCode;- ConfigManager.SaveConfig(config);-_loc.CurrentCulture = new System.Globalization.CultureInfo(languageCode);+ SaveCurrentProfileAsync();}--private void CloseDialogs(){IsProxyRulesDialogOpen = false;@@ -851,8 +812,7 @@ public class MainWindowViewModel : ViewModelBase{try{- var settingsService = new SettingsService();- var settings = settingsService.LoadSettings();+ var settings = _settingsService.LoadSettings();if (!settings.CheckForUpdatesOnStartup)return;@@ -864,7 +824,6 @@ public class MainWindowViewModel : ViewModelBasevar notificationWindow = new UpdateNotificationWindow();var viewModel = new UpdateNotificationViewModel(() => notificationWindow.Close(), versionInfo);notificationWindow.DataContext = viewModel;-_ = notificationWindow.ShowDialog(_mainWindow);}}@@ -873,7 +832,7 @@ public class MainWindowViewModel : ViewModelBasepublic void Cleanup(){- try { SaveConfigurationInternal(); } catch { }+ try { SaveCurrentProfile(); } catch { }try { _proxyService?.Dispose(); _proxyService = null; } catch { }}@@ -904,24 +863,39 @@ public class MainWindowViewModel : ViewModelBasevar settings = _settingsService.LoadSettings();StartWithWindows = settings.StartWithWindows && _settingsService.IsStartupEnabled();- var config = ConfigManager.LoadConfig();+ var profileName = settings.ActiveProfileName;+ if (!ProfileManager.ProfileExists(profileName))+ profileName = ProfileManager.DefaultProfileName;++ _activeProfileName = profileName;+ ActiveProfileName = profileName;+ Title = $"ProxyBridge - {profileName}";++ var profile = ProfileManager.LoadProfile(profileName);- DnsViaProxy = config.DnsViaProxy;- LocalhostViaProxy = config.LocalhostViaProxy;- CloseToTray = config.CloseToTray;- IsTrafficLoggingEnabled = config.IsTrafficLoggingEnabled;+ _dnsViaProxy = profile.DnsViaProxy;+ OnPropertyChanged(nameof(DnsViaProxy));- if (!string.IsNullOrWhiteSpace(config.Language))+ _localhostViaProxy = profile.LocalhostViaProxy;+ OnPropertyChanged(nameof(LocalhostViaProxy));++ _closeToTray = profile.CloseToTray;+ OnPropertyChanged(nameof(CloseToTray));++ _isTrafficLoggingEnabled = profile.IsTrafficLoggingEnabled;+ OnPropertyChanged(nameof(IsTrafficLoggingEnabled));++ if (!string.IsNullOrWhiteSpace(profile.Language)){- _currentLanguage = config.Language;- _loc.CurrentCulture = new System.Globalization.CultureInfo(config.Language);- EnglishCheckmark = config.Language == "en" ? "✓" : "";- ChineseCheckmark = config.Language == "zh" ? "✓" : "";+ _currentLanguage = profile.Language;+ _loc.CurrentCulture = new System.Globalization.CultureInfo(profile.Language);+ EnglishCheckmark = profile.Language == "en" ? "✓" : "";+ ChineseCheckmark = profile.Language == "zh" ? "✓" : "";}- if (config.ProxyConfigs != null)+ if (profile.ProxyConfigs != null){- foreach (var pc in config.ProxyConfigs)+ foreach (var pc in profile.ProxyConfigs){if (string.IsNullOrWhiteSpace(pc.Host)) continue;ProxyConfigs.Add(new ProxyConfig@@ -936,32 +910,30 @@ public class MainWindowViewModel : ViewModelBase}}- if (config.ProxyRules != null && config.ProxyRules.Count > 0)+ if (profile.ProxyRules != null){- foreach (var ruleConfig in config.ProxyRules)+ foreach (var rc in profile.ProxyRules){- if (string.IsNullOrWhiteSpace(ruleConfig.ProcessName))- continue;-- var pc = ruleConfig.ProxyConfigId > 0- ? ProxyConfigs.FirstOrDefault(p => p.Id == ruleConfig.ProxyConfigId)+ if (string.IsNullOrWhiteSpace(rc.ProcessName)) continue;+ var pc = rc.ProxyConfigId > 0+ ? ProxyConfigs.FirstOrDefault(p => p.Id == rc.ProxyConfigId): null;- var rule = new ProxyRule+ ProxyRules.Add(new ProxyRule{- ProcessName = ruleConfig.ProcessName,- TargetHosts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetHosts),- TargetPorts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetPorts),- Protocol = ValidationHelper.DefaultIfEmpty(ruleConfig.Protocol, "TCP"),- Action = ValidationHelper.DefaultIfEmpty(ruleConfig.Action, "PROXY"),- IsEnabled = ruleConfig.IsEnabled,- ProxyConfigId = ruleConfig.ProxyConfigId,+ ProcessName = rc.ProcessName,+ TargetHosts = ValidationHelper.DefaultIfEmpty(rc.TargetHosts),+ TargetPorts = ValidationHelper.DefaultIfEmpty(rc.TargetPorts),+ Protocol = ValidationHelper.DefaultIfEmpty(rc.Protocol, "TCP"),+ Action = ValidationHelper.DefaultIfEmpty(rc.Action, "PROXY"),+ IsEnabled = rc.IsEnabled,+ ProxyConfigId = rc.ProxyConfigId,ProxyConfigDisplay = pc?.DisplayName ?? ""- };- ProxyRules.Add(rule);+ });}}- QueueActivityLog("Configuration loaded successfully");+ RefreshProfileList();+ QueueActivityLog("Configuration loaded");}catch (Exception ex){@@ -969,54 +941,182 @@ public class MainWindowViewModel : ViewModelBase}}- private void SaveConfigurationInternal()+ private void SwitchToProfile(string name){- Task.Run(() => SaveConfigurationInternalAsync());+ 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}";++ _dnsViaProxy = profile.DnsViaProxy;+ OnPropertyChanged(nameof(DnsViaProxy));+ _proxyService?.SetDnsViaProxy(profile.DnsViaProxy);++ _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);+ }++ 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 ?? new List<ProxyConfigEntry>())+ {+ if (string.IsNullOrWhiteSpace(pc.Host) || !ushort.TryParse(pc.Port, out ushort port)) continue;++ 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),+ 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.Protocol, rule.Action, nativeProxyId);+ if (ruleId > 0)+ {+ rule.RuleId = ruleId;+ rule.Index = ProxyRules.Count + 1;+ }+ }++ ProxyRules.Add(rule);+ }++ UpdateSettingsProfile(name);+ RefreshProfileList();}- private void SaveConfigurationInternalAsync()+ private void SaveCurrentProfile(){- try+ ProfileManager.SaveProfile(_activeProfileName, BuildCurrentProfile());+ }++ private void SaveCurrentProfileAsync()+ {+ Task.Run(SaveCurrentProfile);+ }++ private ProxyProfile BuildCurrentProfile()+ {+ return new ProxyProfile{- var config = new AppConfig+ DnsViaProxy = _dnsViaProxy,+ LocalhostViaProxy = _localhostViaProxy,+ IsTrafficLoggingEnabled = _isTrafficLoggingEnabled,+ Language = _currentLanguage,+ CloseToTray = _closeToTray,+ ProxyConfigs = ProxyConfigs.Select(pc => new ProxyConfigEntry{- DnsViaProxy = _dnsViaProxy,- LocalhostViaProxy = _localhostViaProxy,- IsTrafficLoggingEnabled = _isTrafficLoggingEnabled,- Language = _currentLanguage,- CloseToTray = _closeToTray,- 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,- Protocol = r.Protocol,- Action = r.Action,- IsEnabled = r.IsEnabled,- ProxyConfigId = r.ProxyConfigId- }).ToList()- };+ 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,+ Protocol = r.Protocol,+ Action = r.Action,+ IsEnabled = r.IsEnabled,+ ProxyConfigId = r.ProxyConfigId+ }).ToList()+ };+ }- ConfigManager.SaveConfig(config);+ private void RefreshProfileList()+ {+ SwitchProfileItems.Clear();+ foreach (var name in ProfileManager.GetProfileNames())+ {+ var capName = name;+ SwitchProfileItems.Add(new ProfileSwitchItem+ {+ Name = name,+ IsActive = name == _activeProfileName,+ Command = new RelayCommand(() =>+ {+ if (capName == _activeProfileName) return;+ SaveCurrentProfile();+ SwitchToProfile(capName);+ })+ });}- catch { }+ }++ 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");- }}}diff --git a/Windows/gui/ViewModels/ProfileDialogViewModel.cs b/Windows/gui/ViewModels/ProfileDialogViewModel.csnew file mode 100644index 0000000..e92d20e--- /dev/null+++ b/Windows/gui/ViewModels/ProfileDialogViewModel.cs@@ -0,0 +1,35 @@+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/ProfileSwitchItem.cs b/Windows/gui/ViewModels/ProfileSwitchItem.csnew file mode 100644index 0000000..871ee70--- /dev/null+++ b/Windows/gui/ViewModels/ProfileSwitchItem.cs@@ -0,0 +1,10 @@+using System.Windows.Input;++namespace ProxyBridge.GUI.ViewModels;++public class ProfileSwitchItem+{+ public string Name { get; init; } = "";+ public bool IsActive { get; init; }+ public ICommand Command { get; init; } = default!;+}diff --git a/Windows/gui/Views/MainWindow.axaml b/Windows/gui/Views/MainWindow.axamlindex 3669893..b91bec2 100644--- a/Windows/gui/Views/MainWindow.axaml+++ b/Windows/gui/Views/MainWindow.axaml@@ -191,7 +191,7 @@<!-- Title Bar (Custom) --><Border DockPanel.Dock="Top" Background="#FF2D2D30" Height="32" IsHitTestVisible="False"><Grid>- <TextBlock Text="ProxyBridge"+ <TextBlock Text="{Binding Title}"Foreground="#FFE0E0E0"FontSize="12"VerticalAlignment="Center"@@ -260,11 +260,23 @@</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 Header="{Binding Loc.MenuConfig}">- <MenuItem Header="{Binding Loc.MenuImportConfig}" Command="{Binding ImportConfigCommand}"/>- <MenuItem Header="{Binding Loc.MenuExportConfig}" Command="{Binding ExportConfigCommand}"/>+ <MenuItem Header="{Binding Loc.MenuSwitchProfile}" ItemsSource="{Binding SwitchProfileItems}">+ <MenuItem.ItemContainerTheme>+ <ControlTheme TargetType="MenuItem" x:DataType="vm:ProfileSwitchItem">+ <Setter Property="Header" Value="{Binding Name}"/>+ <Setter Property="Command" Value="{Binding Command}"/>+ </ControlTheme>+ </MenuItem.ItemContainerTheme></MenuItem>+ <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}"/>diff --git a/Windows/gui/Views/ProfileDialogWindow.axaml b/Windows/gui/Views/ProfileDialogWindow.axamlnew file mode 100644index 0000000..faf400b--- /dev/null+++ b/Windows/gui/Views/ProfileDialogWindow.axaml@@ -0,0 +1,87 @@+<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.csnew file mode 100644index 0000000..f421b12--- /dev/null+++ b/Windows/gui/Views/ProfileDialogWindow.axaml.cs@@ -0,0 +1,36 @@+using System;+using Avalonia.Controls;++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(); }+ );+ }++ protected override void OnOpened(EventArgs e)+ {+ base.OnOpened(e);+ if (this.FindControl<TextBox>("InputBox") is { } box)+ {+ box.Focus();+ box.SelectAll();+ }+ }+}