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);
+29 -28
View File
@@ -1,35 +1,34 @@
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(inset, totals.Top - inset - serverHeight, innerWidth, serverHeight) ? new Rectangle(0, totals.Top - gap - serverHeight, width, serverHeight)
: Rectangle.Empty; : Rectangle.Empty;
var trendBottom = (showServers ? servers.Top : totals.Top) - inset; var trendBottom = (showServers ? servers.Top : totals.Top) - gap;
var trend = new Rectangle(inset, state.Bottom + S(4), innerWidth, trendBottom - state.Bottom - S(4)); var trend = new Rectangle(0, 0, width, trendBottom);
return new(banner, sidebar, monitor, state, trend, servers, totals, footer); return new(banner, configuration, monitor, state, trend, servers, totals, footer);
} }
internal static bool SelfTest() internal static bool SelfTest()
@@ -38,16 +37,18 @@ internal readonly record struct DashboardWideLayout(Rectangle Banner, Rectangle
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;
+45 -54
View File
@@ -6,15 +6,12 @@ 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 = "设置" };
private readonly DashboardHeaderButton _dashboardClose = new("", DashboardHeaderIcon.Close)
{ AccessibleName = "断开并退出" };
internal WindowChrome? WindowChromeForTest => _windowChrome; internal WindowChrome? WindowChromeForTest => _windowChrome;
// Remove the native caption before HWND creation, not only after its first // Remove the native caption before HWND creation, not only after its first
@@ -41,7 +38,7 @@ internal sealed partial class MainForm
private void InitializeWindowChrome(Panel header) private void InitializeWindowChrome(Panel header)
{ {
if (_windowChrome is not null) return; if (_windowChrome is not null) return;
_windowChrome = new WindowChrome(this, header, RequestExit); _windowChrome = new WindowChrome(this, header, RequestExit, MinimizeToTrayPresentation);
_windowChrome.SetLoginMode(true); _windowChrome.SetLoginMode(true);
InitializeDashboardHeader(header); InitializeDashboardHeader(header);
} }
@@ -51,23 +48,16 @@ internal sealed partial class MainForm
private void InitializeDashboardHeader(Panel header) private void InitializeDashboardHeader(Panel header)
{ {
_dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = _dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible =
_dashboardLogout.Visible = _dashboardMore.Visible = _dashboardClose.Visible = false; _dashboardLogout.Visible = _dashboardMore.Visible = false;
_dashboardSettings.TabIndex = 890; _dashboardSettings.TabIndex = 890;
_dashboardAbout.TabIndex = 891; _dashboardAbout.TabIndex = 891;
_dashboardLogout.TabIndex = 892; _dashboardLogout.TabIndex = 892;
_dashboardMore.TabIndex = 890; _dashboardMore.TabIndex = 890;
_logoutButton.TabIndex = 892; _logoutButton.TabIndex = 892;
_dashboardClose.TabIndex = 901;
_dashboardSettings.Click += (_, _) => OpenDashboardMenu(_dashboardSettings, includeApplicationActions: false); _dashboardSettings.Click += (_, _) => OpenDashboardMenu(_dashboardSettings, includeApplicationActions: false);
_dashboardMore.Click += (_, _) => OpenDashboardMenu(_dashboardMore, includeApplicationActions: true); _dashboardMore.Click += (_, _) => OpenDashboardMenu(_dashboardMore, includeApplicationActions: true);
_dashboardAbout.Click += (_, _) => ShowDashboardAbout(); _dashboardAbout.Click += (_, _) => ShowDashboardAbout();
_dashboardLogout.Click += async (_, _) => await LogoutAsync(); _dashboardLogout.Click += async (_, _) => await LogoutAsync();
_dashboardClose.Click += (_, _) =>
{
if (_settingsMenu?.Visible == true) { _settingsMenu.Close(); return; }
if (_settingsDismissedAt != long.MinValue && Environment.TickCount64 - _settingsDismissedAt < 350) return;
RequestExit();
};
var tip = new ToolTip(); var tip = new ToolTip();
_welcomeLabel.TextChanged += (_, _) => _welcomeLabel.TextChanged += (_, _) =>
{ {
@@ -81,12 +71,15 @@ internal sealed partial class MainForm
if (!Disposing && !IsDisposed) LayoutBrandHeader(); if (!Disposing && !IsDisposed) LayoutBrandHeader();
}; };
header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation(); header.SizeChanged += (_, _) => RefreshDashboardHeaderPresentation();
tip.SetToolTip(_dashboardClose, "断开并退出");
tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置"); tip.SetToolTip(_dashboardSettings, "打开调度、节点、代理模式及趋势范围设置");
tip.SetToolTip(_dashboardMore, "设置与关于"); tip.SetToolTip(_dashboardMore, "设置与关于");
header.Disposed += (_, _) => tip.Dispose(); header.Disposed += (_, _) =>
{
tip.Dispose();
_settingsMenu?.Dispose();
};
header.Controls.AddRange([_dashboardHeaderName, _dashboardSettings, _dashboardAbout, header.Controls.AddRange([_dashboardHeaderName, _dashboardSettings, _dashboardAbout,
_dashboardLogout, _dashboardMore, _dashboardClose]); _dashboardLogout, _dashboardMore]);
} }
private void RefreshDashboardHeaderPresentation() private void RefreshDashboardHeaderPresentation()
@@ -96,10 +89,7 @@ internal sealed partial class MainForm
var wide = WideDashboardPresentation && _dashboardView.Visible; var wide = WideDashboardPresentation && _dashboardView.Visible;
_dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible = _dashboardHeaderName.Visible = _dashboardSettings.Visible = _dashboardAbout.Visible =
_dashboardLogout.Visible = wide; _dashboardLogout.Visible = wide;
_dashboardClose.Visible = chrome.DashboardCloseSlot = _dashboardView.Visible;
chrome.LayoutButtons(); chrome.LayoutButtons();
_dashboardClose.Bounds = chrome.DashboardCloseBounds;
_dashboardClose.BringToFront();
if (!CompactPresentation) LayoutExpandedBrandBounds(); if (!CompactPresentation) LayoutExpandedBrandBounds();
if (!wide) if (!wide)
{ {
@@ -111,7 +101,6 @@ internal sealed partial class MainForm
_dashboardMore.Visible = false; _dashboardMore.Visible = false;
_headerPoem.Visible = false; _headerPoem.Visible = false;
var caption = chrome.MinimizeButton.Bounds; var caption = chrome.MinimizeButton.Bounds;
_dashboardClose.Bounds = chrome.DashboardCloseBounds;
int S(int value) => ScaleLogical(value); int S(int value) => ScaleLogical(value);
int x = caption.Left - S(10); int x = caption.Left - S(10);
foreach (var (button, width) in new[] { (_dashboardLogout, 106), (_dashboardAbout, 76), (_dashboardSettings, 76) }) foreach (var (button, width) in new[] { (_dashboardLogout, 106), (_dashboardAbout, 76), (_dashboardSettings, 76) })
@@ -140,6 +129,7 @@ internal sealed partial class MainForm
{ {
var show = CompactPresentation && _dashboardView.Visible && _logoutButton.Parent == _brandHeader; var show = CompactPresentation && _dashboardView.Visible && _logoutButton.Parent == _brandHeader;
_dashboardMore.Visible = show; _dashboardMore.Visible = show;
_welcomeLabel.Visible = false;
if (!show) return; if (!show) return;
int S(int value) => ScaleLogical(value); int S(int value) => ScaleLogical(value);
@@ -147,13 +137,6 @@ internal sealed partial class MainForm
var settingsLeft = caption.Left - S(38); var settingsLeft = caption.Left - S(38);
_dashboardMore.Bounds = new Rectangle(settingsLeft, caption.Top, S(32), caption.Height); _dashboardMore.Bounds = new Rectangle(settingsLeft, caption.Top, S(32), caption.Height);
_logoutButton.Bounds = new Rectangle(settingsLeft - S(70), caption.Top, S(64), caption.Height); _logoutButton.Bounds = new Rectangle(settingsLeft - S(70), caption.Top, S(64), caption.Height);
var nameWidth = Math.Clamp(_logoutButton.Left - S(191), S(70), S(110));
_welcomeLabel.Bounds = new Rectangle(_logoutButton.Left - nameWidth - S(6), caption.Top, nameWidth, caption.Height);
foreach (var label in _brandHeader.Controls.OfType<Label>())
{
if (label.Tag is not Rectangle) continue;
label.Width = Math.Clamp(_welcomeLabel.Left - label.Left - S(6), S(80), S(180));
}
} }
private void ShowDashboardAbout() => MessageBox.Show(this, private void ShowDashboardAbout() => MessageBox.Show(this,
@@ -163,10 +146,17 @@ internal sealed partial class MainForm
private void OpenDashboardMenu(Control anchor, bool includeApplicationActions) private void OpenDashboardMenu(Control anchor, bool includeApplicationActions)
{ {
if (_exiting || _settingsMenu?.Visible == true) return; if (_exiting || _settingsMenu?.Visible == true) return;
_settingsMenu?.Dispose();
var menu = _settingsMenu = new ContextMenuStrip { BackColor = Brand.Surface, ForeColor = Brand.Text, ShowImageMargin = false }; var menu = _settingsMenu = new ContextMenuStrip { BackColor = Brand.Surface, ForeColor = Brand.Text, ShowImageMargin = false };
var options = menu.Items; var options = menu.Items;
if (includeApplicationActions) if (includeApplicationActions)
{ {
var account = _accountLabel.Text;
if (!string.IsNullOrWhiteSpace(account))
{
options.Add(new ToolStripLabel("当前账号 " + account));
options.Add(new ToolStripSeparator());
}
menu.Items.Add("关于纵横家", null, (_, _) => ShowDashboardAbout()); menu.Items.Add("关于纵横家", null, (_, _) => ShowDashboardAbout());
menu.Items.Add(new ToolStripSeparator()); menu.Items.Add(new ToolStripSeparator());
} }
@@ -182,16 +172,17 @@ internal sealed partial class MainForm
combo.DroppedDown = true; combo.DroppedDown = true;
}); });
} }
menu.Closed += (_, args) =>
{
if (args.CloseReason == ToolStripDropDownCloseReason.AppClicked)
_settingsDismissedAt = Environment.TickCount64;
_settingsMenu = null;
menu.Dispose();
};
menu.Show(anchor, new Point(anchor.Width, anchor.Height), ToolStripDropDownDirection.BelowLeft); menu.Show(anchor, new Point(anchor.Width, anchor.Height), ToolStripDropDownDirection.BelowLeft);
} }
private void MinimizeToTrayPresentation()
{
if (_exiting || IsDisposed || Disposing) return;
UpdateTaskbarPresentation();
Hide();
ShowInTaskbar = false;
}
private void RestoreFromTrayPresentation() private void RestoreFromTrayPresentation()
{ {
ShowInTaskbar = true; ShowInTaskbar = true;
@@ -211,7 +202,7 @@ internal sealed partial class MainForm
internal bool MinimizedOnTaskbarForTest => WindowState == FormWindowState.Minimized && Visible && ShowInTaskbar && !_exiting; internal bool MinimizedOnTaskbarForTest => WindowState == FormWindowState.Minimized && Visible && ShowInTaskbar && !_exiting;
} }
internal enum DashboardHeaderIcon { User, Settings, About, Logout, More, Close } internal enum DashboardHeaderIcon { User, Settings, About, Logout, More }
internal sealed class DashboardHeaderButton : Button internal sealed class DashboardHeaderButton : Button
{ {
@@ -246,23 +237,16 @@ internal sealed class DashboardHeaderButton : Button
var s = DeviceDpi / 96f; var s = DeviceDpi / 96f;
int S(int value) => Math.Max(1, (int)Math.Round(value * s)); int S(int value) => Math.Max(1, (int)Math.Round(value * s));
g.SmoothingMode = SmoothingMode.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias;
var close = _glyph == DashboardHeaderIcon.Close; using var path = UiGeometry.RoundedRectangle(Rectangle.Inflate(ClientRectangle, -2, -2), S(10));
if (!close || _hovered) using var fill = new SolidBrush(_hovered
{ ? Color.FromArgb(237, 220, 239, 255) : Color.FromArgb(176, 242, 250, 255));
using var path = UiGeometry.RoundedRectangle(Rectangle.Inflate(ClientRectangle, -2, -2), S(10)); g.FillPath(fill, path);
using var fill = new SolidBrush(close ? Brand.Danger : _hovered using var border = new Pen(Color.FromArgb(177, 151, 189, 225), Math.Max(1, s));
? Color.FromArgb(237, 220, 239, 255) : Color.FromArgb(176, 242, 250, 255)); g.DrawPath(border, path);
g.FillPath(fill, path);
if (!close)
{
using var border = new Pen(Color.FromArgb(177, 151, 189, 225), Math.Max(1, s));
g.DrawPath(border, path);
}
}
var color = !Enabled ? Brand.Muted : close && _hovered ? Color.White : Brand.Navy; var color = Enabled ? Brand.Navy : Brand.Muted;
var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding; var flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPadding;
var iconSize = S(close ? 18 : 17); var iconSize = S(17);
var hasText = Text.Length != 0; var hasText = Text.Length != 0;
var textWidth = hasText ? TextRenderer.MeasureText(g, Text, Font, Size.Empty, flags).Width : 0; var textWidth = hasText ? TextRenderer.MeasureText(g, Text, Font, Size.Empty, flags).Width : 0;
var gap = hasText ? S(5) : 0; var gap = hasText ? S(5) : 0;
@@ -271,7 +255,7 @@ internal sealed class DashboardHeaderButton : Button
if (hasText) TextRenderer.DrawText(g, Text, Font, if (hasText) TextRenderer.DrawText(g, Text, Font,
new Rectangle(left + iconSize + gap, 0, Math.Max(1, Width - left - iconSize - gap - S(3)), Height), new Rectangle(left + iconSize + gap, 0, Math.Max(1, Width - left - iconSize - gap - S(3)), Height),
color, flags | TextFormatFlags.EndEllipsis); color, flags | TextFormatFlags.EndEllipsis);
if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(g, Rectangle.Inflate(ClientRectangle, -5, -5)); if (Focused && ShowFocusCues) DashboardHeaderDrawing.Focus(g, ClientRectangle, DeviceDpi, color);
} }
} }
@@ -302,6 +286,17 @@ internal sealed class DashboardHeaderIdentity : Label
internal static class DashboardHeaderDrawing internal static class DashboardHeaderDrawing
{ {
internal static void Focus(Graphics graphics, Rectangle bounds, int dpi, Color color)
{
var scale = dpi / 96f;
var inset = Math.Max(3, (int)Math.Round(4 * scale));
var inner = Rectangle.Inflate(bounds, -inset, -inset);
if (inner.Width <= 0 || inner.Height <= 0) return;
using var path = UiGeometry.RoundedRectangle(inner, Math.Max(2, (int)Math.Round(5 * scale)));
using var pen = new Pen(SystemInformation.HighContrast ? SystemColors.Highlight : color, Math.Max(1.25f, 1.4f * scale));
graphics.DrawPath(pen, path);
}
internal static void Paint(Graphics g, DashboardHeaderIcon glyph, Rectangle bounds, Color color) internal static void Paint(Graphics g, DashboardHeaderIcon glyph, Rectangle bounds, Color color)
{ {
if (glyph == DashboardHeaderIcon.Settings) if (glyph == DashboardHeaderIcon.Settings)
@@ -337,10 +332,6 @@ internal static class DashboardHeaderDrawing
using (var dot = new SolidBrush(color)) using (var dot = new SolidBrush(color))
for (var x = 3; x <= 19; x += 8) g.FillEllipse(dot, x, 10.5f, 3.25f, 3.25f); for (var x = 3; x <= 19; x += 8) g.FillEllipse(dot, x, 10.5f, 3.25f, 3.25f);
break; break;
case DashboardHeaderIcon.Close:
g.DrawLine(pen, 5, 5, 19, 19);
g.DrawLine(pen, 19, 5, 5, 19);
break;
} }
} }
finally { g.Restore(state); } 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);
}
}
+8 -2
View File
@@ -11,10 +11,11 @@ internal sealed partial class MainForm
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
&& WindowChromeForTest is { LoginMode: false, MinimizeButton.Action: CaptionAction.Minimize }
&& !_welcomeLabel.Visible && !_logoutButton.Visible; && !_welcomeLabel.Visible && !_logoutButton.Visible;
checks["wide_reuses_configuration_and_range_controls"] = _connectionModeCombo.Parent == _nodeCard checks["wide_reuses_configuration_and_range_controls"] = _connectionModeCombo.Parent == _nodeCard
&& _routeCombo.Parent == _nodeCard && _historyRangeCombo.Parent == _modeCard && _routeCombo.Parent == _nodeCard && _historyRangeCombo.Parent == _speedTrendCard
&& _connectionModeCombo.Enabled && _routeCombo.Enabled && _historyRangeCombo.Enabled; && _connectionModeCombo.Enabled && _routeCombo.Enabled && _historyRangeCombo.Enabled;
_connectionModeCombo.SelectedIndex = 1; _connectionModeCombo.SelectedIndex = 1;
@@ -45,6 +46,9 @@ internal sealed partial class MainForm
for (var i = 0; i < 60; i++) for (var i = 0; i < 60; i++)
_trafficChart.Add(120000 + Math.Sin(i / 3d) * 50000, 600000 + Math.Cos(i / 7d) * 220000, now.AddSeconds(5 * (i - 59))); _trafficChart.Add(120000 + Math.Sin(i / 3d) * 50000, 600000 + Math.Cos(i / 7d) * 220000, now.AddSeconds(5 * (i - 59)));
DisplayTraffic(180000, 920000, "演示样本 · 近 5 分钟"); DisplayTraffic(180000, 920000, "演示样本 · 近 5 分钟");
checks["wide_shows_both_series_and_aligns_chart_heading"] =
_trafficChart.DisplayedSeries == TrafficChartSeries.Both && _trendHeading.Top == _wideUpload.Top
&& _wideUpload.Top == _historyRangeCombo.Top && _trendHeading.Right <= _wideUpload.Left;
_wideDownload.PerformClick(); _wideDownload.PerformClick();
checks["wide_download_tab_changes_chart_series"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Download checks["wide_download_tab_changes_chart_series"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Download
&& _wideDownload.Text.Contains("KB/s") && _wideUpload.Text.Contains("KB/s"); && _wideDownload.Text.Contains("KB/s") && _wideUpload.Text.Contains("KB/s");
@@ -52,6 +56,8 @@ internal sealed partial class MainForm
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[2]; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[2];
checks["wide_upload_tab_and_range_use_existing_chart"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Upload checks["wide_upload_tab_and_range_use_existing_chart"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Upload
&& _trafficChart.PeriodMinutes == 15; && _trafficChart.PeriodMinutes == 15;
_wideUpload.PerformClick();
checks["wide_selected_series_toggles_back_to_both"] = _trafficChart.DisplayedSeries == TrafficChartSeries.Both;
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
checks["wide_connected_has_disconnect_and_live_values"] = _statusCard.Tone == BannerTone.Connected checks["wide_connected_has_disconnect_and_live_values"] = _statusCard.Tone == BannerTone.Connected
&& _connectButton.Text == "断开连接" && !_routeCombo.Enabled && DashboardControlsFit(); && _connectButton.Text == "断开连接" && !_routeCombo.Enabled && DashboardControlsFit();
+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
+6 -5
View File
@@ -107,15 +107,16 @@ internal static class StartupSelfTest
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
&& form.ShowInTaskbar && form.LoginReadyForTest;
chrome.SetLoginMode(true); chrome.SetLoginMode(true);
report["return_to_login_restores_exit_caption"] = chrome.LoginMode report["return_to_login_restores_exit_caption"] = chrome.LoginMode
&& chrome.MinimizeButton.Action == CaptionAction.Close; && chrome.MinimizeButton.Action == CaptionAction.Close;
+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>
+3 -6
View File
@@ -25,8 +25,6 @@ internal sealed class WindowChrome : IDisposable
private int _modeGeneration; private int _modeGeneration;
internal string LastMinMaxForTest { get; private set; } = "none"; internal string LastMinMaxForTest { get; private set; } = "none";
internal bool LoginMode { get; private set; } internal bool LoginMode { get; private set; }
internal bool DashboardCloseSlot { get; set; }
internal Rectangle DashboardCloseBounds { get; private set; }
internal CaptionButton MinimizeButton { get; } = new(CaptionAction.Minimize); internal CaptionButton MinimizeButton { get; } = new(CaptionAction.Minimize);
@@ -154,7 +152,7 @@ internal sealed class WindowChrome : IDisposable
{ {
if (_disposed || _header.IsDisposed) return; if (_disposed || _header.IsDisposed) return;
var width = Scale(46); var width = Scale(46);
var tallHeader = DashboardCloseSlot && _header.ClientSize.Height >= Scale(64); var tallHeader = _header is BrandHeaderPanel && _header.ClientSize.Height >= Scale(64);
var height = Scale(tallHeader ? 36 : CaptionHeight); var height = Scale(tallHeader ? 36 : CaptionHeight);
var maximized = _form.WindowState == FormWindowState.Maximized; var maximized = _form.WindowState == FormWindowState.Maximized;
// Keep the entire clickable button clear of the native resize band. // Keep the entire clickable button clear of the native resize band.
@@ -162,8 +160,7 @@ internal sealed class WindowChrome : IDisposable
var inset = maximized ? 0 : Scale(6); var inset = maximized ? 0 : Scale(6);
var top = tallHeader ? Scale(17) : inset; var top = tallHeader ? Scale(17) : inset;
var right = _header.ClientSize.Width - inset; var right = _header.ClientSize.Width - inset;
DashboardCloseBounds = DashboardCloseSlot ? new Rectangle(right - width, top, width, height) : Rectangle.Empty; MinimizeButton.Bounds = new Rectangle(Math.Max(0, right - width), top, width, height);
MinimizeButton.Bounds = new Rectangle(Math.Max(0, right - width * (DashboardCloseSlot ? 2 : 1)), top, width, height);
_toolTip.SetToolTip(MinimizeButton, MinimizeButton.AccessibleName); _toolTip.SetToolTip(MinimizeButton, MinimizeButton.AccessibleName);
MinimizeButton.BringToFront(); MinimizeButton.BringToFront();
MinimizeButton.Invalidate(); MinimizeButton.Invalidate();
@@ -529,7 +526,7 @@ internal sealed class CaptionButton : Button
break; break;
} }
if (Focused && ShowFocusCues) if (Focused && ShowFocusCues)
ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.Inflate(ClientRectangle, -4, -4), foreground, BackColor); DashboardHeaderDrawing.Focus(e.Graphics, ClientRectangle, DeviceDpi, foreground);
} }
} }
+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();
} }