using System.Drawing.Drawing2D; using System.Text.Json; namespace UCVL.VPNPlus; internal sealed partial class MainForm : Form { private readonly VpnApiClient _api = new(); private readonly XrayManager _xray; private readonly CancellationTokenSource _lifetime = new(); private readonly System.Windows.Forms.Timer _refreshTimer = new() { Interval = 60_000 }; private readonly System.Collections.Concurrent.ConcurrentQueue<(string Token, LearningObservation Observation, long Created)> _observationQueue = new(); private bool _learningSyncing; private readonly System.Windows.Forms.Timer _updateTimer = new() { Interval = 15 * 60_000 }; private readonly System.Windows.Forms.Timer _trafficTimer = new() { Interval = 5_000 }; private readonly System.Windows.Forms.Timer _healthTimer = new() { Interval = 5_000 }; private readonly ConnectionHealthPolicy _connectionHealth = new(); private readonly ConnectionAuthorizationLease _connectionAuthorization = new(); private readonly Label _currentNodeLabel = new(); private readonly TrafficChart _trafficChart = new(); private readonly DailyTrafficChart _dailyChart = new(); private int _availableNodeCount; private string? _currentNodeSlug; private string? _currentNodeName; private bool _currentNodeIsPrivateAuxiliary; private bool _knownTailnetAllowed; private long _privateLeaseDeadlineTicks; private bool _wantConnected, _trafficReading, _healthChecking; private bool _localRoutingFault; private int _lastCoreId; private long _lastUp, _lastDown, _sessionUp, _sessionDown; private DateTimeOffset _lastSample, _nextReconnect; private readonly Dictionary _failedNodes = new(); private readonly NotifyIcon _notifyIcon; private readonly bool _runWindowExitSelfTest; private readonly bool _autoConnect; private readonly bool _uiOnly; private readonly bool _preview; private readonly Func? _startupRecovery; private readonly ScenicPanel _content = new() { ComposeChildren = false, LoginArtwork = true }; private readonly BrandHeaderPanel _brandHeader = new(); private readonly Label _headerPoem = new(); private readonly RoundedCardPanel _loginView = new(); private readonly ScenicPanel _dashboardView = new(); private readonly CardPanel _statusCard = new(); private readonly TextBox _loginText = new(); private readonly TextBox _passwordText = new(); private readonly RoundedButton _loginButton = new(); private readonly LinkLabel _registerLink = new(); private readonly Label _registerPrompt = new(); private readonly Label _loginError = new(); private readonly Label _welcomeLabel = new(); private readonly Label _accountLabel = new(); private readonly DashboardGlyph _statusDot = new(DashboardIcon.Shield); private readonly Label _statusTitle = new(); private readonly Label _statusDetail = new(); private readonly Label _nodeHeading = new(); private readonly Label _routeHeading = new(); private readonly DashboardCombo _routeCombo = new(); private readonly RoundedButton _connectButton = new(); private readonly RoundedButton _logoutButton = new(); private readonly Label _expiryLabel = new(); private readonly Label _planLabel = new(); private string? _accessToken; private long _sessionRevision; private CancellationTokenSource? _connectionAttemptCancellation; private bool _busy; private bool _exiting; private bool _exitRequested; private bool _exitCleanupStarted; private bool _exitCleanupCompleted; private Task? _exitCleanupTask; private bool _exitResourcesDisposed; private bool _sessionEnding; private bool _windowExitSelfTestConnected; private bool _updateCheckRunning; private DateTimeOffset _nextUpdateCheckAt = DateTimeOffset.MinValue; private bool _installerLaunched; internal bool WindowExitSelfTestPassed { get; private set; } internal bool NetworkRecoveryFailed { get; private set; } internal MainForm(bool runWindowExitSelfTest = false, bool preview = false, bool uiOnly = false, bool autoConnect = false, Func? startupRecovery = null) { _uiOnly = uiOnly; _preview = preview; _startupRecovery = startupRecovery; _xray = new XrayManager(recoverStale: !preview && !uiOnly); _runWindowExitSelfTest = runWindowExitSelfTest; _autoConnect = autoConnect; Text = "纵横家"; StartPosition = FormStartPosition.CenterScreen; ShowInTaskbar = true; MinimumSize = new Size(480, 360); ClientSize = new Size(480, 360); BackColor = Brand.Surface; AutoScaleDimensions = new SizeF(96f, 96f); AutoScaleMode = AutoScaleMode.Dpi; Font = Brand.Font(9.5f); DoubleBuffered = true; ResizeRedraw = true; Icon = LoadIcon(); SuspendLayout(); _content.SuspendLayout(); try { BuildLayout(); } finally { _content.ResumeLayout(false); ResumeLayout(true); } _xray.ObservationDetectedAsync = ReportObservationAsync; _xray.StatusMessage = ShowAiStatus; _notifyIcon = BuildNotifyIcon(); Shown += async (_, _) => { LayoutBrandHeader(); if (preview) return; var area = Screen.FromControl(this).WorkingArea; if (Height > area.Height * 0.9 || Width > area.Width * 0.9) { MinimumSize = new Size(Math.Min(MinimumSize.Width, area.Width-40), Math.Min(MinimumSize.Height, area.Height-40)); Size = new Size(Math.Min(Width, area.Width-40), Math.Min(Height, area.Height-40)); CenterToScreen(); } // First paint the existing login view; startup recovery and network // requests must never run synchronously in the form constructor. SetBusy(true, "正在恢复网络状态…"); try { await Task.Yield(); if (_startupRecovery is not null) await _startupRecovery(_lifetime.Token); else if (!_uiOnly) await _xray.InitializeAsync(_lifetime.Token); } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } catch (Exception exception) { AppPaths.WriteError(exception); ShowLogin("网络状态恢复未完成,请重新打开程序或联系管理员。"); return; } finally { if (!_exiting) SetBusy(false); } if (_uiOnly) return; await RestoreSessionAsync(); if (_autoConnect && !string.IsNullOrWhiteSpace(_accessToken) && _availableNodeCount > 0) { await ToggleConnectionAsync(suppressDialogs: true); } if (_runWindowExitSelfTest) { await RunWindowExitSelfTestAsync(); } else { // Update availability must not delay showing the login page. _ = CheckForClientUpdateAsync(); } }; FormClosing += OnFormClosing; Resize += (_, _) => { UpdateTaskbarPresentation(); LayoutBrandHeader(); CenterCards(); LayoutDashboard(); }; DpiChanged += (_, _) => PostUi(() => { LayoutBrandHeader(); CenterCards(); LayoutDashboard(); }); _refreshTimer.Tick += async (_, _) => { await RefreshProfileAsync(silent: true); await SynchronizeLearningAsync(); }; _updateTimer.Tick += async (_, _) => await CheckForClientUpdateAsync(); _updateTimer.Start(); _trafficTimer.Tick += async (_, _) => await RefreshTrafficAsync(); _healthTimer.Tick += async (_, _) => { await CheckTailnetReadinessAsync(); await MaintainConnectionAsync(); }; _trafficTimer.Start(); _healthTimer.Start(); InitializeHandover(); if (preview || uiOnly) { _updateTimer.Stop(); _healthTimer.Stop(); _trafficTimer.Stop(); _notifyIcon.Visible = false; } } private async Task CheckForClientUpdateAsync() { if (_exiting || _uiOnly || _preview || _busy || _installerLaunched || _updateCheckRunning || DateTimeOffset.UtcNow < _nextUpdateCheckAt) return false; var accepted = false; _updateCheckRunning = true; try { var update = await _api.GetUpdateAsync(_lifetime.Token); if (_exiting || _busy) return false; if (!ClientUpdater.ShouldOffer(update)) { _nextUpdateCheckAt = DateTimeOffset.UtcNow.AddMinutes(15); return false; } var notes = string.IsNullOrWhiteSpace(update.Notes) ? "包含稳定性和网络恢复改进。" : update.Notes.Trim(); var choice = MessageBox.Show( $"发现新版本 {update.Version}\n\n{notes}\n\n是否现在安全升级?\n升级将覆盖原安装目录,但会保留账号、设备标识和本机配置。", "纵横家·发现更新", update.Mandatory ? MessageBoxButtons.OKCancel : MessageBoxButtons.YesNo, MessageBoxIcon.Information); accepted = update.Mandatory ? choice == DialogResult.OK : choice == DialogResult.Yes; if (!accepted) { _nextUpdateCheckAt = DateTimeOffset.UtcNow.AddHours(6); return false; } UseWaitCursor = true; Text = $"纵横家 · 正在下载 {update.Version}…"; using var progressWindow = new UpdateProgressForm(update.Version); progressWindow.Show(this); Enabled = false; string installer; try { installer = await ClientUpdater.DownloadAsync(update, _lifetime.Token, new Progress(progressWindow.Report)); } finally { Enabled = true; } // Start and authorize the installer BEFORE stopping the working client. // The installer stages and validates all files, then requests graceful shutdown. // Cancelling UAC or failing to start must leave the current connection alive. var installerProcess = ClientUpdater.LaunchInstaller(installer); _installerLaunched = true; _ = ObserveInstallerAsync(installerProcess); return true; } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return false; } catch (Exception exception) { _nextUpdateCheckAt = DateTimeOffset.UtcNow.AddMinutes(accepted ? 30 : 2); AppPaths.WriteError(exception); if (accepted) { MessageBox.Show( $"更新未启动,已保留当前版本和当前连接。\n\n{exception.Message}", "纵横家·更新未完成", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return false; } finally { _updateCheckRunning = false; UseWaitCursor = false; Text = "纵横家"; } } private async Task ObserveInstallerAsync(System.Diagnostics.Process installer) { try { await installer.WaitForExitAsync(); } catch (Exception exception) { AppPaths.WriteError(exception); } finally { installer.Dispose(); _installerLaunched = false; } } private void BuildLayout() { var header = _brandHeader; header.Dock = DockStyle.Top; header.Height = ScenicTheme.HeaderHeight; header.BackColor = Brand.Surface; header.Controls.Add(new PictureBox { Image = LoadAppLogo(), BackColor = Color.Transparent, SizeMode = PictureBoxSizeMode.Zoom, Bounds = new Rectangle(20, 29, 62, 67) }); header.Controls.Add(NewLabel("纵横家", Brand.Font(21, FontStyle.Bold), Brand.Navy, new Point(92, 33), new Size(295, 39))); header.Controls.Add(NewLabel($"智能安全网络 · v{GetDisplayVersion()}", Brand.Font(9.5f), Brand.Muted, new Point(94, 73), new Size(320, 25))); foreach (Control control in header.Controls) control.Tag = control.Bounds; ConfigureLabel(_headerPoem, "纵横四海 智联未来", new Font("KaiTi", 15, FontStyle.Regular), Brand.DeepBlue); _headerPoem.TextAlign = ContentAlignment.MiddleRight; header.Controls.Add(_headerPoem); InitializeWindowChrome(header); Controls.Add(header); _content.Dock = DockStyle.Fill; _content.BackColor = Brand.Surface; Controls.Add(_content); _content.BringToFront(); BuildLoginView(); BuildDashboardView(); _footerCompanyLogo.Visible = false; _footerCompanySite.Text = "智能连接 · 高效办公"; _footerCompanySite.Font = Brand.Font(9); _footerCompanySite.ForeColor = Brand.DeepBlue; CenterCards(); ShowLogin(); } private void LayoutBrandHeader() { ApplyCompactTypography(); if (CompactPresentation) { LayoutCompactHeader(); return; } _brandHeader.Height = ScaleLogical(ScenicTheme.HeaderHeight); for (var i = 0; i < _brandHeader.Controls.Count; i++) { var control = _brandHeader.Controls[i]; if (control.Tag is not Rectangle rect) continue; control.Bounds = new Rectangle(ScaleLogical(rect.X), ScaleLogical(rect.Y), ScaleLogical(rect.Width), ScaleLogical(rect.Height)); } _headerPoem.Visible = _brandHeader.Width >= ScaleLogical(780); _headerPoem.Bounds = new Rectangle(_brandHeader.Width - ScaleLogical(300), ScaleLogical(58), ScaleLogical(274), ScaleLogical(34)); LayoutWindowChrome(); } private void BuildLoginView() { _loginView.Size = new Size(440, 440); _loginView.BackColor = Color.Transparent; _loginView.Padding = new Padding(28, 18, 28, 18); _content.Controls.Add(_loginView); var appLogo = new PictureBox { Image = LoadAppLogo(), SizeMode = PictureBoxSizeMode.Zoom, Location = new Point(28, 17), Size = new Size(54, 54), BackColor = Color.Transparent, }; _loginView.Controls.Add(appLogo); _loginView.Controls.Add(NewLabel("纵横家", Brand.Font(16, FontStyle.Bold), Brand.Text, new Point(86, 20), new Size(95, 30))); _loginView.Controls.Add(NewLabel("智能安全网络", Brand.Font(7.6f), Brand.Muted, new Point(87, 50), new Size(94, 20))); var brandDivider = new Panel { BackColor = Color.FromArgb(221, 230, 239), Location = new Point(186, 18), Size = new Size(1, 54) }; _loginView.Controls.Add(brandDivider); var poweredLogo = new PictureBox { Image = LoadCompanyLogo(), SizeMode = PictureBoxSizeMode.Zoom, Location = new Point(263, 15), Size = new Size(46, 46), BackColor = Color.Transparent, }; _loginView.Controls.Add(poweredLogo); var headerLine = new Panel { BackColor = Color.FromArgb(232, 238, 245), Location = new Point(28, 86), Size = new Size(384, 1) }; _loginView.Controls.Add(headerLine); _loginView.Controls.Add(NewLabel("账号登录", Brand.Font(13.5f, FontStyle.Bold), Brand.Text, new Point(28, 100), new Size(150, 30))); _loginView.Controls.Add(NewLabel("统一账号安全接入", Brand.Font(8), Brand.Navy, new Point(129, 105), new Size(150, 22))); var versionBadge = NewLabel($"v{GetDisplayVersion()}", Brand.Font(7.2f, FontStyle.Bold), Brand.RoyalBlue, new Point(356, 101), new Size(56, 24)); versionBadge.BackColor = Brand.PaleBlue; versionBadge.TextAlign = ContentAlignment.MiddleCenter; _loginView.Controls.Add(versionBadge); _loginView.Controls.Add(NewLabel("用户名 / 邮箱", Brand.Font(8.8f, FontStyle.Bold), Brand.Text, new Point(28, 136), new Size(180, 22))); _loginText.PlaceholderText = "用户名或 name@example.com"; _loginView.Controls.Add(ConfigureTextBox(_loginText, new Point(28, 158), password: false)); _loginView.Controls.Add(NewLabel("密码", Brand.Font(8.8f, FontStyle.Bold), Brand.Text, new Point(28, 210), new Size(180, 22))); _passwordText.PlaceholderText = "请输入密码"; _loginView.Controls.Add(ConfigureTextBox(_passwordText, new Point(28, 232), password: true)); _passwordText.KeyDown += async (_, eventArgs) => { if (eventArgs.KeyCode == Keys.Enter) { eventArgs.SuppressKeyPress = true; await LoginAsync(); } }; ConfigurePrimaryButton(_loginButton, "安全登录", new Point(28, 290), new Size(384, 44)); _loginButton.Click += async (_, _) => await LoginAsync(); _loginView.Controls.Add(_loginButton); ConfigureLabel(_registerPrompt, "还没有账号?", Brand.Font(9), Brand.Navy); _registerPrompt.Bounds = new Rectangle(100, 346, 112, 28); _registerPrompt.TextAlign = ContentAlignment.MiddleRight; _registerPrompt.UseCompatibleTextRendering = false; _loginView.Controls.Add(_registerPrompt); _registerLink.Text = "注册新用户"; _registerLink.Font = Brand.Font(9, FontStyle.Bold); _registerLink.LinkColor = Brand.Navy; _registerLink.ActiveLinkColor = Brand.Navy; _registerLink.VisitedLinkColor = Brand.Navy; _registerLink.BackColor = Color.Transparent; _registerLink.Location = new Point(220, 346); _registerLink.Size = new Size(112, 28); _registerLink.TextAlign = ContentAlignment.MiddleLeft; _registerLink.UseCompatibleTextRendering = false; _registerLink.Cursor = Cursors.Hand; _registerLink.LinkClicked += (_, _) => OpenRegistrationPage(); _loginView.Controls.Add(_registerLink); var registrationHint = NewLabel("浏览器完成注册 · 管理员审核后即可登录", Brand.Font(7.6f), Brand.Navy, new Point(28, 374), new Size(384, 22)); registrationHint.TextAlign = ContentAlignment.MiddleCenter; _loginView.Controls.Add(registrationHint); _loginError.Location = new Point(28, 402); _loginError.Size = new Size(384, 30); _loginError.ForeColor = Brand.Danger; _loginError.Font = Brand.Font(8.2f); _loginError.TextAlign = ContentAlignment.MiddleCenter; _loginView.Controls.Add(_loginError); // Branding already lives in the compact top bar. Store logical bounds // explicitly: dynamically-created WinForms controls otherwise retain // 96-DPI bounds while their fonts scale to 150/200%. foreach (Control control in _loginView.Controls) { if (control.Top < 86) { control.Visible = false; continue; } control.Tag = new Rectangle(control.Left, control.Top-68, control.Width, control.Height); } } private async Task RestoreSessionAsync() { SetSessionToken(_runWindowExitSelfTest ? Environment.GetEnvironmentVariable("UCVL_VPN_TEST_TOKEN") ?? TokenStore.Load() : TokenStore.Load()); if (string.IsNullOrWhiteSpace(_accessToken)) { ShowLogin(); return; } SetBusy(true, "正在恢复登录…"); try { var profile = await _api.GetProfileAsync(_accessToken, _lifetime.Token); ShowDashboard(profile); } catch (ApiException exception) when (exception.StatusCode is 401 or 403) { AppPaths.WriteError(exception); if (!_runWindowExitSelfTest) TokenStore.Clear(); SetSessionToken(null); ShowLogin("登录已失效,请重新登录。"); } catch (Exception exception) { AppPaths.WriteError(exception); ShowLogin("暂时无法连接平台,已保留登录状态。请稍后重启或重试登录。"); } finally { SetBusy(false); } } private async Task LoginAsync() { if (_uiOnly || _preview) return; if (_busy) return; var login = _loginText.Text.Trim(); var password = _passwordText.Text; if (string.IsNullOrWhiteSpace(login) || string.IsNullOrWhiteSpace(password)) { _loginError.Text = "请输入用户名(或邮箱)和密码。"; return; } SetBusy(true, "正在登录…"); _loginError.Text = ""; try { var response = await _api.LoginAsync(login, password, _lifetime.Token); SetSessionToken(response.AccessToken, response.ExpiresAt); TokenStore.Save(_accessToken); _passwordText.Clear(); ShowDashboard(response.Profile); } catch (ApiException exception) { _loginError.Text = exception.Message; } catch (HttpRequestException exception) { AppPaths.WriteError(exception); _loginError.Text = "无法连接到纵横家平台,请检查网络后重试。"; } catch (TaskCanceledException) when (!_lifetime.IsCancellationRequested) { _loginError.Text = "连接平台超时,请稍后重试。"; } catch (Exception exception) { AppPaths.WriteError(exception); _loginError.Text = "登录时发生错误,请稍后重试。"; } finally { SetBusy(false); } } private async Task ToggleConnectionAsync(bool suppressDialogs = false, bool reconnect = false) { if (_uiOnly || _preview) return; if (!reconnect && TryCancelPendingConnection()) return; if (_handoverOperating && !reconnect) { await DisconnectAsync(); return; } if (_busy) return; if (_wantConnected && !reconnect) { await DisconnectAsync(); return; } if (string.IsNullOrWhiteSpace(_accessToken) || _availableNodeCount == 0 || _routeCombo.SelectedItem is not RouteModeInfo route) { if (!suppressDialogs) { MessageBox.Show("暂无可用工作节点,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information); } return; } ConnectionSelection selection; try { selection = ConnectionSelection.Create(ManualSelection, (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug, _manualNodeCombo.Items.Cast().Select(n => n.Slug)); } catch (InvalidOperationException exception) { if (reconnect) await DisconnectAsync(); _statusDetail.Text = exception.Message; if (!suppressDialogs) MessageBox.Show(exception.Message, "选择工作节点", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } using var attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); _connectionAttemptCancellation = attemptCancellation; var connectionToken = attemptCancellation.Token; SetBusy(true, "正在建立安全连接,可点击取消…"); _connectionHealth.Invalidate(); _nextReconnect = DateTimeOffset.MinValue; _wantConnected = true; if (!reconnect) { _tailnetPreference.ResetForUserConnect(); _transportRetryNodeSlug = null; _failedNodes.Clear(); _sessionUp = _sessionDown = 0; _trafficChart.Reset(); ResetTailnetTraffic(); _sessionMetric.SetBytes(0, hint: "本次连接累计"); } foreach (var slug in _failedNodes.Where(p => p.Value <= DateTimeOffset.UtcNow).Select(p => p.Key).ToList()) _failedNodes.Remove(slug); SetConnectionState(false, "正在连接", selection.Manual ? "正在连接手动指定节点…" : "vpn-ai 正在分配工作节点…"); var replacementStarted = false; try { if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64)) { var refreshed = await _api.GetProfileAsync(_accessToken, connectionToken); UpdateProfile(refreshed, preserveSelections: true); if (!_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64)) throw new ApiException(403, "账号或订阅授权已到期,请重新登录验证。"); } var failures = new List(); ConfigResponse? response = null; var privateGrants = _privateAuxiliaryNodes.Where(n => n.ExpiresAt > DateTimeOffset.UtcNow).ToArray(); if (selection.Manual && _privateAuxiliaryNodes.Any(n => n.Slug == selection.NodeSlug) && !privateGrants.Any(n => n.Slug == selection.NodeSlug)) throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。"); if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug)) throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。"); var rankedPrivate = route.Id == "direct" || _tailnetPreference.DomainOnly ? Array.Empty() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants, _failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning, PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken); var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken); if (reconnect && _transportRetryNodeSlug is { } sameNode && !attempts.Any(a => a.Attempt.Slug == sameNode)) // A same-node public retry must not jump ahead of another usable // overlay candidate. Keep it before only the public AI pass. attempts = attempts.Where(a => a.Attempt.IsPrivate || a.TailnetOnly) .Concat(new[] { new PlannedTransport(new(sameNode, null)) }) .Concat(attempts.Where(a => !a.Attempt.IsPrivate && !a.TailnetOnly)).ToArray(); var connectedPrivate = false; var connectedTailnet = false; PrivateAuxiliaryNode? connectedEndpoint = null; await foreach (var planned in ExpandTransportsAsync(attempts, route.Id, connectionToken)) { var attempt = planned.Attempt; NodeInfo? candidate = planned.KnownCandidate; try { var candidateResponse = await ConfirmDispatchedTransportAsync(planned, route.Id, connectionToken) ?? planned.Cached ?? (attempt.Auxiliary is { } auxiliary ? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken) : await _api.GetConfigAsync( _accessToken, attempt.Slug, route.Id, connectionToken, selection.Manual ? null : _failedNodes.Keys)); connectionToken.ThrowIfCancellationRequested(); selection.ValidateResponse(candidateResponse.Node.Slug); if ((attempt.Slug != "auto" && candidateResponse.Node.Slug != attempt.Slug) || candidateResponse.RouteMode != route.Id) throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。"); if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug)) throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。"); candidate = candidateResponse.Node; var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate); _currentNodeLabel.Text = $"{candidateName} · 正在连接"; SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}"); connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference, async (config, connectionToken) => { replacementStarted = true; await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken, TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(), preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate)); }, _xray.StopAsync, _xray.CheckProxyHealthAsync, address => { TailnetTransport.RequireExistingRoute(address); }, message => { _statusDetail.Text = $"{candidateName} · {message}"; }, () => Environment.TickCount64, connectionToken, allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate, endpointProbe: TailnetTransport.ProbeEndpointAsync, tailnetOnly: planned.TailnetOnly, diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage)); if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken)) throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。"); connectionToken.ThrowIfCancellationRequested(); if (attempt.IsPrivate && candidateResponse.ConfigExpiresAt <= DateTimeOffset.UtcNow) throw new InvalidOperationException("私有节点授权在连接期间已过期。"); connectedPrivate = attempt.IsPrivate; connectedEndpoint = attempt.Auxiliary; if (attempt.IsPrivate) connectedTailnet = attempt.Auxiliary?.ProbeIpv4 == PrivateAuxiliaryRouting.PhoneTailnetAddress; _failedNodes.Remove(candidate.Slug); response = candidateResponse; break; } catch (LocalNetworkException) { throw; } catch (TailnetUnavailableException) { // Connector cleans up only a core it actually attempted. // Retain node eligibility for the later public pass. failures.Add($"{candidate?.Name ?? "内网节点"}: Tailscale 入口未通过,继续其他内网节点。"); } catch (ApiException exception) when (exception.StatusCode is not (401 or 403)) { if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw; failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}"); await _xray.StopAsync(); if (candidate is null) break; _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5); if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…"; } catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 }) { if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw; failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}"); await _xray.StopAsync(); if (candidate is not null) _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5); else break; if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…"; } } if (response is null) { throw new InvalidOperationException( (selection.Manual ? "指定节点连接失败,未切换其他节点,已执行网络恢复。\n\n" : "所有可用线路均未能建立连接,已执行网络恢复。\n\n") + string.Join("\n", failures)); } connectionToken.ThrowIfCancellationRequested(); _currentNodeSlug = response.Node.Slug; _currentNodeIsPrivateAuxiliary = connectedPrivate; _currentPrivateEndpoint = connectedEndpoint; _transportRetryNodeSlug = null; _privateLeaseDeadlineTicks = connectedPrivate ? Environment.TickCount64 + Math.Max(0, (long)(response.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds) : 0; _currentNodeBaseName = NodePresentation.Name(response.Node.Slug, response.Node.Name, connectedPrivate); UpdateConnectedTransportPresentation(connectedTailnet); _handover.Reset(); _currentNodeLabel.Text = _currentNodeName; _connectionHealth.BeginCore(Environment.TickCount64); _tailnetReadiness.Reset(); _tailnetReadiness.TryBegin(ReadTailnetReadinessContext(), Environment.TickCount64, out _); SetConnectionState(true, "已安全连接", $"{_currentNodeName} · {route.Name}" + (connectedPrivate ? " · 私有辅助(TCP)" : "")); _notifyIcon.Text = "纵横家 · 已连接"; _notifyIcon.ShowBalloonTip(1800, "纵横家已连接", $"当前线路:{_currentNodeName}", ToolTipIcon.Info); } catch (Exception) when (connectionToken.IsCancellationRequested) { if (!_exiting) await DisconnectAsync(); } catch (Exception exception) when (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) { AppPaths.WriteLog("调度请求失败,尚未启动替换线路,保留原内核与路由;两分钟后重试。" + exception.GetType().Name); _wantConnected = true; _connectionHealth.ResetFailures(); _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); SetConnectionState(true, "恢复中 · 保留原线路", "调度平台暂时不可用,未中断现有连接;稍后自动重试。"); _currentNodeLabel.Text = _currentNodeName ?? _currentNodeSlug ?? "原工作节点"; } catch (ApiException exception) { await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403); if (!suppressDialogs) { MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); } if (exception.StatusCode is 401 or 403) { await HandleSessionInvalidAsync(); } } catch (Exception exception) { AppPaths.WriteError(exception); await DisconnectAsync(cancelPending: false); if (!suppressDialogs) { MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } finally { if (!_xray.IsRunning && reconnect && !connectionToken.IsCancellationRequested && !string.IsNullOrWhiteSpace(_accessToken)) { _wantConnected = true; _nextReconnect = DateTimeOffset.UtcNow.AddMinutes(2); } if (ReferenceEquals(_connectionAttemptCancellation, attemptCancellation)) _connectionAttemptCancellation = null; SetBusy(false); } } private async Task DisconnectAsync(bool cancelPending = true) { _wantConnected = false; if (cancelPending) _connectionAttemptCancellation?.Cancel(); _tailnetReadiness.Reset(); _tailnetReconnectItem.Enabled = false; _learningSync.Reset(); _learningSyncCore = null; _handoverCancellation?.Cancel(); _handover.Reset(); _connectionHealth.Invalidate(); await _xray.StopAsync(); _currentNodeSlug = null; _currentNodeIsPrivateAuxiliary = false; _currentPrivateEndpoint = null; _currentNodeUsesTailnet = false; SetTailnetTrafficVisibility(false); _transportRetryNodeSlug = null; _privateLeaseDeadlineTicks = 0; _currentNodeName = null; _currentNodeBaseName = null; _currentNodeLabel.Text = "连接后自动分配"; DisplayTraffic(null, null, "已断开"); SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点"); _notifyIcon.Text = "纵横家 · 未连接"; } private async Task RefreshTrafficAsync() { _trafficChart.AdvanceClock(); if (_exiting) return; if (_trafficReading) return; if (_busy || !_xray.IsRunning) { _trafficChart.MarkUnavailable(); _historyStatus.Text = "采样暂停 · 历史时间轴继续推进"; DisplayTraffic(null, null, "采样暂停"); return; } _trafficReading = true; try { var core = _xray.CoreId; var counters = await _xray.ReadTrafficAsync(_lifetime.Token); if (counters is null || core != _xray.CoreId) { _trafficChart.MarkUnavailable(); _historyStatus.Text = "采样暂不可用 · 不补零"; DisplayTraffic(null, null, "采样暂不可用"); return; } var now = DateTimeOffset.UtcNow; if (core != _lastCoreId) { _lastCoreId = core ?? 0; _lastUp = _lastDown = 0; _lastSample = now.AddSeconds(-5); } var seconds = Math.Max(0.1, (now-_lastSample).TotalSeconds); var up = Math.Max(0, counters.Value.Up-_lastUp); var down = Math.Max(0, counters.Value.Down-_lastDown); _sessionUp += up; _sessionDown += down; _lastUp = counters.Value.Up; _lastDown = counters.Value.Down; _lastSample = now; DisplayTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟"); _sessionMetric.SetBytes(_sessionUp + _sessionDown, hint: "本次连接累计"); _trafficChart.Add(up/seconds, down/seconds); _historyStatus.Text = "仅本次运行采样 · KB/s 起"; // This is a view of the SAME proxy sample, not a second counter. // A single connected proxy uses either its Tailnet or public ingress. // Do not read the whole Tailscale adapter or add this subset to usage. if (_currentNodeUsesTailnet) DisplayTailnetTraffic(up / seconds, down / seconds, $"{now.LocalDateTime:HH:mm:ss} · 近 5 分钟"); } catch (OperationCanceledException) { } catch (Exception exception) { _trafficChart.MarkUnavailable(); _historyStatus.Text = "采样暂不可用 · 不补零"; DisplayTraffic(null, null, "采样暂不可用"); AppPaths.WriteError(exception); } finally { _trafficReading = false; } } private async Task MaintainConnectionAsync() { if (_wantConnected && !_connectionAuthorization.AccountIsValid(DateTimeOffset.UtcNow, Environment.TickCount64) && !_busy && !_healthChecking && !_handoverOperating && !_exiting) { await DisconnectAsync(); _statusDetail.Text = "已知账号或订阅授权已到期,请联网重新验证。"; return; } if (_currentNodeIsPrivateAuxiliary && _privateLeaseDeadlineTicks > 0 && Environment.TickCount64 >= _privateLeaseDeadlineTicks && !_busy && !_healthChecking && !_handoverOperating && !_exiting) { _healthChecking = true; try { var expiredSlug = _currentNodeSlug; await DisconnectAsync(); if (expiredSlug is not null) _failedNodes[expiredSlug] = DateTimeOffset.UtcNow.AddMinutes(5); await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); } finally { _healthChecking = false; } return; } await CheckUplinkAsync(); if (_uplinkChecking || _handover.Pending || _handover.Settling) return; if (!_wantConnected || _busy || _xray.IsTransitioning || _healthChecking || _exiting || DateTimeOffset.UtcNow < _nextReconnect) return; _healthChecking = true; try { // Local lease maintenance must run even if the backend is unavailable, // and frequently enough for bounded, ahead-of-expiry rechecks. await _xray.ExpireLearningAsync(_lifetime.Token); if (!_connectionHealth.IsDue(Environment.TickCount64, _xray.IsRunning)) return; var revision = _connectionHealth.Revision; var testedCore = _xray.CoreId; var health = await _xray.CheckHealthWithRepairAsync(_lifetime.Token); var healthy = health.Healthy; var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId, _wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy, _xray.UsesTailnet, health.BusinessUnavailable); if (decision == ConnectionHealthPolicy.Decision.Ignore) return; if (healthy && _xray.IsRunning) { if (_localRoutingFault) { _localRoutingFault = false; SetConnectionState(true, "已安全连接", $"{_currentNodeName ?? _currentNodeSlug} · {_routeCombo.Text}"); _notifyIcon.Text = "纵横家 · 已连接"; AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。"); } ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId); return; } if (decision == ConnectionHealthPolicy.Decision.Degraded) { _localRoutingFault = true; SetConnectionState(true, "网站探测异常,连接保留", $"{_currentNodeName ?? _currentNodeSlug} · 目标网站可用性尚未确认,保留当前线路"); _statusTitle.ForeColor = Color.FromArgb(155, 88, 12); _statusDot.ForeColor = _statusTitle.ForeColor; _notifyIcon.Text = "纵横家 · 网站探测异常"; AppPaths.WriteLog("健康诊断:网站探测异常,保留当前内核和已授权线路;未将网站状态判为节点传输失败。"); return; } if (decision == ConnectionHealthPolicy.Decision.Repair) { _localRoutingFault = true; SetConnectionState(true, "分流异常,正在修复", $"{_currentNodeName ?? _currentNodeSlug} · 代理出口可达,保留现有连接并重试规则验证"); _statusTitle.ForeColor = Color.FromArgb(155, 88, 12); _statusDot.ForeColor = _statusTitle.ForeColor; _notifyIcon.Text = "纵横家 · 分流修复中"; AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。"); return; } ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures); if (decision != ConnectionHealthPolicy.Decision.Switch) return; if (_currentNodeSlug is not null) { if (_currentNodeUsesTailnet) { // Transport failure is not node failure. Retry the same authorized // node through its original ingress before asking for another node. _tailnetPreference.Failed(_currentNodeSlug, Environment.TickCount64); _tailnetPreference.CommitDomainFallback(); _transportRetryNodeSlug = _currentNodeSlug; } else _failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5); } SetConnectionState(false, "链路异常,正在恢复", ManualSelection ? "正在重试手动指定节点,不会切换其他节点" : "连续检查失败,向 vpn-ai 申请备用工作节点"); await ToggleConnectionAsync(suppressDialogs: true, reconnect: true); } catch (OperationCanceledException) { } catch (Exception exception) { AppPaths.WriteError(exception); } finally { _healthChecking = false; } } private async Task RunWindowExitSelfTestAsync() { await ToggleConnectionAsync(suppressDialogs: true); _windowExitSelfTestConnected = _xray.IsRunning; if (_windowExitSelfTestConnected) { await Task.Delay(1500); } Close(); } private Task ReportObservationAsync(LearningObservation observation) { var token = _accessToken; if (!string.IsNullOrWhiteSpace(token) && !_lifetime.IsCancellationRequested && _observationQueue.Count < 64) _observationQueue.Enqueue((token, observation, Environment.TickCount64)); return Task.CompletedTask; } private async Task SynchronizeLearningAsync() { if (_learningSyncing || _busy || _uiOnly || _preview || string.IsNullOrWhiteSpace(_accessToken)) return; _learningSyncing = true; var token = _accessToken; var revision = _sessionRevision; var core = _xray.CoreId; bool IsCurrent() => SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting) && core is not null && core == _xray.CoreId && !_busy; try { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); deadline.CancelAfter(TimeSpan.FromSeconds(15)); await _xray.ExpireLearningAsync(deadline.Token); if (!IsCurrent()) return; if (_learningSyncCore != core) { _learningSync.Reset(); _learningSyncCore = core; } await _learningSync.RunAsync(IsCurrent, async uploadToken => { // A slow optional upload must leave budget for rule fetch. using var uploadDeadline = CancellationTokenSource.CreateLinkedTokenSource(uploadToken); uploadDeadline.CancelAfter(TimeSpan.FromSeconds(4)); for (var count = 0; count < 10 && _observationQueue.TryPeek(out var pending); count++) { if (!IsCurrent()) return; if (pending.Token != token || Environment.TickCount64 - pending.Created > 5 * 60_000) { _observationQueue.TryDequeue(out _); continue; } try { await _api.ReportObservationAsync(token, pending.Observation, uploadDeadline.Token); } catch (ApiException error) when (error.StatusCode == 400) { if (IsCurrent()) _observationQueue.TryDequeue(out _); continue; } if (!IsCurrent()) return; _observationQueue.TryDequeue(out _); } }, fetchToken => _api.GetRoutingRulesAsync(token, fetchToken), async (manifest, applyToken) => { if (!IsCurrent()) return false; await _xray.CacheLearningCandidatesAsync(manifest, core!.Value, applyToken); return IsCurrent(); }, (acceptedRevision, ackToken) => _api.AcknowledgeRoutingAsync(token, acceptedRevision, true, ackToken), deadline.Token, message => AppPaths.WriteLog(message)); } catch (ApiException error) when (error.StatusCode is 401 or 403) { if (!IsCurrent()) return; await DisconnectAsync(); if (SessionOperationFence.IsCurrent(revision, _sessionRevision, token, _accessToken, _exiting)) await HandleSessionInvalidAsync(); } catch (OperationCanceledException) { } catch (Exception error) { if (IsCurrent()) AppPaths.WriteLog("learning.sync.local_failure type=" + error.GetType().Name); } finally { _learningSyncing = false; } } private void ShowAiStatus(string message) { if (_exiting || IsDisposed || Disposing) return; var reportingCore = _xray.CoreId; PostUi(() => { if (_dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore) _statusDetail.Text = NodePresentation.LearningDetail(_selectionUiConnected, _currentNodeName, message); }); } private async Task RefreshProfileAsync(bool silent) { if (_busy || string.IsNullOrWhiteSpace(_accessToken)) return; var sessionToken = _accessToken; var sessionRevision = _sessionRevision; bool IsCurrent() => SessionOperationFence.IsCurrent(sessionRevision, _sessionRevision, sessionToken, _accessToken, _exiting); try { var profile = await _api.GetProfileAsync(sessionToken, _lifetime.Token); if (!IsCurrent() || _busy) return; UpdateProfile(profile, preserveSelections: true); if (_currentNodeIsPrivateAuxiliary && !_privateAuxiliaryNodes.Any(n => n.Slug == _currentNodeSlug)) { await DisconnectAsync(); if (!IsCurrent()) return; _statusDetail.Text = "私有节点授权已撤回,连接已断开。"; } else if (_currentNodeIsPrivateAuxiliary && _xray.CoreId is { } privateCore && !_busy && !_handoverOperating && _routeCombo.SelectedItem is RouteModeInfo privateRoute) { var grant = PrivateAuxiliaryRouting.ForRenewal( _privateAuxiliaryNodes.Single(n => n.Slug == _currentNodeSlug), _currentPrivateEndpoint ?? throw new InvalidOperationException("当前私有节点入口记录缺失。")); var renewed = await _api.GetPrivateAuxiliaryConfigAsync(sessionToken, grant, privateRoute.Id, _lifetime.Token); if (!IsCurrent()) return; if (_currentNodeIsPrivateAuxiliary && _xray.CoreId == privateCore) { var accepted = await _xray.RenewPrivateAuthorizationAsync(renewed.GetRuntimeConfigJson(), privateCore, _lifetime.Token); if (!IsCurrent() || _xray.CoreId != privateCore) return; if (accepted) { _privateLeaseDeadlineTicks = Environment.TickCount64 + Math.Max(0, (long)(renewed.ConfigExpiresAt!.Value - DateTimeOffset.UtcNow).TotalMilliseconds); } else { await DisconnectAsync(); if (!IsCurrent()) return; _statusDetail.Text = "私有节点凭据或配置已变更,请重新连接。"; } } } } catch (ApiException exception) when (exception.StatusCode is 401 or 403) { if (!IsCurrent()) return; await DisconnectAsync(); if (!IsCurrent()) return; await HandleSessionInvalidAsync(); } catch (Exception exception) { if (!IsCurrent()) return; AppPaths.WriteError(exception); if (!silent) { MessageBox.Show("暂时无法刷新账号信息。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } private async Task LogoutAsync() { if (_busy) return; SetBusy(true, "正在退出…"); await DisconnectAsync(); var token = _accessToken; try { if (!string.IsNullOrWhiteSpace(token)) { await _api.LogoutAsync(token, _lifetime.Token); } } catch (Exception exception) { AppPaths.WriteError(exception); } finally { TokenStore.Clear(); SetSessionToken(null); SetBusy(false); ShowLogin(); } } private Task HandleSessionInvalidAsync() { TokenStore.Clear(); SetSessionToken(null); ShowLogin("账号授权或订阅已失效,请重新登录或联系管理员。 "); return Task.CompletedTask; } private void ShowLogin(string error = "") { if (_exiting || IsDisposed || Disposing) return; _knownTailnetAllowed = false; _refreshTimer.Stop(); SetNodeTrafficPermission(false); _content.SuspendLayout(); _loginView.SuspendLayout(); try { _loginError.Text = error; _windowChrome?.SetLoginMode(true); CenterCards(); _dashboardView.Visible = false; if (_welcomeLabel.Parent==_brandHeader) _welcomeLabel.Visible=_logoutButton.Visible=false; _loginView.Visible = true; _loginView.BringToFront(); } finally { _loginView.ResumeLayout(false); _content.ResumeLayout(false); } _loginText.Focus(); } private void ShowDashboard(Profile profile) { if (_exiting || IsDisposed || Disposing) return; _content.SuspendLayout(); try { // Complete data binding and geometry before revealing the restored // account. Hidden docked panels do not always have current bounds. _dashboardView.Bounds = _content.ClientRectangle; UpdateProfile(profile, preserveSelections: false); SetConnectionState(false, "未连接", "点击连接,vpn-ai 自动选择工作节点"); LayoutDashboard(); _loginView.Visible = false; _dashboardView.Visible = true; if (_welcomeLabel.Parent==_brandHeader) _welcomeLabel.Visible=_logoutButton.Visible=true; _dashboardView.BringToFront(); _windowChrome?.SetLoginMode(false); } finally { _content.ResumeLayout(false); } _refreshTimer.Start(); } private void UpdateProfile(Profile profile, bool preserveSelections) { if (_exiting || IsDisposed || Disposing) return; _connectionAuthorization.AcceptProfile(profile.Subscription.Status, profile.Subscription.ExpiresAt, DateTimeOffset.UtcNow, Environment.TickCount64); _knownTailnetAllowed = true; ConfigureNodeTrafficMonitor(profile); var selectedRoute = preserveSelections ? (_routeCombo.SelectedItem as RouteModeInfo)?.Id : null; _welcomeLabel.Text = $"你好,{profile.DisplayName}"; _accountLabel.Text = profile.Email; _identityBadge.Text = profile.IdentityType == "employee" ? "内部员工" : "外部联系人"; _planLabel.Text = $"套餐:{profile.Subscription.Plan} · 设备上限 {profile.Subscription.DeviceLimit} 台"; _expiryLabel.Text = profile.Subscription.ExpiresAt is null ? "长期有效" : $"到期:{profile.Subscription.ExpiresAt.Value.LocalDateTime:yyyy-MM-dd}"; var used = profile.Subscription.UsedBytes; var total = profile.Subscription.TrafficLimitBytes; _usageMetric.SetBytes(used, hint: total > 0 ? $"套餐总量 {FormatBytes(total)}" : "不限流量"); _availableNodeCount = profile.Nodes.Count; UpdateSelectionNodes(profile, preserveSelections); _dailyChart.SetHistory(profile.UsageHistory, profile.UsageHistoryRanges); _routeCombo.BeginUpdate(); _routeCombo.Items.Clear(); foreach (var route in profile.RouteModes) _routeCombo.Items.Add(route); _routeCombo.EndUpdate(); _routeCombo.SelectedItem = profile.RouteModes.FirstOrDefault(route => route.Id == selectedRoute) ?? profile.RouteModes.FirstOrDefault(); _routeReadOnly.Text = _selectionUiConnected ? _routeCombo.Text : "未生效"; _connectButton.Enabled = _availableNodeCount > 0 && !_busy; if (_availableNodeCount == 0 && !_wantConnected) { SetConnectionState(false, "暂无线上的线路", "请联系管理员检查节点状态"); } } private void SetConnectionState(bool connected, string title, string detail) { _selectionUiConnected = connected; ConnectionAcceptanceTrace.Record(connected ? "ui_connected" : "ui_not_connected", _currentNodeSlug, connected, _xray.CoreId); _statusDot.ForeColor = connected ? Brand.Success : Brand.Muted; _statusTitle.Text = title; _statusTitle.ForeColor = connected ? Brand.Success : Brand.Text; _statusDetail.Text = detail; _connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接"; _connectButton.BackColor = Brand.RoyalBlue; if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量"); _routeCombo.Enabled = !connected && !_busy; _routeCombo.Visible = true; _routeReadOnly.Text = connected ? _routeCombo.Text : "未生效"; _routeReadOnly.Visible = true; RefreshSelectionControls(); } private void SetBusy(bool busy, string? status = null) { if (_exiting || IsDisposed || Disposing) return; _busy = busy; UseWaitCursor = busy; _loginButton.Enabled = !busy; _registerLink.Enabled = !busy; _loginText.ReadOnly = busy; _passwordText.ReadOnly = busy; _loginButton.Text = busy && _loginView.Visible ? status ?? "请稍候…" : "安全登录"; _logoutButton.Enabled = !busy; _connectButton.Enabled = _connectionAttemptCancellation is { IsCancellationRequested: false } || !busy && (_availableNodeCount > 0 || _wantConnected); if (_connectionAttemptCancellation is { IsCancellationRequested: false }) _connectButton.Text = "取消连接"; else if (!busy) _connectButton.Text = _selectionUiConnected ? "断开连接" : "连接"; RefreshSelectionControls(); if (busy && _dashboardView.Visible && !string.IsNullOrWhiteSpace(status)) { _statusDetail.Text = status; } } private void CenterCards() { ApplyCompactTypography(); if (CompactPresentation) { LayoutCompactLogin(); return; } _loginView.Size = new Size(ScaleLogical(440), ScaleLogical(374)); foreach (Control control in _loginView.Controls) if (control.Tag is Rectangle rect) control.Bounds = new Rectangle(ScaleLogical(rect.X), ScaleLogical(rect.Y), ScaleLogical(rect.Width), ScaleLogical(rect.Height)); var textFlags = TextFormatFlags.SingleLine; var registration = LoginRegistrationBounds(_loginView.Width, DeviceDpi, TextRenderer.MeasureText(_registerPrompt.Text, _registerPrompt.Font, Size.Empty, textFlags), TextRenderer.MeasureText(_registerLink.Text, _registerLink.Font, Size.Empty, textFlags)); _registerPrompt.Bounds = registration.Prompt; _registerLink.Bounds = registration.Link; var margin = ScaleLogical(24); _loginView.Left = Math.Max(margin, (_content.ClientSize.Width - _loginView.Width) / 2); _loginView.Top = Math.Max(margin, (_content.ClientSize.Height - _loginView.Height) / 2); } private async void OnFormClosing(object? sender, FormClosingEventArgs eventArgs) { if (eventArgs.CloseReason == CloseReason.WindowsShutDown) { CompleteSessionEnding(); return; } if (_exitCleanupCompleted || _sessionEnding) return; if (!_exitRequested && !_runWindowExitSelfTest && _windowChrome?.LoginMode != true && eventArgs.CloseReason == CloseReason.UserClosing) { eventArgs.Cancel = true; return; } if (_uiOnly || _preview) { _ = BeginExitCleanup(); CompleteExitResources(); _exitCleanupCompleted = true; return; } eventArgs.Cancel = true; if (_exitCleanupStarted) return; var cleanup = BeginExitCleanup(); _connectButton.Enabled = false; _logoutButton.Enabled = false; _routeCombo.Enabled = false; Text = "纵横家 · 正在恢复本地网络并退出…"; if (_dashboardView.Visible) { SetConnectionState(false, "正在恢复本地网络", "正在恢复系统代理并关闭内核,请稍候…"); } var error = await cleanup; if (_sessionEnding || IsDisposed || Disposing) return; if (error is not null) { // Never install over a client whose network recovery failed. NetworkRecoveryFailed = true; MessageBox.Show("网络恢复未全部完成,恢复记录已保留;本次不继续自动安装。\n" + error.GetBaseException().Message, "纵横家 · 网络恢复提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } CompleteExitResources(); _exitCleanupCompleted = true; PostUi(Close, allowExiting: true); } private Task BeginExitCleanup() { if (_exitCleanupTask is not null) return _exitCleanupTask; _exitCleanupStarted = true; _exiting = true; _busy = true; StopHandoverMonitoring(); _refreshTimer.Stop(); _updateTimer.Stop(); _trafficTimer.Stop(); _healthTimer.Stop(); _nodeTrafficTimer.Stop(); _lifetime.Cancel(); if (_uiOnly || _preview) return _exitCleanupTask = Task.FromResult(null); // The same tracked cleanup serves menu/installer exit and session end. // Run it without a UI synchronization context so WM_ENDSESSION can // wait within Windows' shutdown budget without blocking its continuations. return _exitCleanupTask = Task.Run(async () => { try { await _xray.DisposeAsync().ConfigureAwait(false); return (Exception?)null; } catch (Exception error) { AppPaths.WriteError(error); return error; } }); } private void CompleteExitResources() { if (_exitResourcesDisposed) return; _exitResourcesDisposed = true; WindowExitSelfTestPassed = !_runWindowExitSelfTest || (_windowExitSelfTestConnected && !_xray.IsRunning); _api.Dispose(); _notifyIcon.Visible = false; _notifyIcon.Dispose(); } protected override void WndProc(ref Message message) { if (message.Msg == 0x11 /* WM_QUERYENDSESSION */) { // A query may be canceled by another application. Do not cancel // our session or await network cleanup until Windows confirms it. message.Result = (IntPtr)1; return; } if (message.Msg == 0x16 /* WM_ENDSESSION */) { if (message.WParam == IntPtr.Zero) { message.Result = IntPtr.Zero; return; } CompleteSessionEnding(); } base.WndProc(ref message); } private void CompleteSessionEnding() { if (_sessionEnding) return; _sessionEnding = true; var cleanup = BeginExitCleanup(); // Windows can terminate us after its short shutdown allowance. Never // remove recovery journals here or display a modal recovery error. _exitCleanupCompleted = cleanup.Wait(TimeSpan.FromSeconds(3)); NetworkRecoveryFailed |= !_exitCleanupCompleted || cleanup.Result is not null; if (NetworkRecoveryFailed) AppPaths.WriteLog("Windows 会话结束:网络恢复未全部完成,保留恢复记录供下次启动继续处理。"); CompleteExitResources(); } private void PostUi(Action action, bool allowExiting = false) { if ((!allowExiting && _exiting) || IsDisposed || Disposing || !IsHandleCreated) return; try { BeginInvoke(() => { if ((!allowExiting && _exiting) || _sessionEnding || IsDisposed || Disposing || !IsHandleCreated) return; action(); }); } catch (InvalidOperationException) { } } private NotifyIcon BuildNotifyIcon() { var exitItem = new ToolStripMenuItem("断开并退出"); var showItem = new ToolStripMenuItem("显示纵横家"); var menu = new ContextMenuStrip(); menu.Items.Add(showItem); menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(exitItem); showItem.Click += (_, _) => ShowFromTray(); exitItem.Click += (_, _) => RequestExit(); var notify = new NotifyIcon { Icon = Icon, Text = "纵横家 · 未连接", Visible = true, ContextMenuStrip = menu, }; notify.DoubleClick += (_, _) => ShowFromTray(); return notify; } internal void ShowFromTray() { // Windows can deliver a queued tray event while the form is already // shutting down. Ignore it instead of touching disposed WinForms state. if (_exiting || IsDisposed || Disposing || !IsHandleCreated) return; RestoreFromTrayPresentation(); Show(); WindowState = FormWindowState.Normal; if (!Screen.AllScreens.Any(screen => screen.WorkingArea.IntersectsWith(Bounds))) CenterToScreen(); BringToFront(); Activate(); } internal bool LoginFieldsVisibleForTest => Visible && _loginView.Visible && _loginText.Visible && _passwordText.Visible && _loginButton.Visible && _loginView.RectangleToScreen(_loginView.ClientRectangle).Contains(_loginText.RectangleToScreen(_loginText.ClientRectangle)) && _loginView.RectangleToScreen(_loginView.ClientRectangle).Contains(_passwordText.RectangleToScreen(_passwordText.ClientRectangle)) && _content.RectangleToScreen(_content.ClientRectangle).Contains(_loginButton.RectangleToScreen(_loginButton.ClientRectangle)); internal bool LoginReadyForTest => LoginFieldsVisibleForTest && _loginButton.Enabled && !_busy; // Measured text, not fixed label widths, keeps the whole row centered after // DPI changes. Both controls use the same font metrics and vertical alignment. internal static (Rectangle Prompt, Rectangle Link) LoginRegistrationBounds(int width, int dpi, Size prompt, Size link) { int S(int value) => Math.Max(1, (int)Math.Round(value * dpi / 96f)); var gap = S(8); var promptWidth = prompt.Width + S(4); var linkWidth = link.Width + S(4); // Scale the endpoints, rather than rounding Y and height separately: // at 125/175% the latter can cross the next row by one device pixel. var height = Math.Max(S(306) - S(278), Math.Max(prompt.Height, link.Height) + S(4)); var left = (width - promptWidth - gap - linkWidth) / 2; return (new Rectangle(left, S(278), promptWidth, height), new Rectangle(left + promptWidth + gap, S(278), linkWidth, height)); } internal bool LoginRegistrationAlignedForTest => _registerPrompt.Top == _registerLink.Top && _registerPrompt.Height == _registerLink.Height && _registerPrompt.Font.FontFamily.Name == _registerLink.Font.FontFamily.Name && Math.Abs(_registerPrompt.Font.SizeInPoints - _registerLink.Font.SizeInPoints) < .01f && _registerPrompt.TextAlign == ContentAlignment.MiddleRight && _registerLink.TextAlign == ContentAlignment.MiddleLeft && _registerPrompt.Right < _registerLink.Left && TextRenderer.MeasureText(_registerPrompt.Text, _registerPrompt.Font, Size.Empty, TextFormatFlags.SingleLine).Width <= _registerPrompt.Width && TextRenderer.MeasureText(_registerLink.Text, _registerLink.Font, Size.Empty, TextFormatFlags.SingleLine).Width <= _registerLink.Width && _loginView.ClientRectangle.Contains(_registerPrompt.Bounds) && _loginView.ClientRectangle.Contains(_registerLink.Bounds) && _registerPrompt.Top >= _loginButton.Bottom && _registerPrompt.Bottom <= (CompactPresentation ? _loginView.Height : ScaleLogical(306)) && Math.Abs((_registerPrompt.Left + _registerLink.Right) / 2f - _loginView.Width / 2f) <= 1; internal void RequestExit() { if (_exiting || IsDisposed || Disposing) return; _exitRequested = true; Close(); } private static void OpenRegistrationPage() { try { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = "https://vpn.example.invalid/register/", UseShellExecute = true, }); } catch (Exception exception) { AppPaths.WriteError(exception); MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.example.invalid/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private int ScaleLogical(int value) => Math.Max(1, (int)Math.Round(value * DeviceDpi / 96f)); private static void ConfigureCard(CardPanel card, Point location, Size size) { card.Location = location; card.Size = size; card.BackColor = Color.White; card.Padding = new Padding(18); } private static void ConfigureLabel(Label label, string text, Font font, Color color) { label.Text = text; label.Font = font; label.ForeColor = color; label.BackColor = Color.Transparent; } private static Label NewLabel(string text, Font font, Color color, Point location, Size size, AnchorStyles anchor = AnchorStyles.Top | AnchorStyles.Left) => new() { Text = text, Font = font, ForeColor = color, Location = location, Size = size, Anchor = anchor, BackColor = Color.Transparent, }; private static ModernInputPanel ConfigureTextBox(TextBox textBox, Point location, bool password) { textBox.BorderStyle = BorderStyle.None; textBox.Font = Brand.Font(10.2f); textBox.ForeColor = Brand.Text; textBox.BackColor = Color.White; textBox.UseSystemPasswordChar = password; return new ModernInputPanel(textBox) { Location = location, Size = new Size(384, 42), }; } private static void ConfigureCombo(DashboardCombo combo, Point location, Size size) { combo.Location = location; combo.Size = size; combo.Font = Brand.Font(10); combo.BackColor = Color.Transparent; combo.ForeColor = Brand.Text; } private static void ConfigurePrimaryButton(Button button, string text, Point location, Size size) { button.Text = text; button.Location = location; button.Size = size; button.FlatStyle = FlatStyle.Flat; button.FlatAppearance.BorderSize = 0; button.FlatAppearance.MouseOverBackColor = Color.FromArgb(10, 75, 185); button.FlatAppearance.MouseDownBackColor = Brand.DeepBlue; button.BackColor = Brand.RoyalBlue; button.ForeColor = Color.White; button.Font = Brand.Font(10.5f, FontStyle.Bold); button.Cursor = Cursors.Hand; } private static void ConfigureSecondaryButton(Button button, string text, Point location, Size size) { button.Text = text; button.Location = location; button.Size = size; button.FlatStyle = FlatStyle.Flat; button.FlatAppearance.BorderColor = Color.FromArgb(202, 215, 228); button.FlatAppearance.BorderSize = 1; button.BackColor = Color.White; button.ForeColor = Brand.Text; button.Font = Brand.Font(9); button.Cursor = Cursors.Hand; } private static Icon LoadIcon() { var path = Path.Combine(AppContext.BaseDirectory, "assets", "zonghengjia-app-v1.ico"); return File.Exists(path) ? new Icon(path) : SystemIcons.Shield; } private static Image? LoadAppLogo() { var path = Path.Combine(AppContext.BaseDirectory, "assets", "zonghengjia-app-logo-v1.png"); return LoadImage(path); } private static Image? LoadCompanyLogo() { var path = Path.Combine(AppContext.BaseDirectory, "assets", "company-logo-original.png"); return LoadImage(path); } private static Image? LoadImage(string path) { if (!File.Exists(path)) return null; using var source = Image.FromFile(path); return new Bitmap(source); } private static string GetDisplayVersion() { var raw = Application.ProductVersion.Split('+', 2)[0].Trim(); if (Version.TryParse(raw, out var version)) { return version.Build >= 0 ? $"{version.Major}.{version.Minor}.{version.Build}" : $"{version.Major}.{version.Minor}"; } return raw; } private static string FormatBytes(long bytes) { string[] units = ["B", "KB", "MB", "GB", "TB"]; var value = (double)Math.Max(0, bytes); var unit = 0; while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } return $"{value:0.##} {units[unit]}"; } } internal class CardPanel : Panel { internal const int SurfaceAlpha = 128; internal bool Embedded { get; set; } internal bool ScenicStatus { get; set; } internal bool AccentBar { get; set; } internal bool MetricBand { get; set; } internal CardPanel() { SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Opaque, false); BackColor = Color.Transparent; } protected override void OnPaintBackground(PaintEventArgs eventArgs) { var g = eventArgs.Graphics; if (Parent is not null) { var state = g.Save(); g.TranslateTransform(-Left, -Top); InvokePaintBackground(Parent, new PaintEventArgs(g, Parent.ClientRectangle)); g.Restore(state); } else g.Clear(Brand.Surface); // Metrics inherit the freshly painted card; never retain the previous // number, or add another white tint on every child repaint. if (Embedded || Width < 16 || Height < 16) return; g.SmoothingMode = SmoothingMode.AntiAlias; var s = DeviceDpi / 96f; var radius = Math.Max(6, (int)(11 * s)); using var shadow = UiGeometry.RoundedRectangle(new Rectangle(1, 3, Width - 3, Height - 4), radius); using var shadowPen = new Pen(Color.FromArgb(32, 110, 169, 199), Math.Max(1, 2 * s)); g.DrawPath(shadowPen, shadow); using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 5), radius); using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 238, 247, 255)); using var border = new Pen(ScenicStatus ? Color.White : Color.FromArgb(201, 227, 249), Math.Max(1, s * (ScenicStatus ? 1.7f : .75f))); g.FillPath(fill, path); if (ScenicStatus) { var state = g.Save(); g.SetClip(path); ScenicTheme.Clouds(g, new Rectangle(Width - (int)(260*s), (int)(14*s), (int)(120*s), (int)(50*s)), .6f); g.Restore(state); } g.DrawPath(border, path); if (AccentBar) { using var bar = UiGeometry.RoundedRectangle(new Rectangle((int)(14*s), (int)(18*s), (int)(4*s), Height-(int)(38*s)), (int)(2*s)); using var accent = new LinearGradientBrush(ClientRectangle, Brand.RoyalBlue, Brand.Cyan, 90); g.FillPath(accent, bar); } if (MetricBand) { using var band = UiGeometry.RoundedRectangle(new Rectangle((int)(12*s), (int)(40*s), Width-(int)(24*s), (int)(88*s)), (int)(8*s)); using var bandPen = new Pen(Color.FromArgb(224, 237, 248), Math.Max(1, s*.7f)); g.DrawPath(bandPen, band); g.DrawLine(bandPen, Width/2, 53*s, Width/2, 116*s); } } } internal static class UiGeometry { internal static GraphicsPath RoundedRectangle(Rectangle bounds, int radius) { var diameter = Math.Max(2, radius * 2); var arc = new Rectangle(bounds.Location, new Size(diameter, diameter)); var path = new GraphicsPath(); path.AddArc(arc, 180, 90); arc.X = bounds.Right - diameter; path.AddArc(arc, 270, 90); arc.Y = bounds.Bottom - diameter; path.AddArc(arc, 0, 90); arc.X = bounds.Left; path.AddArc(arc, 90, 90); path.CloseFigure(); return path; } } internal sealed class RoundedCardPanel : Panel { internal const int SurfaceAlpha = 80; internal RoundedCardPanel() { SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true); SetStyle(ControlStyles.Opaque, false); BackColor = Color.Transparent; } protected override void OnResize(EventArgs eventArgs) { base.OnResize(eventArgs); if (Width <= 4 || Height <= 4) return; using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), Math.Max(8, 12 * DeviceDpi / 96)); Region?.Dispose(); Region = new Region(path); } protected override void OnPaintBackground(PaintEventArgs eventArgs) { var g = eventArgs.Graphics; // Repaint the parent in the original coordinates on every pass. Doing // the tint here also gives transparent child labels the same surface; // no accumulated alpha or old account text survives an invalidation. var state = g.Save(); if (Parent is not null) { g.TranslateTransform(-Left, -Top); InvokePaintBackground(Parent, new PaintEventArgs(g, Parent.ClientRectangle)); g.Restore(state); } else { g.Clear(Brand.Surface); g.Restore(state); } if (Width <= 4 || Height <= 4) return; state = g.Save(); g.SmoothingMode = SmoothingMode.AntiAlias; using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), Math.Max(8, 12 * DeviceDpi / 96)); using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 238, 247, 255)); using var border = new Pen(Color.FromArgb(180, 188, 222, 237), Math.Max(1, DeviceDpi / 96f)); g.FillPath(fill, path); g.DrawPath(border, path); g.Restore(state); } } internal sealed class ModernInputPanel : Panel { private readonly TextBox _editor; internal ModernInputPanel(TextBox editor) { _editor = editor; BackColor = Color.White; SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); Controls.Add(editor); editor.GotFocus += (_, _) => Invalidate(); editor.LostFocus += (_, _) => Invalidate(); Resize += (_, _) => { LayoutEditor(); if (Width <= 4 || Height <= 4) return; using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), 7); Region?.Dispose(); Region = new Region(path); }; LayoutEditor(); } private void LayoutEditor() { _editor.Location = new Point(14, Math.Max(7, (Height - _editor.PreferredHeight) / 2)); _editor.Width = Math.Max(20, Width - 28); } protected override void OnPaint(PaintEventArgs eventArgs) { eventArgs.Graphics.SmoothingMode = SmoothingMode.AntiAlias; using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), 7); using var fill = new SolidBrush(Color.White); using var border = new Pen(ContainsFocus ? Brand.RoyalBlue : Color.FromArgb(194, 207, 221), ContainsFocus ? 1.8f : 1f); eventArgs.Graphics.FillPath(fill, path); eventArgs.Graphics.DrawPath(border, path); } } internal sealed class RoundedButton : Button { private bool _hovered; internal RoundedButton() { SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); } protected override void OnMouseEnter(EventArgs e) { _hovered = true; Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseLeave(EventArgs e) { _hovered = false; Invalidate(); base.OnMouseLeave(e); } protected override void OnPaint(PaintEventArgs e) { if (Width < 8 || Height < 8) return; if (Parent is { } parent) { var state = e.Graphics.Save(); e.Graphics.TranslateTransform(-Left, -Top); InvokePaintBackground(parent, new PaintEventArgs(e.Graphics, parent.ClientRectangle)); e.Graphics.Restore(state); } else e.Graphics.Clear(Color.White); e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), Math.Max(5, DeviceDpi / 16)); var primary = BackColor.ToArgb() != Color.White.ToArgb(); var color = !Enabled ? Color.FromArgb(225, 234, 245) : _hovered ? (primary ? Brand.DeepBlue : Brand.PaleBlue) : BackColor; using Brush fill = primary && Enabled ? new LinearGradientBrush(ClientRectangle, _hovered ? Brand.DeepBlue : Color.FromArgb(0, 116, 233), Brand.RoyalBlue, 20) : new SolidBrush(color); e.Graphics.FillPath(fill, path); if (!primary) { using var pen = new Pen(Color.FromArgb(168, 199, 246), Math.Max(1, DeviceDpi / 96f)); e.Graphics.DrawPath(pen, path); } TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Enabled ? ForeColor : Brand.Muted, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.Inflate(ClientRectangle, -6, -6)); } protected override void OnResize(EventArgs eventArgs) { base.OnResize(eventArgs); if (Width <= 2 || Height <= 2) return; using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), 8); Region?.Dispose(); Region = new Region(path); } }