Compare commits

...

3 Commits

22 changed files with 1749 additions and 1718 deletions
+2 -3
View File
@@ -118,9 +118,8 @@ internal sealed partial class MainForm
var isWide = WideDashboardPresentation; var isWide = WideDashboardPresentation;
var rowFits = _currentNodeLabel.Visible && _modeCard.ClientRectangle.Contains(_currentNodeLabel.Bounds) var rowFits = _currentNodeLabel.Visible && _modeCard.ClientRectangle.Contains(_currentNodeLabel.Bounds)
&& _nodeHeading.Right <= _currentNodeLabel.Left && _nodeHeading.Right <= _currentNodeLabel.Left
&& (isWide && _currentNodeLabel.Bottom <= _routeReadOnly.Top
? _currentNodeLabel.Right <= _modeIcon.Left && _routeReadOnly.Right <= _historyRangeCombo.Left && (!isWide || !_wideSummaryState.Visible || _currentNodeLabel.Right <= _wideSummaryState.Left);
: _currentNodeLabel.Bottom <= _routeReadOnly.Top);
result["connected_node_does_not_overlap_mode_or_range_" + label] = rowFits; result["connected_node_does_not_overlap_mode_or_range_" + label] = rowFits;
result["connected_node_name_fits_" + label] = _currentNodeLabel.Text == NodePresentation.JinanName && FitsNodeText(); result["connected_node_name_fits_" + label] = _currentNodeLabel.Text == NodePresentation.JinanName && FitsNodeText();
allConnectedLayoutsFit &= rowFits && FitsNodeText(); allConnectedLayoutsFit &= rowFits && FitsNodeText();
+1 -1
View File
@@ -145,7 +145,7 @@ internal sealed class MetricCard : CardPanel
using var divider = new Pen(Color.FromArgb(145, 148, 188, 218), Math.Max(1, s * .7f)); 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)); g.DrawLine(divider, 0, S(12), 0, Height - S(12));
using var heading = Brand.Font(10); using var heading = Brand.Font(10);
using var value = Brand.Font(Width < S(190) ? 13 : 17, FontStyle.Bold); using var value = Brand.Font(12, FontStyle.Bold);
var inlineFlags = ChartAxis.PaintFlags | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter var inlineFlags = ChartAxis.PaintFlags | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter
| TextFormatFlags.NoPadding | TextFormatFlags.EndEllipsis; | TextFormatFlags.NoPadding | TextFormatFlags.EndEllipsis;
var headingWidth = S(39); var headingWidth = S(39);
+15
View File
@@ -41,6 +41,21 @@ internal sealed partial class MainForm
PerformLayout(); PerformLayout();
LayoutDashboard(); LayoutDashboard();
Application.DoEvents(); Application.DoEvents();
checks["compact_chrome_has_only_minimize_caption"] = WindowChromeForTest is
{ LoginMode: false, MinimizeButton.Action: CaptionAction.Minimize }
&& _brandHeader.Controls.OfType<CaptionButton>().Count(button => button.Visible) == 1
&& !_brandHeader.Controls.OfType<Button>().Any(button => button.Visible && button.AccessibleName == "断开并退出");
checks["compact_header_no_truncated_greeting"] = !_welcomeLabel.Visible
&& _dashboardMore.Visible && _logoutButton.Visible;
_dashboardMore.PerformClick();
Application.DoEvents();
checks["compact_settings_identifies_current_account"] = _settingsMenu?.Items.OfType<ToolStripLabel>()
.Any(item => item.Text?.Contains(profile.Email, StringComparison.Ordinal) == true) == true;
_settingsMenu?.Close();
checks["compact_graph_top_controls_share_one_row"] = _trendHeading.Top == _uploadLegend.Top
&& _uploadLegend.Top == _downloadLegend.Top && _downloadLegend.Top == _historyRangeCombo.Top
&& _trendHeading.Right <= _uploadLegend.Left && _uploadLegend.Right <= _downloadLegend.Left
&& _downloadLegend.Right <= _historyRangeCombo.Left;
int Limit() => Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1); int Limit() => Math.Max(0, _dashboardScrollBar.Maximum - _dashboardScrollBar.LargeChange + 1);
bool Wheel(Control target, int delta, Point? screenPoint = null) bool Wheel(Control target, int delta, Point? screenPoint = null)
{ {
+7 -5
View File
@@ -30,16 +30,18 @@ internal static class DashboardLayout
var traffic = Rectangle.Empty; var traffic = Rectangle.Empty;
var tailnet = Rectangle.Empty; var tailnet = Rectangle.Empty;
var footer = new Rectangle(margin, viewport.Height - margin - S(18), width, S(18)); var footer = new Rectangle(margin, viewport.Height - margin - S(18), width, S(18));
var daily = new Rectangle(margin, footer.Top - gap - S(22), width, S(22)); var daily = new Rectangle(margin, footer.Top - gap - S(20), width, S(20));
var trendTop = configuration.Bottom + gap; var trendTop = configuration.Bottom + gap;
var graphHeight = Math.Max(S(72), daily.Top - gap - trendTop); var graphHeight = Math.Max(S(72), daily.Top - gap - trendTop);
var serverHeight = showServerTraffic ? Math.Min(S(100), (int)Math.Round((graphHeight-gap)*.52)) : 0; var serverHeight = showServerTraffic ? Math.Min(S(100), (int)Math.Round((graphHeight-gap)*.52)) : 0;
var trend = new Rectangle(margin, trendTop, width, graphHeight - (showServerTraffic ? serverHeight+gap : 0)); var trend = new Rectangle(margin, trendTop, width, graphHeight - (showServerTraffic ? serverHeight+gap : 0));
var servers = showServerTraffic ? new Rectangle(margin, trend.Bottom+gap, width, serverHeight) : Rectangle.Empty; var servers = showServerTraffic ? new Rectangle(margin, trend.Bottom+gap, width, serverHeight) : Rectangle.Empty;
var headingWidth = S(120); var headingWidth = S(106);
var speedWidth = (width - headingWidth - S(10)) / 2; var columnWidth = (width - headingWidth - S(10)) / 2;
Rectangle Speed(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, S(22)); var metricWidth = Math.Min(S(138), columnWidth);
Rectangle Total(int column) => new(headingWidth + column * speedWidth, 0, speedWidth, daily.Height - S(2)); int MetricLeft(int column) => headingWidth + column * columnWidth + (columnWidth - metricWidth) / 2;
Rectangle Speed(int column) => new(MetricLeft(column), 0, metricWidth, S(20));
Rectangle Total(int column) => new(MetricLeft(column), 0, metricWidth, daily.Height - S(2));
Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)]; Rectangle[] metrics = [Total(0), Speed(0), Speed(1), Total(1)];
return new(welcome, account, identity, logout, status, configuration, actual, metrics, return new(welcome, account, identity, logout, status, configuration, actual, metrics,
traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f); traffic, tailnet, trend, daily, servers, footer, viewport.Height, true, 1f);
+67 -66
View File
@@ -1,66 +1,67 @@
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal readonly record struct DashboardWideLayout(Rectangle Banner, Rectangle Sidebar, Rectangle Monitor, internal readonly record struct DashboardWideLayout(Rectangle Banner, Rectangle Configuration, Rectangle Monitor,
Rectangle State, Rectangle Trend, Rectangle Servers, Rectangle Totals, Rectangle Footer) Rectangle State, Rectangle Trend, Rectangle Servers, Rectangle Totals, Rectangle Footer)
{ {
// State, Trend, Servers and Totals are relative to the monitor card. // State belongs to the configuration card. The remaining panels belong to the monitor.
internal static DashboardWideLayout Calculate(Size size, int dpi, bool showServers) internal static DashboardWideLayout Calculate(Size size, int dpi, bool showServers, bool showManualNode = false)
{ {
int S(double logical) => (int)Math.Round(logical * dpi / 96d); int S(double logical) => (int)Math.Round(logical * dpi / 96d);
var dense = size.Height < S(465); var dense = size.Height < S(465);
var margin = S(dense ? 16 : 20); var margin = S(dense ? 13 : 20);
var gap = S(dense ? 8 : 12); var gap = S(dense ? 6 : 10);
var width = size.Width - 2 * margin; 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 banner = new Rectangle(margin, S(3), width, S(dense ? 53 : 62));
var footer = new Rectangle(margin, size.Height - S(dense ? 40 : 52), width, S(dense ? 32 : 40)); var footer = new Rectangle(margin, size.Height - S(dense ? 31 : 40), width, S(dense ? 25 : 31));
var middleTop = banner.Bottom + gap; var middleTop = banner.Bottom + gap;
var middleHeight = footer.Top - gap - middleTop; var rowHeight = S(dense ? 26 : 31);
var leftWidth = Math.Clamp((int)(width * .252), S(212), S(320)); var configuration = new Rectangle(margin, middleTop, width, rowHeight * (showManualNode ? 3 : 2) + S(10));
var sidebar = new Rectangle(margin, middleTop, leftWidth, middleHeight); var stateLeft = (int)(width * .48);
var monitor = new Rectangle(sidebar.Right + gap, middleTop, width - leftWidth - gap, middleHeight); var state = new Rectangle(stateLeft, S(5), width - stateLeft - S(12), rowHeight * 2);
var inset = S(dense ? 6 : 8); var monitorTop = configuration.Bottom + gap;
var innerWidth = monitor.Width - 2 * inset; var monitor = new Rectangle(margin, monitorTop, width, footer.Top - gap - monitorTop);
var state = new Rectangle(inset, inset, innerWidth, S(dense ? 36 : 44)); var totalHeight = S(dense ? 30 : 38);
var totalHeight = S(dense ? 45 : 62); var totals = new Rectangle(0, monitor.Height - totalHeight, width, totalHeight);
var totals = new Rectangle(inset, monitor.Height - inset - totalHeight, innerWidth, totalHeight); var serverHeight = showServers ? Math.Clamp(monitor.Height / 3, S(dense ? 58 : 80), S(dense ? 105 : 150)) : 0;
var serverHeight = showServers ? Math.Clamp(monitor.Height / 4, S(dense ? 66 : 90), S(dense ? 100 : 144)) : 0; var servers = showServers
var servers = showServers ? new Rectangle(0, totals.Top - gap - serverHeight, width, serverHeight)
? new Rectangle(inset, totals.Top - inset - serverHeight, innerWidth, serverHeight) : Rectangle.Empty;
: Rectangle.Empty; var trendBottom = (showServers ? servers.Top : totals.Top) - gap;
var trendBottom = (showServers ? servers.Top : totals.Top) - inset; var trend = new Rectangle(0, 0, width, trendBottom);
var trend = new Rectangle(inset, state.Bottom + S(4), innerWidth, trendBottom - state.Bottom - S(4)); return new(banner, configuration, monitor, state, trend, servers, totals, footer);
return new(banner, sidebar, monitor, state, trend, servers, totals, footer); }
}
internal static bool SelfTest()
internal static bool SelfTest() {
{ foreach (var dpi in new[] { 96, 120, 144, 192, 240, 288 })
foreach (var dpi in new[] { 96, 120, 144, 192, 240, 288 }) foreach (var width in new[] { 840, 960, 1160, 1440 })
foreach (var width in new[] { 840, 960, 1160, 1440 }) foreach (var height in new[] { 390, 420, 465, 515, 650, 850 })
foreach (var height in new[] { 390, 420, 465, 515, 650, 850 }) foreach (var servers in new[] { false, true })
foreach (var servers in new[] { false, true }) foreach (var manualNode in new[] { false, true })
{ {
var size = new Size(width * dpi / 96, height * dpi / 96); var size = new Size(width * dpi / 96, height * dpi / 96);
var layout = Calculate(size, dpi, servers); var layout = Calculate(size, dpi, servers, manualNode);
Rectangle[] outer = [layout.Banner, layout.Sidebar, layout.Monitor, layout.Footer]; Rectangle[] outer = [layout.Banner, layout.Configuration, layout.Monitor, layout.Footer];
Rectangle[] inner = servers Rectangle[] inner = servers
? [layout.State, layout.Trend, layout.Servers, layout.Totals] ? [layout.Trend, layout.Servers, layout.Totals]
: [layout.State, layout.Trend, layout.Totals]; : [layout.Trend, layout.Totals];
if (!Fits(outer, size) || !Fits(inner, layout.Monitor.Size)) return false; if (!Fits(outer, size) || !Fits(inner, layout.Monitor.Size)
var controlRows = height < 465 ? 41 : 51; || !new Rectangle(Point.Empty, layout.Configuration.Size).Contains(layout.State)) return false;
if (layout.Trend.Height <= controlRows * dpi / 96 || layout.Sidebar.Height != layout.Monitor.Height) return false; if (layout.Trend.Height < 80 * dpi / 96 || layout.Trend.Width != layout.Banner.Width
} || layout.Totals.Height > Math.Ceiling(38 * dpi / 96d)) return false;
return true; }
return true;
static bool Fits(Rectangle[] cards, Size size)
{ static bool Fits(Rectangle[] cards, Size size)
var bounds = new Rectangle(Point.Empty, size); {
for (var i = 0; i < cards.Length; i++) 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].IsEmpty || !bounds.Contains(cards[i])) return false;
if (cards[i].IntersectsWith(cards[j])) return false; for (var j = i + 1; j < cards.Length; j++)
} if (cards[i].IntersectsWith(cards[j])) return false;
return true; }
} return true;
} }
} }
}
+339 -348
View File
@@ -1,348 +1,339 @@
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
private WindowChrome? _windowChrome; private WindowChrome? _windowChrome;
private ContextMenuStrip? _settingsMenu; private ContextMenuStrip? _settingsMenu;
private long _settingsDismissedAt = long.MinValue; private readonly DashboardHeaderIdentity _dashboardHeaderName = new();
private readonly DashboardHeaderIdentity _dashboardHeaderName = new(); private readonly DashboardHeaderButton _dashboardSettings = new("设置", DashboardHeaderIcon.Settings);
private readonly DashboardHeaderButton _dashboardSettings = new("设置", DashboardHeaderIcon.Settings); private readonly DashboardHeaderButton _dashboardAbout = new("关于", DashboardHeaderIcon.About);
private readonly DashboardHeaderButton _dashboardAbout = new("关于", DashboardHeaderIcon.About); private readonly DashboardHeaderButton _dashboardLogout = new("退出账号", DashboardHeaderIcon.Logout);
private readonly DashboardHeaderButton _dashboardLogout = new("退出账号", DashboardHeaderIcon.Logout); private readonly DashboardHeaderButton _dashboardMore = new("", DashboardHeaderIcon.Settings)
private readonly DashboardHeaderButton _dashboardMore = new("", DashboardHeaderIcon.Settings) { AccessibleName = "设置" };
{ AccessibleName = "设置" }; internal WindowChrome? WindowChromeForTest => _windowChrome;
private readonly DashboardHeaderButton _dashboardClose = new("", DashboardHeaderIcon.Close)
{ AccessibleName = "断开并退出" }; // Remove the native caption before HWND creation, not only after its first
internal WindowChrome? WindowChromeForTest => _windowChrome; // style/paint messages. This avoids a transient second caption at startup.
protected override CreateParams CreateParams
// Remove the native caption before HWND creation, not only after its first {
// style/paint messages. This avoids a transient second caption at startup. get
protected override CreateParams CreateParams {
{ var parameters = base.CreateParams;
get parameters.Style = unchecked((int)ChromeNative.ClientChromeStyle(parameters.Style));
{ return parameters;
var parameters = base.CreateParams; }
parameters.Style = unchecked((int)ChromeNative.ClientChromeStyle(parameters.Style)); }
return parameters;
} protected override void OnLoad(EventArgs e)
} {
base.OnLoad(e);
protected override void OnLoad(EventArgs e) LayoutBrandHeader();
{ CenterCards();
base.OnLoad(e); LayoutDashboard();
LayoutBrandHeader(); }
CenterCards();
LayoutDashboard(); // Explicit title/tray Exit and installer IPC share the graceful exit path.
} private void InitializeWindowChrome(Panel header)
{
// Explicit title/tray Exit and installer IPC share the graceful exit path. if (_windowChrome is not null) return;
private void InitializeWindowChrome(Panel header) _windowChrome = new WindowChrome(this, header, RequestExit, MinimizeToTrayPresentation);
{ _windowChrome.SetLoginMode(true);
if (_windowChrome is not null) return; InitializeDashboardHeader(header);
_windowChrome = new WindowChrome(this, header, RequestExit); }
_windowChrome.SetLoginMode(true);
InitializeDashboardHeader(header); private void LayoutWindowChrome() => RefreshDashboardHeaderPresentation();
}
private void InitializeDashboardHeader(Panel header)
private void LayoutWindowChrome() => RefreshDashboardHeaderPresentation(); {
_dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible =
private void InitializeDashboardHeader(Panel header) _dashboardLogout.Visible = _dashboardMore.Visible = false;
{ _dashboardSettings.TabIndex = 890;
_dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = _dashboardAbout.TabIndex = 891;
_dashboardLogout.Visible = _dashboardMore.Visible = _dashboardClose.Visible = false; _dashboardLogout.TabIndex = 892;
_dashboardSettings.TabIndex = 890; _dashboardMore.TabIndex = 890;
_dashboardAbout.TabIndex = 891; _logoutButton.TabIndex = 892;
_dashboardLogout.TabIndex = 892; _dashboardSettings.Click += (_, _) => OpenDashboardMenu(_dashboardSettings, includeApplicationActions: false);
_dashboardMore.TabIndex = 890; _dashboardMore.Click += (_, _) => OpenDashboardMenu(_dashboardMore, includeApplicationActions: true);
_logoutButton.TabIndex = 892; _dashboardAbout.Click += (_, _) => ShowDashboardAbout();
_dashboardClose.TabIndex = 901; _dashboardLogout.Click += async (_, _) => await LogoutAsync();
_dashboardSettings.Click += (_, _) => OpenDashboardMenu(_dashboardSettings, includeApplicationActions: false); var tip = new ToolTip();
_dashboardMore.Click += (_, _) => OpenDashboardMenu(_dashboardMore, includeApplicationActions: true); _welcomeLabel.TextChanged += (_, _) =>
_dashboardAbout.Click += (_, _) => ShowDashboardAbout(); {
_dashboardLogout.Click += async (_, _) => await LogoutAsync(); _dashboardHeaderName.Text = _welcomeLabel.Text;
_dashboardClose.Click += (_, _) => tip.SetToolTip(_dashboardHeaderName, _welcomeLabel.Text);
{ tip.SetToolTip(_welcomeLabel, _welcomeLabel.Text);
if (_settingsMenu?.Visible == true) { _settingsMenu.Close(); return; } };
if (_settingsDismissedAt != long.MinValue && Environment.TickCount64 - _settingsDismissedAt < 350) return; _logoutButton.EnabledChanged += (_, _) => _dashboardLogout.Enabled = _logoutButton.Enabled;
RequestExit(); _dashboardView.VisibleChanged += (_, _) =>
}; {
var tip = new ToolTip(); if (!Disposing && !IsDisposed) LayoutBrandHeader();
_welcomeLabel.TextChanged += (_, _) => };
{ header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation();
_dashboardHeaderName.Text = _welcomeLabel.Text; tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置");
tip.SetToolTip(_dashboardHeaderName, _welcomeLabel.Text); tip.SetToolTip(_dashboardMore, "设置与关于");
tip.SetToolTip(_welcomeLabel, _welcomeLabel.Text); header.Disposed += (_, _) =>
}; {
_logoutButton.EnabledChanged += (_, _) => _dashboardLogout.Enabled = _logoutButton.Enabled; tip.Dispose();
_dashboardView.VisibleChanged += (_, _) => _settingsMenu?.Dispose();
{ };
if (!Disposing && !IsDisposed) LayoutBrandHeader(); header.Controls.AddRange([_dashboardHeaderName, _dashboardSettings, _dashboardAbout,
}; _dashboardLogout, _dashboardMore]);
header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation(); }
tip.SetToolTip(_dashboardClose, "断开并退出");
tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置"); private void RefreshDashboardHeaderPresentation()
tip.SetToolTip(_dashboardMore, "设置与关于"); {
header.Disposed += (_, _) => tip.Dispose(); if (Disposing || IsDisposed || _windowChrome is not { } chrome || _brandHeader.IsDisposed) return;
header.Controls.AddRange([_dashboardHeaderName, _dashboardSettings, _dashboardAbout, _content.HeaderArtworkOffset = _dashboardView.HeaderArtworkOffset = _brandHeader.Height;
_dashboardLogout, _dashboardMore, _dashboardClose]); var wide = WideDashboardPresentation && _dashboardView.Visible;
} _dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible =
_dashboardLogout.Visible = wide;
private void RefreshDashboardHeaderPresentation() chrome.LayoutButtons();
{ if (!CompactPresentation) LayoutExpandedBrandBounds();
if (Disposing || IsDisposed || _windowChrome is not { } chrome || _brandHeader.IsDisposed) return; if (!wide)
_content.HeaderArtworkOffset = _dashboardView.HeaderArtworkOffset = _brandHeader.Height; {
var wide = WideDashboardPresentation && _dashboardView.Visible; _headerPoem.Visible = !CompactPresentation && _brandHeader.Width >= ScaleLogical(780);
_dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = LayoutCompactDashboardActions();
_dashboardLogout.Visible = wide; return;
_dashboardClose.Visible = chrome.DashboardCloseSlot = _dashboardView.Visible; }
chrome.LayoutButtons();
_dashboardClose.Bounds = chrome.DashboardCloseBounds; _dashboardMore.Visible = false;
_dashboardClose.BringToFront(); _headerPoem.Visible = false;
if (!CompactPresentation) LayoutExpandedBrandBounds(); var caption = chrome.MinimizeButton.Bounds;
if (!wide) int S(int value) => ScaleLogical(value);
{ int x = caption.Left - S(10);
_headerPoem.Visible = !CompactPresentation && _brandHeader.Width >= ScaleLogical(780); foreach (var (button, width) in new[] { (_dashboardLogout, 106), (_dashboardAbout, 76), (_dashboardSettings, 76) })
LayoutCompactDashboardActions(); {
return; x -= S(width);
} button.Bounds = new Rectangle(x, caption.Top, S(width), caption.Height);
x -= S(8);
_dashboardMore.Visible = false; }
_headerPoem.Visible = false; var nameWidth = Math.Min(S(224), Math.Max(S(96), x - S(316)));
var caption = chrome.MinimizeButton.Bounds; _dashboardHeaderName.Bounds = new Rectangle(x - nameWidth, caption.Top, nameWidth, caption.Height);
_dashboardClose.Bounds = chrome.DashboardCloseBounds; }
int S(int value) => ScaleLogical(value);
int x = caption.Left - S(10); private void LayoutExpandedBrandBounds()
foreach (var (button, width) in new[] { (_dashboardLogout, 106), (_dashboardAbout, 76), (_dashboardSettings, 76) }) {
{ int S(int value) => ScaleLogical(value);
x -= S(width); foreach (Control control in _brandHeader.Controls)
button.Bounds = new Rectangle(x, caption.Top, S(width), caption.Height); {
x -= S(8); if (control.Tag is not Rectangle) continue;
} if (control is PictureBox) control.Bounds = new Rectangle(S(24), S(9), S(64), S(68));
var nameWidth = Math.Min(S(224), Math.Max(S(96), x - S(316))); else if (control is Label { Text: "纵横家" }) control.Bounds = new Rectangle(S(99), S(10), S(146), S(36));
_dashboardHeaderName.Bounds = new Rectangle(x - nameWidth, caption.Top, nameWidth, caption.Height); else control.Bounds = new Rectangle(S(101), S(47), S(210), S(24));
} }
}
private void LayoutExpandedBrandBounds()
{ private void LayoutCompactDashboardActions()
int S(int value) => ScaleLogical(value); {
foreach (Control control in _brandHeader.Controls) var show = CompactPresentation && _dashboardView.Visible && _logoutButton.Parent == _brandHeader;
{ _dashboardMore.Visible = show;
if (control.Tag is not Rectangle) continue; _welcomeLabel.Visible = false;
if (control is PictureBox) control.Bounds = new Rectangle(S(24), S(9), S(64), S(68)); if (!show) return;
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)); 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);
private void LayoutCompactDashboardActions() _logoutButton.Bounds = new Rectangle(settingsLeft - S(70), caption.Top, S(64), caption.Height);
{ }
var show = CompactPresentation && _dashboardView.Visible && _logoutButton.Parent == _brandHeader;
_dashboardMore.Visible = show; private void ShowDashboardAbout() => MessageBox.Show(this,
if (!show) return; $"纵横家 v{GetDisplayVersion()}\n智能安全网络\n\n优创未来(UCVL)\n管理服务器 {PlatformBootstrapTransport.ManagementAddress}",
"关于纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information);
int S(int value) => ScaleLogical(value);
var caption = _windowChrome!.MinimizeButton.Bounds; private void OpenDashboardMenu(Control anchor, bool includeApplicationActions)
var settingsLeft = caption.Left - S(38); {
_dashboardMore.Bounds = new Rectangle(settingsLeft, caption.Top, S(32), caption.Height); if (_exiting || _settingsMenu?.Visible == true) return;
_logoutButton.Bounds = new Rectangle(settingsLeft - S(70), caption.Top, S(64), caption.Height); _settingsMenu?.Dispose();
var nameWidth = Math.Clamp(_logoutButton.Left - S(191), S(70), S(110)); var menu = _settingsMenu = new ContextMenuStrip { BackColor = Brand.Surface, ForeColor = Brand.Text, ShowImageMargin = false };
_welcomeLabel.Bounds = new Rectangle(_logoutButton.Left - nameWidth - S(6), caption.Top, nameWidth, caption.Height); var options = menu.Items;
foreach (var label in _brandHeader.Controls.OfType<Label>()) if (includeApplicationActions)
{ {
if (label.Tag is not Rectangle) continue; var account = _accountLabel.Text;
label.Width = Math.Clamp(_welcomeLabel.Left - label.Left - S(6), S(80), S(180)); if (!string.IsNullOrWhiteSpace(account))
} {
} options.Add(new ToolStripLabel("当前账号 " + account));
options.Add(new ToolStripSeparator());
private void ShowDashboardAbout() => MessageBox.Show(this, }
$"纵横家 v{GetDisplayVersion()}\n智能安全网络\n\n优创未来(UCVL)\n管理服务器 {PlatformBootstrapTransport.ManagementAddress}", menu.Items.Add("关于纵横家", null, (_, _) => ShowDashboardAbout());
"关于纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information); menu.Items.Add(new ToolStripSeparator());
}
private void OpenDashboardMenu(Control anchor, bool includeApplicationActions) foreach (var (label, combo) in new[] { ("调度方式", _connectionModeCombo), ("工作节点", _manualNodeCombo),
{ ("代理模式", _routeCombo), ("流量趋势时间范围", _historyRangeCombo) })
if (_exiting || _settingsMenu?.Visible == true) return; {
var menu = _settingsMenu = new ContextMenuStrip { BackColor = Brand.Surface, ForeColor = Brand.Text, ShowImageMargin = false }; var item = options.Add(label);
var options = menu.Items; item.Enabled = combo.Visible && combo.Enabled && combo.Items.Count > 0;
if (includeApplicationActions) item.Click += (_, _) => BeginInvoke(() =>
{ {
menu.Items.Add("关于纵横家", null, (_, _) => ShowDashboardAbout()); if (_exiting || !combo.Visible || !combo.Enabled) return;
menu.Items.Add(new ToolStripSeparator()); combo.Focus();
} combo.DroppedDown = true;
foreach (var (label, combo) in new[] { ("调度方式", _connectionModeCombo), ("工作节点", _manualNodeCombo), });
("代理模式", _routeCombo), ("流量趋势时间范围", _historyRangeCombo) }) }
{ menu.Show(anchor, new Point(anchor.Width, anchor.Height), ToolStripDropDownDirection.BelowLeft);
var item = options.Add(label); }
item.Enabled = combo.Visible && combo.Enabled && combo.Items.Count > 0;
item.Click += (_, _) => BeginInvoke(() => private void MinimizeToTrayPresentation()
{ {
if (_exiting || !combo.Visible || !combo.Enabled) return; if (_exiting || IsDisposed || Disposing) return;
combo.Focus(); UpdateTaskbarPresentation();
combo.DroppedDown = true; Hide();
}); ShowInTaskbar = false;
} }
menu.Closed += (_, args) =>
{ private void RestoreFromTrayPresentation()
if (args.CloseReason == ToolStripDropDownCloseReason.AppClicked) {
_settingsDismissedAt = Environment.TickCount64; ShowInTaskbar = true;
_settingsMenu = null; WindowState = FormWindowState.Normal;
menu.Dispose(); UpdateTaskbarPresentation();
}; }
menu.Show(anchor, new Point(anchor.Width, anchor.Height), ToolStripDropDownDirection.BelowLeft);
} private void UpdateTaskbarPresentation()
{
private void RestoreFromTrayPresentation() if (_exitResourcesDisposed) return;
{ _notifyIcon.Visible = ShouldShowTrayIcon(WindowState, _preview || _uiOnly || _exiting);
ShowInTaskbar = true; }
WindowState = FormWindowState.Normal;
UpdateTaskbarPresentation(); internal static bool ShouldShowTrayIcon(FormWindowState state, bool suppressed) =>
} !suppressed;
private void UpdateTaskbarPresentation() internal bool MinimizedOnTaskbarForTest => WindowState == FormWindowState.Minimized && Visible && ShowInTaskbar && !_exiting;
{ }
if (_exitResourcesDisposed) return;
_notifyIcon.Visible = ShouldShowTrayIcon(WindowState, _preview || _uiOnly || _exiting); internal enum DashboardHeaderIcon { User, Settings, About, Logout, More }
}
internal sealed class DashboardHeaderButton : Button
internal static bool ShouldShowTrayIcon(FormWindowState state, bool suppressed) => {
!suppressed; private readonly DashboardHeaderIcon _glyph;
private bool _hovered;
internal bool MinimizedOnTaskbarForTest => WindowState == FormWindowState.Minimized && Visible && ShowInTaskbar && !_exiting;
} internal DashboardHeaderButton(string text, DashboardHeaderIcon glyph)
{
internal enum DashboardHeaderIcon { User, Settings, About, Logout, More, Close } _glyph = glyph;
Text = text;
internal sealed class DashboardHeaderButton : Button AccessibleName = text;
{ Font = Brand.Font(10f);
private readonly DashboardHeaderIcon _glyph; Cursor = Cursors.Hand;
private bool _hovered; FlatStyle = FlatStyle.Flat;
FlatAppearance.BorderSize = 0;
internal DashboardHeaderButton(string text, DashboardHeaderIcon glyph) UseVisualStyleBackColor = false;
{ SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint |
_glyph = glyph; ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
Text = text; SetStyle(ControlStyles.Opaque, false);
AccessibleName = text; BackColor = Color.Transparent;
Font = Brand.Font(10f); }
Cursor = Cursors.Hand;
FlatStyle = FlatStyle.Flat; protected override void OnMouseEnter(EventArgs e) { _hovered = true; Invalidate(); base.OnMouseEnter(e); }
FlatAppearance.BorderSize = 0; protected override void OnMouseLeave(EventArgs e) { _hovered = false; Invalidate(); base.OnMouseLeave(e); }
UseVisualStyleBackColor = false; protected override void OnGotFocus(EventArgs e) { Invalidate(); base.OnGotFocus(e); }
SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | protected override void OnLostFocus(EventArgs e) { Invalidate(); base.OnLostFocus(e); }
ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true);
SetStyle(ControlStyles.Opaque, false); protected override void OnPaint(PaintEventArgs e)
BackColor = Color.Transparent; {
} if (Width < 8 || Height < 8) return;
var g = e.Graphics;
protected override void OnMouseEnter(EventArgs e) { _hovered = true; Invalidate(); base.OnMouseEnter(e); } var s = DeviceDpi / 96f;
protected override void OnMouseLeave(EventArgs e) { _hovered = false; Invalidate(); base.OnMouseLeave(e); } int S(int value) => Math.Max(1, (int)Math.Round(value * s));
protected override void OnGotFocus(EventArgs e) { Invalidate(); base.OnGotFocus(e); } g.SmoothingMode = SmoothingMode.AntiAlias;
protected override void OnLostFocus(EventArgs e) { Invalidate(); base.OnLostFocus(e); } using var path = UiGeometry.RoundedRectangle(Rectangle.Inflate(ClientRectangle, -2, -2), S(10));
using var fill = new SolidBrush(_hovered
protected override void OnPaint(PaintEventArgs e) ? Color.FromArgb(237, 220, 239, 255) : Color.FromArgb(176, 242, 250, 255));
{ g.FillPath(fill, path);
if (Width < 8 || Height < 8) return; using var border = new Pen(Color.FromArgb(177, 151, 189, 225), Math.Max(1, s));
var g = e.Graphics; g.DrawPath(border, path);
var s = DeviceDpi / 96f;
int S(int value) => Math.Max(1, (int)Math.Round(value * s)); var color = Enabled ? Brand.Navy : Brand.Muted;
g.SmoothingMode = SmoothingMode.AntiAlias; var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding;
var close = _glyph == DashboardHeaderIcon.Close; var iconSize = S(17);
if (!close || _hovered) var hasText = Text.Length != 0;
{ var textWidth = hasText ? TextRenderer.MeasureText(g, Text, Font, Size.Empty, flags).Width : 0;
using var path = UiGeometry.RoundedRectangle(Rectangle.Inflate(ClientRectangle, -2, -2), S(10)); var gap = hasText ? S(5) : 0;
using var fill = new SolidBrush(close ? Brand.Danger : _hovered var left = Math.Max(S(3), (Width - iconSize - gap - textWidth) / 2);
? Color.FromArgb(237, 220, 239, 255) : Color.FromArgb(176, 242, 250, 255)); DashboardHeaderDrawing.Paint(g, _glyph, new Rectangle(left, (Height - iconSize) / 2, iconSize, iconSize), color);
g.FillPath(fill, path); if (hasText) TextRenderer.DrawText(g, Text, Font,
if (!close) new Rectangle(left + iconSize + gap, 0, Math.Max(1, Width - left - iconSize - gap - S(3)), Height),
{ color, flags | TextFormatFlags.EndEllipsis);
using var border = new Pen(Color.FromArgb(177, 151, 189, 225), Math.Max(1, s)); if (Focused && ShowFocusCues) DashboardHeaderDrawing.Focus(g, ClientRectangle, DeviceDpi, color);
g.DrawPath(border, path); }
} }
}
internal sealed class DashboardHeaderIdentity : Label
var color = !Enabled ? Brand.Muted : close && _hovered ? Color.White : Brand.Navy; {
var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding; internal DashboardHeaderIdentity()
var iconSize = S(close ? 18 : 17); {
var hasText = Text.Length != 0; BackColor = Color.Transparent;
var textWidth = hasText ? TextRenderer.MeasureText(g, Text, Font, Size.Empty, flags).Width : 0; ForeColor = Brand.Navy;
var gap = hasText ? S(5) : 0; Font = Brand.Font(11f, FontStyle.Bold);
var left = Math.Max(S(3), (Width - iconSize - gap - textWidth) / 2); AccessibleName = "当前登录用户";
DashboardHeaderDrawing.Paint(g, _glyph, new Rectangle(left, (Height - iconSize) / 2, iconSize, iconSize), color); }
if (hasText) TextRenderer.DrawText(g, Text, Font,
new Rectangle(left + iconSize + gap, 0, Math.Max(1, Width - left - iconSize - gap - S(3)), Height), protected override void OnPaint(PaintEventArgs e)
color, flags | TextFormatFlags.EndEllipsis); {
if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(ClientRectangle, -5, -5)); var iconSize = (int)Math.Round(18 * DeviceDpi / 96.0);
} var gap = (int)Math.Round(6 * DeviceDpi / 96.0);
} var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding;
var textWidth = TextRenderer.MeasureText(e.Graphics, Text, Font, Size.Empty, flags).Width;
internal sealed class DashboardHeaderIdentity : Label var left = Math.Max(0, Width - iconSize - gap - textWidth - gap);
{ DashboardHeaderDrawing.Paint(e.Graphics, DashboardHeaderIcon.User,
internal DashboardHeaderIdentity() new Rectangle(left, (Height - iconSize) / 2, iconSize, iconSize), ForeColor);
{ var textLeft = left + iconSize + gap;
BackColor = Color.Transparent; TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(textLeft, 0, Math.Max(1, Width - textLeft), Height),
ForeColor = Brand.Navy; ForeColor, flags | TextFormatFlags.EndEllipsis);
Font = Brand.Font(11f, FontStyle.Bold); }
AccessibleName = "当前登录用户"; }
}
internal static class DashboardHeaderDrawing
protected override void OnPaint(PaintEventArgs e) {
{ internal static void Focus(Graphics graphics, Rectangle bounds, int dpi, Color color)
var iconSize = (int)Math.Round(18 * DeviceDpi / 96.0); {
var gap = (int)Math.Round(6 * DeviceDpi / 96.0); var scale = dpi / 96f;
var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding; var inset = Math.Max(3, (int)Math.Round(4 * scale));
var textWidth = TextRenderer.MeasureText(e.Graphics, Text, Font, Size.Empty, flags).Width; var inner = Rectangle.Inflate(bounds, -inset, -inset);
var left = Math.Max(0, Width - iconSize - gap - textWidth - gap); if (inner.Width <= 0 || inner.Height <= 0) return;
DashboardHeaderDrawing.Paint(e.Graphics, DashboardHeaderIcon.User, using var path = UiGeometry.RoundedRectangle(inner, Math.Max(2, (int)Math.Round(5 * scale)));
new Rectangle(left, (Height - iconSize) / 2, iconSize, iconSize), ForeColor); using var pen = new Pen(SystemInformation.HighContrast ? SystemColors.Highlight : color, Math.Max(1.25f, 1.4f * scale));
var textLeft = left + iconSize + gap; graphics.DrawPath(pen, path);
TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(textLeft, 0, Math.Max(1, Width - textLeft), Height), }
ForeColor, flags | TextFormatFlags.EndEllipsis);
} internal static void Paint(Graphics g, DashboardHeaderIcon glyph, Rectangle bounds, Color color)
} {
if (glyph == DashboardHeaderIcon.Settings)
internal static class DashboardHeaderDrawing {
{ DashboardDrawing.Icon(g, DashboardIcon.Settings, bounds, color);
internal static void Paint(Graphics g, DashboardHeaderIcon glyph, Rectangle bounds, Color color) return;
{ }
if (glyph == DashboardHeaderIcon.Settings) var state = g.Save();
{ try
DashboardDrawing.Icon(g, DashboardIcon.Settings, bounds, color); {
return; g.SmoothingMode = SmoothingMode.AntiAlias;
} g.TranslateTransform(bounds.Left, bounds.Top);
var state = g.Save(); g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f);
try using var pen = new Pen(color, 1.85f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round };
{ switch (glyph)
g.SmoothingMode = SmoothingMode.AntiAlias; {
g.TranslateTransform(bounds.Left, bounds.Top); case DashboardHeaderIcon.User:
g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f); g.DrawEllipse(pen, 8, 2, 8, 8);
using var pen = new Pen(color, 1.85f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }; g.DrawArc(pen, 3, 11, 18, 15, 180, 180);
switch (glyph) g.DrawLine(pen, 3, 18.5f, 21, 18.5f);
{ break;
case DashboardHeaderIcon.User: case DashboardHeaderIcon.About:
g.DrawEllipse(pen, 8, 2, 8, 8); g.DrawEllipse(pen, 2, 2, 20, 20);
g.DrawArc(pen, 3, 11, 18, 15, 180, 180); g.DrawLine(pen, 12, 11, 12, 17);
g.DrawLine(pen, 3, 18.5f, 21, 18.5f); g.DrawLine(pen, 12, 7.5f, 12, 8);
break; break;
case DashboardHeaderIcon.About: case DashboardHeaderIcon.Logout:
g.DrawEllipse(pen, 2, 2, 20, 20); g.DrawLines(pen, [new PointF(11, 3), new(3, 3), new(3, 21), new(11, 21)]);
g.DrawLine(pen, 12, 11, 12, 17); g.DrawLine(pen, 9, 12, 21, 12);
g.DrawLine(pen, 12, 7.5f, 12, 8); g.DrawLines(pen, [new PointF(16, 7), new(21, 12), new(16, 17)]);
break; break;
case DashboardHeaderIcon.Logout: case DashboardHeaderIcon.More:
g.DrawLines(pen, [new PointF(11, 3), new(3, 3), new(3, 21), new(11, 21)]); using (var dot = new SolidBrush(color))
g.DrawLine(pen, 9, 12, 21, 12); for (var x = 3; x <= 19; x += 8) g.FillEllipse(dot, x, 10.5f, 3.25f, 3.25f);
g.DrawLines(pen, [new PointF(16, 7), new(21, 12), new(16, 17)]); break;
break; }
case DashboardHeaderIcon.More: }
using (var dot = new SolidBrush(color)) finally { g.Restore(state); }
for (var x = 3; x <= 19; x += 8) g.FillEllipse(dot, x, 10.5f, 3.25f, 3.25f); }
break; }
case DashboardHeaderIcon.Close:
g.DrawLine(pen, 5, 5, 19, 19);
g.DrawLine(pen, 19, 5, 5, 19);
break;
}
}
finally { g.Restore(state); }
}
}
+30 -21
View File
@@ -6,8 +6,8 @@ internal sealed partial class MainForm
private bool WideDashboardPresentation => ClientSize.Width >= ScaleLogical(840) && ClientSize.Height >= ScaleLogical(480); private bool WideDashboardPresentation => ClientSize.Width >= ScaleLogical(840) && ClientSize.Height >= ScaleLogical(480);
private bool CompactPresentation => !WideDashboardPresentation; private bool CompactPresentation => !WideDashboardPresentation;
private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold); private readonly Font _compactStatusFont=Brand.Font(9.5f,FontStyle.Bold);
private readonly Font _wideStatusFont=Brand.Font(20f,FontStyle.Bold); private readonly Font _wideStatusFont=Brand.Font(17f,FontStyle.Bold);
private readonly Font _denseStatusFont=Brand.Font(16f,FontStyle.Bold); private readonly Font _denseStatusFont=Brand.Font(15f,FontStyle.Bold);
private readonly Font _wideChartFont=Brand.Font(9f); private readonly Font _wideChartFont=Brand.Font(9f);
private readonly Font _compactChartFont=Brand.Font(7.5f); private readonly Font _compactChartFont=Brand.Font(7.5f);
private readonly Font _compactFieldFont=Brand.Font(7.5f, FontStyle.Bold); private readonly Font _compactFieldFont=Brand.Font(7.5f, FontStyle.Bold);
@@ -80,7 +80,7 @@ internal sealed partial class MainForm
LayoutWindowChrome(); LayoutWindowChrome();
if (_welcomeLabel.Parent == _brandHeader) if (_welcomeLabel.Parent == _brandHeader)
{ {
_welcomeLabel.Visible=_dashboardView.Visible; _welcomeLabel.Visible=false;
_logoutButton.Visible=_dashboardView.Visible; _logoutButton.Visible=_dashboardView.Visible;
} }
} }
@@ -121,7 +121,8 @@ internal sealed partial class MainForm
{ {
_welcomeLabel.Parent=_brandHeader; _welcomeLabel.Parent=_brandHeader;
_logoutButton.Parent=_brandHeader; _logoutButton.Parent=_brandHeader;
_welcomeLabel.Visible=_logoutButton.Visible=_dashboardView.Visible; _welcomeLabel.Visible=false;
_logoutButton.Visible=_dashboardView.Visible;
LayoutCompactDashboardActions(); LayoutCompactDashboardActions();
_accountLabel.Visible=_identityBadge.Visible=false; _accountLabel.Visible=_identityBadge.Visible=false;
} }
@@ -141,19 +142,19 @@ internal sealed partial class MainForm
_nodeIcon.Visible=_modeIcon.Visible=false; _nodeIcon.Visible=_modeIcon.Visible=false;
_scheduleBadge.Visible=false; _scheduleBadge.Visible=false;
var leftWidth=_modeCard.Left-S(8); var leftWidth=_modeCard.Left-S(8);
_selectionHeading.Bounds=R(10,1,34,20); _selectionHeading.Bounds=R(10,2,34,20);
_routeHeading.Bounds=R(10,23,34,20); _routeHeading.Bounds=R(10,22,34,20);
_routeHeading.Text="模式"; _routeHeading.Text="模式";
var fieldLeft=S(46); var fieldWidth=leftWidth-fieldLeft; var fieldLeft=S(44); var fieldWidth=leftWidth-fieldLeft;
var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2); var splitWidth=Math.Max(S(84),(fieldWidth-S(4))/2);
_connectionModeCombo.Bounds=new(fieldLeft,S(1),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20)); _connectionModeCombo.Bounds=new(fieldLeft,S(2),_manualNodeCombo.Visible?splitWidth:fieldWidth,S(20));
_manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(1),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20)); _manualNodeCombo.Bounds=new(_connectionModeCombo.Right+S(4),S(2),Math.Max(S(60),fieldWidth-splitWidth-S(4)),S(20));
_routeCombo.Bounds=new(fieldLeft,S(23),fieldWidth,S(20)); _routeCombo.Bounds=new(fieldLeft,S(22),fieldWidth,S(20));
_nodeHeading.Text="节点"; _nodeHeading.Text="节点";
_nodeHeading.Bounds=R(8,1,34,20); _nodeHeading.Bounds=R(10,2,34,20);
_currentNodeLabel.Bounds=new(S(44),S(1),_modeCard.Width-S(46),S(20)); _currentNodeLabel.Bounds=new(fieldLeft,S(2),_modeCard.Width-fieldLeft-S(2),S(20));
_actualModeHeading.Bounds=R(8,23,34,20); _actualModeHeading.Bounds=R(10,22,34,20);
_routeReadOnly.Bounds=new(S(44),S(23),_modeCard.Width-S(46),S(20)); _routeReadOnly.Bounds=new(fieldLeft,S(22),_modeCard.Width-fieldLeft-S(2),S(20));
foreach(var label in new[]{_selectionHeading,_routeHeading,_nodeHeading,_actualModeHeading,_currentNodeLabel}) foreach(var label in new[]{_selectionHeading,_routeHeading,_nodeHeading,_actualModeHeading,_currentNodeLabel})
{ label.TextAlign=ContentAlignment.MiddleLeft; label.Padding=Padding.Empty; } { label.TextAlign=ContentAlignment.MiddleLeft; label.Padding=Padding.Empty; }
_selectionHeading.Font = _routeHeading.Font = _nodeHeading.Font = _actualModeHeading.Font = _compactFieldFont; _selectionHeading.Font = _routeHeading.Font = _nodeHeading.Font = _actualModeHeading.Font = _compactFieldFont;
@@ -170,17 +171,25 @@ internal sealed partial class MainForm
_tailnetUploadMetric.Bounds=_uploadMetric.Bounds; _tailnetUploadMetric.Bounds=_uploadMetric.Bounds;
_tailnetDownloadMetric.Bounds=_downloadMetric.Bounds; _tailnetDownloadMetric.Bounds=_downloadMetric.Bounds;
} }
_trendHeading.Text="本机代理趋势 · "+(_selectionUiConnected?(_currentNodeUsesTailnet?"Tailscale":"公网入口"):"未连接"); _trendHeading.Text = !_selectionUiConnected ? "本机代理趋势" :
_trendHeading.Bounds=new(S(10),S(2),_speedTrendCard.Width-S(120),S(18)); _currentNodeUsesTailnet ? "代理趋势 · Tailscale" : "代理趋势 · 公网入口";
var headerTop = S(2);
var headerHeight = S(20);
var inset = S(10);
var headingWidth = S(116);
var rangeWidth = S(78);
var rangeLeft = _speedTrendCard.Width - rangeWidth - inset;
_trendHeading.Bounds = new(inset, headerTop, headingWidth, headerHeight);
_trendHeading.TextAlign=ContentAlignment.MiddleLeft; _trendHeading.TextAlign=ContentAlignment.MiddleLeft;
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(98),S(2),S(88),S(18)); _historyRangeCombo.Bounds = new(rangeLeft, headerTop, rangeWidth, headerHeight);
var legendWidth = Math.Max(S(90), (_speedTrendCard.Width - S(118)) / 2); var legendLeft = _trendHeading.Right + S(4);
_uploadLegend.Bounds=new(S(10),S(20),legendWidth,S(16)); var legendWidth = Math.Max(1, (rangeLeft - S(5) - legendLeft) / 2);
_downloadLegend.Bounds=new(_uploadLegend.Right,S(20),legendWidth,S(16)); _uploadLegend.Bounds = new(legendLeft, headerTop, legendWidth, headerHeight);
_downloadLegend.Bounds = new(_uploadLegend.Right, headerTop, legendWidth, headerHeight);
_uploadLegend.TextAlign=_downloadLegend.TextAlign=ContentAlignment.MiddleLeft; _uploadLegend.TextAlign=_downloadLegend.TextAlign=ContentAlignment.MiddleLeft;
_uploadLegend.Visible=_downloadLegend.Visible=true; _uploadLegend.Visible=_downloadLegend.Visible=true;
_trafficChart.Font=_compactChartFont; _trafficChart.Font=_compactChartFont;
_trafficChart.Bounds=new(S(8),S(36),_speedTrendCard.Width-S(16),Math.Max(S(22),_speedTrendCard.Height-S(40))); _trafficChart.Bounds = new(S(8), S(23), _speedTrendCard.Width - S(16), Math.Max(1, _speedTrendCard.Height - S(27)));
_historyStatus.Visible=false; _historyStatus.Visible=false;
_sampleLabel.Visible=false; _sampleLabel.Visible=false;
_planLabel.Visible=false; _planLabel.Visible=false;
+2 -2
View File
@@ -96,7 +96,7 @@ internal sealed partial class MainForm
_modeCard.Paint += (_, e) => _modeCard.Paint += (_, e) =>
{ {
using var divider = new Pen(Color.FromArgb(130, 160, 189, 211), Math.Max(1, DeviceDpi / 96f * .6f)); using var divider = new Pen(Color.FromArgb(130, 160, 189, 211), Math.Max(1, DeviceDpi / 96f * .6f));
var x = WideDashboardPresentation ? _modeIcon.Left - ScaleLogical(7) : 0; const int x = 0;
e.Graphics.DrawLine(divider, x, ScaleLogical(8), x, _modeCard.Height - ScaleLogical(8)); e.Graphics.DrawLine(divider, x, ScaleLogical(8), x, _modeCard.Height - ScaleLogical(8));
}; };
BuildConnectionSelection(); BuildConnectionSelection();
@@ -377,7 +377,7 @@ internal sealed partial class MainForm
if(checks.Values.Any(value=>!value))throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json"); if(checks.Values.Any(value=>!value))throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json");
} }
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _footer, _wideMonitor, _wideSummary } private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _footer, _wideMonitor }
.Where(parent => parent.Visible) .Where(parent => parent.Visible)
.All(parent => parent.Controls.Cast<Control>().Where(c => c.Visible).All(c => c.Left >= 0 && c.Top >= 0 && c.Right <= parent.ClientSize.Width && c.Bottom <= parent.ClientSize.Height)); .All(parent => parent.Controls.Cast<Control>().Where(c => c.Visible).All(c => c.Left >= 0 && c.Top >= 0 && c.Right <= parent.ClientSize.Width && c.Bottom <= parent.ClientSize.Height));
} }
+2 -3
View File
@@ -63,9 +63,8 @@ internal sealed partial class MainForm
_checkingTailnetReadiness = true; _checkingTailnetReadiness = true;
try try
{ {
if (_xray.TailnetProbeEndpoint is { } endpoint) reachable = await TailnetEndpointConfirmation.ProbeAsync(
reachable = await TailnetEndpointConfirmation.ProbeAsync( _xray.ProbeCurrentOrPreferredTailnetAsync, _lifetime.Token);
probeToken => TailnetTransport.ProbeEndpointAsync(endpoint.Address, endpoint.Port, probeToken), _lifetime.Token);
} }
catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; } catch (OperationCanceledException) when (_lifetime.IsCancellationRequested) { return; }
catch (Exception) { /* Fixed diagnostics below contain no credentials. */ } catch (Exception) { /* Fixed diagnostics below contain no credentials. */ }
+85 -220
View File
@@ -1,44 +1,24 @@
using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
private readonly CardPanel _wideMonitor = new() { Visible = false }; private readonly CardPanel _wideMonitor = new() { Visible = false, Embedded = true };
private readonly TrendSummaryPanel _wideSummary = new() { Visible = false }; private readonly Label _wideSummaryState = new();
private readonly Label _wideSummaryState = new(), _wideSidebarPlan = new(), _wideFooterState = new();
private readonly DashboardGlyph _wideFooterClock = new(DashboardIcon.History);
private readonly DashboardGlyph _wideFooterShield = new(DashboardIcon.Shield);
private readonly RoundedButton _wideUpload = new(), _wideDownload = new(); private readonly RoundedButton _wideUpload = new(), _wideDownload = new();
private readonly DashboardFeature[] _wideFeatures =
[
new(DashboardIcon.Server, "线路调度", "自动分配或手动选择"),
new(DashboardIcon.Shield, "入口验证", "Tailscale 与青岛公网", true),
new(DashboardIcon.Layers, "灵活代理", "以已生效的模式为准", true),
];
private bool _wideDashboardBuilt; private bool _wideDashboardBuilt;
private TrafficChartSeries _wideSeries = TrafficChartSeries.Upload; private TrafficChartSeries _wideSeries = TrafficChartSeries.Both;
private void BuildWideDashboard() private void BuildWideDashboard()
{ {
_wideMonitor.AccessibleName = "连接状态和流量监控"; _wideMonitor.AccessibleName = "连接状态和流量监控";
_dashboardBody.Controls.Add(_wideMonitor); _dashboardBody.Controls.Add(_wideMonitor);
ConfigureLabel(_wideSummaryState, "", Brand.Font(10, FontStyle.Bold), Brand.Text); ConfigureLabel(_wideSummaryState, "", Brand.Font(8, FontStyle.Bold), Brand.Muted);
ConfigureLabel(_wideSidebarPlan, "", Brand.Font(8), Brand.Muted); _wideSummaryState.AutoEllipsis = true;
ConfigureLabel(_wideFooterState, "", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); _wideSummaryState.TextAlign = ContentAlignment.MiddleRight;
foreach (var label in new[] { _wideSummaryState, _wideSidebarPlan, _wideFooterState }) _modeCard.Controls.Add(_wideSummaryState);
{
label.AutoEllipsis = true;
label.TextAlign = ContentAlignment.MiddleLeft;
}
_wideSummary.Controls.Add(_wideSummaryState);
_nodeCard.Controls.Add(_wideSummary);
_nodeCard.Controls.Add(_wideSidebarPlan);
_nodeCard.Controls.AddRange(_wideFeatures);
_connectionModeCombo.LeadingIcon = DashboardIcon.Settings; _connectionModeCombo.LeadingIcon = DashboardIcon.Settings;
_routeCombo.LeadingIcon = DashboardIcon.Layers; _routeCombo.LeadingIcon = DashboardIcon.Layers;
_manualNodeCombo.LeadingIcon = DashboardIcon.Server; _manualNodeCombo.LeadingIcon = DashboardIcon.Server;
_footer.Controls.AddRange([_wideFooterClock, _wideFooterShield, _wideFooterState]);
_modeCard.Controls.AddRange([_nodeIcon, _modeIcon]); _modeCard.Controls.AddRange([_nodeIcon, _modeIcon]);
ConfigureSecondaryButton(_wideUpload, "↑ 上传 —", Point.Empty, new(144, 29)); ConfigureSecondaryButton(_wideUpload, "↑ 上传 —", Point.Empty, new(144, 29));
ConfigureSecondaryButton(_wideDownload, "↓ 下载 —", Point.Empty, new(144, 29)); ConfigureSecondaryButton(_wideDownload, "↓ 下载 —", Point.Empty, new(144, 29));
@@ -53,20 +33,20 @@ internal sealed partial class MainForm
private void SelectWideTrafficSeries(TrafficChartSeries series) private void SelectWideTrafficSeries(TrafficChartSeries series)
{ {
_wideSeries = series; _wideSeries = _wideSeries == series ? TrafficChartSeries.Both : series;
ApplyWideTrafficSeries(WideDashboardPresentation); ApplyWideTrafficSeries(WideDashboardPresentation);
} }
private void ApplyWideTrafficSeries(bool wide) private void ApplyWideTrafficSeries(bool wide)
{ {
_trafficChart.DisplayedSeries = wide ? _wideSeries : TrafficChartSeries.Both; _trafficChart.DisplayedSeries = wide ? _wideSeries : TrafficChartSeries.Both;
UpdateTab(_wideUpload, _wideSeries == TrafficChartSeries.Upload); UpdateTab(_wideUpload, Brand.RoyalBlue, _wideSeries != TrafficChartSeries.Download);
UpdateTab(_wideDownload, _wideSeries == TrafficChartSeries.Download); UpdateTab(_wideDownload, TrafficChart.DownloadColor, _wideSeries != TrafficChartSeries.Upload);
static void UpdateTab(RoundedButton button, bool selected) static void UpdateTab(RoundedButton button, Color accent, bool visible)
{ {
button.BackColor = selected ? Brand.RoyalBlue : Color.White; button.BackColor = Color.White;
button.ForeColor = selected ? Color.White : Brand.DeepBlue; button.ForeColor = visible ? accent : Brand.Muted;
button.AccessibleDescription = selected ? "当前显示" : "点击切换"; button.AccessibleDescription = visible ? "曲线可见,点击切换" : "曲线已隐藏,点击显示";
} }
} }
@@ -77,31 +57,20 @@ internal sealed partial class MainForm
{ {
if (!ReferenceEquals(control.Parent, parent)) control.Parent = parent; if (!ReferenceEquals(control.Parent, parent)) control.Parent = parent;
} }
Move(_modeCard, wide ? _wideMonitor : _nodeCard);
Move(_speedTrendCard, wide ? _wideMonitor : _dashboardBody); Move(_speedTrendCard, wide ? _wideMonitor : _dashboardBody);
Move(_dailyCard, wide ? _wideMonitor : _dashboardBody); Move(_dailyCard, wide ? _wideMonitor : _dashboardBody);
Move(_nodeTrafficPanel, wide ? _wideMonitor : _dashboardBody); Move(_nodeTrafficPanel, wide ? _wideMonitor : _dashboardBody);
Move(_trendHeading, wide ? _wideSummary : _speedTrendCard);
var rangeParent = wide ? _modeCard : _speedTrendCard;
if (_historyRangeCombo.Parent != rangeParent)
{
_historyRangeCombo.DroppedDown = false;
Move(_historyRangeCombo, rangeParent);
}
_wideMonitor.Visible = wide; _wideMonitor.Visible = wide;
_wideSummary.Visible = _wideSidebarPlan.Visible = wide; _wideSummaryState.Visible = wide;
_wideUpload.Visible = _wideDownload.Visible = wide; _wideUpload.Visible = _wideDownload.Visible = wide;
_wideFooterClock.Visible = _wideFooterShield.Visible = _wideFooterState.Visible = wide;
_footerCompanySite.Visible = !wide; _footerCompanySite.Visible = !wide;
_dailyIcon.Visible = wide; _dailyIcon.Visible = wide;
foreach (var feature in _wideFeatures) feature.Visible = wide;
_usageMetric.InlineTotal = _sessionMetric.InlineTotal = wide; _usageMetric.InlineTotal = _sessionMetric.InlineTotal = wide;
_statusCard.WideBanner = wide; _statusCard.WideBanner = false;
_connectButton.Capsule = wide; _connectButton.Capsule = wide;
_nodeCard.GlassRim = _wideMonitor.GlassRim = _wideSummary.GlassRim _nodeCard.GlassRim = _speedTrendCard.GlassRim = _dailyCard.GlassRim = _footer.GlassRim = wide;
= _speedTrendCard.GlassRim = _dailyCard.GlassRim = _footer.GlassRim = wide;
_uploadLegend.Visible = _downloadLegend.Visible = !wide; _uploadLegend.Visible = _downloadLegend.Visible = !wide;
_historyStatus.Visible = wide; _historyStatus.Visible = false;
ApplyWideTrafficSeries(wide); ApplyWideTrafficSeries(wide);
RefreshConnectionAppearance(); RefreshConnectionAppearance();
} }
@@ -110,13 +79,13 @@ internal sealed partial class MainForm
{ {
int S(int value) => ScaleLogical(value); int S(int value) => ScaleLogical(value);
var dense = viewport.Height < S(465); var dense = viewport.Height < S(465);
var layout = DashboardWideLayout.Calculate(viewport, DeviceDpi, _canViewNodeTraffic); var layout = DashboardWideLayout.Calculate(viewport, DeviceDpi, _canViewNodeTraffic, _manualNodeCombo.Visible);
_dashboardBody.Bounds = new Rectangle(Point.Empty, viewport); _dashboardBody.Bounds = new Rectangle(Point.Empty, viewport);
if (_welcomeLabel.Parent != _dashboardBody) _welcomeLabel.Parent = _dashboardBody; if (_welcomeLabel.Parent != _dashboardBody) _welcomeLabel.Parent = _dashboardBody;
if (_logoutButton.Parent != _dashboardBody) _logoutButton.Parent = _dashboardBody; if (_logoutButton.Parent != _dashboardBody) _logoutButton.Parent = _dashboardBody;
_welcomeLabel.Visible = _logoutButton.Visible = _accountLabel.Visible = _identityBadge.Visible = false; _welcomeLabel.Visible = _logoutButton.Visible = _accountLabel.Visible = _identityBadge.Visible = false;
_statusCard.Bounds = layout.Banner; _statusCard.Bounds = layout.Banner;
_nodeCard.Bounds = layout.Sidebar; _nodeCard.Bounds = layout.Configuration;
_wideMonitor.Bounds = layout.Monitor; _wideMonitor.Bounds = layout.Monitor;
_modeCard.Bounds = layout.State; _modeCard.Bounds = layout.State;
_speedTrendCard.Bounds = layout.Trend; _speedTrendCard.Bounds = layout.Trend;
@@ -127,114 +96,85 @@ internal sealed partial class MainForm
_tailnetSampleLabel.Visible = false; _tailnetSampleLabel.Visible = false;
var bannerHeight = _statusCard.Height; var bannerHeight = _statusCard.Height;
var actionWidth = S(dense ? 132 : 158); var actionWidth = S(dense ? 120 : 138);
var actionHeight = S(dense ? 36 : 42); var actionHeight = S(dense ? 34 : 38);
var shieldSize = S(dense ? 43 : 52); var shieldSize = S(dense ? 36 : 42);
_statusDot.Bounds = new Rectangle(S(22), (bannerHeight - shieldSize) / 2, shieldSize, shieldSize); var pad = S(dense ? 14 : 18);
_connectButton.Bounds = new Rectangle(_statusCard.Width - actionWidth - S(22), (bannerHeight - actionHeight) / 2, actionWidth, actionHeight); _statusDot.Bounds = new Rectangle(pad, (bannerHeight - shieldSize) / 2, shieldSize, shieldSize);
var statusLeft = S(dense ? 77 : 90); _connectButton.Bounds = new Rectangle(_statusCard.Width - actionWidth - pad, (bannerHeight - actionHeight) / 2, actionWidth, actionHeight);
var statusWidth = _connectButton.Left - statusLeft - S(13); var statusLeft = _statusDot.Right + S(12);
_statusTitle.Bounds = new Rectangle(statusLeft, bannerHeight / 2 - S(dense ? 24 : 30), statusWidth, S(dense ? 26 : 33)); var statusWidth = _connectButton.Left - statusLeft - S(12);
_statusDetail.Bounds = new Rectangle(statusLeft + S(2), bannerHeight / 2 + S(dense ? 1 : 4), statusWidth, S(dense ? 20 : 23)); _statusTitle.Bounds = new Rectangle(statusLeft, bannerHeight / 2 - S(dense ? 22 : 26), statusWidth, S(dense ? 25 : 29));
_statusDetail.Bounds = new Rectangle(statusLeft, bannerHeight / 2 + S(2), statusWidth, S(20));
var sidebarWidth = _nodeCard.Width; var rowHeight = S(dense ? 26 : 31);
var selectorWidth = sidebarWidth - S(75); var fieldHeight = rowHeight - S(3);
var firstRow = S(dense ? 9 : 15); var firstRow = layout.State.Top;
var rowStep = S(dense ? 33 : 40); var valueLeft = pad + S(43);
var rowHeight = S(dense ? 28 : 32); var fieldWidth = layout.State.Left - valueLeft - S(16);
_selectionHeading.Bounds = new Rectangle(S(15), firstRow, S(47), rowHeight); _selectionHeading.Bounds = new Rectangle(pad, firstRow, S(39), fieldHeight);
_routeHeading.Bounds = new Rectangle(S(15), firstRow + rowStep, S(47), rowHeight); _routeHeading.Bounds = new Rectangle(pad, firstRow + rowHeight, S(39), fieldHeight);
_routeHeading.Text = "模式"; _routeHeading.Text = "模式";
_selectionHeading.TextAlign = _routeHeading.TextAlign = ContentAlignment.MiddleLeft; _selectionHeading.TextAlign = _routeHeading.TextAlign = ContentAlignment.MiddleLeft;
_connectionModeCombo.Bounds = new Rectangle(S(60), firstRow, selectorWidth, rowHeight); _connectionModeCombo.Bounds = new Rectangle(valueLeft, firstRow, fieldWidth, fieldHeight);
_routeCombo.Bounds = new Rectangle(S(60), firstRow + rowStep, selectorWidth, rowHeight); _routeCombo.Bounds = new Rectangle(valueLeft, firstRow + rowHeight, fieldWidth, fieldHeight);
_manualNodeCombo.Bounds = new Rectangle(S(60), firstRow + 2 * rowStep, selectorWidth, S(29)); _manualNodeCombo.Bounds = new Rectangle(valueLeft, firstRow + 2 * rowHeight, fieldWidth, fieldHeight);
var summaryTop = firstRow + (_manualNodeCombo.Visible ? 3 : 2) * rowStep + S(3);
var remaining = _nodeCard.Height - summaryTop - S(24);
var summaryHeight = Math.Clamp(remaining / 3, S(dense ? 55 : 65), S(115));
_wideSummary.Bounds = new Rectangle(S(10), summaryTop, sidebarWidth - S(20), summaryHeight);
_trendHeading.Text = "本机代理趋势";
_trendHeading.Bounds = new Rectangle(S(13), S(8), _wideSummary.Width - S(26), S(22));
_trendHeading.TextAlign = ContentAlignment.MiddleLeft;
_wideSummaryState.Bounds = new Rectangle(S(13), S(31), _wideSummary.Width - S(26), S(22));
_wideSidebarPlan.Bounds = new Rectangle(S(14), _nodeCard.Height - S(25), sidebarWidth - S(28), S(16));
var featureTop = _wideSummary.Bottom + S(5);
var featureHeight = Math.Min(S(66), (_wideSidebarPlan.Top - featureTop - S(4)) / _wideFeatures.Length);
for (var index = 0; index < _wideFeatures.Length; index++)
{
var feature = _wideFeatures[index];
feature.Visible = featureHeight >= S(30);
if (feature.Visible) feature.Bounds = new Rectangle(S(12), featureTop + index * featureHeight, sidebarWidth - S(24), featureHeight);
}
var stateHeight = _modeCard.Height; var headingLeft = S(12);
var rangeWidth = S(129); var headingWidth = S(45);
var statesWidth = _modeCard.Width - rangeWidth - S(23); var stateValueLeft = headingLeft + headingWidth;
using var metrics = _modeCard.CreateGraphics(); var entryWidth = _selectionUiConnected ? S(105) : 0;
int TextWidth(string text, Font font) => TextRenderer.MeasureText(metrics, text, font, var stateWidth = _modeCard.Width - stateValueLeft - S(8);
Size.Empty, TextFormatFlags.SingleLine).Width;
var headingLeft = S(34);
var headingWidth = Math.Max(S(40), Math.Max(TextWidth("节点", _nodeHeading.Font),
TextWidth("模式", _actualModeHeading.Font)) + S(2));
var valueInset = headingLeft + headingWidth;
var modeWidth = Math.Clamp(TextWidth(_routeReadOnly.Text, _routeReadOnly.Font) + S(6), S(79), S(146));
var splitLimit = Math.Max(valueInset + S(35), statesWidth - valueInset - modeWidth);
var nodeRoom = splitLimit - valueInset - S(4);
var nodeText = _selectionUiConnected && !string.IsNullOrWhiteSpace(_currentNodeName) ? _currentNodeName : _currentNodeLabel.Text;
var nodeFont = _currentNodeLabel.Font;
if (TextWidth(nodeText, nodeFont) > nodeRoom)
{
// The sidebar already identifies the active transport. Omit its
// duplicate suffix here if it would crowd out the actual name.
if (_selectionUiConnected && _currentNodeUsesTailnet && !string.IsNullOrWhiteSpace(_currentNodeBaseName))
nodeText = _currentNodeBaseName;
if (TextWidth(nodeText, nodeFont) > nodeRoom)
nodeFont = TextWidth(nodeText, _narrowNodeFont) <= nodeRoom ? _narrowNodeFont : _minimumNodeFont;
}
_currentNodeLabel.Text = nodeText;
_currentNodeLabel.Font = nodeFont;
var split = Math.Min(splitLimit, Math.Max(statesWidth / 2, valueInset + TextWidth(nodeText, nodeFont) + S(4)));
_historyRangeCombo.Bounds = new Rectangle(_modeCard.Width - rangeWidth - S(6), (stateHeight - S(31)) / 2, rangeWidth, S(31));
_nodeIcon.Bounds = new Rectangle(S(7), (stateHeight - S(26)) / 2, S(26), S(26));
_nodeHeading.Text = "节点"; _nodeHeading.Text = "节点";
_nodeHeading.Bounds = new Rectangle(headingLeft, 0, headingWidth, stateHeight); _nodeHeading.Bounds = new Rectangle(headingLeft, 0, headingWidth, fieldHeight);
_currentNodeLabel.Bounds = new Rectangle(valueInset, 0, Math.Max(S(31), split - valueInset - S(4)), stateHeight); _currentNodeLabel.Bounds = new Rectangle(stateValueLeft, 0, stateWidth - entryWidth, fieldHeight);
_modeIcon.Bounds = new Rectangle(split + S(7), (stateHeight - S(25)) / 2, S(25), S(25)); _actualModeHeading.Bounds = new Rectangle(headingLeft, rowHeight, headingWidth, fieldHeight);
_actualModeHeading.Bounds = new Rectangle(split + headingLeft, 0, headingWidth, stateHeight); _routeReadOnly.Bounds = new Rectangle(stateValueLeft, rowHeight, stateWidth, fieldHeight);
_routeReadOnly.Bounds = new Rectangle(split + valueInset, 0, Math.Max(S(35), statesWidth - split - valueInset), stateHeight); _wideSummaryState.Bounds = new Rectangle(_modeCard.Width - entryWidth - S(8), 0, entryWidth, fieldHeight);
_nodeIcon.Visible = _modeIcon.Visible = true; _wideSummaryState.Visible = _selectionUiConnected;
if (_selectionUiConnected && !string.IsNullOrWhiteSpace(_currentNodeBaseName))
_currentNodeLabel.Text = _currentNodeBaseName;
using (var metrics = _modeCard.CreateGraphics())
{
int NodeWidth(Font font) => TextRenderer.MeasureText(metrics, _currentNodeLabel.Text, font,
Size.Empty, TextFormatFlags.SingleLine).Width;
if (NodeWidth(_currentNodeLabel.Font) > _currentNodeLabel.Width)
_currentNodeLabel.Font = NodeWidth(_narrowNodeFont) <= _currentNodeLabel.Width ? _narrowNodeFont : _minimumNodeFont;
}
_nodeIcon.Visible = _modeIcon.Visible = false;
_nodeHeading.TextAlign = _actualModeHeading.TextAlign = ContentAlignment.MiddleLeft; _nodeHeading.TextAlign = _actualModeHeading.TextAlign = ContentAlignment.MiddleLeft;
var trendWidth = _speedTrendCard.Width; var trendWidth = _speedTrendCard.Width;
var tabWidth = Math.Min(S(164), (trendWidth - S(30)) / 2); var tabTop = S(7);
var tabTop = S(dense ? 6 : 9); var tabHeight = S(dense ? 24 : 28);
var tabHeight = S(dense ? 26 : 31); var rangeWidth = S(128);
_wideUpload.Bounds = new Rectangle(S(12), tabTop, tabWidth, tabHeight); var tabWidth = S(135);
_wideDownload.Bounds = new Rectangle(_wideUpload.Right + S(4), tabTop, tabWidth, tabHeight); _historyRangeCombo.Bounds = new Rectangle(trendWidth - pad - rangeWidth, tabTop, rangeWidth, tabHeight);
_historyStatus.Bounds = new Rectangle(_wideDownload.Right + S(6), tabTop, Math.Max(1, trendWidth - _wideDownload.Right - S(18)), tabHeight); _wideDownload.Bounds = new Rectangle(_historyRangeCombo.Left - S(14) - tabWidth, tabTop, tabWidth, tabHeight);
_historyStatus.Text = "实时代理采样"; _wideUpload.Bounds = new Rectangle(_wideDownload.Left - S(5) - tabWidth, tabTop, tabWidth, tabHeight);
_trendHeading.Text = "本机代理趋势";
_trendHeading.Bounds = new Rectangle(pad, tabTop, _wideUpload.Left - pad - S(8), tabHeight);
_trendHeading.TextAlign = ContentAlignment.MiddleLeft;
_trafficChart.Font = _wideChartFont; _trafficChart.Font = _wideChartFont;
var chartTop = _wideUpload.Bottom + S(3); var chartTop = _wideUpload.Bottom + S(3);
_trafficChart.Bounds = new Rectangle(S(10), chartTop, trendWidth - S(20), _speedTrendCard.Height - chartTop - S(7)); _trafficChart.Bounds = new Rectangle(S(9), chartTop, trendWidth - S(18), _speedTrendCard.Height - chartTop - S(6));
var totalsHeight = _dailyCard.Height; var totalsHeight = _dailyCard.Height;
var titleWidth = Math.Min(S(155), _dailyCard.Width / 4); var titleWidth = S(140);
_dailyIcon.Bounds = new Rectangle(S(12), (totalsHeight - S(28)) / 2, S(28), S(28)); var iconSize = S(18);
_dailyHeading.Bounds = new Rectangle(S(47), 0, Math.Max(1, titleWidth - S(48)), totalsHeight); _dailyIcon.Bounds = new Rectangle(pad, (totalsHeight - iconSize) / 2, iconSize, iconSize);
_dailyHeading.Bounds = new Rectangle(_dailyIcon.Right + S(8), 0, titleWidth - _dailyIcon.Right - S(8), totalsHeight);
_dailyHeading.TextAlign = ContentAlignment.MiddleLeft; _dailyHeading.TextAlign = ContentAlignment.MiddleLeft;
var metricWidth = (_dailyCard.Width - titleWidth - S(9)) / 2; var metricWidth = Math.Min(S(178), (_dailyCard.Width - titleWidth - pad) / 2);
_usageMetric.Bounds = new Rectangle(titleWidth, S(3), metricWidth, totalsHeight - S(9)); _usageMetric.Bounds = new Rectangle(titleWidth, S(1), metricWidth, totalsHeight - S(3));
_sessionMetric.Bounds = new Rectangle(_usageMetric.Right, S(3), metricWidth, totalsHeight - S(9)); _sessionMetric.Bounds = new Rectangle(_usageMetric.Right, S(1), metricWidth, totalsHeight - S(3));
var footerHeight = _footer.Height; var footerHeight = _footer.Height;
_wideFooterClock.Bounds = new Rectangle(S(11), (footerHeight - S(22)) / 2, S(22), S(22)); _expiryLabel.Bounds = new Rectangle(pad, 0, S(110), footerHeight);
_expiryLabel.Bounds = new Rectangle(S(40), 0, S(126), footerHeight); _planLabel.Bounds = new Rectangle(_expiryLabel.Right + S(8), 0, _footer.Width - S(390), footerHeight);
_wideFooterShield.Bounds = new Rectangle(S(171), (footerHeight - S(22)) / 2, S(22), S(22)); _footerHint.Bounds = new Rectangle(_footer.Width - S(229) - pad, 0, S(229), footerHeight);
_wideFooterState.Bounds = new Rectangle(S(200), 0, Math.Max(1, _footer.Width - S(452)), footerHeight); _footerHint.Visible = _planLabel.Visible = true;
_footerHint.Bounds = new Rectangle(_footer.Width - S(243), 0, S(229), footerHeight); _footerPoem.Visible = false;
_footerHint.Visible = true;
_planLabel.Visible = _footerPoem.Visible = false;
_wideSidebarPlan.Text = _planLabel.Text;
} }
private void RefreshConnectionAppearance() private void RefreshConnectionAppearance()
@@ -265,8 +205,7 @@ internal sealed partial class MainForm
_ => Color.FromArgb(13, 99, 195), _ => Color.FromArgb(13, 99, 195),
} : accent; } : accent;
_statusDot.Featured = _statusCard.WideBanner; _statusDot.Featured = _statusCard.WideBanner;
_wideFooterShield.ForeColor = accent; _statusDot.Glyph = tone switch
_statusDot.Glyph = _wideFooterShield.Glyph = tone switch
{ {
BannerTone.Connected => DashboardIcon.Shield, BannerTone.Connected => DashboardIcon.Shield,
BannerTone.Error or BannerTone.Attention => DashboardIcon.ShieldAlert, BannerTone.Error or BannerTone.Attention => DashboardIcon.ShieldAlert,
@@ -276,7 +215,6 @@ internal sealed partial class MainForm
_wideSummaryState.Text = _selectionUiConnected _wideSummaryState.Text = _selectionUiConnected
? (_currentNodeUsesTailnet ? "● Tailscale 入口" : "● 公网入口") ? (_currentNodeUsesTailnet ? "● Tailscale 入口" : "● 公网入口")
: "● " + title; : "● " + title;
_wideFooterState.Text = tone == BannerTone.Connected ? "网络连接 · 已连接" : "网络连接 · " + title;
_footerCompanySite.Text = tone switch _footerCompanySite.Text = tone switch
{ {
BannerTone.Connected => "网络 · 已连接", BannerTone.Connected => "网络 · 已连接",
@@ -288,76 +226,3 @@ internal sealed partial class MainForm
_footerCompanySite.ForeColor = accent; _footerCompanySite.ForeColor = accent;
} }
} }
internal sealed class TrendSummaryPanel : CardPanel
{
protected override void OnPaintBackground(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (Width < 20 || Height < 48) return;
var g = e.Graphics;
var state = g.Save();
var scale = DeviceDpi / 96f;
var inset = Math.Max(1, (int)Math.Round(scale * 2));
using var clip = UiGeometry.RoundedRectangle(new Rectangle(inset, inset, Width - 2 * inset - 1, Height - 2 * inset - 2),
Math.Min((int)Math.Round(12 * scale), (Height - 2 * inset - 2) / 2));
g.SetClip(clip, CombineMode.Intersect);
var y = Height * .84f;
using var wave = new GraphicsPath();
wave.AddBezier(0, y, Width * .35f, Height * .43f, Width * .52f, Height * 1.25f, Width, Height * .66f);
wave.AddLine(Width, Height, 0, Height);
wave.CloseFigure();
using var fill = new LinearGradientBrush(ClientRectangle, Color.FromArgb(36, 117, 194, 244), Color.FromArgb(80, 114, 192, 246), 90);
using var line = new Pen(Color.FromArgb(96, 66, 152, 217), Math.Max(1f, .7f * scale));
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillPath(fill, wave);
g.DrawBezier(line, 0, y, Width * .35f, Height * .43f, Width * .52f, Height * 1.25f, Width, Height * .66f);
g.Restore(state);
}
}
internal sealed class DashboardFeature : Control
{
private readonly DashboardIcon _icon;
private readonly string _title, _detail;
private readonly bool _divider;
internal DashboardFeature(DashboardIcon icon, string title, string detail, bool divider = false)
{
_icon = icon;
_title = title;
_detail = detail;
_divider = divider;
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
BackColor = Color.Transparent;
AccessibleName = title;
AccessibleDescription = detail;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
var g = e.Graphics;
var scale = DeviceDpi / 96f;
int S(float value) => (int)Math.Round(value * scale);
var side = Math.Min(S(36), Height - S(6));
var icon = new Rectangle(S(5), (Height - side) / 2, side, side);
g.SmoothingMode = SmoothingMode.AntiAlias;
using var bubble = new SolidBrush(Color.FromArgb(92, 174, 217, 251));
g.FillEllipse(bubble, icon);
DashboardDrawing.Icon(g, _icon, Rectangle.Inflate(icon, -S(7), -S(7)), Brand.DeepBlue);
using var title = Brand.Font(10.5f, FontStyle.Bold);
using var detail = Brand.Font(8.5f);
var x = icon.Right + S(10);
var width = Width - x - S(4);
var middle = Height / 2;
if (_divider && Height >= S(38))
{
using var divider = new Pen(Color.FromArgb(108, 167, 198, 223), Math.Max(1f, .65f * scale));
g.DrawLine(divider, S(6), 0, Width - S(7), 0);
}
var flags = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter;
TextRenderer.DrawText(g, _title, title, new Rectangle(x, middle - S(16), width, S(18)), Brand.Navy, flags);
TextRenderer.DrawText(g, _detail, detail, new Rectangle(x, middle + S(2), width, S(16)), Brand.Muted, flags);
}
}
+132 -126
View File
@@ -1,126 +1,132 @@
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
private void ExerciseWideDashboardPreview(Dictionary<string, bool> checks, Action<string> capture) private void ExerciseWideDashboardPreview(Dictionary<string, bool> checks, Action<string> capture)
{ {
var compactSize = ClientSize; var compactSize = ClientSize;
ClientSize = new Size(ScaleLogical(1160), ScaleLogical(738)); ClientSize = new Size(ScaleLogical(1160), ScaleLogical(738));
LayoutBrandHeader(); LayoutBrandHeader();
LayoutDashboard(); LayoutDashboard();
checks["wide_geometry_all_viewport_and_dpi_cases"] = DashboardWideLayout.SelfTest(); checks["wide_geometry_all_viewport_and_dpi_cases"] = DashboardWideLayout.SelfTest();
checks["wide_header_account_and_actions"] = _dashboardHeaderName.Visible checks["wide_header_account_and_actions"] = _dashboardHeaderName.Visible
&& _dashboardHeaderName.Text == _welcomeLabel.Text && _dashboardHeaderName.Text == _welcomeLabel.Text
&& _dashboardSettings.Visible && _dashboardAbout.Visible && _dashboardLogout.Visible && _dashboardClose.Visible && _dashboardSettings.Visible && _dashboardAbout.Visible && _dashboardLogout.Visible
&& !_welcomeLabel.Visible && !_logoutButton.Visible; && WindowChromeForTest is { LoginMode: false, MinimizeButton.Action: CaptionAction.Minimize }
checks["wide_reuses_configuration_and_range_controls"] = _connectionModeCombo.Parent == _nodeCard && !_welcomeLabel.Visible && !_logoutButton.Visible;
&& _routeCombo.Parent == _nodeCard && _historyRangeCombo.Parent == _modeCard checks["wide_reuses_configuration_and_range_controls"] = _connectionModeCombo.Parent == _nodeCard
&& _connectionModeCombo.Enabled && _routeCombo.Enabled && _historyRangeCombo.Enabled; && _routeCombo.Parent == _nodeCard && _historyRangeCombo.Parent == _speedTrendCard
&& _connectionModeCombo.Enabled && _routeCombo.Enabled && _historyRangeCombo.Enabled;
_connectionModeCombo.SelectedIndex = 1;
checks["wide_manual_node_visible_and_fitted"] = _manualNodeCombo.Visible && _manualNodeCombo.Items.Count > 0 && DashboardControlsFit(); _connectionModeCombo.SelectedIndex = 1;
_connectionModeCombo.SelectedIndex = 0; checks["wide_manual_node_visible_and_fitted"] = _manualNodeCombo.Visible && _manualNodeCombo.Items.Count > 0 && DashboardControlsFit();
SetConnectionState(false, "未连接", "连接后显示代理速度趋势"); _connectionModeCombo.SelectedIndex = 0;
checks["wide_disconnected_and_no_fake_speed"] = _statusCard.Tone == BannerTone.Idle && _connectButton.Text == "连接" SetConnectionState(false, "未连接", "连接后显示代理速度趋势");
&& _wideUpload.Text.EndsWith("—") && _wideDownload.Text.EndsWith("—"); checks["wide_disconnected_and_no_fake_speed"] = _statusCard.Tone == BannerTone.Idle && _connectButton.Text == "连接"
capture("wide-disconnected"); && _wideUpload.Text.EndsWith("—") && _wideDownload.Text.EndsWith("—");
capture("wide-disconnected");
using (var pending = new CancellationTokenSource())
{ using (var pending = new CancellationTokenSource())
_connectionAttemptCancellation = pending; {
SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口"); _connectionAttemptCancellation = pending;
SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口"); SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口");
checks["wide_connecting_can_cancel"] = _statusCard.Tone == BannerTone.Connecting SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口");
&& _connectButton.Text == "取消连接" && _connectButton.Enabled checks["wide_connecting_can_cancel"] = _statusCard.Tone == BannerTone.Connecting
&& !_connectionModeCombo.Enabled && !_routeCombo.Enabled; && _connectButton.Text == "取消连接" && _connectButton.Enabled
capture("wide-connecting"); && !_connectionModeCombo.Enabled && !_routeCombo.Enabled;
checks["wide_cancel_handler_cancels_owned_attempt"] = TryCancelPendingConnection() capture("wide-connecting");
&& pending.IsCancellationRequested && !_connectButton.Enabled && _statusDetail.Text.Contains("取消"); checks["wide_cancel_handler_cancels_owned_attempt"] = TryCancelPendingConnection()
_connectionAttemptCancellation = null; && pending.IsCancellationRequested && !_connectButton.Enabled && _statusDetail.Text.Contains("取消");
SetBusy(false); _connectionAttemptCancellation = null;
} SetBusy(false);
}
SetConnectionState(true, "已安全连接", "VPN002 · Tailscale 入口 · AI 智能代理");
var now = DateTimeOffset.UtcNow; SetConnectionState(true, "已安全连接", "VPN002 · Tailscale 入口 · AI 智能代理");
for (var i = 0; i < 60; i++) var now = DateTimeOffset.UtcNow;
_trafficChart.Add(120000 + Math.Sin(i / 3d) * 50000, 600000 + Math.Cos(i / 7d) * 220000, now.AddSeconds(5 * (i - 59))); for (var i = 0; i < 60; i++)
DisplayTraffic(180000, 920000, "演示样本 · 近 5 分钟"); _trafficChart.Add(120000 + Math.Sin(i / 3d) * 50000, 600000 + Math.Cos(i / 7d) * 220000, now.AddSeconds(5 * (i - 59)));
_wideDownload.PerformClick(); DisplayTraffic(180000, 920000, "演示样本 · 近 5 分钟");
checks["wide_download_tab_changes_chart_series"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Download checks["wide_shows_both_series_and_aligns_chart_heading"] =
&& _wideDownload.Text.Contains("KB/s") && _wideUpload.Text.Contains("KB/s"); _trafficChart.DisplayedSeries == TrafficChartSeries.Both && _trendHeading.Top == _wideUpload.Top
_wideUpload.PerformClick(); && _wideUpload.Top == _historyRangeCombo.Top && _trendHeading.Right <= _wideUpload.Left;
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[2]; _wideDownload.PerformClick();
checks["wide_upload_tab_and_range_use_existing_chart"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Upload checks["wide_download_tab_changes_chart_series"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Download
&& _trafficChart.PeriodMinutes == 15; && _wideDownload.Text.Contains("KB/s") && _wideUpload.Text.Contains("KB/s");
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; _wideUpload.PerformClick();
checks["wide_connected_has_disconnect_and_live_values"] = _statusCard.Tone == BannerTone.Connected _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[2];
&& _connectButton.Text == "断开连接" && !_routeCombo.Enabled && DashboardControlsFit(); checks["wide_upload_tab_and_range_use_existing_chart"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Upload
capture("wide-connected"); && _trafficChart.PeriodMinutes == 15;
_wideUpload.PerformClick();
checks["wide_degraded_retains_disconnect"] = TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.WebsiteUnavailable) checks["wide_selected_series_toggles_back_to_both"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Both;
&& _statusCard.Tone == BannerTone.Attention && _connectButton.Text == "断开连接"; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
checks["wide_website_warning_confirms_proxy_and_fits_width"] = _statusDetail.Text.Contains("代理出口可达") && WarningTextFitsWidth(); checks["wide_connected_has_disconnect_and_live_values"] = _statusCard.Tone == BannerTone.Connected
capture("wide-website-warning"); && _connectButton.Text == "断开连接" && !_routeCombo.Enabled && DashboardControlsFit();
capture("wide-connected");
checks["wide_tailnet_egress_warning_retains_ingress_and_disconnect"] =
TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.TailnetEgressUnverified) checks["wide_degraded_retains_disconnect"] = TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.WebsiteUnavailable)
&& _statusCard.Tone == BannerTone.Attention && _connectButton.Text == "断开连接" && _statusCard.Tone == BannerTone.Attention && _connectButton.Text == "断开连接";
&& _wideSummaryState.Text.Contains("Tailscale 入口"); checks["wide_website_warning_confirms_proxy_and_fits_width"] = _statusDetail.Text.Contains("代理出口可达") && WarningTextFitsWidth();
checks["wide_tailnet_egress_warning_reports_uncertainty_and_fits_width"] = _statusDetail.Text.Contains("代理出口尚未确认") && WarningTextFitsWidth(); capture("wide-website-warning");
capture("wide-tailnet-egress-warning");
checks["wide_tailnet_egress_warning_retains_ingress_and_disconnect"] =
SetConnectionState(true, "已恢复安全连接", "VPN002 · Tailscale 入口"); TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision.TailnetEgressUnverified)
checks["wide_recovered_is_connected"] = _statusCard.Tone == BannerTone.Connected && _displayedHealthWarning is null; && _statusCard.Tone == BannerTone.Attention && _connectButton.Text == "断开连接"
SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。"); && _wideSummaryState.Text.Contains("Tailscale 入口");
_trafficChart.Reset(); checks["wide_tailnet_egress_warning_reports_uncertainty_and_fits_width"] = _statusDetail.Text.Contains("代理出口尚未确认") && WarningTextFitsWidth();
checks["wide_error_detail_and_retry_remain_visible"] = _statusCard.Tone == BannerTone.Error capture("wide-tailnet-egress-warning");
&& _statusDetail.Text.Contains("检查当前网络") && _connectButton.Text == "连接" && _connectButton.Enabled;
capture("wide-error"); SetConnectionState(true, "已恢复安全连接", "VPN002 · Tailscale 入口");
checks["wide_recovered_is_connected"] = _statusCard.Tone == BannerTone.Connected && _displayedHealthWarning is null;
ClientSize = new Size(ScaleLogical(840), ScaleLogical(480)); SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。");
LayoutDashboard(); _trafficChart.Reset();
checks["wide_minimum_children_fit"] = WideDashboardPresentation && _wideMonitor.Visible && DashboardControlsFit(); checks["wide_error_detail_and_retry_remain_visible"] = _statusCard.Tone == BannerTone.Error
capture("wide-minimum"); && _statusDetail.Text.Contains("检查当前网络") && _connectButton.Text == "连接" && _connectButton.Enabled;
SetNodeTrafficPermission(true); capture("wide-error");
LayoutDashboard();
checks["wide_minimum_permission_panel_preserved"] = _nodeTrafficPanel.Visible ClientSize = new Size(ScaleLogical(840), ScaleLogical(480));
&& _nodeTrafficPanel.Top > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top LayoutDashboard();
&& _trafficChart.Height >= ScaleLogical(40) && DashboardControlsFit(); checks["wide_minimum_children_fit"] = WideDashboardPresentation && _wideMonitor.Visible && DashboardControlsFit();
capture("wide-minimum-server-panel"); capture("wide-minimum");
SetNodeTrafficPermission(false); SetNodeTrafficPermission(true);
LayoutDashboard();
var screen = Screen.FromControl(this).WorkingArea; checks["wide_minimum_permission_panel_preserved"] = _nodeTrafficPanel.Visible
var realWidth = Math.Min(ScaleLogical(1160), screen.Width - ScaleLogical(16)); && _nodeTrafficPanel.Top > _speedTrendCard.Bottom && _nodeTrafficPanel.Bottom < _dailyCard.Top
var realHeight = Math.Min(ScaleLogical(738), screen.Height - ScaleLogical(16)); && _trafficChart.Height >= ScaleLogical(40) && DashboardControlsFit();
if (realWidth >= ScaleLogical(840) && realHeight >= ScaleLogical(480)) capture("wide-minimum-server-panel");
{ SetNodeTrafficPermission(false);
ClientSize = new Size(realWidth, realHeight);
LayoutDashboard(); var screen = Screen.FromControl(this).WorkingArea;
checks["wide_fits_actual_screen_work_area"] = _wideMonitor.Visible && Width <= screen.Width var realWidth = Math.Min(ScaleLogical(1160), screen.Width - ScaleLogical(16));
&& Height <= screen.Height && DashboardControlsFit(); var realHeight = Math.Min(ScaleLogical(738), screen.Height - ScaleLogical(16));
SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口"); if (realWidth >= ScaleLogical(840) && realHeight >= ScaleLogical(480))
using var screenAttempt = new CancellationTokenSource(); {
_connectionAttemptCancellation = screenAttempt; ClientSize = new Size(realWidth, realHeight);
SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口"); LayoutDashboard();
capture("wide-current-screen"); checks["wide_fits_actual_screen_work_area"] = _wideMonitor.Visible && Width <= screen.Width
_connectionAttemptCancellation = null; && Height <= screen.Height && DashboardControlsFit();
SetBusy(false); SetConnectionState(false, "正在连接", "VPN002 · 正在验证 Tailscale 节点入口");
SetConnectionState(false, "未连接", "点击连接,AI 自动选择工作节点"); using var screenAttempt = new CancellationTokenSource();
} _connectionAttemptCancellation = screenAttempt;
ClientSize = compactSize; SetBusy(true, "VPN002 · 正在验证 Tailscale 节点入口");
LayoutBrandHeader(); capture("wide-current-screen");
LayoutDashboard(); _connectionAttemptCancellation = null;
checks["return_to_compact_restores_chart_and_controls"] = !_wideMonitor.Visible && _modeCard.Parent == _nodeCard SetBusy(false);
&& _historyRangeCombo.Parent == _speedTrendCard && _trafficChart.DisplayedSeries == TrafficChartSeries.Both SetConnectionState(false, "未连接", "点击连接,AI 自动选择工作节点");
&& !_dashboardSettings.Visible && _dashboardMore.Visible && DashboardControlsFit(); }
capture("compact-final"); ClientSize = compactSize;
LayoutBrandHeader();
bool WarningTextFitsWidth() LayoutDashboard();
{ checks["return_to_compact_restores_chart_and_controls"] = !_wideMonitor.Visible && _modeCard.Parent == _nodeCard
using var graphics = _statusCard.CreateGraphics(); && _historyRangeCombo.Parent == _speedTrendCard && _trafficChart.DisplayedSeries == TrafficChartSeries.Both
return FitsWidth(_statusTitle) && FitsWidth(_statusDetail); && !_dashboardSettings.Visible && _dashboardMore.Visible && DashboardControlsFit();
capture("compact-final");
bool FitsWidth(Label label) => TextRenderer.MeasureText(graphics, label.Text, label.Font).Width <= label.ClientSize.Width;
} bool WarningTextFitsWidth()
} {
} using var graphics = _statusCard.CreateGraphics();
return FitsWidth(_statusTitle) && FitsWidth(_statusDetail);
bool FitsWidth(Label label) => TextRenderer.MeasureText(graphics, label.Text, label.Font).Width <= label.ClientSize.Width;
}
}
}
+9 -3
View File
@@ -564,19 +564,25 @@ internal sealed partial class MainForm : Form
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate); var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
_currentNodeLabel.Text = $"{candidateName} · 正在连接"; _currentNodeLabel.Text = $"{candidateName} · 正在连接";
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}"); SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
TailnetTransport.RouteBinding? tailnetBinding = null;
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference, connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
async (config, connectionToken) => { async (config, connectionToken) => {
candidateStarted = true; candidateStarted = true;
replacementStarted = true; replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken, await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(), TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate)); preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate),
tailnetBinding: TailnetTransport.Address(config) is null ? null : tailnetBinding);
}, _xray.StopAsync, _xray.CheckProxyHealthAsync, }, _xray.StopAsync, _xray.CheckProxyHealthAsync,
TailnetTransport.RequireProbeRoute, null,
message => { _statusDetail.Text = $"{candidateName} · {message}"; }, message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, connectionToken, () => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate, allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync, endpointProbe: async (address, port, probeToken) =>
{
tailnetBinding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return tailnetBinding is not null;
},
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage)); diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken)) if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。"); throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
+2 -2
View File
@@ -71,7 +71,7 @@ internal static class NodeTransportConnector
// No background race or periodic optimization may replace a healthy session. // No background race or periodic optimization may replace a healthy session.
internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference, internal static async Task<bool> ConnectAsync(ConfigResponse response, TailnetPreference preference,
Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth, Func<string, CancellationToken, Task> start, Func<Task> stop, Func<CancellationToken, Task<bool>> proxyHealth,
Action<string> requireRoute, Action<string> status, Func<long> ticks, Action<string>? requireRoute, Action<string> status, Func<long> ticks,
CancellationToken token, bool allowKnownEndpoints = false, CancellationToken token, bool allowKnownEndpoints = false,
Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null, Func<string, int, CancellationToken, Task<bool>>? endpointProbe = null,
Action<TransportDiagnostic>? diagnostic = null) Action<TransportDiagnostic>? diagnostic = null)
@@ -83,7 +83,7 @@ internal static class NodeTransportConnector
void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug)); void Report(string action, string code) => diagnostic?.Invoke(new(action, code, response.Node.Slug));
if (tailnet is null) Report("tailnet_skipped", reason); if (tailnet is null) Report("tailnet_skipped", reason);
else Report("tailnet_candidate", reason); else Report("tailnet_candidate", reason);
if (tailnet is not null) if (tailnet is not null && requireRoute is not null)
{ {
try try
{ {
+13 -1
View File
@@ -1,5 +1,17 @@
# 优创⁺纵横家 Windows 客户端 # 优创⁺纵横家 Windows 客户端
## Windows 0.3.19
修复公司路由已经提供内网路径时,客户端仍跳过已授权代理入口的问题。客户端验证当前网卡能否访问节点代理端口,并将代理绑定到验证通过的网卡。持续检查使用当前连接的实际网卡。
内网入口或代理出网验证失败时,通过青岛转发连接同一台海外节点。公网回退通过 HTTPS 出网验证后显示连接成功,正常的公网会话继续使用当前入口。
2026 年 11 月 24 日从实际账号取得配置,分别测试 VPN002、VPN003、VPN004 的域名入口和青岛固定 IP。具体测试范围、安装包摘要和源码随版本验收记录提供。
## Windows 0.3.18
宽屏和紧凑窗口采用同一阅读顺序。左侧设置调度与代理模式,右侧显示生效的节点和模式。本机上传与下载趋势默认同屏,下方显示有权限查看的服务器走势。累计用量使用一条数字栏。登录后的窗口按钮收起到系统托盘,托盘图标提供恢复和退出。
## Windows 0.3.17 ## Windows 0.3.17
智能代理和全局代理优先验证已授权的 Tailscale 入口。内网代理端口或出口持续异常时,客户端通过同一节点的公网入口重新连接,并在收到经代理转发的 HTTPS 响应后显示连接成功。切换网络后重新验证代理出口,Tailscale 控制和中继流量使用直连路由。 智能代理和全局代理优先验证已授权的 Tailscale 入口。内网代理端口或出口持续异常时,客户端通过同一节点的公网入口重新连接,并在收到经代理转发的 HTTPS 响应后显示连接成功。切换网络后重新验证代理出口,Tailscale 控制和中继流量使用直连路由。
@@ -9,7 +21,7 @@
1. 验收客户端连接、断开及覆盖升级,发布同一构建的源码标签和安装包,从旧客户端核对更新提示及安装包摘要。 1. 验收客户端连接、断开及覆盖升级,发布同一构建的源码标签和安装包,从旧客户端核对更新提示及安装包摘要。
2. 将同一版本登记到公司内部资源中心,并验证员工可下载。 2. 将同一版本登记到公司内部资源中心,并验证员工可下载。
3. 在公司网站「公司动态」发布版本新闻并配一张产品图,匿名检查栏目、正文和配图。 3. 在公司网站「公司动态」发布版本新闻并配一张产品图,匿名检查栏目、正文和配图。
4. 经小小优运维发送本次更新通知,核对发送回执。发布重试时按产品、平台及版本查找现有记录。 4. 在尚书台「通知」频道发布公司更新通知,核对发送回执。发布重试时按产品、平台及版本查找现有记录。
## Windows 0.3.8 ## Windows 0.3.8
+253 -252
View File
@@ -1,252 +1,253 @@
using System.Diagnostics; using System.Diagnostics;
using System.Text.Json; using System.Text.Json;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal static class StartupSelfTest internal static class StartupSelfTest
{ {
// Runs real WinForms first-show/resize/restore behavior, but never reads a // Runs real WinForms first-show/resize/restore behavior, but never reads a
// login token, calls the platform API, starts a core or touches networking. // login token, calls the platform API, starts a core or touches networking.
internal static int Run() internal static int Run()
{ {
var report = new Dictionary<string, object>(); var report = new Dictionary<string, object>();
try try
{ {
using (var control = new Control()) using (var control = new Control())
{ {
_ = control.Handle; _ = control.Handle;
report["synchronization_context"] = SynchronizationContext.Current?.GetType().Name ?? "none"; report["synchronization_context"] = SynchronizationContext.Current?.GetType().Name ?? "none";
async Task OldBlockingPattern() { await Task.Delay(100); } async Task OldBlockingPattern() { await Task.Delay(100); }
var old = OldBlockingPattern(); var old = OldBlockingPattern();
report["old_sync_wait_would_block"] = !old.Wait(350); report["old_sync_wait_would_block"] = !old.Wait(350);
// Resume only this synthetic callback after the bounded probe. // Resume only this synthetic callback after the bounded probe.
Application.DoEvents(); Application.DoEvents();
} }
var recoveryFinished = false; var recoveryFinished = false;
var heartbeat = 0; var heartbeat = 0;
var visibleDuringRecovery = false; var visibleDuringRecovery = false;
var watch = Stopwatch.StartNew(); var watch = Stopwatch.StartNew();
using var form = new MainForm(uiOnly: true, startupRecovery: async token => using var form = new MainForm(uiOnly: true, startupRecovery: async token =>
{ {
await Task.Delay(1400, token); await Task.Delay(1400, token);
recoveryFinished = true; recoveryFinished = true;
}); });
form.TopMost = true; // Owned UI fixture only; never a production window policy. form.TopMost = true; // Owned UI fixture only; never a production window policy.
using var timer = new System.Windows.Forms.Timer { Interval = 80 }; using var timer = new System.Windows.Forms.Timer { Interval = 80 };
var passed = false; var passed = false;
timer.Tick += async (_, _) => timer.Tick += async (_, _) =>
{ {
try try
{ {
heartbeat++; heartbeat++;
if (!recoveryFinished && form.LoginFieldsVisibleForTest) visibleDuringRecovery = true; if (!recoveryFinished && form.LoginFieldsVisibleForTest) visibleDuringRecovery = true;
if (recoveryFinished && heartbeat >= 22) if (recoveryFinished && heartbeat >= 22)
{ {
timer.Stop(); // Input probes resume through the normal UI message loop. timer.Stop(); // Input probes resume through the normal UI message loop.
report["first_login_visible_while_recovering"] = visibleDuringRecovery; report["first_login_visible_while_recovering"] = visibleDuringRecovery;
report["login_ready_after_recovery"] = form.LoginReadyForTest; report["login_ready_after_recovery"] = form.LoginReadyForTest;
report["registration_text_and_link_same_row"] = form.LoginRegistrationAlignedForTest; report["registration_text_and_link_same_row"] = form.LoginRegistrationAlignedForTest;
var registrationDpiPass = true; var registrationDpiPass = true;
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 }) foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288 })
{ {
int S(int n) => (int)Math.Round(n * dpi / 96f); int S(int n) => (int)Math.Round(n * dpi / 96f);
// Geometry fixture only; not a claim of physical // Geometry fixture only; not a claim of physical
// per-monitor rendering at these simulated DPIs. // per-monitor rendering at these simulated DPIs.
var row = MainForm.LoginRegistrationBounds(S(440), dpi, new Size(S(92), S(18)), new Size(S(86), S(18))); var row = MainForm.LoginRegistrationBounds(S(440), dpi, new Size(S(92), S(18)), new Size(S(86), S(18)));
registrationDpiPass &= row.Prompt.Top == row.Link.Top && row.Prompt.Height == row.Link.Height registrationDpiPass &= row.Prompt.Top == row.Link.Top && row.Prompt.Height == row.Link.Height
&& row.Prompt.Right < row.Link.Left && row.Prompt.Left >= S(28) && row.Link.Right <= S(412) && row.Prompt.Right < row.Link.Left && row.Prompt.Left >= S(28) && row.Link.Right <= S(412)
&& Math.Abs((row.Prompt.Left + row.Link.Right) / 2f - S(440) / 2f) <= 1 && Math.Abs((row.Prompt.Left + row.Link.Right) / 2f - S(440) / 2f) <= 1
&& row.Prompt.Bottom <= S(306); && row.Prompt.Bottom <= S(306);
} }
report["registration_geometry_100_to_300_percent"] = registrationDpiPass; report["registration_geometry_100_to_300_percent"] = registrationDpiPass;
CheckLoginSurface(report); CheckLoginSurface(report);
report["dpi"] = form.DeviceDpi; report["dpi"] = form.DeviceDpi;
report["ui_heartbeat_ticks"] = heartbeat; report["ui_heartbeat_ticks"] = heartbeat;
var chrome = form.WindowChromeForTest var chrome = form.WindowChromeForTest
?? throw new InvalidOperationException("Owned MainForm did not initialize window chrome"); ?? throw new InvalidOperationException("Owned MainForm did not initialize window chrome");
report["login_caption_is_exit_not_minimize"] = chrome.LoginMode report["login_caption_is_exit_not_minimize"] = chrome.LoginMode
&& chrome.MinimizeButton.Action == CaptionAction.Close && chrome.MinimizeButton.Action == CaptionAction.Close
&& chrome.MinimizeButton.AccessibleName == "退出软件"; && chrome.MinimizeButton.AccessibleName == "退出软件";
// A separate UI-only window exercises the actual login // A separate UI-only window exercises the actual login
// X -> RequestExit -> cleanup path, even during recovery. // X -> RequestExit -> cleanup path, even during recovery.
// It never loads credentials, starts a core or changes networking. // It never loads credentials, starts a core or changes networking.
using (var loginExitProbe = new MainForm(uiOnly: true, using (var loginExitProbe = new MainForm(uiOnly: true,
startupRecovery: token => Task.Delay(Timeout.Infinite, token))) startupRecovery: token => Task.Delay(Timeout.Infinite, token)))
{ {
var closed = false; var closed = false;
loginExitProbe.FormClosed += (_, _) => closed = true; loginExitProbe.FormClosed += (_, _) => closed = true;
loginExitProbe.Show(); loginExitProbe.Show();
await Task.Delay(30); await Task.Delay(30);
var exitChrome = loginExitProbe.WindowChromeForTest; var exitChrome = loginExitProbe.WindowChromeForTest;
var exitWasVisible = exitChrome is { LoginMode: true } var exitWasVisible = exitChrome is { LoginMode: true }
&& exitChrome.MinimizeButton.Action == CaptionAction.Close; && exitChrome.MinimizeButton.Action == CaptionAction.Close;
exitChrome?.MinimizeButton.PerformClick(); exitChrome?.MinimizeButton.PerformClick();
report["login_x_closes_software_during_recovery"] = exitWasVisible report["login_x_closes_software_during_recovery"] = exitWasVisible
&& closed && loginExitProbe.IsDisposed; && closed && loginExitProbe.IsDisposed;
} }
form.Activate(); form.Activate();
// Caption-state fixture only, not an authenticated login. // Caption-state fixture only, not an authenticated login.
// Keep the login card visible for the rendering checks. // Keep the login card visible for the rendering checks.
chrome.SetLoginMode(false); chrome.SetLoginMode(false);
report["dashboard_caption_is_minimize_not_exit"] = !chrome.LoginMode report["dashboard_caption_is_minimize_not_exit"] = !chrome.LoginMode
&& chrome.MinimizeButton.Action == CaptionAction.Minimize && chrome.MinimizeButton.Action == CaptionAction.Minimize
&& chrome.MinimizeButton.AccessibleName == "最小化"; && chrome.MinimizeButton.AccessibleName == "最小化";
form.Close(); form.Close();
// After authentication, only explicit menu/installer // After authentication, only explicit menu/installer
// exit may terminate the form; ordinary Close is blocked. // exit may terminate the form; ordinary Close is blocked.
report["ordinary_close_blocked_without_hiding"] = form.Visible && !form.IsDisposed; report["ordinary_close_blocked_without_hiding"] = form.Visible && !form.IsDisposed;
form.Hide(); // Synthetic tray-hidden state, not a close request. form.Hide(); // Synthetic tray-hidden state, not a close request.
form.ShowFromTray(); form.ShowFromTray();
report["hidden_window_restored"] = form.LoginReadyForTest; report["hidden_window_restored"] = form.LoginReadyForTest;
form.WindowState = FormWindowState.Minimized; form.WindowState = FormWindowState.Minimized;
report["minimized_on_taskbar_without_exit"] = form.MinimizedOnTaskbarForTest; report["minimized_on_taskbar_without_exit"] = form.MinimizedOnTaskbarForTest;
report["production_minimized_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Minimized, false); report["production_minimized_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Minimized, false);
report["production_restored_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Normal, false); report["production_restored_tray_available"] = MainForm.ShouldShowTrayIcon(FormWindowState.Normal, false);
report["offline_preview_never_publishes_tray"] = Enum.GetValues<FormWindowState>() report["offline_preview_never_publishes_tray"] = Enum.GetValues<FormWindowState>()
.All(state => !MainForm.ShouldShowTrayIcon(state, true)); .All(state => !MainForm.ShouldShowTrayIcon(state, true));
form.ShowFromTray(); form.ShowFromTray();
report["minimized_window_restored"] = form.WindowState == FormWindowState.Normal && form.LoginReadyForTest; report["minimized_window_restored"] = form.WindowState == FormWindowState.Normal && form.LoginReadyForTest;
var minimizeButton = form.Controls.OfType<BrandHeaderPanel>().Single().Controls.OfType<CaptionButton>().Single(); var minimizeButton = form.Controls.OfType<BrandHeaderPanel>().Single().Controls.OfType<CaptionButton>().Single();
var programmaticMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: false); var programmaticMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: false, tray: true);
report["mainform_performclick_detail"] = programmaticMinimize; report["mainform_performclick_detail"] = programmaticMinimize;
report["mainform_performclick_minimizes_on_taskbar"] = programmaticMinimize.Passed && form.MinimizedOnTaskbarForTest; report["mainform_performclick_hides_to_tray"] = programmaticMinimize.Passed && !form.IsDisposed;
form.ShowFromTray(); form.ShowFromTray();
var mouseMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: true); var mouseMinimize = await WindowChromeSelfTest.ProbeMinimizeInputAsync(form, minimizeButton, mouse: true, tray: true);
report["mainform_mouse_minimize_detail"] = mouseMinimize; report["mainform_mouse_minimize_detail"] = mouseMinimize;
report["mainform_mouse_down_up_click_minimizes_on_taskbar"] = mouseMinimize.Passed && form.MinimizedOnTaskbarForTest; report["mainform_mouse_down_up_click_hides_to_tray"] = mouseMinimize.Passed && !form.IsDisposed;
form.ShowFromTray(); form.ShowFromTray();
report["mainform_mouse_minimize_restores"] = form.WindowState == FormWindowState.Normal && form.LoginReadyForTest; report["mainform_mouse_minimize_restores"] = form.WindowState == FormWindowState.Normal
chrome.SetLoginMode(true); && form.ShowInTaskbar && form.LoginReadyForTest;
report["return_to_login_restores_exit_caption"] = chrome.LoginMode chrome.SetLoginMode(true);
&& chrome.MinimizeButton.Action == CaptionAction.Close; report["return_to_login_restores_exit_caption"] = chrome.LoginMode
var originalSize = form.Size; && chrome.MinimizeButton.Action == CaptionAction.Close;
form.Size = form.MinimumSize; var originalSize = form.Size;
report["minimum_size_login_visible"] = form.LoginFieldsVisibleForTest; form.Size = form.MinimumSize;
report["minimum_size_registration_aligned"] = form.LoginRegistrationAlignedForTest; report["minimum_size_login_visible"] = form.LoginFieldsVisibleForTest;
form.Size = originalSize; report["minimum_size_registration_aligned"] = form.LoginRegistrationAlignedForTest;
using var screenshot = new Bitmap(form.Width, form.Height); form.Size = originalSize;
form.DrawToBitmap(screenshot, new Rectangle(Point.Empty, screenshot.Size)); using var screenshot = new Bitmap(form.Width, form.Height);
screenshot.Save(Path.Combine(AppContext.BaseDirectory, "startup-login-test.png")); form.DrawToBitmap(screenshot, new Rectangle(Point.Empty, screenshot.Size));
passed = visibleDuringRecovery && form.LoginReadyForTest screenshot.Save(Path.Combine(AppContext.BaseDirectory, "startup-login-test.png"));
&& report.Where(item => item.Value is bool).All(item => (bool)item.Value); passed = visibleDuringRecovery && form.LoginReadyForTest
timer.Stop(); && report.Where(item => item.Value is bool).All(item => (bool)item.Value);
form.RequestExit(); timer.Stop();
} form.RequestExit();
else if (watch.Elapsed > TimeSpan.FromSeconds(12)) }
{ else if (watch.Elapsed > TimeSpan.FromSeconds(12))
report["timeout"] = true; {
timer.Stop(); form.RequestExit(); report["timeout"] = true;
} timer.Stop(); form.RequestExit();
} }
catch (Exception error) { report["error"] = error.ToString(); timer.Stop(); form.RequestExit(); } }
}; catch (Exception error) { report["error"] = error.ToString(); timer.Stop(); form.RequestExit(); }
form.Shown += (_, _) => timer.Start(); };
Application.Run(form); form.Shown += (_, _) => timer.Start();
report["passed"] = passed; Application.Run(form);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "startup-self-test.json"), report["passed"] = passed;
JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "startup-self-test.json"),
return passed ? 0 : 20; JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
} return passed ? 0 : 20;
catch (Exception error) }
{ catch (Exception error)
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "startup-self-test.json"), error.ToString()); {
return 21; File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "startup-self-test.json"), error.ToString());
} return 21;
} }
}
private static void CheckLoginSurface(Dictionary<string, object> report)
{ private static void CheckLoginSurface(Dictionary<string, object> report)
// Owned, off-screen paint fixture only. Never capture the desktop or {
// use account values; these pixels are not production UI evidence. // Owned, off-screen paint fixture only. Never capture the desktop or
using var parent = new ScenicPanel { LoginArtwork = true }; // use account values; these pixels are not production UI evidence.
_ = parent.Handle; using var parent = new ScenicPanel { LoginArtwork = true };
var fixtureDpi = parent.DeviceDpi; _ = parent.Handle;
int S(int value) => (int)Math.Round(value * fixtureDpi / 96f); var fixtureDpi = parent.DeviceDpi;
Point P(int x, int y) => new(S(x), S(y)); int S(int value) => (int)Math.Round(value * fixtureDpi / 96f);
parent.Size = new Size(S(900), S(640)); Point P(int x, int y) => new(S(x), S(y));
using var card = new RoundedCardPanel { Bounds = new Rectangle(S(230), S(100), S(440), S(374)) }; parent.Size = new Size(S(900), S(640));
parent.Controls.Add(card); using var card = new RoundedCardPanel { Bounds = new Rectangle(S(230), S(100), S(440), S(374)) };
_ = card.Handle; parent.Controls.Add(card);
using var first = new Bitmap(card.Width, card.Height); _ = card.Handle;
using var repeated = new Bitmap(card.Width, card.Height); using var first = new Bitmap(card.Width, card.Height);
using (var g = Graphics.FromImage(first)) g.Clear(Color.Magenta); using var repeated = new Bitmap(card.Width, card.Height);
using (var g = Graphics.FromImage(repeated)) g.Clear(Color.Lime); using (var g = Graphics.FromImage(first)) g.Clear(Color.Magenta);
card.DrawToBitmap(first, card.ClientRectangle); using (var g = Graphics.FromImage(repeated)) g.Clear(Color.Lime);
for (var i = 0; i < 3; i++) card.DrawToBitmap(repeated, card.ClientRectangle); card.DrawToBitmap(first, card.ClientRectangle);
var stable = true; for (var i = 0; i < 3; i++) card.DrawToBitmap(repeated, card.ClientRectangle);
for (var x = S(36); x < card.Width - S(36); x += S(17)) var stable = true;
for (var y = S(36); y < card.Height - S(36); y += S(17)) for (var x = S(36); x < card.Width - S(36); x += S(17))
stable &= first.GetPixel(x, y).ToArgb() == repeated.GetPixel(x, y).ToArgb(); for (var y = S(36); y < card.Height - S(36); y += S(17))
report["login_surface_repaint_does_not_accumulate_alpha"] = stable; stable &= first.GetPixel(x, y).ToArgb() == repeated.GetPixel(x, y).ToArgb();
report["login_surface_is_not_opaque_white"] = first.GetPixel(S(40), S(300)).ToArgb() != Color.White.ToArgb(); report["login_surface_repaint_does_not_accumulate_alpha"] = stable;
report["login_card_background_at_least_two_thirds_transparent"] = RoundedCardPanel.SurfaceAlpha <= 85; report["login_surface_is_not_opaque_white"] = first.GetPixel(S(40), S(300)).ToArgb() != Color.White.ToArgb();
// The login card uses the blue glass surface (238,247,255), not pure report["login_card_background_at_least_two_thirds_transparent"] = RoundedCardPanel.SurfaceAlpha <= 85;
// white. Keep the same strict pixel tolerance while predicting each // The login card uses the blue glass surface (238,247,255), not pure
// channel of that tint over the artwork in parent coordinates. // white. Keep the same strict pixel tolerance while predicting each
Color Tint(Color background) // channel of that tint over the artwork in parent coordinates.
{ Color Tint(Color background)
int Channel(int value, int tint) => (tint * RoundedCardPanel.SurfaceAlpha {
+ value * (255 - RoundedCardPanel.SurfaceAlpha)) / 255; int Channel(int value, int tint) => (tint * RoundedCardPanel.SurfaceAlpha
return Color.FromArgb(Channel(background.R, 238), Channel(background.G, 247), Channel(background.B, 255)); + value * (255 - RoundedCardPanel.SurfaceAlpha)) / 255;
} return Color.FromArgb(Channel(background.R, 238), Channel(background.G, 247), Channel(background.B, 255));
var tintedPlainSurface = Tint(Brand.Surface); }
var sceneryVisible = false; var tintedPlainSurface = Tint(Brand.Surface);
var contrast = double.MaxValue; var sceneryVisible = false;
for (var x = S(36); x < card.Width - S(36); x += S(17)) var contrast = double.MaxValue;
for (var y = S(36); y < card.Height - S(36); y += S(17)) for (var x = S(36); x < card.Width - S(36); x += S(17))
{ for (var y = S(36); y < card.Height - S(36); y += S(17))
var background = first.GetPixel(x, y); {
contrast = Math.Min(contrast, Contrast(Brand.Navy, background)); var background = first.GetPixel(x, y);
if (y < S(170)) contrast = Math.Min(contrast, Contrast(Brand.Navy, background));
sceneryVisible |= Math.Abs(background.R - tintedPlainSurface.R) if (y < S(170))
+ Math.Abs(background.G - tintedPlainSurface.G) + Math.Abs(background.B - tintedPlainSurface.B) > 12; sceneryVisible |= Math.Abs(background.R - tintedPlainSurface.R)
} + Math.Abs(background.G - tintedPlainSurface.G) + Math.Abs(background.B - tintedPlainSurface.B) > 12;
report["login_landscape_visible_behind_upper_card"] = sceneryVisible; }
report["login_secondary_text_contrast_at_least_4_5"] = contrast >= 4.5; report["login_landscape_visible_behind_upper_card"] = sceneryVisible;
report["login_secondary_text_minimum_contrast"] = Math.Round(contrast, 3); report["login_secondary_text_contrast_at_least_4_5"] = contrast >= 4.5;
card.Location = P(130, 220); report["login_secondary_text_minimum_contrast"] = Math.Round(contrast, 3);
using var moved = new Bitmap(card.Width, card.Height); card.Location = P(130, 220);
card.DrawToBitmap(moved, card.ClientRectangle); using var moved = new Bitmap(card.Width, card.Height);
using var backdrop = new Bitmap(parent.Width, parent.Height); card.DrawToBitmap(moved, card.ClientRectangle);
using (var g = Graphics.FromImage(backdrop)) using var backdrop = new Bitmap(parent.Width, parent.Height);
ScenicTheme.Backdrop(g, parent.ClientSize, fixtureDpi, login: true); using (var g = Graphics.FromImage(backdrop))
report["login_lower_scene_embedded"] = ScenicTheme.LoginSceneAvailable; ScenicTheme.Backdrop(g, parent.ClientSize, fixtureDpi, login: true);
var (sceneArea, sceneSource) = ScenicTheme.LoginSceneLayout(parent.ClientSize); report["login_lower_scene_embedded"] = ScenicTheme.LoginSceneAvailable;
report["login_lower_scene_avoids_original_black_borders"] = sceneSource.Left >= 352 && sceneSource.Right <= 2270; var (sceneArea, sceneSource) = ScenicTheme.LoginSceneLayout(parent.ClientSize);
report["login_lower_scene_preserves_aspect_and_stays_below_header"] = sceneArea.Bottom == parent.Height report["login_lower_scene_avoids_original_black_borders"] = sceneSource.Left >= 352 && sceneSource.Right <= 2270;
&& sceneArea.Top >= parent.Height / 3 && Math.Abs(sceneArea.Width / (double)sceneArea.Height report["login_lower_scene_preserves_aspect_and_stays_below_header"] = sceneArea.Bottom == parent.Height
- sceneSource.Width / (double)sceneSource.Height) < .01; && sceneArea.Top >= parent.Height / 3 && Math.Abs(sceneArea.Width / (double)sceneArea.Height
var lowerDetail = backdrop.GetPixel(parent.Width * 4 / 5, parent.Height * 4 / 5); - sceneSource.Width / (double)sceneSource.Height) < .01;
report["login_lower_scene_visible_in_previously_empty_area"] = Math.Abs(lowerDetail.R - Brand.Surface.R) var lowerDetail = backdrop.GetPixel(parent.Width * 4 / 5, parent.Height * 4 / 5);
+ Math.Abs(lowerDetail.G - Brand.Surface.G) + Math.Abs(lowerDetail.B - Brand.Surface.B) > 30; report["login_lower_scene_visible_in_previously_empty_area"] = Math.Abs(lowerDetail.R - Brand.Surface.R)
var originCorrect = true; + Math.Abs(lowerDetail.G - Brand.Surface.G) + Math.Abs(lowerDetail.B - Brand.Surface.B) > 30;
var maximumChannelError = 0; var originCorrect = true;
var originPixels = new List<object>(); var maximumChannelError = 0;
foreach (var point in new[] { P(40, 180), P(220, 300), P(400, 330) }) var originPixels = new List<object>();
{ foreach (var point in new[] { P(40, 180), P(220, 300), P(400, 330) })
var background = backdrop.GetPixel(card.Left + point.X, card.Top + point.Y); {
var actual = moved.GetPixel(point.X, point.Y); var background = backdrop.GetPixel(card.Left + point.X, card.Top + point.Y);
var expected = Tint(background); var actual = moved.GetPixel(point.X, point.Y);
var difference = Math.Max(Math.Abs(actual.R - expected.R), var expected = Tint(background);
Math.Max(Math.Abs(actual.G - expected.G), Math.Abs(actual.B - expected.B))); var difference = Math.Max(Math.Abs(actual.R - expected.R),
maximumChannelError = Math.Max(maximumChannelError, difference); Math.Max(Math.Abs(actual.G - expected.G), Math.Abs(actual.B - expected.B)));
originCorrect &= difference <= 2; maximumChannelError = Math.Max(maximumChannelError, difference);
originPixels.Add(new { point.X, point.Y, background = background.ToArgb(), actual = actual.ToArgb(), expected = expected.ToArgb(), difference }); originCorrect &= difference <= 2;
} originPixels.Add(new { point.X, point.Y, background = background.ToArgb(), actual = actual.ToArgb(), expected = expected.ToArgb(), difference });
report["login_surface_move_pixel_probes"] = originPixels; }
report["login_surface_move_maximum_channel_error"] = maximumChannelError; report["login_surface_move_pixel_probes"] = originPixels;
report["login_surface_move_keeps_parent_artwork_coordinates"] = originCorrect; report["login_surface_move_maximum_channel_error"] = maximumChannelError;
} report["login_surface_move_keeps_parent_artwork_coordinates"] = originCorrect;
}
private static double Contrast(Color foreground, Color background)
{ private static double Contrast(Color foreground, Color background)
static double Luminance(Color color) {
{ static double Luminance(Color color)
static double Linear(byte value) => value / 255d <= .04045 {
? value / 255d / 12.92 : Math.Pow((value / 255d + .055) / 1.055, 2.4); static double Linear(byte value) => value / 255d <= .04045
return .2126 * Linear(color.R) + .7152 * Linear(color.G) + .0722 * Linear(color.B); ? value / 255d / 12.92 : Math.Pow((value / 255d + .055) / 1.055, 2.4);
} return .2126 * Linear(color.R) + .7152 * Linear(color.G) + .0722 * Linear(color.B);
var a = Luminance(foreground); var b = Luminance(background); }
return (Math.Max(a, b) + .05) / (Math.Min(a, b) + .05); var a = Luminance(foreground); var b = Luminance(background);
} return (Math.Max(a, b) + .05) / (Math.Min(a, b) + .05);
} }
}
+76 -15
View File
@@ -100,9 +100,40 @@ internal static class TailnetTransport
internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>(); internal static int Port(string json) => JsonNode.Parse(json)![Marker]!["port"]!.GetValue<int>();
// Check the authorized proxy port through the existing OS route. Proxy internal sealed record RouteBinding(string InterfaceName, int InterfaceIndex, IPAddress LocalAddress, IPAddress? Gateway = null);
// authentication and egress are verified separately after startup.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token) // A company router can forward the authorized address over its Tailscale even
// when Windows has only a default route. Bind the probe to the chosen interface.
// A TCP response only permits trying the node; the normal proxy proof still runs.
internal static async Task<RouteBinding?> ProbeAuthorizedRouteAsync(string address, int port, CancellationToken token,
Func<string, RouteBinding>? readSpecificRoute = null,
Func<PhysicalUplink.Reading>? readUplink = null,
Func<string, int, RouteBinding, CancellationToken, Task<bool>>? probe = null)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return null;
RouteBinding? binding;
try { binding = readSpecificRoute is null ? ResolveRoute(address, true) : readSpecificRoute(address); }
catch (Exception error) when (IsRouteUnavailable(error))
{
var uplink = readUplink is null ? PhysicalUplink.Read() : readUplink();
binding = uplink.Success ? GatewayBinding(uplink.Network) : null;
}
token.ThrowIfCancellationRequested();
if (binding is null) return null;
var reachable = await (probe ?? ProbeBoundEndpointAsync)(address, port, binding, token);
token.ThrowIfCancellationRequested();
return reachable ? binding : null;
}
private static RouteBinding? GatewayBinding(TunRouting.PhysicalNetwork? network)
{
if (network is null || network.InterfaceIndex <= 0 || network.Ipv4Gateway.Equals(IPAddress.Any)
|| IsTailnetAddress(network.Ipv4Address.ToString())) return null;
return new(network.InterfaceName, network.InterfaceIndex, network.Ipv4Address, network.Ipv4Gateway);
}
internal static async Task<bool> ProbeBoundEndpointAsync(string address, int port, RouteBinding binding, CancellationToken token)
{ {
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false; if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
@@ -110,16 +141,47 @@ internal static class TailnetTransport
deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds)); deadline.CancelAfter(TimeSpan.FromSeconds(EndpointProbeTimeoutSeconds));
try try
{ {
RequireProbeRoute(address); using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// The first connection may need to establish a Tailscale path. // Winsock IP_UNICAST_IF expects the IPv4 interface index in network byte order.
// Test the actual proxy listener instead of gating on ICMP. const SocketOptionName ipUnicastInterface = (SocketOptionName)31;
using var socket = new TcpClient(AddressFamily.InterNetwork); socket.SetSocketOption(SocketOptionLevel.IP, ipUnicastInterface, IPAddress.HostToNetworkOrder(binding.InterfaceIndex));
socket.Bind(new IPEndPoint(binding.LocalAddress, 0));
await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false); await socket.ConnectAsync(IPAddress.Parse(address), port, deadline.Token).ConfigureAwait(false);
return true; return true;
} }
catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; } catch (OperationCanceledException) when (!token.IsCancellationRequested) { return false; }
catch (Exception e) when (e is SocketException or NetworkInformationException catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception) { return false; } }
private static bool IsRouteUnavailable(Exception error) => error is SocketException or NetworkInformationException
or InvalidOperationException or IOException or System.ComponentModel.Win32Exception;
internal static RouteBinding RequireCurrentBinding(string address, RouteBinding? binding, TunRouting.PhysicalNetwork physicalNetwork)
{
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
if (binding?.Gateway is not null)
{
var uplink = PhysicalUplink.Read(binding.InterfaceIndex);
if (!uplink.Success || GatewayBinding(uplink.Network) != binding || GatewayBinding(physicalNetwork) != binding)
throw new InvalidOperationException("公司网关路径已变化,请重新检测内网入口。");
return binding;
}
var current = ResolveRoute(address, true);
if (binding is not null && current != binding)
throw new InvalidOperationException("Tailscale 路由已变化,请重新检测内网入口。");
return current;
}
// Strict native-route detection for private-node policy and the standalone probe.
internal static async Task<bool> ProbeEndpointAsync(string address, int port, CancellationToken token)
{
token.ThrowIfCancellationRequested();
if (!IsTailnetAddress(address) || port is < 1 or > 65535) return false;
try
{
return await ProbeBoundEndpointAsync(address, port, ResolveRoute(address, true), token).ConfigureAwait(false);
}
catch (Exception error) when (IsRouteUnavailable(error)) { return false; }
} }
internal static bool SameAuthorizedFallback(string current, string? fallback) internal static bool SameAuthorizedFallback(string current, string? fallback)
@@ -144,13 +206,13 @@ internal static class TailnetTransport
// default route. No adapter-name, service or route-prefix prerequisite. // default route. No adapter-name, service or route-prefix prerequisite.
// This UDP Connect sends no payload. Refuse our own TUN to avoid recursion; // This UDP Connect sends no payload. Refuse our own TUN to avoid recursion;
// no /32 or user route is manufactured or removed. // no /32 or user route is manufactured or removed.
internal static string RequireExistingRoute(string address) => ResolveRoute(address, false); internal static string RequireExistingRoute(string address) => ResolveRoute(address, false).InterfaceName;
// Candidate discovery requires a specific existing route to the authorized // Candidate discovery requires a specific existing route to the authorized
// Tailnet address. A generic internet default must not carry probe packets. // Tailnet address. A generic internet default must not carry probe packets.
internal static void RequireProbeRoute(string address) => ResolveRoute(address, true); internal static void RequireProbeRoute(string address) => ResolveRoute(address, true);
private static string ResolveRoute(string address, bool requireSpecificRoute) private static RouteBinding ResolveRoute(string address, bool requireSpecificRoute)
{ {
if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。"); if (!IsTailnetAddress(address)) throw new InvalidOperationException("Tailscale 地址无效。");
using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); using var route = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
@@ -160,12 +222,11 @@ internal static class TailnetTransport
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback
&& !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase)) && !n.Name.StartsWith(TunRouting.AdapterName, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local))); .FirstOrDefault(n => n.GetIPProperties().UnicastAddresses.Any(a => a.Address.Equals(local)));
if (owner is null) if (local is null || owner?.GetIPProperties().GetIPv4Properties()?.Index is not { } index)
throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。"); throw new InvalidOperationException("代理内网 IP 路径暂不可用,保留公网入口作为回退。");
if (requireSpecificRoute && (owner.GetIPProperties().GetIPv4Properties()?.Index is not { } index if (requireSpecificRoute && SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index)
|| SelectRoute(address, new WindowsRouteTable().Snapshot(), new HashSet<int> { index }) != index))
throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。"); throw new InvalidOperationException("未找到可验证的 Tailscale 节点探测路由。");
return owner.Name; return new(owner.Name, index, local);
} }
internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable) internal static int? SelectRoute(string address, IEnumerable<Ipv4Route> routes, IReadOnlySet<int> usable)
+37
View File
@@ -1,3 +1,4 @@
using System.Net;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
@@ -74,6 +75,42 @@ internal static class TailnetTransportSelfTest
checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null; checks["ambiguous_interface_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route,route with {InterfaceIndex=9}],usable) is null;
checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null; checks["noncontiguous_mask_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Mask="255.0.255.0"}],usable) is null;
checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null; checks["unrelated_route_refused"] = TailnetTransport.SelectRoute("100.99.142.38", [route with {Destination="172.16.0.0",Mask="255.255.0.0"}],usable) is null;
const string target = "100.99.142.38";
const int targetPort = 10803;
var native = new TailnetTransport.RouteBinding("Tailscale", 34, IPAddress.Parse("100.65.4.8"));
var office = new TunRouting.PhysicalNetwork("Ethernet", 9, IPAddress.Parse("172.16.1.154"),
24, IPAddress.Parse("172.16.1.1"), [IPAddress.Parse("172.16.1.1")]);
var gateway = new TailnetTransport.RouteBinding(office.InterfaceName, office.InterfaceIndex,
office.Ipv4Address, office.Ipv4Gateway);
TailnetTransport.RouteBinding NoSpecificRoute(string _) => throw new InvalidOperationException();
PhysicalUplink.Reading OfficeUplink() => new(true, office);
var testedBindings = new List<TailnetTransport.RouteBinding>();
Task<bool> Reachable(string address, int port, TailnetTransport.RouteBinding binding, CancellationToken token)
{
token.ThrowIfCancellationRequested();
testedBindings.Add(binding);
return Task.FromResult(address == target && port == targetPort);
}
checks["native_route_precedes_gateway"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, _ => native, () => throw new InvalidOperationException("Unused uplink"), Reachable) == native
&& testedBindings.SequenceEqual([native]);
testedBindings.Clear();
checks["company_gateway_requires_authorized_port_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, Reachable) == gateway
&& testedBindings.SequenceEqual([gateway]);
checks["unreachable_company_gateway_falls_back"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, OfficeUplink, (_, _, _, _) => Task.FromResult(false)) is null;
checks["no_gateway_no_unbound_probe"] = await TailnetTransport.ProbeAuthorizedRouteAsync(target, targetPort,
CancellationToken.None, NoSpecificRoute, () => new(true, office with { Ipv4Gateway = IPAddress.Any }),
(_, _, _, _) => throw new InvalidOperationException("Unbound probe")) is null;
checks["non_tailnet_address_never_probed"] = await TailnetTransport.ProbeAuthorizedRouteAsync("198.51.100.20", targetPort,
CancellationToken.None, _ => throw new InvalidOperationException("Unexpected route lookup"), OfficeUplink, Reachable) is null;
var routerRuntime = JsonNode.Parse(TunConfigBuilder.Build(prepared, office.InterfaceName, false, includeTun: false,
tailnetInterfaceName: gateway.InterfaceName))!.AsObject();
checks["router_runtime_binds_only_chosen_physical_interface"] =
routerRuntime["outbounds"]![0]!["streamSettings"]!["sockopt"]!["interface"]!.GetValue<string>() == office.InterfaceName
&& Host(prepared) == target;
var preference = new TailnetPreference(); var preference = new TailnetPreference();
long tick = 100; long tick = 100;
+6 -1
View File
@@ -66,7 +66,12 @@ internal sealed class TrafficChart : Control
base.OnPaint(e); base.OnPaint(e);
_timeline.AdvanceClock(); _timeline.AdvanceClock();
var points = VisiblePoints(); var points = VisiblePoints();
var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => Math.Max(p.Up, p.Down))); var peak = points.Length == 0 ? 1024 : Math.Max(1024, points.Max(p => DisplayedSeries switch
{
TrafficChartSeries.Upload => p.Up,
TrafficChartSeries.Download => p.Down,
_ => Math.Max(p.Up, p.Down),
}));
var axis = ChartAxisY.Create(peak, speed: true); var axis = ChartAxisY.Create(peak, speed: true);
var g = e.Graphics; var g = e.Graphics;
var scale = DeviceDpi / 96f; var scale = DeviceDpi / 96f;
+4 -3
View File
@@ -112,7 +112,8 @@ internal static class TunRouting
IReadOnlyCollection<IPAddress> proxyServerAddresses, IReadOnlyCollection<IPAddress> proxyServerAddresses,
CancellationToken cancellationToken, CancellationToken cancellationToken,
bool preservePrivateNodeRoute = false, bool preservePrivateNodeRoute = false,
string? preserveTailnetAddress = null) string? preserveTailnetAddress = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。"); if (!IsElevated()) throw new InvalidOperationException("TUN 全电脑代理需要管理员权限,请以管理员身份重新启动优创⁺纵横家。");
var proxyIpv4Addresses = proxyServerAddresses var proxyIpv4Addresses = proxyServerAddresses
@@ -134,7 +135,6 @@ internal static class TunRouting
if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1 if (preservePrivateNodeRoute || proxyIpv4Addresses.Count != 1
|| proxyIpv4Addresses[0].ToString() != preserveTailnetAddress) || proxyIpv4Addresses[0].ToString() != preserveTailnetAddress)
throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。"); throw new InvalidOperationException("Tailscale 节点旁路目标不匹配。");
TailnetTransport.RequireExistingRoute(preserveTailnetAddress);
} }
var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault(); var tunDnsServer = physicalNetwork.Ipv4DnsServers.FirstOrDefault();
if (tunDnsServer is null) if (tunDnsServer is null)
@@ -153,7 +153,8 @@ internal static class TunRouting
if (preservePrivateNodeRoute || preserveTailnetAddress is not null) if (preservePrivateNodeRoute || preserveTailnetAddress is not null)
{ {
if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString()); if (preservePrivateNodeRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(proxyIpv4Addresses[0].ToString());
if (preserveTailnetAddress is not null) TailnetTransport.RequireExistingRoute(preserveTailnetAddress); if (preserveTailnetAddress is not null)
TailnetTransport.RequireCurrentBinding(preserveTailnetAddress, tailnetBinding, physicalNetwork);
} }
var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index, var routes = CreateOwnedRoutes(physicalNetwork, proxyIpv4Addresses, index,
preservePrivateNodeRoute || preserveTailnetAddress is not null); preservePrivateNodeRoute || preserveTailnetAddress is not null);
+4 -4
View File
@@ -10,10 +10,10 @@
<ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon> <ApplicationIcon>assets\zonghengjia-app-v1.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest> <ApplicationManifest>app.manifest</ApplicationManifest>
<ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode> <ApplicationHighDpiMode>PerMonitorV2</ApplicationHighDpiMode>
<Version>0.3.17</Version> <Version>0.3.19</Version>
<AssemblyVersion>0.3.17.0</AssemblyVersion> <AssemblyVersion>0.3.19.0</AssemblyVersion>
<FileVersion>0.3.17.0</FileVersion> <FileVersion>0.3.19.0</FileVersion>
<InformationalVersion>0.3.17</InformationalVersion> <InformationalVersion>0.3.19</InformationalVersion>
<Product>纵横家</Product> <Product>纵横家</Product>
<Company>优创未来(UCVL)</Company> <Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description> <Description>纵横家 Windows 智能网络客户端</Description>
+627 -630
View File
File diff suppressed because it is too large Load Diff
+36 -12
View File
@@ -32,7 +32,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
// A public fallback is sticky: automatic physical-network recovery must // A public fallback is sticky: automatic physical-network recovery must
// never promote it to this cached internal alternative. // never promote it to this cached internal alternative.
private string? _preferredTailnetConfigJson; private string? _preferredTailnetConfigJson;
private string? _tailnetInterfaceName; private TailnetTransport.RouteBinding? _tailnetBinding;
internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null; internal bool UsesTailnet => _baseConfigJson is not null && TailnetTransport.Address(_baseConfigJson) is not null;
internal (string Address, int Port)? TailnetProbeEndpoint internal (string Address, int Port)? TailnetProbeEndpoint
{ {
@@ -56,6 +56,18 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred)); return (TailnetTransport.Address(preferred)!, TailnetTransport.Port(preferred));
} }
} }
internal async Task<bool> ProbeCurrentOrPreferredTailnetAsync(CancellationToken token)
{
if (TailnetProbeEndpoint is not { } endpoint) return false;
if (!UsesTailnet)
return await TailnetTransport.ProbeAuthorizedRouteAsync(endpoint.Address, endpoint.Port, token) is not null;
var binding = _tailnetBinding;
// For an active session, verify the path used by Xray. A healthy
// alternate interface must not conceal failure of the current one.
return binding is not null
&& await TailnetTransport.ProbeBoundEndpointAsync(endpoint.Address, endpoint.Port, binding, token);
}
private string _routeMode = "smart"; private string _routeMode = "smart";
private string _nodeSlug = ""; private string _nodeSlug = "";
private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe"); private string XrayPath => Path.Combine(_xrayDirectory, "xray.exe");
@@ -89,12 +101,20 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
replacementStarted = true; replacementStarted = true;
await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests. await StopCoreAsync(); // Restore old routes/DNS BEFORE any DNS/network requests.
token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested();
TailnetTransport.RouteBinding? binding = null;
_baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson, _baseConfigJson = await NodeTransportConnector.RebindAsync(_baseConfigJson!, _tailnetFallbackConfigJson,
async (config, rebindToken) => { _baseConfigJson = config; await StartCoreAsync(rebindToken); }, async (config, rebindToken) =>
{
_baseConfigJson = config;
await StartCoreAsync(rebindToken, tailnetBinding: TailnetTransport.Address(config) is null ? null : binding);
},
StopCoreAsync, CheckProxyHealthAsync, token, StopCoreAsync, CheckProxyHealthAsync, token,
preferredTailnetConfig: _preferredTailnetConfigJson, preferredTailnetConfig: _preferredTailnetConfigJson,
requireRoute: address => { TailnetTransport.RequireExistingRoute(address); }, endpointProbe: async (address, port, probeToken) =>
endpointProbe: TailnetTransport.ProbeEndpointAsync, {
binding = await TailnetTransport.ProbeAuthorizedRouteAsync(address, port, probeToken);
return binding is not null;
},
diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage), diagnostic: entry => AppPaths.WriteLog((entry with { Node = _nodeSlug }).SafeMessage),
verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!)); verifyPublicEgress: _routeMode is "smart" or "global" && !PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson!));
} }
@@ -209,7 +229,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
} }
internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken, internal async Task StartAsync(string configJson, string routeMode, string nodeSlug, CancellationToken cancellationToken,
string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null) string? tailnetFallbackConfigJson = null, string? preferredTailnetConfigJson = null,
TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
// Fail locally before ownership/recovery or stopping a healthy core. // Fail locally before ownership/recovery or stopping a healthy core.
ValidateRuntime(); ValidateRuntime();
@@ -237,7 +258,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_preferredTailnetConfigJson = preferred; _preferredTailnetConfigJson = preferred;
_routeMode = routeMode; _routeMode = routeMode;
_nodeSlug = nodeSlug; _nodeSlug = nodeSlug;
await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null); await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null, tailnetBinding);
} }
catch catch
{ {
@@ -264,7 +285,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
_baseConfigJson = null; _baseConfigJson = null;
_tailnetFallbackConfigJson = null; _tailnetFallbackConfigJson = null;
_preferredTailnetConfigJson = null; _preferredTailnetConfigJson = null;
_tailnetInterfaceName = null; _tailnetBinding = null;
_nodeSlug = ""; _nodeSlug = "";
_boundNetwork = null; _boundNetwork = null;
} }
@@ -289,7 +310,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
} }
private async Task StartCoreAsync(CancellationToken cancellationToken, private async Task StartCoreAsync(CancellationToken cancellationToken,
Action<CancellationToken>? beginStartupLearning = null) Action<CancellationToken>? beginStartupLearning = null, TailnetTransport.RouteBinding? tailnetBinding = null)
{ {
ValidateRuntime(); ValidateRuntime();
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。"); if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
@@ -299,10 +320,12 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost; var preservePrivateRoute = privateAuxiliary && PrivateAuxiliaryRuntime.Address(_baseConfigJson) != PrivateAuxiliaryRouting.PublicPhoneHost;
if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson)); if (preservePrivateRoute) PrivateAuxiliaryRuntime.RequireExistingRoute(PrivateAuxiliaryRuntime.Address(_baseConfigJson));
var tailnetAddress = TailnetTransport.Address(_baseConfigJson); var tailnetAddress = TailnetTransport.Address(_baseConfigJson);
var tailnetInterface = tailnetAddress is null ? null : TailnetTransport.RequireExistingRoute(tailnetAddress);
_tailnetInterfaceName = tailnetInterface;
var proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken); var proxyServerAddresses = await ResolveProxyServerAddressesAsync(_baseConfigJson, cancellationToken);
var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses); var physicalNetwork = TunRouting.GetPhysicalNetwork(proxyServerAddresses);
_tailnetBinding = tailnetAddress is null ? null : TailnetTransport.RequireCurrentBinding(tailnetAddress, tailnetBinding, physicalNetwork);
var tailnetInterface = _tailnetBinding?.InterfaceName;
if (_tailnetBinding?.Gateway is not null)
AppPaths.WriteLog(new TransportDiagnostic("tailnet_route", "authorized_port_reached_via_gateway", _nodeSlug).SafeMessage);
_learningEpoch = new CancellationTokenSource(); _learningEpoch = new CancellationTokenSource();
_learningBudget = new LearningProbeBudget(); _learningBudget = new LearningProbeBudget();
_networkLearned.Clear(); _networkLearned.Clear();
@@ -389,7 +412,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
try try
{ {
await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken, preservePrivateRoute, tailnetAddress); await TunRouting.EnableAsync(physicalNetwork, proxyServerAddresses, cancellationToken,
preservePrivateRoute, tailnetAddress, _tailnetBinding);
// Apply 0.2.5 routing first, then wait until Windows has completed // Apply 0.2.5 routing first, then wait until Windows has completed
// DAD before applications can use the tunnel's DNS/IPv4 path. // DAD before applications can use the tunnel's DNS/IPv4 path.
await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true); await TunRouting.WaitForAdapterAsync(cancellationToken, requireIpv4Ready: true);
@@ -534,7 +558,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1, var config = LearningPolicy.Merge(_directFirstConfig, new RoutingManifest { Contract = 1,
Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() }); Revision = new string('0', 64), Rules = _networkLearned.Targets.ToList() });
var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName, var routing = TunConfigBuilder.BuildLearningRouting(config, _boundNetwork.InterfaceName,
_learningProbePort, _directProbePort, _tailnetInterfaceName); _learningProbePort, _directProbePort, _tailnetBinding?.InterfaceName);
await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token); await XrayRoutingUpdater.ApplyAsync(XrayPath, _routingApiPort, routing, token);
_networkLearned.Applied(); _networkLearned.Applied();
} }