diff --git a/windows/ClientRuntimeSelfTest.cs b/windows/ClientRuntimeSelfTest.cs index 198df8a..5f5e284 100644 --- a/windows/ClientRuntimeSelfTest.cs +++ b/windows/ClientRuntimeSelfTest.cs @@ -72,9 +72,9 @@ internal static class ClientRuntimeSelfTest && !error.Diagnostic.Contains('\n') && !error.Diagnostic.Contains('\r'); var response = JsonSerializer.Deserialize(""" {"config_contract":2,"connection_scope":"public","node":{"slug":"tokyo","name":"VPN002"},"route_mode":"smart", - "tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.64.0.2","port":10803}, + "tailscale_endpoint":{"contract":1,"node_slug":"tokyo","address":"100.99.142.38","port":10803}, "config":{"inbounds":[],"outbounds":[ - {"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"vpn002.example.invalid","port":11082,"users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]}, + {"tag":"proxy","protocol":"vless","settings":{"vnext":[{"address":"002.vpn.toplc.cn","port":11082,"users":[{"id":"11111111-1111-1111-1111-111111111111","encryption":"none","flow":"xtls-rprx-vision"}]}]}, "streamSettings":{"network":"tcp","security":"reality","realitySettings":{"serverName":"one.one.one.one","publicKey":"fixture-key","shortId":"aabb"}}}, {"tag":"direct","protocol":"freedom"},{"tag":"block","protocol":"blackhole"}],"routing":{"rules":[]}}} """)!; diff --git a/windows/ClientShutdownUiSelfTest.cs b/windows/ClientShutdownUiSelfTest.cs index b600485..9c3f6b6 100644 --- a/windows/ClientShutdownUiSelfTest.cs +++ b/windows/ClientShutdownUiSelfTest.cs @@ -90,8 +90,8 @@ internal static class ClientShutdownUiSelfTest { confirmed.Show(); PumpUntil(() => confirmed.LoginReadyForTest); Dispatch(confirmed, 0x11, IntPtr.Zero); - Invoke(confirmed, "CompleteSessionEnding"); - Invoke(confirmed, "CompleteSessionEnding"); + Dispatch(confirmed, 0x16, (IntPtr)1); + Dispatch(confirmed, 0x16, (IntPtr)1); Dispatch(confirmed, 0x16, IntPtr.Zero); checks["confirmed_session_finalizes_once_and_cannot_resume"] = disposals == 1 && Lifetime(confirmed).IsCancellationRequested && !confirmed.NetworkRecoveryFailed; diff --git a/windows/ConnectionHealthPolicy.cs b/windows/ConnectionHealthPolicy.cs index f3abb0d..ab9b660 100644 --- a/windows/ConnectionHealthPolicy.cs +++ b/windows/ConnectionHealthPolicy.cs @@ -4,12 +4,17 @@ namespace UCVL.VPNPlus; // A delayed probe must not undo a user's disconnect or judge a different core. internal sealed class ConnectionHealthPolicy { - internal enum Decision { Ignore, Keep, Repair, Degraded, Switch } + internal enum Decision { Ignore, Keep, Repair, PendingAdvisory, WebsiteUnavailable, TailnetEgressUnverified, Switch } internal long Revision { get; private set; } internal int Failures { get; private set; } internal bool HasBeenHealthy { get; private set; } private long _nextProbe; - internal void Invalidate() => Revision++; + private Decision? _advisoryCandidate; + internal void Invalidate() + { + Revision++; + _advisoryCandidate = null; + } internal void BeginCore(long now) { Invalidate(); Failures = 0; HasBeenHealthy = false; @@ -24,6 +29,7 @@ internal sealed class ConnectionHealthPolicy if (revision != Revision || testedCore != currentCore || !wanted || busy || transitioning || exiting) return Decision.Ignore; if (healthy && currentCore is not null) { + _advisoryCandidate = null; HasBeenHealthy = true; Failures = 0; _nextProbe = now + 20_000; return Decision.Keep; } @@ -31,8 +37,12 @@ internal sealed class ConnectionHealthPolicy // Third-party HTTP diagnostics cannot identify an active Tailnet // transport failure. The bounded periodic ICMP policy owns fallback. Failures = 0; _nextProbe = now + 20_000; - return Decision.Degraded; + var advisory = proxyHealthy ? Decision.WebsiteUnavailable : Decision.TailnetEgressUnverified; + var confirmed = _advisoryCandidate == advisory; + _advisoryCandidate = advisory; + return confirmed ? advisory : Decision.PendingAdvisory; } + _advisoryCandidate = null; if (proxyHealthy && currentCore is not null) { // Do not punish/restart a working node for a local smart-rule fault. // The UI must show degraded routing, not declare the business path healthy. diff --git a/windows/ConnectionHealthSelfTest.cs b/windows/ConnectionHealthSelfTest.cs index 7ac6a12..39395f8 100644 --- a/windows/ConnectionHealthSelfTest.cs +++ b/windows/ConnectionHealthSelfTest.cs @@ -52,18 +52,34 @@ internal static class ConnectionHealthSelfTest == ConnectionHealthPolicy.Decision.Switch; checks["stale_proxy_proof_cannot_affect_new_core"] = policy.Observe(policy.Revision,10,11,true,false,false,false,false,500_000,true) == ConnectionHealthPolicy.Decision.Ignore; + ConnectionHealthPolicy.Decision Website(long now) => policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, now, proxyHealthy: true, businessUnavailable: true); + ConnectionHealthPolicy.Decision TailnetEgress(long now) => policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, now, activeTailnet: true); + policy.BeginCore(600_000); - checks["website_failures_do_not_rebuild_live_tailnet_core"] = Enumerable.Range(0, 12).All(i => - policy.Observe(policy.Revision, 10, 10, true, false, false, false, false, 605_000 + i * 20_000, - false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Degraded) && policy.Failures == 0; - checks["transport_proof_with_site_outage_is_degraded_not_false_green"] = policy.Observe(policy.Revision, 10, 10, - true, false, false, false, false, 900_000, true, businessUnavailable: true) == ConnectionHealthPolicy.Decision.Degraded; + checks["one_tailnet_egress_failure_waits_for_confirmation"] = TailnetEgress(605_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && !policy.IsDue(624_999, true) && policy.IsDue(625_000, true); + checks["repeated_egress_failures_do_not_rebuild_live_tailnet_core"] = Enumerable.Range(0, 12).All(i => + TailnetEgress(625_000 + i * 20_000) == ConnectionHealthPolicy.Decision.TailnetEgressUnverified) && policy.Failures == 0; + checks["site_failure_is_distinct_and_requires_its_own_confirmation"] = Website(900_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && Website(920_000) == ConnectionHealthPolicy.Decision.WebsiteUnavailable && policy.Failures == 0; + checks["success_resets_advisory_confirmation"] = Observe(true, 940_000) == ConnectionHealthPolicy.Decision.Keep + && Website(960_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["alternating_advisory_categories_do_not_confirm_each_other"] = TailnetEgress(980_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && Website(1_000_000) == ConnectionHealthPolicy.Decision.PendingAdvisory + && TailnetEgress(1_020_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + checks["routing_repair_interrupts_advisory_confirmation"] = policy.Observe(policy.Revision, 10, 10, + true, false, false, false, false, 1_040_000, proxyHealthy: true) == ConnectionHealthPolicy.Decision.Repair + && TailnetEgress(1_060_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; + policy.BeginCore(1_080_000); + checks["new_core_starts_advisory_confirmation_over"] = TailnetEgress(1_085_000) == ConnectionHealthPolicy.Decision.PendingAdvisory; checks["dead_tailnet_core_still_requests_fast_recovery"] = policy.Observe(policy.Revision, null, null, - true, false, false, false, false, 920_000, false, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch; + true, false, false, false, false, 1_105_000, activeTailnet: true) == ConnectionHealthPolicy.Decision.Switch; revision = policy.Revision; policy.Invalidate(); checks["new_login_fence_blocks_old_probe_even_if_core_id_same"] = policy.Observe(revision, 10, 10, - true, false, false, false, true, 940_000, true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore; + true, false, false, false, true, 1_125_000, proxyHealthy: true, activeTailnet: true) == ConnectionHealthPolicy.Decision.Ignore; foreach (var check in ConnectionAuthorizationSelfTest.Check()) checks.Add(check.Key, check.Value); var passed = checks.Values.All(v => v); File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"connection-health-self-test.json"), diff --git a/windows/ConnectionSelection.cs b/windows/ConnectionSelection.cs index a53641f..0d2f724 100644 --- a/windows/ConnectionSelection.cs +++ b/windows/ConnectionSelection.cs @@ -12,7 +12,7 @@ internal sealed record ConnectionSelection(string NodeSlug, bool Manual) return new(selectedSlug, true); } - internal int Attempts(int availableCount) => Manual ? 1 : Math.Min(availableCount, 8); + internal int Attempts(int availableCount) => Manual ? 1 : Math.Clamp(availableCount, 0, 3); internal void ValidateResponse(string actualSlug) { @@ -20,4 +20,18 @@ internal sealed record ConnectionSelection(string NodeSlug, bool Manual) || (Manual && !string.Equals(NodeSlug, actualSlug, StringComparison.Ordinal))) throw new InvalidOperationException("服务器返回的节点与连接选择不一致,已拒绝连接。"); } + + internal void ValidateConfig(ConnectionAttempt attempt, ConfigResponse response, string routeMode, + IEnumerable authorizedNodes, IReadOnlyDictionary excludedNodes) + { + var slug = response.Node.Slug; + ValidateResponse(slug); + if ((attempt.Slug != "auto" && slug != attempt.Slug) || response.RouteMode != routeMode) + throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。"); + if (!attempt.IsPrivate && (response.ConnectionScope is not ("" or "public") + || !authorizedNodes.Any(n => n is not PrivateAuxiliaryNode && n.Slug == slug))) + throw new InvalidOperationException("公共配置的节点不属于当前账号的授权范围,已拒绝连接。"); + if (attempt.Slug == "auto" && excludedNodes.ContainsKey(slug)) + throw new InvalidOperationException("后台返回了本次连接已排除的节点,未再次尝试。"); + } } diff --git a/windows/ConnectionSelectionSelfTest.cs b/windows/ConnectionSelectionSelfTest.cs index 96db7e6..44c1678 100644 --- a/windows/ConnectionSelectionSelfTest.cs +++ b/windows/ConnectionSelectionSelfTest.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; namespace UCVL.VPNPlus; @@ -15,7 +15,7 @@ internal static class ConnectionSelectionSelfTest string[] authorized = ["office-test", "remote-test"]; var auto = ConnectionSelection.Create(false, "office-test", authorized); checks["default_auto_ignores_previous_manual_choice"] = auto.NodeSlug == "auto" && !auto.Manual; - checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 8 && auto.Attempts(2) == 2; + checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 3 && auto.Attempts(2) == 2; var manual = ConnectionSelection.Create(true, "office-test", authorized); checks["manual_uses_exact_authorized_node"] = manual.Manual && manual.NodeSlug == "office-test"; checks["manual_has_no_fallback_attempt"] = manual.Attempts(12) == 1; @@ -52,7 +52,11 @@ internal sealed partial class MainForm internal Dictionary CheckSelectionUi() { var result = new Dictionary(); - var profile = new Profile { Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }] }; + var profile = new Profile + { + Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }], + RouteModes = [new() { Id = "smart", Name = "AI 智能代理" }], + }; _availableNodeCount = 2; UpdateSelectionNodes(profile, false); result["ui_defaults_to_auto"] = !ManualSelection; @@ -106,31 +110,47 @@ internal sealed partial class MainForm _currentNodeLabel.Text = _currentNodeName; SetConnectionState(true, "已安全连接", _currentNodeName); LayoutDashboard(); - var fullConnectedRow = true; - foreach (var (size, label) in new[] { (new Size(480, 360), "compact"), (new Size(960, 720), "wide") }) + var allConnectedLayoutsFit = true; + foreach (var (size, label) in new[] { (new Size(480, 360), "compact"), (new Size(840, 480), "minimum_wide"), (new Size(960, 720), "wide") }) { ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); PerformLayout(); LayoutDashboard(); Application.DoEvents(); - var rightInset = _modeCard.ClientSize.Width - _currentNodeLabel.Right; - // The node keeps the available row, with only a small edge inset. - // Exact decorative padding can differ between compact and wide UI. - var usesRow = _currentNodeLabel.Visible && _currentNodeLabel.Left >= 0 - && rightInset >= 0 && rightInset <= ScaleLogical(16) - && _currentNodeLabel.Width >= _modeCard.ClientSize.Width * .75; - result["connected_node_full_row_" + label] = usesRow; - result["connected_node_name_fits_" + label] = TextRenderer.MeasureText(_currentNodeName, - _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; - fullConnectedRow &= usesRow; + var isWide = WideDashboardPresentation; + var rowFits = _currentNodeLabel.Visible && _modeCard.ClientRectangle.Contains(_currentNodeLabel.Bounds) + && _nodeHeading.Right <= _currentNodeLabel.Left + && (isWide + ? _currentNodeLabel.Right <= _modeIcon.Left && _routeReadOnly.Right <= _historyRangeCombo.Left + : _currentNodeLabel.Bottom <= _routeReadOnly.Top); + result["connected_node_does_not_overlap_mode_or_range_" + label] = rowFits; + result["connected_node_name_fits_" + label] = _currentNodeLabel.Text == NodePresentation.JinanName && FitsNodeText(); + allConnectedLayoutsFit &= rowFits && FitsNodeText(); + if (isWide) + { + _currentNodeBaseName = NodePresentation.JinanName; + UpdateConnectedTransportPresentation(true); + LayoutDashboard(); + result["long_tailnet_name_keeps_node_and_transport_visible_" + label] = FitsNodeText() + && (_currentNodeLabel.Text == _currentNodeName || _currentNodeLabel.Text == _currentNodeBaseName) + && _wideSummaryState.Text.Contains("Tailscale", StringComparison.Ordinal); + UpdateConnectedTransportPresentation(false); + LayoutDashboard(); + } } - result["connected_node_has_dedicated_actual_state_row"] = fullConnectedRow; + result["connected_node_has_dedicated_actual_state_space"] = allConnectedLayoutsFit; result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible; - result["zero3_name_fits_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; Size = MinimumSize; PerformLayout(); LayoutDashboard(); Application.DoEvents(); - result["zero3_name_fits_compact_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; + result["zero3_name_fits_compact_connected_row"] = FitsNodeText(); RequestExit(); return result; + + bool FitsNodeText() + { + using var graphics = _currentNodeLabel.CreateGraphics(); + return TextRenderer.MeasureText(graphics, _currentNodeLabel.Text, _currentNodeLabel.Font, + Size.Empty, TextFormatFlags.SingleLine).Width <= _currentNodeLabel.ClientSize.Width; + } } } diff --git a/windows/ConnectionSelfTest.cs b/windows/ConnectionSelfTest.cs index 725cf8b..4cba802 100644 --- a/windows/ConnectionSelfTest.cs +++ b/windows/ConnectionSelfTest.cs @@ -96,7 +96,8 @@ internal static class ConnectionSelfTest result.Probes.Add(await ProbeAsync(client, "OpenAI API", "https://api.openai.com/v1/models", timeout.Token)); result.Probes.Add(await ProbeAsync(client, "Codex endpoint (unauthenticated)", "https://chatgpt.com/backend-api/codex/models", timeout.Token)); result.Probes.Add(await ProbeAsync(client, "ChatGPT", "https://chatgpt.com/", timeout.Token)); - result.Probes.Add(await ProbeAsync(client, "管理平台", "https://vpn.example.invalid/health/", timeout.Token)); + using var management = new HttpClient(PlatformBootstrapTransport.CreateHandler()) { Timeout = TimeSpan.FromSeconds(15) }; + result.Probes.Add(await ProbeAsync(management, "管理平台", VpnApiClient.BaseAddress + "health/", timeout.Token)); // A browser following an explicit HTTP proxy is not evidence that // native clients use the global TUN. Exercise both paths separately. diff --git a/windows/DashboardConnectionBanner.cs b/windows/DashboardConnectionBanner.cs new file mode 100644 index 0000000..70bc81f --- /dev/null +++ b/windows/DashboardConnectionBanner.cs @@ -0,0 +1,87 @@ +using System.Drawing.Drawing2D; + +namespace UCVL.VPNPlus; + +internal enum BannerTone { Idle, Connecting, Connected, Attention, Error } + +internal sealed class DashboardConnectionBanner : CardPanel +{ + private bool _wide; + private BannerTone _tone; + + internal bool WideBanner + { + get => _wide; + set { if (_wide != value) { _wide = value; Invalidate(true); } } + } + + internal BannerTone Tone + { + get => _tone; + set { if (_tone != value) { _tone = value; Invalidate(true); } } + } + + protected override void OnPaintBackground(PaintEventArgs e) + { + base.OnPaintBackground(e); + if (!WideBanner || Width < 30 || Height < 30) return; + var g = e.Graphics; + var state = g.Save(); + g.SmoothingMode = SmoothingMode.AntiAlias; + var scale = DeviceDpi / 96f; + var inset = Math.Max(1, (int)Math.Round(scale)); + var bounds = new Rectangle(inset, inset, Width - 2 * inset - 1, Height - 3 * inset - 1); + using var path = UiGeometry.RoundedRectangle(bounds, Math.Min(bounds.Height / 2, (int)Math.Round(15 * scale))); + var (start, middle, end) = Tone switch + { + BannerTone.Connected => (Color.FromArgb(21, 93, 153), Color.FromArgb(13, 84, 151), Color.FromArgb(13, 105, 147)), + BannerTone.Attention => (Color.FromArgb(36, 81, 134), Color.FromArgb(39, 73, 124), Color.FromArgb(66, 81, 128)), + BannerTone.Error => (Color.FromArgb(44, 75, 132), Color.FromArgb(59, 67, 120), Color.FromArgb(92, 67, 121)), + BannerTone.Connecting => (Color.FromArgb(25, 102, 174), Color.FromArgb(11, 84, 158), Color.FromArgb(13, 108, 176)), + _ => (Color.FromArgb(41, 94, 146), Color.FromArgb(30, 78, 132), Color.FromArgb(29, 101, 156)), + }; + using var fill = new LinearGradientBrush(bounds, start, end, 8) + { + InterpolationColors = new ColorBlend { Colors = [start, middle, end], Positions = [0f, .56f, 1f] }, + }; + g.FillPath(fill, path); + g.SetClip(path, CombineMode.Intersect); + using var sheen = new LinearGradientBrush(bounds, Color.FromArgb(36, 183, 230, 255), Color.Transparent, 90); + g.FillPath(sheen, path); + + var left = Width * .40f; + var right = Width - 3 * scale; + var center = new PointF(Width * .70f, Height * .55f); + using var flare = new GraphicsPath(); + flare.AddEllipse(center.X - Width * .23f, center.Y - Height * .71f, Width * .46f, Height * 1.42f); + using (var glow = new PathGradientBrush(flare) { CenterColor = Color.FromArgb(60, 116, 222, 255), SurroundColors = [Color.Transparent] }) + g.FillPath(glow, flare); + + using var route = new GraphicsPath(); + route.AddBezier(left, Height * .86f, Width * .58f, Height * .93f, Width * .58f, Height * .18f, center.X, center.Y); + route.AddBezier(center.X, center.Y, Width * .81f, Height * .93f, Width * .86f, Height * .28f, right, Height * .36f); + using (var halo = new Pen(Color.FromArgb(37, 108, 225, 255), Math.Max(2f, 5f * scale))) g.DrawPath(halo, route); + using (var line = new Pen(Color.FromArgb(172, 182, 241, 255), Math.Max(1f, .85f * scale))) g.DrawPath(line, route); + for (var i = 0; i < 2; i++) + { + using var line = new Pen(Color.FromArgb(44 + 18 * i, 166, 231, 255), Math.Max(1, scale * .65f)); + g.DrawBezier(line, left + Width * .06f, Height * (.91f + .05f * i), Width * .66f, Height * (1.09f - .1f * i), + Width * .73f, Height * (.15f + .12f * i), right, Height * (.50f + .14f * i)); + } + using var dot = new SolidBrush(Color.FromArgb(84, 200, 241, 255)); + var step = Math.Max(3, (int)(5 * scale)); + for (var y = (int)(8 * scale); y < Height * .74f; y += step) + for (var x = (int)(Width * .61f); x < Width * .86f; x += step) + { + var dx = (x - Width * .73f) / (Width * .12f); + var dy = (y - Height * .32f) / (Height * .31f); + if (dx * dx + dy * dy < 1) g.FillEllipse(dot, x, y, Math.Max(1, scale), Math.Max(1, scale)); + } + using (var nodeHalo = new SolidBrush(Color.FromArgb(105, 125, 232, 255))) + g.FillEllipse(nodeHalo, center.X - 3 * scale, center.Y - 3 * scale, 6 * scale, 6 * scale); + g.FillEllipse(Brushes.White, center.X - 1.4f * scale, center.Y - 1.4f * scale, 2.8f * scale, 2.8f * scale); + g.Restore(state); + using var edge = new Pen(Color.FromArgb(233, 227, 248, 255), Math.Max(1, 1.05f * scale)); + g.DrawPath(edge, path); + } +} diff --git a/windows/DashboardControls.cs b/windows/DashboardControls.cs index f05688c..04452ec 100644 --- a/windows/DashboardControls.cs +++ b/windows/DashboardControls.cs @@ -1,19 +1,19 @@ -using System.Drawing.Drawing2D; +using System.Drawing.Drawing2D; namespace UCVL.VPNPlus; -internal enum DashboardIcon { Server, Settings, Database, Upload, Download, Document, Chart, History, Shield } +internal enum DashboardIcon { Server, Settings, Database, Upload, Download, Document, Chart, History, Shield, Layers, ShieldPending, ShieldAlert } // Code-drawn icons keep the existing brand assets and remain crisp at high DPI. internal static class DashboardDrawing { - internal static void Icon(Graphics g, DashboardIcon icon, Rectangle bounds, Color color) + internal static void Icon(Graphics g, DashboardIcon icon, Rectangle bounds, Color color, bool featured = false) { var state = g.Save(); g.SmoothingMode = SmoothingMode.AntiAlias; g.TranslateTransform(bounds.Left, bounds.Top); g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f); - using var pen = new Pen(color, 1.8f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }; + using var pen = new Pen(color, 1.65f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }; switch (icon) { case DashboardIcon.Server: @@ -40,18 +40,41 @@ internal static class DashboardDrawing for (var i = 0; i < 4; i++) g.DrawLine(pen, 4 + i * 5, 21, 4 + i * 5, 16 - i * 4); break; case DashboardIcon.History: g.DrawArc(pen, 2, 2, 20, 20, -85, 350); g.DrawLine(pen, 12, 2, 12, 12); g.DrawLine(pen, 12, 12, 22, 12); break; + case DashboardIcon.Layers: + g.DrawPolygon(pen, [new PointF(2, 7), new(12, 2), new(22, 7), new(12, 12)]); + g.DrawLines(pen, [new PointF(2, 12), new(12, 17), new(22, 12)]); + g.DrawLines(pen, [new PointF(2, 17), new(12, 22), new(22, 17)]); break; case DashboardIcon.Shield: + case DashboardIcon.ShieldPending: + case DashboardIcon.ShieldAlert: using (var shield = new GraphicsPath()) { - shield.AddLines([new PointF(12, 1), new(22, 5), new(22, 12)]); - shield.AddBezier(22, 12, 22, 18, 15, 22, 12, 24); - shield.AddBezier(12, 24, 9, 22, 2, 18, 2, 12); - shield.AddLine(2, 12, 2, 5); shield.CloseFigure(); - using var fill = new LinearGradientBrush(new Point(2, 2), new Point(22, 24), Color.FromArgb(100, color), color); + shield.AddLines([new PointF(12, 1.2f), new(22, 5.3f), new(22, 11.8f)]); + shield.AddBezier(22, 11.8f, 22, 17.8f, 15, 21.8f, 12, 23); + shield.AddBezier(12, 23, 9, 21.8f, 2, 17.8f, 2, 11.8f); + shield.AddLine(2, 11.8f, 2, 5.3f); + shield.CloseFigure(); + using var fill = new LinearGradientBrush(new Point(2, 2), new Point(22, 24), + featured ? Color.FromArgb(125, 107, 215, 255) : Color.FromArgb(176, color), color); g.FillPath(fill, shield); + if (featured) + { + using var halo = new Pen(Color.FromArgb(100, 114, 217, 255), 1.9f) { LineJoin = LineJoin.Round }; + using var edge = new Pen(Color.FromArgb(244, 213, 245, 255), .85f) { LineJoin = LineJoin.Round }; + g.DrawPath(halo, shield); + g.DrawPath(edge, shield); + } + } + using (var mark = new Pen(Color.White, featured ? 1.9f : 2.25f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }) + { + if (icon == DashboardIcon.Shield) g.DrawLines(mark, [new PointF(7, 12), new(10.5f, 15.5f), new(17, 9)]); + else if (icon == DashboardIcon.ShieldAlert) + { + g.DrawLine(mark, 12, 7, 12, 12); + g.FillEllipse(Brushes.White, 10.8f, 14.5f, 2.4f, 2.4f); + } + else for (var x = 7; x <= 17; x += 5) g.FillEllipse(Brushes.White, x - 1.2f, 10.8f, 2.4f, 2.4f); } - using (var check = new Pen(Color.White, 2.4f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }) - g.DrawLines(check, [new PointF(7, 12), new(10.5f, 15.5f), new(17, 9)]); break; } g.Restore(state); @@ -60,13 +83,16 @@ internal static class DashboardDrawing internal sealed class DashboardGlyph : Control { - internal DashboardIcon Glyph { get; set; } + private DashboardIcon _glyph; + private bool _featured; + internal DashboardIcon Glyph { get => _glyph; set { if (_glyph != value) { _glyph = value; Invalidate(); } } } + internal bool Featured { get => _featured; set { if (_featured != value) { _featured = value; Invalidate(); } } } internal DashboardGlyph(DashboardIcon glyph) { Glyph = glyph; DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; ForeColor = Brand.RoyalBlue; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); var side = Math.Min(Width, Height) - 4; - if (side > 0) DashboardDrawing.Icon(e.Graphics, Glyph, new((Width - side) / 2, (Height - side) / 2, side, side), ForeColor); + if (side > 0) DashboardDrawing.Icon(e.Graphics, Glyph, new((Width - side) / 2, (Height - side) / 2, side, side), ForeColor, Featured); } } @@ -86,6 +112,7 @@ internal sealed class MetricCard : CardPanel internal string ValueText { get; private set; } = "—"; internal string UnitText { get; private set; } = ""; internal string Hint { get; private set; } = "仅代理流量"; + internal bool InlineTotal { get; set; } internal MetricCard(string heading, DashboardIcon glyph) { Heading = heading; Glyph = glyph; AccessibleName = heading; } internal void SetBytes(double? bytes, bool speed = false, string? hint = null) { @@ -113,6 +140,21 @@ internal sealed class MetricCard : CardPanel var s = DeviceDpi / 96f; int S(int n) => (int)Math.Round(n * s); var g = e.Graphics; + if (InlineTotal) + { + using var divider = new Pen(Color.FromArgb(145, 148, 188, 218), Math.Max(1, s * .7f)); + g.DrawLine(divider, 0, S(12), 0, Height - S(12)); + using var heading = Brand.Font(10); + using var value = Brand.Font(Width < S(190) ? 13 : 17, FontStyle.Bold); + var inlineFlags = ChartAxis.PaintFlags | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter + | TextFormatFlags.NoPadding | TextFormatFlags.EndEllipsis; + var headingWidth = S(39); + TextRenderer.DrawText(g, Heading.Replace("代理流量", ""), heading, + new Rectangle(S(12), 0, headingWidth, Height), Brand.Muted, inlineFlags); + TextRenderer.DrawText(g, (ValueText + " " + UnitText).TrimEnd(), value, + new Rectangle(S(12) + headingWidth, 0, Math.Max(1, Width - S(18) - headingWidth), Height), Brand.Navy, inlineFlags); + return; + } if(Height Items { get; } = []; + internal DashboardIcon? LeadingIcon { get; set; } private int _selectedIndex = -1; private bool _hovered; private ContextMenuStrip? _popup; @@ -276,11 +319,17 @@ internal sealed class DashboardCombo : Control if (Width < 10 || Height < 10) return; var s = DeviceDpi / 96f; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; - using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(4, (int)(5*s))); + using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(4, (int)((Height >= 28*s ? 9 : 5)*s))); using var fill = new SolidBrush(Color.FromArgb(Enabled ? 208 : 115, 245, 250, 255)); using var border = new Pen(Color.FromArgb(_hovered && Enabled ? 125 : 155, 151, 185, 213), Math.Max(1, s * .65f)); e.Graphics.FillPath(fill, path); e.Graphics.DrawPath(border, path); var pad = (int)(7*s); var arrowX = Width - (int)(10*s); var arrowY = Height / 2; + if (LeadingIcon is { } icon && Height >= 26*s) + { + var side = (int)(19*s); + DashboardDrawing.Icon(e.Graphics, icon, new Rectangle(pad + 2, (Height - side)/2, side, side), Enabled ? Brand.RoyalBlue : Brand.Muted); + pad += side + (int)(8*s); + } TextRenderer.DrawText(e.Graphics, SelectedItem?.ToString() ?? "选择节点", Font, new Rectangle(pad, 0, Math.Max(1, Width-pad-(int)(20*s)), Height), Enabled ? ForeColor : Brand.Muted, ChartAxis.PaintFlags | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding | TextFormatFlags.EndEllipsis); diff --git a/windows/DashboardInteractionSelfTest.cs b/windows/DashboardInteractionSelfTest.cs index 397070b..7bbd77c 100644 --- a/windows/DashboardInteractionSelfTest.cs +++ b/windows/DashboardInteractionSelfTest.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; namespace UCVL.VPNPlus; @@ -94,7 +94,8 @@ internal sealed partial class MainForm _historyRangeCombo.DroppedDown = true; checks["open_selector_does_not_scroll_page"] = !Wheel(_historyRangeCombo, -120) && _dashboardScrollBar.Value == 0; _historyRangeCombo.DroppedDown = false; - checks["dashboard_reuses_full_login_artwork"] = _dashboardView.LoginArtwork && _dashboardBody.ParentArtwork; + checks["dashboard_uses_scenic_backdrop_and_keeps_login_artwork"] = _dashboardView.DashboardArtwork + && _dashboardBody.ParentArtwork && _content.LoginArtwork; checks["card_surface_is_half_transparent"] = CardPanel.SurfaceAlpha == 128; checks["whole_content_composition_disabled"] = !_content.ComposeChildren; checks["metric_dirty_refresh_clears_previous_digits"] = CheckMetricRefreshPaint(); diff --git a/windows/DashboardLayout.cs b/windows/DashboardLayout.cs index f29259d..079052f 100644 --- a/windows/DashboardLayout.cs +++ b/windows/DashboardLayout.cs @@ -1,4 +1,4 @@ -namespace UCVL.VPNPlus; +namespace UCVL.VPNPlus; internal readonly record struct DashboardGeometry( Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge, diff --git a/windows/DashboardTailnetLayoutSelfTest.cs b/windows/DashboardTailnetLayoutSelfTest.cs index adfd53c..16dda14 100644 --- a/windows/DashboardTailnetLayoutSelfTest.cs +++ b/windows/DashboardTailnetLayoutSelfTest.cs @@ -1,4 +1,4 @@ -namespace UCVL.VPNPlus; +namespace UCVL.VPNPlus; internal sealed partial class MainForm { @@ -25,20 +25,24 @@ internal sealed partial class MainForm ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); SetTailnetTrafficVisibility(false); LayoutDashboard(); var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size); - checks[$"no_tailnet_one_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible - && _speedTrendCard.Width == _statusCard.Width && _dailyCard.Top > _speedTrendCard.Bottom; - SetTailnetTrafficVisibility(true); - checks[$"tailnet_does_not_duplicate_local_chart_{size.Width}"] = !_tailnetTrafficCard.Visible && !_trafficCard.Visible + var key = $"{size.Width}x{size.Height}"; + Control chartContainer = WideDashboardPresentation ? _wideMonitor : _dashboardBody; + checks[$"no_tailnet_one_local_chart_{key}"] = !_tailnetTrafficCard.Visible + && _speedTrendCard.Parent == chartContainer + && _speedTrendCard.Controls.OfType().Single() == _trafficChart && _dailyCard.Top > _speedTrendCard.Bottom; - checks[$"tailnet_never_increases_page_{size.Width}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 + SetTailnetTrafficVisibility(true); + checks[$"tailnet_does_not_duplicate_local_chart_{key}"] = !_tailnetTrafficCard.Visible && !_trafficCard.Visible + && _dailyCard.Top > _speedTrendCard.Bottom; + checks[$"tailnet_never_increases_page_{key}"] = _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 && !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty; - checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit(); + checks[$"all_card_controls_fit_{key}"] = DashboardControlsFit(); using(var headingGraphics=_nodeCard.CreateGraphics()) - checks[$"dense_headings_remain_complete_when_resized_{size.Width}"] = new[] - { _nodeHeading, _routeHeading, _actualModeHeading, _trafficHeading, _dailyHeading } + checks[$"dense_headings_remain_complete_when_resized_{key}"] = new[] + { _nodeHeading, _selectionHeading, _routeHeading, _actualModeHeading, _dailyHeading } .All(label=>TextRenderer.MeasureText(headingGraphics,label.Text,label.Font,Size.Empty,TextFormatFlags.SingleLine).Width<=label.Width); SetTailnetTrafficVisibility(false); - checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1 + checks[$"tailnet_hide_restores_geometry_{key}"] = _trafficCard.Bounds == baseline.Item1 && _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3; } ClientSize=new Size(ScaleLogical(480),ScaleLogical(360)); diff --git a/windows/DashboardWideLayout.cs b/windows/DashboardWideLayout.cs new file mode 100644 index 0000000..542d264 --- /dev/null +++ b/windows/DashboardWideLayout.cs @@ -0,0 +1,66 @@ +namespace UCVL.VPNPlus; + +internal readonly record struct DashboardWideLayout(Rectangle Banner, Rectangle Sidebar, Rectangle Monitor, + Rectangle State, Rectangle Trend, Rectangle Servers, Rectangle Totals, Rectangle Footer) +{ + // State, Trend, Servers and Totals are relative to the monitor card. + internal static DashboardWideLayout Calculate(Size size, int dpi, bool showServers) + { + int S(double logical) => (int)Math.Round(logical * dpi / 96d); + var dense = size.Height < S(465); + var margin = S(dense ? 16 : 20); + var gap = S(dense ? 8 : 12); + var width = size.Width - 2 * margin; + var banner = new Rectangle(margin, S(4), width, Math.Clamp(size.Height / 7, S(dense ? 56 : 68), S(dense ? 68 : 92))); + var footer = new Rectangle(margin, size.Height - S(dense ? 40 : 52), width, S(dense ? 32 : 40)); + var middleTop = banner.Bottom + gap; + var middleHeight = footer.Top - gap - middleTop; + var leftWidth = Math.Clamp((int)(width * .252), S(212), S(320)); + var sidebar = new Rectangle(margin, middleTop, leftWidth, middleHeight); + var monitor = new Rectangle(sidebar.Right + gap, middleTop, width - leftWidth - gap, middleHeight); + var inset = S(dense ? 6 : 8); + var innerWidth = monitor.Width - 2 * inset; + var state = new Rectangle(inset, inset, innerWidth, S(dense ? 36 : 44)); + var totalHeight = S(dense ? 45 : 62); + var totals = new Rectangle(inset, monitor.Height - inset - totalHeight, innerWidth, totalHeight); + var serverHeight = showServers ? Math.Clamp(monitor.Height / 4, S(dense ? 66 : 90), S(dense ? 100 : 144)) : 0; + var servers = showServers + ? new Rectangle(inset, totals.Top - inset - serverHeight, innerWidth, serverHeight) + : Rectangle.Empty; + var trendBottom = (showServers ? servers.Top : totals.Top) - inset; + var trend = new Rectangle(inset, state.Bottom + S(4), innerWidth, trendBottom - state.Bottom - S(4)); + return new(banner, sidebar, monitor, state, trend, servers, totals, footer); + } + + internal static bool SelfTest() + { + foreach (var dpi in new[] { 96, 120, 144, 192, 240, 288 }) + foreach (var width in new[] { 840, 960, 1160, 1440 }) + foreach (var height in new[] { 390, 420, 465, 515, 650, 850 }) + foreach (var servers in new[] { false, true }) + { + var size = new Size(width * dpi / 96, height * dpi / 96); + var layout = Calculate(size, dpi, servers); + Rectangle[] outer = [layout.Banner, layout.Sidebar, layout.Monitor, layout.Footer]; + Rectangle[] inner = servers + ? [layout.State, layout.Trend, layout.Servers, layout.Totals] + : [layout.State, layout.Trend, layout.Totals]; + if (!Fits(outer, size) || !Fits(inner, layout.Monitor.Size)) return false; + var controlRows = height < 465 ? 41 : 51; + if (layout.Trend.Height <= controlRows * dpi / 96 || layout.Sidebar.Height != layout.Monitor.Height) return false; + } + return true; + + static bool Fits(Rectangle[] cards, Size size) + { + var bounds = new Rectangle(Point.Empty, size); + for (var i = 0; i < cards.Length; i++) + { + if (cards[i].IsEmpty || !bounds.Contains(cards[i])) return false; + for (var j = i + 1; j < cards.Length; j++) + if (cards[i].IntersectsWith(cards[j])) return false; + } + return true; + } + } +} diff --git a/windows/GitReleasePolicySelfTest.cs b/windows/GitReleasePolicySelfTest.cs index 0c88d01..c3029c9 100644 --- a/windows/GitReleasePolicySelfTest.cs +++ b/windows/GitReleasePolicySelfTest.cs @@ -22,7 +22,7 @@ internal static class GitReleasePolicySelfTest var release = JsonNode.Parse(JsonSerializer.Serialize(new { tag_name="windows-v0.2.16", draft=false, prerelease=false, body="fixture", assets=new[] { - new { name=Name, size=300000, browser_download_url="http://192.0.2.21:3000/untrusted.exe" }, + new { name=Name, size=300000, browser_download_url="http://172.16.0.21:3000/untrusted.exe" }, new { name=Name+".sha256", size=120, browser_download_url="https://untrusted.invalid/sha" }, }, }))!; diff --git a/windows/InstallationIntegration.cs b/windows/InstallationIntegration.cs index f05686c..cf957d0 100644 --- a/windows/InstallationIntegration.cs +++ b/windows/InstallationIntegration.cs @@ -105,7 +105,7 @@ internal static class InstallationIntegration !string.Equals(InstallationTransaction.Root((string)Decode(registered)), target, StringComparison.OrdinalIgnoreCase))) throw new IOException("安装目录与当前登记不一致,未覆盖其它安装。"); object[] next = [Path.Combine(target, "VPNPlus.exe"), target, "优创⁺纵横家", Path.Combine(target, "VPNPlus.exe"), - version, "优创未来(UCVL)", "https://vpn.example.invalid/", "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1]; + version, "优创未来(UCVL)", VpnApiClient.BaseAddress, "\"" + Path.Combine(target, "Uninstall.exe") + "\"", 1, 1]; var values = Names.Select((name, i) => new Registration(i, Encode(next[i], i < 8 ? RegistryValueKind.String : RegistryValueKind.DWord), Read(hive, Key(target, isolated, KeyIndex(i)), name))).ToList(); diff --git a/windows/KnownTailnetEndpoints.cs b/windows/KnownTailnetEndpoints.cs index a52d5cb..75acaa7 100644 --- a/windows/KnownTailnetEndpoints.cs +++ b/windows/KnownTailnetEndpoints.cs @@ -28,9 +28,9 @@ internal static class KnownTailnetEndpoints if (response.RouteMode is not ("smart" or "global")) return null; var mapping = response.Node.Slug switch { - "aliyun-tokyo-002" => (Host: "vpn002.example.invalid", PublicPort: 11082, Address: "100.64.0.2", Port: 10803), - "aliyun-siliconvalley-003" => (Host: "vpn003.example.invalid", PublicPort: 11083, Address: "100.64.0.3", Port: 11083), - "racknerd-newyork-004" => (Host: "004.vpn.example.invalid", PublicPort: 11084, Address: "100.64.0.44", Port: 11084), + "aliyun-tokyo-002" => (Host: "002.vpn.toplc.cn", PublicPort: 11082, Address: "100.99.142.38", Port: 10803), + "aliyun-siliconvalley-003" => (Host: "003.vpn.toplc.cn", PublicPort: 11083, Address: "100.124.242.104", Port: 11083), + "racknerd-newyork-004" => (Host: "004.vpn.toplc.cn", PublicPort: 11084, Address: "100.67.30.7", Port: 11084), _ => default }; reason = "known_node_unmapped"; diff --git a/windows/LearningSelfTest.cs b/windows/LearningSelfTest.cs index 1239233..6651d50 100644 --- a/windows/LearningSelfTest.cs +++ b/windows/LearningSelfTest.cs @@ -17,8 +17,8 @@ internal static class LearningSelfTest checks["acceptance_is_not_success"] = Parse("from tcp:127.0.0.1:777 accepted tcp:learn.example.com:443 [socks-in -> direct]") is null; checks["http_auth_status_is_not_failure"] = Parse("HTTP 401 / 403 / 429 direct learn.example.com:443") is null; checks["proxy_failures_not_direct"] = Parse(line.Replace("proxy/freedom", "proxy/vless/outbound")) is null; - checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "192.168.50.111")) is null; - checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.example.invalid")) is null; + checks["private_failures_not_collected"] = Parse(line.Replace("learn.example.com", "172.16.0.111")) is null; + checks["company_not_collected"] = Parse(line.Replace("learn.example.com", "vpn.toplc.cn")) is null; checks["source_not_misidentified"] = Parse("tcp:127.0.0.1:777 " + line)?.Target == "learn.example.com"; checks["oversized_line_rejected"] = Parse(new string('x', 8193) + line) is null; const string attempt = "[Info] [1753901314] app/dispatcher: taking detour [direct] for [tcp:tls-gap.example.com:443]"; @@ -32,7 +32,7 @@ internal static class LearningSelfTest checks["attempt_is_not_failure_evidence"] = Parse(attempt) is null; checks["probe_not_recursively_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[ucvl-learning-direct]"),"fixture","public") is null; checks["proxy_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("[direct]","[proxy]"),"fixture","public") is null; - checks["private_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","192.168.50.111"),"fixture","public") is null; + checks["private_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","172.16.0.111"),"fixture","public") is null; checks["non_tls_attempt_not_observed"] = LearningPolicy.ParseAttempt(attempt.Replace(":443]",":80]"),"fixture","public") is null; checks["no_url_collection"] = LearningPolicy.ParseAttempt(attempt.Replace("tls-gap.example.com","example.com/path?token=x"),"fixture","public") is null; foreach (bool? directTls in new bool?[] { true, false, null }) @@ -54,7 +54,7 @@ internal static class LearningSelfTest checks["rate_window_recovers"] = rate.TryEnter("new",160_001); foreach (var host in new[] { "127.0.0.1", "100.100.1.1", "192.168.1.1", "169.254.169.254", "::1", "::ffff:127.0.0.1", "203.0.113.1" }) checks["nonpublic_ip_" + host] = !LearningPolicy.Allowed("ip", host); - foreach (var host in new[] { "192.168.50.111", "a.local", "a.invalid", "x.toplc.cn", "a.com/path", "a.com?secret=1", "bad_.com", "-bad.com" }) + foreach (var host in new[] { "172.16.0.111", "a.local", "a.invalid", "x.toplc.cn", "a.com/path", "a.com?secret=1", "bad_.com", "-bad.com" }) checks["unsafe_domain_" + host] = !LearningPolicy.Allowed("domain", host); checks["public_ip_allowed"] = LearningPolicy.Allowed("ip", "8.8.8.8"); var direct = LearningPolicy.DirectFirst(baseConfig); @@ -71,7 +71,7 @@ internal static class LearningSelfTest checks["private_precedes_learned"] = JsonNode.Parse(verified)!["routing"]!["rules"]![0]!["ip"]![0]!.GetValue() == "geoip:private"; checks["expiry_restores_direct"] = !LearningPolicy.Merge(verified, new() { Contract=1, Revision=new string('b',64) }).Contains("learn.example.com"); checks["network_change_restores_direct"] = !LearningPolicy.DirectFirst(verified).Contains("learn.example.com"); - checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.example.invalid"))); + checks["unsafe_manifest_rejected"] = Throws(() => LearningPolicy.Merge(direct, Rules("vpn.toplc.cn"))); checks["invalid_manifest_contract_rejected"] = Throws(() => LearningPolicy.Merge(direct, new() { Contract=99, Revision=new string('a',64) })); var runtime = JsonNode.Parse(TunConfigBuilder.Build(direct, "Ethernet", true, includeTun:false, routingApiPort:18090, learningProbePort:18091))!; checks["info_in_memory_access_disabled"] = runtime["log"]!["loglevel"]!.GetValue() == "info" && runtime["log"]!["access"]!.GetValue() == "none"; diff --git a/windows/LearningTransportSelfTest.cs b/windows/LearningTransportSelfTest.cs index a8e64ef..cd6f2fe 100644 --- a/windows/LearningTransportSelfTest.cs +++ b/windows/LearningTransportSelfTest.cs @@ -49,7 +49,7 @@ internal static class LearningTransportSelfTest var checks = new Dictionary(); foreach (var target in new[] { "www.google.com", "chatgpt.com" }) checks[target] = await ProxyProbe.ProbeTlsAsync(new() { TargetType="domain", Target=target, Port=443, Network="tcp" }, port, deadline.Token) == true; - checks["private_destination_rejected"] = await ProxyProbe.ProbeTlsAsync(new() { TargetType="ip", Target="192.168.50.111", Port=443, Network="tcp" }, port, deadline.Token) is null; + checks["private_destination_rejected"] = await ProxyProbe.ProbeTlsAsync(new() { TargetType="ip", Target="172.16.0.111", Port=443, Network="tcp" }, port, deadline.Token) is null; report["checks"] = checks; report["passed"] = checks.Values.All(value => value); return checks.Values.All(value => value) ? 0 : 32; diff --git a/windows/MainForm.Chrome.cs b/windows/MainForm.Chrome.cs index c32fb47..c7291b2 100644 --- a/windows/MainForm.Chrome.cs +++ b/windows/MainForm.Chrome.cs @@ -1,9 +1,20 @@ +using System.Drawing.Drawing2D; + namespace UCVL.VPNPlus; internal sealed partial class MainForm { private WindowChrome? _windowChrome; - private bool _minimizedToTray; + private ContextMenuStrip? _settingsMenu; + private long _settingsDismissedAt = long.MinValue; + private readonly DashboardHeaderIdentity _dashboardHeaderName = new(); + private readonly DashboardHeaderButton _dashboardSettings = new("设置", DashboardHeaderIcon.Settings); + private readonly DashboardHeaderButton _dashboardAbout = new("关于", DashboardHeaderIcon.About); + private readonly DashboardHeaderButton _dashboardLogout = new("退出账号", DashboardHeaderIcon.Logout); + private readonly DashboardHeaderButton _dashboardMore = new("", DashboardHeaderIcon.Settings) + { AccessibleName = "设置" }; + private readonly DashboardHeaderButton _dashboardClose = new("", DashboardHeaderIcon.Close) + { AccessibleName = "断开并退出" }; internal WindowChrome? WindowChromeForTest => _windowChrome; // Remove the native caption before HWND creation, not only after its first @@ -30,26 +41,159 @@ internal sealed partial class MainForm private void InitializeWindowChrome(Panel header) { if (_windowChrome is not null) return; - _windowChrome = new WindowChrome(this, header, RequestExit, MinimizeToTray); + _windowChrome = new WindowChrome(this, header, RequestExit); _windowChrome.SetLoginMode(true); + InitializeDashboardHeader(header); } - private void LayoutWindowChrome() => _windowChrome?.LayoutButtons(); + private void LayoutWindowChrome() => RefreshDashboardHeaderPresentation(); - // Keep the core and timers alive. Only the window presentation changes; - // restore/exit remain the existing tray menu actions. - private void MinimizeToTray() + private void InitializeDashboardHeader(Panel header) { - if (_exiting || IsDisposed || Disposing || _windowChrome is not { LoginMode: false }) return; - _minimizedToTray = true; - Hide(); - ShowInTaskbar = false; - UpdateTaskbarPresentation(); + _dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = + _dashboardLogout.Visible = _dashboardMore.Visible = _dashboardClose.Visible = false; + _dashboardSettings.TabIndex = 890; + _dashboardAbout.TabIndex = 891; + _dashboardLogout.TabIndex = 892; + _dashboardMore.TabIndex = 890; + _logoutButton.TabIndex = 892; + _dashboardClose.TabIndex = 901; + _dashboardSettings.Click += (_, _) => OpenDashboardMenu(_dashboardSettings, includeApplicationActions: false); + _dashboardMore.Click += (_, _) => OpenDashboardMenu(_dashboardMore, includeApplicationActions: true); + _dashboardAbout.Click += (_, _) => ShowDashboardAbout(); + _dashboardLogout.Click += async (_, _) => await LogoutAsync(); + _dashboardClose.Click += (_, _) => + { + if (_settingsMenu?.Visible == true) { _settingsMenu.Close(); return; } + if (_settingsDismissedAt != long.MinValue && Environment.TickCount64 - _settingsDismissedAt < 350) return; + RequestExit(); + }; + var tip = new ToolTip(); + _welcomeLabel.TextChanged += (_, _) => + { + _dashboardHeaderName.Text = _welcomeLabel.Text; + tip.SetToolTip(_dashboardHeaderName, _welcomeLabel.Text); + tip.SetToolTip(_welcomeLabel, _welcomeLabel.Text); + }; + _logoutButton.EnabledChanged += (_, _) => _dashboardLogout.Enabled = _logoutButton.Enabled; + _dashboardView.VisibleChanged += (_, _) => + { + if (!Disposing && !IsDisposed) LayoutBrandHeader(); + }; + header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation(); + tip.SetToolTip(_dashboardClose, "断开并退出"); + tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置"); + tip.SetToolTip(_dashboardMore, "设置与关于"); + header.Disposed += (_, _) => tip.Dispose(); + header.Controls.AddRange([_dashboardHeaderName, _dashboardSettings, _dashboardAbout, + _dashboardLogout, _dashboardMore, _dashboardClose]); + } + + private void RefreshDashboardHeaderPresentation() + { + if (Disposing || IsDisposed || _windowChrome is not { } chrome || _brandHeader.IsDisposed) return; + _content.HeaderArtworkOffset = _dashboardView.HeaderArtworkOffset = _brandHeader.Height; + var wide = WideDashboardPresentation && _dashboardView.Visible; + _dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = + _dashboardLogout.Visible = wide; + _dashboardClose.Visible = chrome.DashboardCloseSlot = _dashboardView.Visible; + chrome.LayoutButtons(); + _dashboardClose.Bounds = chrome.DashboardCloseBounds; + _dashboardClose.BringToFront(); + if (!CompactPresentation) LayoutExpandedBrandBounds(); + if (!wide) + { + _headerPoem.Visible = !CompactPresentation && _brandHeader.Width >= ScaleLogical(780); + LayoutCompactDashboardActions(); + return; + } + + _dashboardMore.Visible = false; + _headerPoem.Visible = false; + var caption = chrome.MinimizeButton.Bounds; + _dashboardClose.Bounds = chrome.DashboardCloseBounds; + int S(int value) => ScaleLogical(value); + int x = caption.Left - S(10); + foreach (var (button, width) in new[] { (_dashboardLogout, 106), (_dashboardAbout, 76), (_dashboardSettings, 76) }) + { + x -= S(width); + button.Bounds = new Rectangle(x, caption.Top, S(width), caption.Height); + x -= S(8); + } + var nameWidth = Math.Min(S(224), Math.Max(S(96), x - S(316))); + _dashboardHeaderName.Bounds = new Rectangle(x - nameWidth, caption.Top, nameWidth, caption.Height); + } + + private void LayoutExpandedBrandBounds() + { + int S(int value) => ScaleLogical(value); + foreach (Control control in _brandHeader.Controls) + { + if (control.Tag is not Rectangle) continue; + if (control is PictureBox) control.Bounds = new Rectangle(S(24), S(9), S(64), S(68)); + else if (control is Label { Text: "纵横家" }) control.Bounds = new Rectangle(S(99), S(10), S(146), S(36)); + else control.Bounds = new Rectangle(S(101), S(47), S(210), S(24)); + } + } + + private void LayoutCompactDashboardActions() + { + var show = CompactPresentation && _dashboardView.Visible && _logoutButton.Parent == _brandHeader; + _dashboardMore.Visible = show; + if (!show) return; + + int S(int value) => ScaleLogical(value); + var caption = _windowChrome!.MinimizeButton.Bounds; + var settingsLeft = caption.Left - S(38); + _dashboardMore.Bounds = new Rectangle(settingsLeft, caption.Top, S(32), caption.Height); + _logoutButton.Bounds = new Rectangle(settingsLeft - S(70), caption.Top, S(64), caption.Height); + var nameWidth = Math.Clamp(_logoutButton.Left - S(191), S(70), S(110)); + _welcomeLabel.Bounds = new Rectangle(_logoutButton.Left - nameWidth - S(6), caption.Top, nameWidth, caption.Height); + foreach (var label in _brandHeader.Controls.OfType