Publish Zonghengjia Windows 0.3.13 client source

This commit is contained in:
2026-11-13 10:35:04 +08:00
parent 1590443809
commit 839434a313
55 changed files with 2324 additions and 963 deletions
+151 -119
View File
@@ -26,7 +26,7 @@ internal sealed partial class MainForm : Form
private bool _knownTailnetAllowed;
private long _privateLeaseDeadlineTicks;
private bool _wantConnected, _trafficReading, _healthChecking;
private bool _localRoutingFault;
private ConnectionHealthPolicy.Decision? _displayedHealthWarning;
private int _lastCoreId;
private long _lastUp, _lastDown, _sessionUp, _sessionDown;
private DateTimeOffset _lastSample, _nextReconnect;
@@ -43,7 +43,7 @@ internal sealed partial class MainForm : Form
private readonly Label _headerPoem = new();
private readonly RoundedCardPanel _loginView = new();
private readonly ScenicPanel _dashboardView = new();
private readonly CardPanel _statusCard = new();
private readonly DashboardConnectionBanner _statusCard = new();
private readonly TextBox _loginText = new();
private readonly TextBox _passwordText = new();
private readonly RoundedButton _loginButton = new();
@@ -85,6 +85,7 @@ internal sealed partial class MainForm : Form
internal bool WindowExitSelfTestPassed { get; private set; }
internal bool NetworkRecoveryFailed { get; private set; }
internal bool WindowsSessionEnded => _sessionEnding;
internal MainForm(bool runWindowExitSelfTest = false, bool preview = false, bool uiOnly = false,
bool autoConnect = false, Func<CancellationToken, Task>? startupRecovery = null,
@@ -330,14 +331,7 @@ internal sealed partial class MainForm : Form
BackColor = Color.Transparent,
};
_loginView.Controls.Add(poweredLogo);
var headerLine = new Panel { BackColor = Color.FromArgb(232, 238, 245), Location = new Point(28, 86), Size = new Size(384, 1) };
_loginView.Controls.Add(headerLine);
_loginView.Controls.Add(NewLabel("账号登录", Brand.Font(13.5f, FontStyle.Bold), Brand.Text, new Point(28, 100), new Size(150, 30)));
_loginView.Controls.Add(NewLabel("统一账号安全接入", Brand.Font(8), Brand.Navy, new Point(129, 105), new Size(150, 22)));
var versionBadge = NewLabel($"v{GetDisplayVersion()}", Brand.Font(7.2f, FontStyle.Bold), Brand.RoyalBlue, new Point(356, 101), new Size(56, 24));
versionBadge.BackColor = Brand.PaleBlue;
versionBadge.TextAlign = ContentAlignment.MiddleCenter;
_loginView.Controls.Add(versionBadge);
_loginView.Controls.Add(NewLabel("用户名 / 邮箱", Brand.Font(8.8f, FontStyle.Bold), Brand.Text, new Point(28, 136), new Size(180, 22)));
_loginText.PlaceholderText = "用户名或 name@example.com";
@@ -366,9 +360,9 @@ internal sealed partial class MainForm : Form
_loginView.Controls.Add(_registerPrompt);
_registerLink.Text = "注册新用户";
_registerLink.Font = Brand.Font(9, FontStyle.Bold);
_registerLink.LinkColor = Brand.Navy;
_registerLink.ActiveLinkColor = Brand.Navy;
_registerLink.VisitedLinkColor = Brand.Navy;
_registerLink.LinkColor = Brand.DeepBlue;
_registerLink.ActiveLinkColor = Brand.RoyalBlue;
_registerLink.VisitedLinkColor = Brand.DeepBlue;
_registerLink.BackColor = Color.Transparent;
_registerLink.Location = new Point(220, 346);
_registerLink.Size = new Size(112, 28);
@@ -489,7 +483,7 @@ internal sealed partial class MainForm : Form
}
if (string.IsNullOrWhiteSpace(_accessToken) || _availableNodeCount == 0 || _routeCombo.SelectedItem is not RouteModeInfo route)
{
if (!suppressDialogs)
if (!suppressDialogs && !_exiting)
{
MessageBox.Show("暂无可用工作节点,请联系管理员。", "纵横家", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
@@ -542,58 +536,42 @@ internal sealed partial class MainForm : Form
throw new InvalidOperationException("私有节点授权已过期,请刷新账号信息后重试。");
if (route.Id == "direct" && selection.Manual && privateGrants.Any(n => n.Slug == selection.NodeSlug))
throw new InvalidOperationException("济南办私有辅助节点用于代理连接,请选择智能或全局代理。");
var rankedPrivate = route.Id == "direct" || _tailnetPreference.DomainOnly ? Array.Empty<PrivateAuxiliaryNode>() : await PrivateAuxiliaryRouting.RankForSelectionAsync(selection, privateGrants,
_failedNodes.Keys.ToHashSet(StringComparer.Ordinal), _xray.IsRunning,
PrivateAuxiliaryRouting.MeasureEndpointAsync, connectionToken);
var attempts = await PlanTransportsAsync(selection, rankedPrivate, route.Id, connectionToken);
if (reconnect && _transportRetryNodeSlug is { } sameNode
&& !attempts.Any(a => a.Attempt.Slug == sameNode))
// A same-node public retry must not jump ahead of another usable
// overlay candidate. Keep it before only the public AI pass.
attempts = attempts.Where(a => a.Attempt.IsPrivate || a.TailnetOnly)
.Concat(new[] { new PlannedTransport(new(sameNode, null)) })
.Concat(attempts.Where(a => !a.Attempt.IsPrivate && !a.TailnetOnly)).ToArray();
var retryPublicSlug = reconnect && !_currentNodeIsPrivateAuxiliary ? _transportRetryNodeSlug : null;
var attempts = TransportPlan.AttemptsAsync(selection, route.Id, _publicNodeCount, retryPublicSlug,
token => RankPrivateConnectionAsync(selection, privateGrants, token), connectionToken);
var connectedPrivate = false;
var connectedTailnet = false;
var publicPoolUnavailable = false;
PrivateAuxiliaryNode? connectedEndpoint = null;
await foreach (var planned in ExpandTransportsAsync(attempts, route.Id, connectionToken))
await foreach (var attempt in attempts)
{
var attempt = planned.Attempt;
NodeInfo? candidate = planned.KnownCandidate;
if (publicPoolUnavailable && attempt.Slug == "auto") continue;
NodeInfo? candidate = attempt.Auxiliary;
var candidateStarted = false;
try
{
var candidateResponse = await ConfirmDispatchedTransportAsync(planned, route.Id, connectionToken) ?? planned.Cached ?? (attempt.Auxiliary is { } auxiliary
var candidateResponse = attempt.Auxiliary is { } auxiliary
? await _api.GetPrivateAuxiliaryConfigAsync(_accessToken, auxiliary, route.Id, connectionToken)
: await _api.GetConfigAsync(
_accessToken,
attempt.Slug,
route.Id,
connectionToken,
selection.Manual ? null : _failedNodes.Keys));
: await _api.GetConfigAsync(_accessToken, attempt.Slug, route.Id, connectionToken, _failedNodes.Keys);
connectionToken.ThrowIfCancellationRequested();
selection.ValidateResponse(candidateResponse.Node.Slug);
if ((attempt.Slug != "auto" && candidateResponse.Node.Slug != attempt.Slug)
|| candidateResponse.RouteMode != route.Id)
throw new InvalidOperationException("服务器返回的节点或代理模式与请求不一致,已拒绝连接。");
if (!attempt.IsPrivate && _privateAuxiliaryNodes.Any(n => n.Slug == candidateResponse.Node.Slug))
throw new InvalidOperationException("公共调度返回了私有辅助节点,已拒绝混用配置。");
selection.ValidateConfig(attempt, candidateResponse, route.Id, _manualNodeCombo.Items.Cast<NodeInfo>(), _failedNodes);
candidate = candidateResponse.Node;
var candidateName = NodePresentation.Name(candidate.Slug, candidate.Name, attempt.IsPrivate);
_currentNodeLabel.Text = $"{candidateName} · 正在连接";
SetConnectionState(false, "正在连接", $"{candidateName} · {route.Name}");
connectedTailnet = await NodeTransportConnector.ConnectAsync(candidateResponse, _tailnetPreference,
async (config, connectionToken) => {
candidateStarted = true;
replacementStarted = true;
await _xray.StartAsync(config, route.Id, candidate.Slug, connectionToken,
TailnetTransport.Address(config) is null ? null : candidateResponse.GetRuntimeConfigJson(),
preferredTailnetConfigJson: TailnetTransport.TryPrepare(candidateResponse, _knownTailnetAllowed && !attempt.IsPrivate));
}, _xray.StopAsync, _xray.CheckProxyHealthAsync,
address => { TailnetTransport.RequireExistingRoute(address); },
TailnetTransport.RequireProbeRoute,
message => { _statusDetail.Text = $"{candidateName} · {message}"; },
() => Environment.TickCount64, connectionToken,
allowKnownEndpoints: _knownTailnetAllowed && !attempt.IsPrivate,
endpointProbe: TailnetTransport.ProbeEndpointAsync,
tailnetOnly: planned.TailnetOnly,
diagnostic: entry => AppPaths.WriteLog(entry.SafeMessage));
if (attempt.IsPrivate && !await _xray.CheckHealthAsync(connectionToken))
throw new InvalidOperationException("私有节点入口已连接,但出口检查未通过。");
@@ -609,28 +587,27 @@ internal sealed partial class MainForm : Form
}
catch (LocalNetworkException) { throw; }
catch (ClientRuntimeException) { throw; }
catch (TailnetUnavailableException)
{
// Connector cleans up only a core it actually attempted.
// Retain node eligibility for the later public pass.
failures.Add($"{candidate?.Name ?? "内网节点"}: Tailscale 入口未通过,继续其他内网节点。");
}
catch (ApiException exception) when (exception.StatusCode is not (401 or 403))
{
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync();
if (candidate is null) break;
_failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…";
}
catch (Exception exception) when (exception is not OperationCanceledException && exception is not ApiException { StatusCode: 401 or 403 })
{
if (ConnectionRecoveryPolicy.KeepExisting(reconnect, replacementStarted, _xray.IsRunning, exception, CanRetainAuthorizedCore())) throw;
failures.Add($"{candidate?.Name ?? "AI 调度"}: {exception.Message}");
await _xray.StopAsync();
if (candidate is not null) _failedNodes[candidate.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
else break;
if (candidateStarted)
{
await _xray.StopAsync();
_failedNodes[candidate!.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
if (!selection.Manual && !attempt.IsPrivate)
_tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
else if (!selection.Manual && !attempt.IsPrivate && exception is ApiException { StatusCode: 404 })
{
if (attempt.Slug == "auto") publicPoolUnavailable = true;
else
{
_failedNodes[attempt.Slug] = DateTimeOffset.UtcNow.AddMinutes(5);
_tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
}
else if (!attempt.IsPrivate) break;
if (attempt.IsPrivate && !selection.Manual) _statusDetail.Text = "私有节点暂不可用,正在回到公共节点…";
}
}
@@ -679,7 +656,9 @@ internal sealed partial class MainForm : Form
catch (ApiException exception)
{
await DisconnectAsync(cancelPending: exception.StatusCode is 401 or 403);
if (!suppressDialogs)
if (exception.StatusCode is not (401 or 403) && !_exiting && !IsDisposed)
SetConnectionState(false, "连接失败", exception.Message);
if (!suppressDialogs && !_exiting)
{
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
@@ -692,6 +671,8 @@ internal sealed partial class MainForm : Form
{
AppPaths.WriteError(exception);
await DisconnectAsync(cancelPending: false);
if (!_exiting && !IsDisposed)
SetConnectionState(false, "连接失败", "请检查当前网络和节点状态,再试一次。");
if (!suppressDialogs)
{
MessageBox.Show(exception.Message, "连接失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
@@ -865,35 +846,17 @@ internal sealed partial class MainForm : Form
var decision = _connectionHealth.Observe(revision, testedCore, _xray.CoreId,
_wantConnected, _busy, _xray.IsTransitioning, _exiting, healthy, Environment.TickCount64, health.ProxyHealthy,
_xray.UsesTailnet, health.BusinessUnavailable);
if (decision == ConnectionHealthPolicy.Decision.Ignore) return;
if (decision is ConnectionHealthPolicy.Decision.Ignore or ConnectionHealthPolicy.Decision.PendingAdvisory) return;
if (healthy && _xray.IsRunning) {
if (_localRoutingFault) {
_localRoutingFault = false;
if (_displayedHealthWarning is not null) {
SetConnectionState(true, "已安全连接", $"{_currentNodeName ?? _currentNodeSlug} · {_routeCombo.Text}");
_notifyIcon.Text = "纵横家 · 已连接";
AppPaths.WriteLog("普通智能路径已恢复,沿用原内核与工作节点。");
AppPaths.WriteLog("连接探测已恢复,沿用原内核与工作节点。");
}
ConnectionAcceptanceTrace.Record("health_ok", _currentNodeSlug, true, _xray.CoreId);
return;
}
if (decision == ConnectionHealthPolicy.Decision.Degraded) {
_localRoutingFault = true;
SetConnectionState(true, "网站探测异常,连接保留", $"{_currentNodeName ?? _currentNodeSlug} · 目标网站可用性尚未确认,保留当前线路");
_statusTitle.ForeColor = Color.FromArgb(155, 88, 12);
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 网站探测异常";
AppPaths.WriteLog("健康诊断:网站探测异常,保留当前内核和已授权线路;未将网站状态判为节点传输失败。");
return;
}
if (decision == ConnectionHealthPolicy.Decision.Repair) {
_localRoutingFault = true;
SetConnectionState(true, "分流异常,正在修复", $"{_currentNodeName ?? _currentNodeSlug} · 代理出口可达,保留现有连接并重试规则验证");
_statusTitle.ForeColor = Color.FromArgb(155, 88, 12);
_statusDot.ForeColor = _statusTitle.ForeColor;
_notifyIcon.Text = "纵横家 · 分流修复中";
AppPaths.WriteLog($"健康诊断:普通路径失败、代理路径正常;保留内核 {_xray.CoreId},未判为节点故障。");
return;
}
if (TryShowConnectionHealthWarning(decision)) return;
ConnectionAcceptanceTrace.Record("health_failed", _currentNodeSlug, _xray.IsRunning, _xray.CoreId, _connectionHealth.Failures);
if (decision != ConnectionHealthPolicy.Decision.Switch) return;
if (!PreflightClientRuntime(suppressDialogs: true)) return;
@@ -907,7 +870,11 @@ internal sealed partial class MainForm : Form
_tailnetPreference.CommitDomainFallback();
_transportRetryNodeSlug = _currentNodeSlug;
}
else _failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5);
else
{
_failedNodes[_currentNodeSlug] = DateTimeOffset.UtcNow.AddMinutes(5);
if (!ManualSelection) _tailnetPreference.ReleaseDomainFallbackAfterNodeFailure();
}
}
SetConnectionState(false, "链路异常,正在恢复", ManualSelection
? "正在重试手动指定节点,不会切换其他节点"
@@ -919,6 +886,25 @@ internal sealed partial class MainForm : Form
finally { _healthChecking = false; }
}
private bool TryShowConnectionHealthWarning(ConnectionHealthPolicy.Decision decision)
{
if (_displayedHealthWarning == decision) return true;
(string Title, string Detail)? warning = decision switch
{
ConnectionHealthPolicy.Decision.WebsiteUnavailable => ("网站探测异常,连接保留", "代理出口可达,目标网站未通过探测"),
ConnectionHealthPolicy.Decision.TailnetEgressUnverified => ("出口探测异常,连接保留", "保持 Tailscale 入口,代理出口尚未确认"),
ConnectionHealthPolicy.Decision.Repair => ("分流异常,正在修复", "代理出口可达,正在复测分流规则"),
_ => null,
};
if (warning is not { } display) return false;
SetConnectionState(true, display.Title, $"{display.Detail} · {_currentNodeName ?? _currentNodeSlug}", decision);
_notifyIcon.Text = $"纵横家 · {display.Title}";
if (!_preview && !_uiOnly)
AppPaths.WriteLog($"健康诊断:{display.Detail},保留当前内核和已授权线路。");
return true;
}
private async Task RunWindowExitSelfTestAsync()
{
await ToggleConnectionAsync(suppressDialogs: true);
@@ -1000,7 +986,8 @@ internal sealed partial class MainForm : Form
var reportingCore = _xray.CoreId;
PostUi(() =>
{
if (!_runtimeRepairRequired && _dashboardView.Visible && _wantConnected && _xray.CoreId == reportingCore)
if (!_runtimeRepairRequired && _displayedHealthWarning is null && _dashboardView.Visible
&& _wantConnected && _xray.CoreId == reportingCore)
_statusDetail.Text = NodePresentation.LearningDetail(_selectionUiConnected, _currentNodeName, message);
});
}
@@ -1181,14 +1168,14 @@ internal sealed partial class MainForm : Form
}
}
private void SetConnectionState(bool connected, string title, string detail)
private void SetConnectionState(bool connected, string title, string detail, ConnectionHealthPolicy.Decision? healthWarning = null)
{
_displayedHealthWarning = healthWarning;
_selectionUiConnected = connected;
ConnectionAcceptanceTrace.Record(connected ? "ui_connected" : "ui_not_connected", _currentNodeSlug, connected, _xray.CoreId);
_statusDot.ForeColor = connected ? Brand.Success : Brand.Muted;
_statusTitle.Text = title;
_statusTitle.ForeColor = connected ? Brand.Success : Brand.Text;
_statusDetail.Text = detail;
RefreshConnectionAppearance();
_connectButton.Text = _connectionAttemptCancellation is { IsCancellationRequested: false } ? "取消连接" : connected ? "断开连接" : "连接";
_connectButton.BackColor = Brand.RoyalBlue;
if (!connected) DisplayTraffic(null, null, "未连接 · 仅代理流量");
@@ -1327,6 +1314,7 @@ internal sealed partial class MainForm : Form
{
if (_exitResourcesDisposed) return;
_exitResourcesDisposed = true;
_settingsMenu?.Close();
WindowExitSelfTestPassed = !_runWindowExitSelfTest
|| (_windowExitSelfTestConnected && !_xray.IsRunning);
_api.Dispose();
@@ -1351,6 +1339,8 @@ internal sealed partial class MainForm : Form
message.Result = IntPtr.Zero; return;
}
CompleteSessionEnding();
message.Result = IntPtr.Zero;
return;
}
base.WndProc(ref message);
}
@@ -1360,14 +1350,22 @@ internal sealed partial class MainForm : Form
if (_sessionEnding) return;
_sessionEnding = true;
_xray.ConfirmSessionShutdown();
var cleanup = BeginExitCleanup();
// Windows can terminate us after its short shutdown allowance. Never
// remove recovery journals here or display a modal recovery error.
_exitCleanupCompleted = cleanup.Wait(TimeSpan.FromSeconds(3));
NetworkRecoveryFailed |= !_exitCleanupCompleted || cleanup.Result is not null;
try
{
var cleanup = BeginExitCleanup();
_exitCleanupCompleted = cleanup.Wait(TimeSpan.FromSeconds(3));
NetworkRecoveryFailed |= !_exitCleanupCompleted || cleanup.Result is not null;
}
catch (Exception error)
{
NetworkRecoveryFailed = true;
AppPaths.WriteError(error);
}
finally { CompleteExitResources(); }
if (NetworkRecoveryFailed)
AppPaths.WriteLog("Windows 会话结束:网络恢复未全部完成,保留恢复记录供下次启动继续处理。");
CompleteExitResources();
}
private void PostUi(Action action, bool allowExiting = false)
@@ -1402,6 +1400,11 @@ internal sealed partial class MainForm : Form
ContextMenuStrip = menu,
};
notify.DoubleClick += (_, _) => ShowFromTray();
notify.MouseClick += (_, args) =>
{
if (args.Button == MouseButtons.Left) ShowFromTray();
};
notify.Disposed += (_, _) => menu.Dispose();
return notify;
}
@@ -1478,14 +1481,14 @@ internal sealed partial class MainForm : Form
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = "https://vpn.example.invalid/register/",
FileName = VpnApiClient.BaseAddress + "register/",
UseShellExecute = true,
});
}
catch (Exception exception)
{
AppPaths.WriteError(exception);
MessageBox.Show("无法打开注册页面,请在浏览器访问 https://vpn.example.invalid/register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("无法打开注册页面,请在浏览器访问 " + VpnApiClient.BaseAddress + "register/", "注册新用户", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
@@ -1628,6 +1631,7 @@ internal class CardPanel : Panel
internal bool ScenicStatus { get; set; }
internal bool AccentBar { get; set; }
internal bool MetricBand { get; set; }
internal bool GlassRim { get; set; }
internal CardPanel()
{
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw
@@ -1652,18 +1656,24 @@ internal class CardPanel : Panel
if (Embedded || Width < 16 || Height < 16) return;
g.SmoothingMode = SmoothingMode.AntiAlias;
var s = DeviceDpi / 96f;
var radius = Math.Max(6, (int)(11 * s));
using var shadow = UiGeometry.RoundedRectangle(new Rectangle(1, 3, Width - 3, Height - 4), radius);
using var shadowPen = new Pen(Color.FromArgb(32, 110, 169, 199), Math.Max(1, 2 * s));
g.DrawPath(shadowPen, shadow);
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 5), radius);
using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 238, 247, 255));
using var border = new Pen(ScenicStatus ? Color.White : Color.FromArgb(201, 227, 249), Math.Max(1, s * (ScenicStatus ? 1.7f : .75f)));
var inset = Math.Max(1, (int)Math.Round(s));
var bounds = new Rectangle(inset, inset, Width - 2 * inset - 1, Height - 3 * inset - 1);
if (bounds.Width < 2 || bounds.Height < 2) return;
var radius = Math.Min(Math.Min(bounds.Width, bounds.Height) / 2, (int)Math.Round((GlassRim ? 14 : 10) * s));
using var path = UiGeometry.RoundedRectangle(bounds, radius);
using var shadow = new Pen(Color.FromArgb(28, 67, 128, 178), Math.Max(1f, 1.5f * s));
var shadowState = g.Save();
g.TranslateTransform(0, .85f * s);
g.DrawPath(shadow, path);
g.Restore(shadowState);
using var fill = new SolidBrush(Color.FromArgb(SurfaceAlpha, 246, 251, 255));
var edge = GlassRim ? Color.FromArgb(215, 255, 255, 255) : Color.FromArgb(122, 167, 199, 224);
using var border = new Pen(edge, Math.Max(1, s * .8f));
g.FillPath(fill, path);
if (ScenicStatus)
{
var state = g.Save(); g.SetClip(path);
ScenicTheme.Clouds(g, new Rectangle(Width - (int)(260*s), (int)(14*s), (int)(120*s), (int)(50*s)), .6f);
ScenicTheme.Clouds(g, new Rectangle(Width - (int)(260*s), (int)(8*s), (int)(120*s), (int)(42*s)), .26f);
g.Restore(state);
}
g.DrawPath(border, path);
@@ -1755,34 +1765,39 @@ internal sealed class ModernInputPanel : Panel
internal ModernInputPanel(TextBox editor)
{
_editor = editor;
BackColor = Color.White;
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw
| ControlStyles.AllPaintingInWmPaint | ControlStyles.SupportsTransparentBackColor, true);
BackColor = Color.Transparent;
Controls.Add(editor);
editor.GotFocus += (_, _) => Invalidate();
editor.LostFocus += (_, _) => Invalidate();
Resize += (_, _) =>
{
LayoutEditor();
if (Width <= 4 || Height <= 4) return;
using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), 7);
Region?.Dispose();
Region = new Region(path);
};
Resize += (_, _) => LayoutEditor();
LayoutEditor();
}
protected override void OnDpiChangedAfterParent(EventArgs eventArgs)
{
base.OnDpiChangedAfterParent(eventArgs);
LayoutEditor();
}
private void LayoutEditor()
{
_editor.Location = new Point(14, Math.Max(7, (Height - _editor.PreferredHeight) / 2));
_editor.Width = Math.Max(20, Width - 28);
var inset = (int)Math.Round(11 * DeviceDpi / 96f);
_editor.Location = new Point(inset, Math.Max(0, (Height - _editor.PreferredHeight) / 2));
_editor.Width = Math.Max(1, Width - 2 * inset);
}
protected override void OnPaint(PaintEventArgs eventArgs)
{
if (Width <= 4 || Height <= 4) return;
var scale = DeviceDpi / 96f;
eventArgs.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), 7);
eventArgs.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), (int)Math.Round(7 * scale));
using var fill = new SolidBrush(Color.White);
using var border = new Pen(ContainsFocus ? Brand.RoyalBlue : Color.FromArgb(194, 207, 221), ContainsFocus ? 1.8f : 1f);
using var border = new Pen(ContainsFocus ? Brand.RoyalBlue : Color.FromArgb(167, 193, 217),
Math.Max(1, (ContainsFocus ? 1.3f : .8f) * scale));
eventArgs.Graphics.FillPath(fill, path);
eventArgs.Graphics.DrawPath(border, path);
}
@@ -1791,6 +1806,12 @@ internal sealed class ModernInputPanel : Panel
internal sealed class RoundedButton : Button
{
private bool _hovered;
private bool _capsule;
internal bool Capsule
{
get => _capsule;
set { if (_capsule != value) { _capsule = value; UpdateShape(); Invalidate(); } }
}
internal RoundedButton()
{
SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true);
@@ -1810,14 +1831,20 @@ internal sealed class RoundedButton : Button
}
else e.Graphics.Clear(Color.White);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), Math.Max(5, DeviceDpi / 16));
var radius = Capsule ? Math.Max(4, (Height - 3) / 2) : Math.Max(5, DeviceDpi / 16);
using var path = UiGeometry.RoundedRectangle(new Rectangle(1, 1, Width - 3, Height - 3), radius);
var primary = BackColor.ToArgb() != Color.White.ToArgb();
var color = !Enabled ? Color.FromArgb(225, 234, 245) : _hovered ? (primary ? Brand.DeepBlue : Brand.PaleBlue) : BackColor;
using Brush fill = primary && Enabled
? new LinearGradientBrush(ClientRectangle, _hovered ? Brand.DeepBlue : Color.FromArgb(0, 116, 233), Brand.RoyalBlue, 20)
: new SolidBrush(color);
: new SolidBrush(Capsule && !primary && Enabled && !_hovered ? Color.FromArgb(205, 219, 239, 255) : color);
e.Graphics.FillPath(fill, path);
if (!primary) { using var pen = new Pen(Color.FromArgb(168, 199, 246), Math.Max(1, DeviceDpi / 96f)); e.Graphics.DrawPath(pen, path); }
else if (Capsule && Enabled)
{
using var pen = new Pen(Color.FromArgb(189, 158, 231, 255), Math.Max(1, DeviceDpi / 96f));
e.Graphics.DrawPath(pen, path);
}
TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, Enabled ? ForeColor : Brand.Muted,
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
if (Focused && ShowFocusCues) ControlPaint.DrawFocusRectangle(e.Graphics, Rectangle.Inflate(ClientRectangle, -6, -6));
@@ -1826,8 +1853,13 @@ internal sealed class RoundedButton : Button
protected override void OnResize(EventArgs eventArgs)
{
base.OnResize(eventArgs);
UpdateShape();
}
private void UpdateShape()
{
if (Width <= 2 || Height <= 2) return;
using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), 8);
using var path = UiGeometry.RoundedRectangle(new Rectangle(0, 0, Width, Height), Capsule ? Math.Min(Width, Height) / 2 : 8);
Region?.Dispose();
Region = new Region(path);
}