Compare commits

...

1 Commits

23 changed files with 4001 additions and 3092 deletions
+141
View File
@@ -475,5 +475,146 @@
], ],
"SourceOnly": true, "SourceOnly": true,
"Version": "0.3.1" "Version": "0.3.1"
},
"Windows032ConnectCompactDelta": {
"CandidateSha256": "85fac03989c71cbc61bdf756ac7e7194ac9cd003533c0aa6bc1c355eeb375813",
"ExampleEndpointChanges": [
{
"Count": 4,
"Path": "windows/KnownTailnetEndpoints.cs"
},
{
"Count": 3,
"Path": "windows/LearningSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/LearningTransportSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/NetworkHandoverSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/PlatformBootstrapTransport.cs"
},
{
"Count": 5,
"Path": "windows/PlatformBootstrapTransportSelfTest.cs"
},
{
"Count": 4,
"Path": "windows/PrivateAuxiliaryRouting.cs"
},
{
"Count": 25,
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/PublicTailnetSelectionSelfTest.cs"
},
{
"Count": 65,
"Path": "windows/TailnetTransportSelfTest.cs"
},
{
"Count": 1,
"Path": "windows/ConnectionSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/GitReleasePolicySelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/InstallationIntegration.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/LearningSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/MainForm.Dashboard.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/MainForm.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/PlatformBootstrapTransport.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 6,
"Path": "windows/PlatformBootstrapTransportSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/PrivateAuxiliaryRouting.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 7,
"Path": "windows/PrivateAuxiliaryRoutingSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/TailnetTransportProbe.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/TailnetTransportSelfTest.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 2,
"Path": "windows/TunConfigBuilder.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/VpnApiClient.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/XrayManager.cs",
"RuleSet": "windows-monitor-20261027"
},
{
"Count": 1,
"Path": "windows/installer/VPNPlus.nsi",
"RuleSet": "windows-monitor-20261027"
}
],
"FrozenSha256": "18d98d6e58c67ecf6d0293668eaeaa6946e2a2e7b879177f1410e7bf08503f7f",
"Omitted": [
"windows/assets/login-cloud-scene-v1.jpg"
],
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "bf4a9f7360d2d44b11a8e94db881cc60d7234d2db7a3e89bffef0515ad244991",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "1cf54a46e495d6f0f74b7b4b67e1786b2c51d5a2",
"PublicDownloadDomainsRetained": [
"pro.ucvl.cn"
],
"SourceOnly": true,
"Version": "0.3.2"
} }
} }
+1 -1
View File
@@ -1,6 +1,6 @@
# 纵横家开源源码 # 纵横家开源源码
此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.1、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。 此仓库是无私有 Git 历史的清洁源码快照:Windows 0.3.2、Django 后台及 iPhone/iPad 1.0.2。公司自有代码按 MIT 开源;第三方组件遵守原许可,公司商标及 Logo 不在 MIT 授权范围。Android 保留原 GPL-3.0 公开仓库,不重复拷贝或改换许可。
| 目录 | 内容与状态 | | 目录 | 内容与状态 |
| --- | --- | | --- | --- |
+35 -16
View File
@@ -4,7 +4,7 @@
"ExportDiffersFromOriginalCandidates": true, "ExportDiffersFromOriginalCandidates": true,
"FilesBeforeProvenanceAndAudit": { "FilesBeforeProvenanceAndAudit": {
"LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e", "LICENSE": "b7e94910b8dc377b0a05ccde3c6e5941838dfc15c9dd790078d11728205b524e",
"README.md": "c2c081754048ff7561f65eb5a471c08e7293acaddbbe48839ab302a3ec37b6d7", "README.md": "bdaeafc190ac7c8bde109937d37c9f0437b044c9be78dc9dabcb13a2cb56d13c",
"SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c", "SECURITY.md": "34e56cd9b8f6aa5fee45921c6eb831a542e05e76e41850fc31c44e09de088b3c",
"THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "THIRD_PARTY_NOTICES.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c", "android/README.md": "bb4387da9a055e97f33bb29a883c543e0938fa858df3fd744abc80553a5ec65c",
@@ -190,13 +190,13 @@
"windows/ConnectionHealthSelfTest.cs": "5a483194f754ad51366acd9df00554c8ceecaa5dadba73972c4922b72dc7e2fe", "windows/ConnectionHealthSelfTest.cs": "5a483194f754ad51366acd9df00554c8ceecaa5dadba73972c4922b72dc7e2fe",
"windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6", "windows/ConnectionRecoveryPolicy.cs": "860bd4cedf393f157fc1dd68e407776e1fe0fa1cc6cef7e99cd5581b64c6f5f6",
"windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc", "windows/ConnectionSelection.cs": "def94b338b9e1fd940c19b8991e4268a4e59bec741ea624f5a6e4fb7a7d3bbcc",
"windows/ConnectionSelectionSelfTest.cs": "12bd82071989c5e539031f6e7921660edb4eb10a4136ac332cc84eca2e2d96de", "windows/ConnectionSelectionSelfTest.cs": "0d8f131cf461648aa91651a9790924b6da9cedd1801ef44cc79852164bc9f0d5",
"windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3", "windows/ConnectionSelfTest.cs": "6ad3f227cec3e26514d833ec1cb996818597a0cb27901053362faa45e3c1c9b3",
"windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716", "windows/DailyTrafficChart.cs": "4af8d8a91559e6a3fc1dd56db11f3534606aeb486ff918b2b301db0b82e4c716",
"windows/DashboardControls.cs": "1be17efd73acec775aade94461e59c7255a988bd46d056ad8613fdc3e4bd126d", "windows/DashboardControls.cs": "d1ced56aa6e7b1a896fecaf23249adbd7c9c9ba7ba3f6ea20e171b9b96886d72",
"windows/DashboardInteractionSelfTest.cs": "ad4845d14b5b5db4d91a180f95536dd1093458fab86ec8767b74983891a456b4", "windows/DashboardInteractionSelfTest.cs": "ad4845d14b5b5db4d91a180f95536dd1093458fab86ec8767b74983891a456b4",
"windows/DashboardLayout.cs": "a07985d84c69ed68783068d847059452db889ee244a98d7ab4e02ace4a5528ba", "windows/DashboardLayout.cs": "e30bb9b0f3bc6038f482a4be7b3daab04f34a96a7d367a4ac47a29f692c981d7",
"windows/DashboardTailnetLayoutSelfTest.cs": "64ed480d434f673137c5edc5b2b1a5d51f8aa31f8440efb734c052a472bf81d6", "windows/DashboardTailnetLayoutSelfTest.cs": "ff632fc070ec04a4a47a350f2ba0d543c4895423f88db64f38b53519dc82cd47",
"windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f", "windows/DashboardWheelRouter.cs": "d903097a5febbff296febb65855dc10b4e056ea5bb54d2df71b5d1f0297dcc1f",
"windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61", "windows/GitReleasePolicySelfTest.cs": "9e49ba957ab15a5c23d889004b171856c3d523f98cecf10088df4fcd8b577c61",
"windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b", "windows/GitReleaseUpdater.cs": "dcd00a0feca6801aad4e346c7565d8bcd80b3fd24a4accbe5cd4643d04264b9b",
@@ -220,13 +220,14 @@
"windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c", "windows/LearningSyncCoordinatorSelfTest.cs": "471ec344130fe74d892c1115637bd98c517084fc309e982d4d11d3f0ee19403c",
"windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7", "windows/LearningTransportSelfTest.cs": "05dcfd3fcfc6f25e20612c020583eb6c36934c1b251e50e70fcd29501ad0efe7",
"windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a", "windows/MainForm.Chrome.cs": "30dc6520a44a5120c78c472c9fb053e2e4dea8e254b5531d04a5342964969c7a",
"windows/MainForm.Dashboard.cs": "1e081c6039eac155e87c057919d7381eecdc2388615b9d56f211de0e379386f4", "windows/MainForm.Compact.cs": "45599d3d795a14c031be051abff4b039480df5e6867aba57c3724488950d280d",
"windows/MainForm.Dashboard.cs": "0b8c2489483dd221d4b94f21f14058d8b4bda28a4326f89c8cc612c6dac05421",
"windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6", "windows/MainForm.Handover.cs": "4a914f4de335331f1f9d2397407328f17ae372e9119329e534af218555dc92e6",
"windows/MainForm.NextGeneration.cs": "b560218aed601359310e9ee57f9628d28432be046342748931253c22dbc2d8b5", "windows/MainForm.NextGeneration.cs": "b560218aed601359310e9ee57f9628d28432be046342748931253c22dbc2d8b5",
"windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3", "windows/MainForm.Selection.cs": "d872004a98fc634e40c5edebf85eac7f3dfbb62fad8cafaae66a5c8470cfdaf3",
"windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b", "windows/MainForm.TailnetTraffic.cs": "432ea16a7f5fe66006530b5b90af6eab59362a2b02685ec2130dadfd43c1652b",
"windows/MainForm.TransportSelection.cs": "92e1dd715f39cc40f217e65125d89747bb8c9bedf9a11f70bcd577926e75b995", "windows/MainForm.TransportSelection.cs": "92e1dd715f39cc40f217e65125d89747bb8c9bedf9a11f70bcd577926e75b995",
"windows/MainForm.cs": "0c202d8c136fc8ae5ed812582bff5d9177c14d009b27e47bd24f5ea518f8c9dd", "windows/MainForm.cs": "9bea6d7edfa294cb620398e0199379c91a2483fed5ddf882406292efe5f504e2",
"windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371", "windows/NOTICE.md": "8c862f2f6b71440616a887e6deb7444a1262cf7d9f144208cc04041c3f9a3371",
"windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46", "windows/NetworkHandover.cs": "b43548be0051cf92dfd332e537951e4b5083f2a123be8021994513bbc3748d46",
"windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73", "windows/NetworkHandoverSelfTest.cs": "681d0154dc0aa5f49d7ce1f3088b465eea3ed82571b464951df8d4c89cecdf73",
@@ -237,11 +238,12 @@
"windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc", "windows/NetworkRecoveryTool.cs": "2dec1406ca0719af3eacedf2d8f83659927c44bc4a1eaccc1babe84c0d3d99cc",
"windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3", "windows/NetworkRouteLease.cs": "0b57aa0e3499ec3f9f7f7a4c683cecca0f6d7f275734e126a5da4f7849cd7ae3",
"windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1", "windows/NextGenerationSelfTest.cs": "a92cbbf4c8ba0cde0ec12faf2e1cdbcd2c86f758d440d677471968569030f8f1",
"windows/NodeHealthProbe.cs": "c49e5cf6b3a62242ae0e486aa3fd267d50485269ec0bd769cf140e743850fec7", "windows/NodeHealthProbe.cs": "5c501094402010d2f8ecdc4145f1084ef084b749c2b47794fca0c0f60c4441fb",
"windows/NodeHealthProbeSelfTest.cs": "85d645160ed53f2646b58ba29d2ec17d6ff8fa54b658dc15e15c9609514c16ea",
"windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d", "windows/NodeMatrixSelfTest.cs": "eed8e56036d300fdffd82b83cca87ea6b2806e8598b2c4fc916aded15197f20d",
"windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0", "windows/NodePresentation.cs": "c70a8be06cce937f309fd10531d97b02b675a72509fff2419e412fbdf84977c0",
"windows/NodeTrafficMonitor.cs": "365c821eb9fc08f33e9387369c9f985f31992470214a5a13758f51dc3c84f0b8", "windows/NodeTrafficMonitor.cs": "6e04288302ebe2cad0e15fd77ea22e13fa8f06998af079a303e66a7fe1ae4170",
"windows/NodeTrafficSelfTest.cs": "33d7c8e16d23d19396f60e36d3204196e9499546022c09b3a8aaca9b957e01f2", "windows/NodeTrafficSelfTest.cs": "0d11d2d1c4b04f50449487af5948960f282c9b58651c233a06def5d93ce34b48",
"windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1", "windows/NodeTransportConnector.cs": "91d53471f35470fc9a4578e2819863e56a790cda62a7dbfe891a71149d2386e1",
"windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63", "windows/PhysicalUplink.cs": "b0a0eca6b9f724972d0e445c2dc352326ea4d7357317b98639972d60dadc2e63",
"windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b", "windows/PlatformBootstrapTransport.cs": "0eef4a4272449c0e2adfac2e4652bd9cff9c1b2bc11011ca2049dde2f97e4e2b",
@@ -250,18 +252,19 @@
"windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df", "windows/PrivateAuxiliaryRoutingSelfTest.cs": "8b2e867f562017e680def8f74c7fba972404442816abae7bf54fcab5d47339df",
"windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf", "windows/PrivateAuxiliaryRuntime.cs": "dcfb406508e3d7e9a9163163cfe5e2724a6955a18ae4604e2d9f890da61308cf",
"windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3", "windows/PrivateTransportProbe.cs": "e29e9bd0180a37bdcecf7104fde5069be799aca92b747881d0485a62d382d9b3",
"windows/Program.cs": "632a984e5c971b016a5f15b2ff1804b99cfd279661bd637a45f40dcd42e68ecd", "windows/Program.cs": "c5fba480cc2f8864862205a8beaf99e4daae15b90ac966ca768528a60ff6474f",
"windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0", "windows/ProxyDnsPolicy.cs": "997e2e922ad43956932c1bd0a6da3457bc308ee723f4f77ff8e52aa23fa954c0",
"windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec", "windows/ProxyProbe.cs": "5d27b5a6c6b192a0c0f3ec4637c5a876a71130497af57f7cb4a04ab4735ca1ec",
"windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a", "windows/PublicTailnetSelection.cs": "cdd6e9195e678bd29dcef96aa9d16ffac9bf42bfe1a10ef293aefd31a2c4a68a",
"windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0", "windows/PublicTailnetSelectionSelfTest.cs": "aed90554aa88aa7701eaccc925307a48d4a79e244c40d0c456b88f1207b540c0",
"windows/README.md": "7296f084849469b2420a091cbee1ed381986d95956dd79d94338b4b924167671", "windows/README.md": "5e4cff115fd3a8e2270d026ae9e37b913479ee620baa8350126819b2365e04af",
"windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1", "windows/ReplacementContinuitySelfTest.cs": "107878ab2b367f1812377c0b209f6d620da390091c3882e4be53a48e517d86a1",
"windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9", "windows/RouteLeaseSelfTest.cs": "6189c66b9f66c58bed26de4441c58a9ec02b67257bfa04ed66d702acfcd054d9",
"windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e", "windows/RoutingRuleBatches.cs": "9997bfa766fffe7bed7352f307c1f6f118a9be9aa86653eaefae3b2bdaa26c1e",
"windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d", "windows/RoutingUpdateSelfTest.cs": "48c99fc7a01037aa0368c53ccdb7eec0fea1edfac3bb2532c0de89631343206d",
"windows/ScenicTheme.cs": "da0ec888a65216b57f881cf5bbc2ed551a07363afae9f2b6a54f22c6502169c7", "windows/ScenicTheme.cs": "da0ec888a65216b57f881cf5bbc2ed551a07363afae9f2b6a54f22c6502169c7",
"windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277", "windows/SessionOperationFence.cs": "86e8dff164dc7f6f45ba3a41126b8e2e36af9de098479a08a9007604ff112277",
"windows/StartupLearningWarmup.cs": "137041f1c1f83147ce50b824208470832c58db775a9b72197d1d106316466f8b",
"windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013", "windows/StartupSelfTest.cs": "cb035bf5d22624ed5034b719f0c52a4c1527ace4c371e966f15f7c25c8126013",
"windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe", "windows/SystemPowerShell.cs": "1f9247d2e4f8c9bad1d71105886d2ab33d8958006dcff7fadc63f27502eda6fe",
"windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916", "windows/SystemProxy.cs": "beaf443f1e285e227e0c390d8e9114d5cf8464e0078a8bb842efa9eeb2b5e916",
@@ -272,7 +275,7 @@
"windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a", "windows/TailnetTransportProbe.cs": "c71a0d946cbefb2713e0b564ea95ae99cbd70f0ec19c8cfc416a12e16589f99a",
"windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3", "windows/TailnetTransportSelfTest.cs": "8ace8cc2f443c1ce576bbb9471cb46f107ac28f999090baa30431412d8a263f3",
"windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb", "windows/TokenStore.cs": "e07cf7d1a4cf7a1bba871c19e50b9d6355cb8c1546657346b0256c8215fed8bb",
"windows/TrafficChart.cs": "9b2b42761d9f636cd3be3d6015ce4eff73bf7c0645105c7679f1987b1f5571a0", "windows/TrafficChart.cs": "c7bd65735ffaaace1a8b5075e6e977d7449b481858f4130d42da70069c34c883",
"windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194", "windows/TunConfigBuilder.cs": "35a17b9da204e338dde5ed6cd4f2e979d94ad73c4c01cc0001fc582e94b67194",
"windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86", "windows/TunConnectivitySelfTest.cs": "a7d7aff1d03e45dff921807cbfb8f83b5013c9df5c7e06b6662d84a8686b2f86",
"windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1", "windows/TunRouting.cs": "c6b3e1070a0ba0a3c42dbd12becba55404e540d06aba03cb1cc1053fa426a4c1",
@@ -280,11 +283,11 @@
"windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771", "windows/UpdateSelfTest.cs": "453165bb611efb8db0d8a8c9ea13f3553e0047aa22b838c43096e3d83fe18771",
"windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1", "windows/UpdateStreamSelfTest.cs": "ad059016c0197f33582b1969ab3280c5b9589a28d659613b3e97ce4a357d38c1",
"windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069", "windows/UsageHistorySeries.cs": "9e7515ceede1899e06116352de79edd6252c921048bcae9958bf9358d93b3069",
"windows/VPNPlus.csproj": "cc59524a6a01f8a606bece97ae45ca6cf25f9fb5ec83b36372d68a0f02f76cab", "windows/VPNPlus.csproj": "6ace89a08e32b1527bcebf5d9406451ab4e00a8e0b2448a3dbf7290cfcbe9555",
"windows/VpnApiClient.cs": "187829698d9f26b896dbfef596bc71b12a9ed4e014261abde0497e6763e40ae3", "windows/VpnApiClient.cs": "187829698d9f26b896dbfef596bc71b12a9ed4e014261abde0497e6763e40ae3",
"windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c", "windows/WindowChrome.cs": "0eceea0879e792b8ae83a74eaf5658d4a7be6a798fbdb026ff8d19fa9aa6af2c",
"windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be", "windows/WindowChromeSelfTest.cs": "c17dd805a0102d12b71a3e32c77ceeb45e303e08612de5d3c5259c78327532be",
"windows/XrayManager.cs": "024178506c01a7fe6074c4a05973125338999862e3b52181a0a0ce7399209375", "windows/XrayManager.cs": "b6422093815b939b5a9c4cdbf7ba95fddeb6e32831e427aab074858606101146",
"windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5", "windows/XrayRoutingUpdater.cs": "91fd2b5db25477dbe4de7118faef79f9c51f9a8a3dd86e8b26c676092de3bca5",
"windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6", "windows/app.manifest": "4c9a2e8e2056c3bb0ae45a5f7b2e223298ee683a82b70ba4910e17f5728cf5b6",
"windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163", "windows/assets/company-logo-original.png": "04cf7f754a5353b96cddbed4a57a557154342c190a1785487e3bfb36cab04163",
@@ -304,6 +307,8 @@
"windows/build/OwnedProcessGroup.cs": "00fc73e00dbc25bdf5ff6557f0d81786ba1ef235822ea290bead9b8a5ac66618", "windows/build/OwnedProcessGroup.cs": "00fc73e00dbc25bdf5ff6557f0d81786ba1ef235822ea290bead9b8a5ac66618",
"windows/build/ProductionInstallationBaseline.ps1": "1079dcc459af2b217d7cbddb81d286888d1210f1069cada6272d3b79a531062a", "windows/build/ProductionInstallationBaseline.ps1": "1079dcc459af2b217d7cbddb81d286888d1210f1069cada6272d3b79a531062a",
"windows/build/ProductionNetworkBaseline.ps1": "aa3600f92ba19d3041b0c50696d1035efe68013dec7ae3f7973e75b5fc17f9b1", "windows/build/ProductionNetworkBaseline.ps1": "aa3600f92ba19d3041b0c50696d1035efe68013dec7ae3f7973e75b5fc17f9b1",
"windows/build/StartupLearningWarmupHarness.cs": "1d5266159f1e8426dafd2e035a85644d03a9ed15c9207e7cd629e0fc03a3e310",
"windows/build/StartupLearningWarmupHarness.csproj": "2fee8f47a9b6b3cffcee0689fae4960525a2beadad73c5c3a4146e292f30bee2",
"windows/build/Test-InstallerGuardianGate.ps1": "5289a4643cc41279eae8d32a7cfdabfdd528506b03cc9fadaf33880dea996694", "windows/build/Test-InstallerGuardianGate.ps1": "5289a4643cc41279eae8d32a7cfdabfdd528506b03cc9fadaf33880dea996694",
"windows/build/Test-ProductionInstallationBaseline.ps1": "7d5afbffd8e4ed595917fdc8054469cdf071cfe4c932955bb84840d867eec0f0", "windows/build/Test-ProductionInstallationBaseline.ps1": "7d5afbffd8e4ed595917fdc8054469cdf071cfe4c932955bb84840d867eec0f0",
"windows/build/Test-ProductionNetworkBaseline.ps1": "842d84027e8ec68e94ab860500a176b8d8f284b7ca0d4e55751d0e81818742ac", "windows/build/Test-ProductionNetworkBaseline.ps1": "842d84027e8ec68e94ab860500a176b8d8f284b7ca0d4e55751d0e81818742ac",
@@ -322,7 +327,8 @@
"windows/release/RELEASE-NOTES-0.2.22.md": "bf6c8b448481f59a05e8653fbaa1356d986d2d481c3cbaf02fe6402dcf55d499", "windows/release/RELEASE-NOTES-0.2.22.md": "bf6c8b448481f59a05e8653fbaa1356d986d2d481c3cbaf02fe6402dcf55d499",
"windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76", "windows/release/RELEASE-NOTES-0.2.23.md": "2f8aea1ec4d4f1bcc9860d8945dc6266be6ea924ff9958c589a6e4eb0550dc76",
"windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2", "windows/release/RELEASE-NOTES-0.3.0.md": "cc1e398354ffb562c0647dbe91ffd3f43e614f3923298005c76999c457b77bf2",
"windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132" "windows/release/RELEASE-NOTES-0.3.1.md": "e28a99d049842adc34f593e39bbc33484dd4dfc9e31568cbcb1aef1f3bcd4132",
"windows/release/RELEASE-NOTES-0.3.2.md": "29f2030b0be583a541dc0289ee9916d42156cf3bbd823bd5cf7867f097fb2abd"
}, },
"IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6", "IosSourceCommit": "b07d085413b1b6370245866fd82271b76590b6d6",
"Kind": "clean-history-free-open-source-export", "Kind": "clean-history-free-open-source-export",
@@ -557,5 +563,18 @@
"SourceOnly": true, "SourceOnly": true,
"Version": "0.3.1" "Version": "0.3.1"
}, },
"Windows032ConnectCompactDelta": {
"CandidateSha256": "85fac03989c71cbc61bdf756ac7e7194ac9cd003533c0aa6bc1c355eeb375813",
"FrozenSha256": "18d98d6e58c67ecf6d0293668eaeaa6946e2a2e7b879177f1410e7bf08503f7f",
"OptionalUnlicensedSceneRemainsOmitted": true,
"OriginalAcceptanceTransferred": false,
"OriginalSourceManifestSha256": "bf4a9f7360d2d44b11a8e94db881cc60d7234d2db7a3e89bffef0515ad244991",
"OtherComponentsModified": false,
"PrivateHistoryIncluded": false,
"ProductionAccepted": false,
"PublicBaseCommit": "1cf54a46e495d6f0f74b7b4b67e1786b2c51d5a2",
"SourceOnly": true,
"Version": "0.3.2"
},
"WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38" "WindowsSourceCommit": "0d463e6af91a3802c564b06dabb6bf86ebff5a38"
} }
+136 -120
View File
@@ -1,120 +1,136 @@
using System.Text.Json; using System.Text.Json;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal static class ConnectionSelectionSelfTest internal static class ConnectionSelectionSelfTest
{ {
internal static int Run() internal static int Run()
{ {
var checks = new Dictionary<string, bool>(); var checks = new Dictionary<string, bool>();
bool Rejected(Action action) bool Rejected(Action action)
{ {
try { action(); return false; } try { action(); return false; }
catch (InvalidOperationException) { return true; } catch (InvalidOperationException) { return true; }
} }
string[] authorized = ["office-test", "remote-test"]; string[] authorized = ["office-test", "remote-test"];
var auto = ConnectionSelection.Create(false, "office-test", authorized); var auto = ConnectionSelection.Create(false, "office-test", authorized);
checks["default_auto_ignores_previous_manual_choice"] = auto.NodeSlug == "auto" && !auto.Manual; checks["default_auto_ignores_previous_manual_choice"] = auto.NodeSlug == "auto" && !auto.Manual;
checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 8 && auto.Attempts(2) == 2; checks["auto_attempts_are_bounded"] = auto.Attempts(12) == 8 && auto.Attempts(2) == 2;
var manual = ConnectionSelection.Create(true, "office-test", authorized); var manual = ConnectionSelection.Create(true, "office-test", authorized);
checks["manual_uses_exact_authorized_node"] = manual.Manual && manual.NodeSlug == "office-test"; checks["manual_uses_exact_authorized_node"] = manual.Manual && manual.NodeSlug == "office-test";
checks["manual_has_no_fallback_attempt"] = manual.Attempts(12) == 1; checks["manual_has_no_fallback_attempt"] = manual.Attempts(12) == 1;
checks["missing_choice_rejected"] = Rejected(() => ConnectionSelection.Create(true, null, authorized)); checks["missing_choice_rejected"] = Rejected(() => ConnectionSelection.Create(true, null, authorized));
checks["removed_permission_rejected"] = Rejected(() => ConnectionSelection.Create(true, "removed", authorized)); checks["removed_permission_rejected"] = Rejected(() => ConnectionSelection.Create(true, "removed", authorized));
checks["manual_auto_slug_rejected"] = Rejected(() => ConnectionSelection.Create(true, "auto", ["auto"])); checks["manual_auto_slug_rejected"] = Rejected(() => ConnectionSelection.Create(true, "auto", ["auto"]));
checks["different_server_node_rejected"] = Rejected(() => manual.ValidateResponse("remote-test")); checks["different_server_node_rejected"] = Rejected(() => manual.ValidateResponse("remote-test"));
checks["empty_server_node_rejected"] = Rejected(() => auto.ValidateResponse("")); checks["empty_server_node_rejected"] = Rejected(() => auto.ValidateResponse(""));
checks["manual_exact_response_accepted"] = !Rejected(() => manual.ValidateResponse("office-test")); checks["manual_exact_response_accepted"] = !Rejected(() => manual.ValidateResponse("office-test"));
checks["auto_concrete_response_accepted"] = !Rejected(() => auto.ValidateResponse("remote-test")); checks["auto_concrete_response_accepted"] = !Rejected(() => auto.ValidateResponse("remote-test"));
var siteName = NodePresentation.Name(NodePresentation.JinanSlug, "济南(博翠明湖)", true); var siteName = NodePresentation.Name(NodePresentation.JinanSlug, "济南(博翠明湖)", true);
checks["private_connected_name_follows_registered_site"] = siteName == "济南(博翠明湖)"; checks["private_connected_name_follows_registered_site"] = siteName == "济南(博翠明湖)";
checks["legacy_private_empty_name_keeps_zero3_fallback"] = NodePresentation.Name(NodePresentation.JinanSlug, "", true) == NodePresentation.JinanName; checks["legacy_private_empty_name_keeps_zero3_fallback"] = NodePresentation.Name(NodePresentation.JinanSlug, "", true) == NodePresentation.JinanName;
checks["public_node_not_relabelled_as_zero3"] = NodePresentation.Name(NodePresentation.JinanSlug, "VPN002", false) == "VPN002"; checks["public_node_not_relabelled_as_zero3"] = NodePresentation.Name(NodePresentation.JinanSlug, "VPN002", false) == "VPN002";
checks["fallback_shows_actual_public_node"] = NodePresentation.Name("aliyun-tokyo-002", "VPN002", false) == "VPN002"; checks["fallback_shows_actual_public_node"] = NodePresentation.Name("aliyun-tokyo-002", "VPN002", false) == "VPN002";
checks["learning_keeps_connected_node_name"] = NodePresentation.LearningDetail(true, siteName, "规则已更新") == siteName + " · 规则已更新"; checks["learning_keeps_connected_node_name"] = NodePresentation.LearningDetail(true, siteName, "规则已更新") == siteName + " · 规则已更新";
checks["learning_after_fallback_names_public_node"] = NodePresentation.LearningDetail(true, "VPN002", "规则已更新") == "VPN002 · 规则已更新"; checks["learning_after_fallback_names_public_node"] = NodePresentation.LearningDetail(true, "VPN002", "规则已更新") == "VPN002 · 规则已更新";
checks["unconnected_selection_does_not_claim_actual_node"] = NodePresentation.LearningDetail(false, siteName, "正在验证") == "正在验证"; checks["unconnected_selection_does_not_claim_actual_node"] = NodePresentation.LearningDetail(false, siteName, "正在验证") == "正在验证";
checks["public_transport_has_no_suffix"] = NodePresentation.WithTransport("VPN002", false) == "VPN002"; checks["public_transport_has_no_suffix"] = NodePresentation.WithTransport("VPN002", false) == "VPN002";
checks["tailnet_transport_has_explicit_suffix"] = NodePresentation.WithTransport("VPN002", true) == "VPN002 + Tailscale"; checks["tailnet_transport_has_explicit_suffix"] = NodePresentation.WithTransport("VPN002", true) == "VPN002 + Tailscale";
checks["second_node_uses_same_transport_format"] = NodePresentation.WithTransport("VPN003", true) == "VPN003 + Tailscale"; checks["second_node_uses_same_transport_format"] = NodePresentation.WithTransport("VPN003", true) == "VPN003 + Tailscale";
using (var form = new MainForm(preview: true, uiOnly: true)) using (var form = new MainForm(preview: true, uiOnly: true))
foreach (var check in form.CheckSelectionUi()) checks.Add(check.Key, check.Value); foreach (var check in form.CheckSelectionUi()) checks.Add(check.Key, check.Value);
var passed = checks.Values.All(v => v); var passed = checks.Values.All(v => v);
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "connection-selection-self-test.json"), File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "connection-selection-self-test.json"),
JsonSerializer.Serialize(new { passed, network_modified = false, local_office_gateway_tested = false, checks }, JsonSerializer.Serialize(new { passed, network_modified = false, local_office_gateway_tested = false, checks },
new JsonSerializerOptions { WriteIndented = true })); new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 18; return passed ? 0 : 18;
} }
} }
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
internal Dictionary<string, bool> CheckSelectionUi() internal Dictionary<string, bool> CheckSelectionUi()
{ {
var result = new Dictionary<string, bool>(); var result = new Dictionary<string, bool>();
var profile = new Profile { Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }] }; var profile = new Profile { Nodes = [new() { Slug = "office-test", Name = "优创未来·济南办" }, new() { Slug = "remote-test", Name = "远程测试" }] };
_availableNodeCount = 2; _availableNodeCount = 2;
UpdateSelectionNodes(profile, false); UpdateSelectionNodes(profile, false);
result["ui_defaults_to_auto"] = !ManualSelection; result["ui_defaults_to_auto"] = !ManualSelection;
_connectionModeCombo.SelectedIndex = 1; _connectionModeCombo.SelectedIndex = 1;
_manualNodeCombo.SelectedIndex = 0; _manualNodeCombo.SelectedIndex = 0;
result["ui_manual_has_authorized_choices"] = ManualSelection && _manualNodeCombo.Items.Count == 2; result["ui_manual_has_authorized_choices"] = ManualSelection && _manualNodeCombo.Items.Count == 2;
SetBusy(true); SetBusy(true);
result["ui_locked_during_connect"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; result["ui_locked_during_connect"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled;
SetBusy(false); SetBusy(false);
_wantConnected = true; _wantConnected = true;
RefreshSelectionControls(); RefreshSelectionControls();
result["ui_locked_during_connection_or_recovery"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled; result["ui_locked_during_connection_or_recovery"] = !_connectionModeCombo.Enabled && !_manualNodeCombo.Enabled;
_wantConnected = false; _wantConnected = false;
RefreshSelectionControls(); RefreshSelectionControls();
result["ui_editable_after_disconnect"] = _connectionModeCombo.Enabled && _manualNodeCombo.Enabled; result["ui_editable_after_disconnect"] = _connectionModeCombo.Enabled && _manualNodeCombo.Enabled;
UpdateSelectionNodes(profile, true); UpdateSelectionNodes(profile, true);
result["profile_refresh_keeps_exact_manual_choice"] = (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug == "office-test"; result["profile_refresh_keeps_exact_manual_choice"] = (_manualNodeCombo.SelectedItem as NodeInfo)?.Slug == "office-test";
UpdateSelectionNodes(new Profile { Nodes = [profile.Nodes[1]] }, true); UpdateSelectionNodes(new Profile { Nodes = [profile.Nodes[1]] }, true);
result["removed_node_not_silently_replaced"] = ManualSelection && _manualNodeCombo.SelectedItem is null; result["removed_node_not_silently_replaced"] = ManualSelection && _manualNodeCombo.SelectedItem is null;
UpdateSelectionNodes(profile, false); UpdateSelectionNodes(profile, false);
result["new_login_resets_to_auto"] = !ManualSelection && _manualNodeCombo.SelectedItem is null; result["new_login_resets_to_auto"] = !ManualSelection && _manualNodeCombo.SelectedItem is null;
var nodeCount = _manualNodeCombo.Items.Count; var nodeCount = _manualNodeCombo.Items.Count;
_currentNodeSlug = "office-test"; _currentNodeSlug = "office-test";
_currentNodeBaseName = "VPN002"; _currentNodeBaseName = "VPN002";
_currentNodeIsPrivateAuxiliary = false; _currentNodeIsPrivateAuxiliary = false;
UpdateConnectedTransportPresentation(false); UpdateConnectedTransportPresentation(false);
result["connected_public_name_is_plain_node"] = _currentNodeName == "VPN002" && !_currentNodeUsesTailnet; result["connected_public_name_is_plain_node"] = _currentNodeName == "VPN002" && !_currentNodeUsesTailnet;
UpdateConnectedTransportPresentation(true); UpdateConnectedTransportPresentation(true);
result["connected_tailnet_name_marks_actual_transport"] = _currentNodeName == "VPN002 + Tailscale" && _currentNodeUsesTailnet; result["connected_tailnet_name_marks_actual_transport"] = _currentNodeName == "VPN002 + Tailscale" && _currentNodeUsesTailnet;
UpdateConnectedTransportPresentation(true); UpdateConnectedTransportPresentation(true);
result["tailnet_refresh_does_not_duplicate_suffix"] = _currentNodeName == "VPN002 + Tailscale"; result["tailnet_refresh_does_not_duplicate_suffix"] = _currentNodeName == "VPN002 + Tailscale";
UpdateConnectedTransportPresentation(false); UpdateConnectedTransportPresentation(false);
result["tailnet_fallback_removes_suffix_keeps_node"] = _currentNodeName == "VPN002" && _currentNodeSlug == "office-test" && !_currentNodeUsesTailnet; result["tailnet_fallback_removes_suffix_keeps_node"] = _currentNodeName == "VPN002" && _currentNodeSlug == "office-test" && !_currentNodeUsesTailnet;
result["transport_does_not_duplicate_node_choices"] = _manualNodeCombo.Items.Count == nodeCount && nodeCount == 2; result["transport_does_not_duplicate_node_choices"] = _manualNodeCombo.Items.Count == nodeCount && nodeCount == 2;
_currentNodeIsPrivateAuxiliary = true; _currentNodeIsPrivateAuxiliary = true;
_currentNodeBaseName = NodePresentation.JinanName; _currentNodeBaseName = NodePresentation.JinanName;
UpdateConnectedTransportPresentation(true); UpdateConnectedTransportPresentation(true);
result["private_tailnet_connection_shows_actual_transport"] = _currentNodeName == NodePresentation.JinanName + " + Tailscale" && _currentNodeUsesTailnet; result["private_tailnet_connection_shows_actual_transport"] = _currentNodeName == NodePresentation.JinanName + " + Tailscale" && _currentNodeUsesTailnet;
_currentNodeBaseName = null; _currentNodeBaseName = null;
UpdateConnectedTransportPresentation(false); UpdateConnectedTransportPresentation(false);
result["cleared_connection_does_not_claim_tailnet"] = _currentNodeName is null && !_currentNodeUsesTailnet; result["cleared_connection_does_not_claim_tailnet"] = _currentNodeName is null && !_currentNodeUsesTailnet;
// Exercise real dashboard layout, not the hidden login page's stale bounds. // Exercise real dashboard layout, not the hidden login page's stale bounds.
Opacity = 0; Opacity = 0;
ShowInTaskbar = false; ShowInTaskbar = false;
Show(); Show();
ShowDashboard(profile); ShowDashboard(profile);
_refreshTimer.Stop(); _refreshTimer.Stop();
PerformLayout(); PerformLayout();
Application.DoEvents(); Application.DoEvents();
_currentNodeName = NodePresentation.JinanName; _currentNodeName = NodePresentation.JinanName;
_currentNodeLabel.Text = _currentNodeName; _currentNodeLabel.Text = _currentNodeName;
SetConnectionState(true, "已安全连接", _currentNodeName); SetConnectionState(true, "已安全连接", _currentNodeName);
LayoutDashboard(); LayoutDashboard();
result["connected_node_gets_full_width"] = _currentNodeLabel.Right == _nodeCard.Width - ScaleLogical(14); var fullConnectedRow = true;
result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible; foreach (var (size, label) in new[] { (new Size(480, 360), "compact"), (new Size(960, 720), "wide") })
result["zero3_name_fits_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; {
Size = MinimumSize; ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
PerformLayout(); PerformLayout(); LayoutDashboard(); Application.DoEvents();
LayoutDashboard(); var rightInset = _nodeCard.ClientSize.Width - _currentNodeLabel.Right;
Application.DoEvents(); // The node keeps the available row, with only a small edge inset.
result["zero3_name_fits_compact_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width; // Exact decorative padding can differ between compact and wide UI.
RequestExit(); var usesRow = _currentNodeLabel.Visible && _currentNodeLabel.Left >= 0
return result; && rightInset >= 0 && rightInset <= ScaleLogical(16)
} && _currentNodeLabel.Width >= _nodeCard.ClientSize.Width * .75;
} result["connected_node_full_row_" + label] = usesRow;
result["connected_node_name_fits_" + label] = TextRenderer.MeasureText(_currentNodeName,
_currentNodeLabel.Font).Width <= _currentNodeLabel.Width;
fullConnectedRow &= usesRow;
}
result["connected_node_gets_full_width"] = fullConnectedRow;
result["connected_mode_badge_does_not_cover_name"] = !_scheduleBadge.Visible;
result["zero3_name_fits_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width;
Size = MinimumSize;
PerformLayout();
LayoutDashboard();
Application.DoEvents();
result["zero3_name_fits_compact_connected_row"] = TextRenderer.MeasureText(_currentNodeName, _currentNodeLabel.Font).Width <= _currentNodeLabel.Width;
RequestExit();
return result;
}
}
+185 -177
View File
@@ -1,177 +1,185 @@
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal enum DashboardIcon { Server, Settings, Database, Upload, Download, Document, Chart, History, Shield } internal enum DashboardIcon { Server, Settings, Database, Upload, Download, Document, Chart, History, Shield }
// Code-drawn icons keep the existing brand assets and remain crisp at high DPI. // Code-drawn icons keep the existing brand assets and remain crisp at high DPI.
internal static class DashboardDrawing internal static class DashboardDrawing
{ {
internal static void Icon(Graphics g, DashboardIcon icon, Rectangle bounds, Color color) internal static void Icon(Graphics g, DashboardIcon icon, Rectangle bounds, Color color)
{ {
var state = g.Save(); var state = g.Save();
g.SmoothingMode = SmoothingMode.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias;
g.TranslateTransform(bounds.Left, bounds.Top); g.TranslateTransform(bounds.Left, bounds.Top);
g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f); g.ScaleTransform(bounds.Width / 24f, bounds.Height / 24f);
using var pen = new Pen(color, 1.8f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }; using var pen = new Pen(color, 1.8f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round };
switch (icon) switch (icon)
{ {
case DashboardIcon.Server: case DashboardIcon.Server:
g.DrawRectangle(pen, 2, 3, 20, 7); g.DrawRectangle(pen, 2, 14, 20, 7); g.DrawRectangle(pen, 2, 3, 20, 7); g.DrawRectangle(pen, 2, 14, 20, 7);
g.DrawLine(pen, 6, 6, 6, 7); g.DrawLine(pen, 6, 17, 6, 18); g.DrawLine(pen, 6, 6, 6, 7); g.DrawLine(pen, 6, 17, 6, 18);
g.DrawLine(pen, 15, 6.5f, 18, 6.5f); g.DrawLine(pen, 15, 17.5f, 18, 17.5f); break; g.DrawLine(pen, 15, 6.5f, 18, 6.5f); g.DrawLine(pen, 15, 17.5f, 18, 17.5f); break;
case DashboardIcon.Settings: case DashboardIcon.Settings:
g.DrawEllipse(pen, 5, 5, 14, 14); g.DrawEllipse(pen, 9, 9, 6, 6); g.DrawEllipse(pen, 5, 5, 14, 14); g.DrawEllipse(pen, 9, 9, 6, 6);
for (var i = 0; i < 8; i++) { var a = i * Math.PI / 4; g.DrawLine(pen, 12 + (float)Math.Cos(a) * 8, 12 + (float)Math.Sin(a) * 8, 12 + (float)Math.Cos(a) * 10, 12 + (float)Math.Sin(a) * 10); } break; for (var i = 0; i < 8; i++) { var a = i * Math.PI / 4; g.DrawLine(pen, 12 + (float)Math.Cos(a) * 8, 12 + (float)Math.Sin(a) * 8, 12 + (float)Math.Cos(a) * 10, 12 + (float)Math.Sin(a) * 10); } break;
case DashboardIcon.Database: case DashboardIcon.Database:
g.DrawEllipse(pen, 3, 3, 18, 6); g.DrawLine(pen, 3, 6, 3, 18); g.DrawLine(pen, 21, 6, 21, 18); g.DrawEllipse(pen, 3, 3, 18, 6); g.DrawLine(pen, 3, 6, 3, 18); g.DrawLine(pen, 21, 6, 21, 18);
g.DrawArc(pen, 3, 9, 18, 6, 0, 180); g.DrawArc(pen, 3, 15, 18, 6, 0, 180); break; g.DrawArc(pen, 3, 9, 18, 6, 0, 180); g.DrawArc(pen, 3, 15, 18, 6, 0, 180); break;
case DashboardIcon.Upload: case DashboardIcon.Upload:
case DashboardIcon.Download: case DashboardIcon.Download:
var up = icon == DashboardIcon.Upload; var up = icon == DashboardIcon.Upload;
g.DrawLine(pen, 12, 3, 12, 16); g.DrawLine(pen, 12, 3, 12, 16);
g.DrawLines(pen, up ? [new PointF(7, 8), new(12, 3), new(17, 8)] : [new PointF(7, 11), new(12, 16), new(17, 11)]); g.DrawLines(pen, up ? [new PointF(7, 8), new(12, 3), new(17, 8)] : [new PointF(7, 11), new(12, 16), new(17, 11)]);
g.DrawLines(pen, [new PointF(3, 16), new(3, 21), new(21, 21), new(21, 16)]); break; g.DrawLines(pen, [new PointF(3, 16), new(3, 21), new(21, 21), new(21, 16)]); break;
case DashboardIcon.Document: case DashboardIcon.Document:
g.DrawLines(pen, [new PointF(5, 2), new(15, 2), new(20, 7), new(20, 22), new(5, 22), new(5, 2)]); g.DrawLines(pen, [new PointF(5, 2), new(15, 2), new(20, 7), new(20, 22), new(5, 22), new(5, 2)]);
g.DrawLines(pen, [new PointF(15, 2), new(15, 7), new(20, 7)]); g.DrawLines(pen, [new PointF(15, 2), new(15, 7), new(20, 7)]);
g.DrawLine(pen, 9, 12, 16, 12); g.DrawLine(pen, 9, 16, 16, 16); break; g.DrawLine(pen, 9, 12, 16, 12); g.DrawLine(pen, 9, 16, 16, 16); break;
case DashboardIcon.Chart: case DashboardIcon.Chart:
for (var i = 0; i < 4; i++) g.DrawLine(pen, 4 + i * 5, 21, 4 + i * 5, 16 - i * 4); break; for (var i = 0; i < 4; i++) g.DrawLine(pen, 4 + i * 5, 21, 4 + i * 5, 16 - i * 4); break;
case DashboardIcon.History: case DashboardIcon.History:
g.DrawArc(pen, 2, 2, 20, 20, -85, 350); g.DrawLine(pen, 12, 2, 12, 12); g.DrawLine(pen, 12, 12, 22, 12); break; g.DrawArc(pen, 2, 2, 20, 20, -85, 350); g.DrawLine(pen, 12, 2, 12, 12); g.DrawLine(pen, 12, 12, 22, 12); break;
case DashboardIcon.Shield: case DashboardIcon.Shield:
using (var shield = new GraphicsPath()) using (var shield = new GraphicsPath())
{ {
shield.AddLines([new PointF(12, 1), new(22, 5), new(22, 12)]); shield.AddLines([new PointF(12, 1), new(22, 5), new(22, 12)]);
shield.AddBezier(22, 12, 22, 18, 15, 22, 12, 24); shield.AddBezier(22, 12, 22, 18, 15, 22, 12, 24);
shield.AddBezier(12, 24, 9, 22, 2, 18, 2, 12); shield.AddBezier(12, 24, 9, 22, 2, 18, 2, 12);
shield.AddLine(2, 12, 2, 5); shield.CloseFigure(); shield.AddLine(2, 12, 2, 5); shield.CloseFigure();
using var fill = new LinearGradientBrush(new Point(2, 2), new Point(22, 24), Color.FromArgb(100, color), color); using var fill = new LinearGradientBrush(new Point(2, 2), new Point(22, 24), Color.FromArgb(100, color), color);
g.FillPath(fill, shield); g.FillPath(fill, shield);
} }
using (var check = new Pen(Color.White, 2.4f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round }) using (var check = new Pen(Color.White, 2.4f) { StartCap = LineCap.Round, EndCap = LineCap.Round, LineJoin = LineJoin.Round })
g.DrawLines(check, [new PointF(7, 12), new(10.5f, 15.5f), new(17, 9)]); g.DrawLines(check, [new PointF(7, 12), new(10.5f, 15.5f), new(17, 9)]);
break; break;
} }
g.Restore(state); g.Restore(state);
} }
} }
internal sealed class DashboardGlyph : Control internal sealed class DashboardGlyph : Control
{ {
internal DashboardIcon Glyph { get; set; } internal DashboardIcon Glyph { get; set; }
internal DashboardGlyph(DashboardIcon glyph) { Glyph = glyph; DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; ForeColor = Brand.RoyalBlue; } internal DashboardGlyph(DashboardIcon glyph) { Glyph = glyph; DoubleBuffered = true; SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; ForeColor = Brand.RoyalBlue; }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
base.OnPaint(e); base.OnPaint(e);
var side = Math.Min(Width, Height) - 4; var side = Math.Min(Width, Height) - 4;
if (side > 0) DashboardDrawing.Icon(e.Graphics, Glyph, new((Width - side) / 2, (Height - side) / 2, side, side), ForeColor); if (side > 0) DashboardDrawing.Icon(e.Graphics, Glyph, new((Width - side) / 2, (Height - side) / 2, side, side), ForeColor);
} }
} }
internal sealed class BrandHeaderPanel : Panel internal sealed class BrandHeaderPanel : Panel
{ {
internal BrandHeaderPanel() { DoubleBuffered = true; ResizeRedraw = true; } internal BrandHeaderPanel() { DoubleBuffered = true; ResizeRedraw = true; }
protected override void OnPaintBackground(PaintEventArgs e) protected override void OnPaintBackground(PaintEventArgs e)
{ {
ScenicTheme.Backdrop(e.Graphics, ClientSize, DeviceDpi, header: true); ScenicTheme.Backdrop(e.Graphics, ClientSize, DeviceDpi, header: true);
} }
} }
internal sealed class MetricCard : CardPanel internal sealed class MetricCard : CardPanel
{ {
internal DashboardIcon Glyph { get; } internal DashboardIcon Glyph { get; }
internal string Heading { get; } internal string Heading { get; }
internal string ValueText { get; private set; } = "—"; internal string ValueText { get; private set; } = "—";
internal string UnitText { get; private set; } = ""; internal string UnitText { get; private set; } = "";
internal string Hint { get; private set; } = "仅代理流量"; internal string Hint { get; private set; } = "仅代理流量";
internal MetricCard(string heading, DashboardIcon glyph) { Heading = heading; Glyph = glyph; AccessibleName = heading; } internal MetricCard(string heading, DashboardIcon glyph) { Heading = heading; Glyph = glyph; AccessibleName = heading; }
internal void SetBytes(double? bytes, bool speed = false, string? hint = null) internal void SetBytes(double? bytes, bool speed = false, string? hint = null)
{ {
string[] units = ["B", "KB", "MB", "GB", "TB"]; string[] units = ["B", "KB", "MB", "GB", "TB"];
var value = bytes.HasValue && double.IsFinite(bytes.Value) ? Math.Max(0, bytes.Value) : (double?)null; var value = bytes.HasValue && double.IsFinite(bytes.Value) ? Math.Max(0, bytes.Value) : (double?)null;
var unit = 0; var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
ValueText = value.HasValue ? (value == 0 ? "0" : value.Value.ToString("0.##")) : "—"; ValueText = value.HasValue ? (value == 0 ? "0" : value.Value.ToString("0.##")) : "—";
UnitText = value.HasValue ? units[unit] + (speed ? "/s" : "") : ""; UnitText = value.HasValue ? units[unit] + (speed ? "/s" : "") : "";
Hint = hint ?? "仅代理流量"; Hint = hint ?? "仅代理流量";
AccessibleDescription = $"{Heading} {ValueText} {UnitText},{Hint}"; AccessibleDescription = $"{Heading} {ValueText} {UnitText},{Hint}";
Invalidate(); Invalidate();
} }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
base.OnPaint(e); base.OnPaint(e);
var s = DeviceDpi / 96f; var s = DeviceDpi / 96f;
int S(int n) => (int)Math.Round(n * s); int S(int n) => (int)Math.Round(n * s);
var g = e.Graphics; var g = e.Graphics;
var narrow = Width < S(180); if(Height<S(30))
var shortCard = Height < S(75); {
if (!narrow) DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue); using var denseFont=Brand.Font(8,FontStyle.Bold);
var x = S(narrow ? 8 : 49); var right = Width - S(8); var available = Math.Max(1, right - x); var arrow=Glyph==DashboardIcon.Download?"↓":"↑";
using var headingFont = Brand.Font(shortCard || narrow ? 8 : 9); TextRenderer.DrawText(g,$"{arrow} {ValueText} {UnitText}",denseFont,ClientRectangle,Brand.Navy,
using var unitFont = Brand.Font(shortCard || narrow ? 8 : 9); ChartAxis.PaintFlags|TextFormatFlags.VerticalCenter|TextFormatFlags.HorizontalCenter|TextFormatFlags.SingleLine|TextFormatFlags.EndEllipsis);
using var hintFont = Brand.Font(7.2f); return;
var paintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping; }
var headingHeight = Math.Min(S(22), Math.Max(S(14), Height / 3)); var narrow = Width < S(180);
TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, 0, available, headingHeight), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); var shortCard = Height < S(75);
var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine | paintFlags; if (!narrow) DashboardDrawing.Icon(g, Glyph, new(S(10), S(18), S(22), S(22)), Glyph == DashboardIcon.Download ? Brand.Cyan : Brand.RoyalBlue);
var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width; var x = S(narrow ? 8 : 49); var right = Width - S(8); var available = Math.Max(1, right - x);
var size = shortCard ? 17f : 22f; using var headingFont = Brand.Font(Width<S(180)?6.8f:shortCard?8:9);
Font valueFont; using var unitFont = Brand.Font(Width<S(180)?6.8f:shortCard?8:9);
while (true) using var hintFont = Brand.Font(7.2f);
{ var paintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
valueFont = Brand.Font(size, FontStyle.Bold); var headingHeight = Math.Min(S(22), Math.Max(S(14), Height / 3));
if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 10) break; TextRenderer.DrawText(g, Heading, headingFont, new Rectangle(x, 0, available, headingHeight), Brand.Text, paintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
valueFont.Dispose(); size--; var flags = TextFormatFlags.NoPadding | TextFormatFlags.SingleLine | paintFlags;
} var unitWidth = TextRenderer.MeasureText(g, UnitText, unitFont, Size.Empty, flags).Width;
using (valueFont) var size = shortCard ? 17f : 22f;
{ Font valueFont;
var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width; while (true)
var valueHeight = Math.Max(1, Height - headingHeight - (shortCard ? 0 : S(18))); {
TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, headingHeight, Math.Max(1, available - unitWidth - S(4)), valueHeight), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); valueFont = Brand.Font(size, FontStyle.Bold);
TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + Math.Min(valueWidth, available - unitWidth - S(4)) + S(4), headingHeight, unitWidth, valueHeight), Brand.Muted, flags | TextFormatFlags.VerticalCenter); if (TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width + unitWidth + S(5) <= available || size <= 10) break;
} valueFont.Dispose(); size--;
if (!shortCard) TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, Height - S(17), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis); }
} using (valueFont)
} {
var valueWidth = TextRenderer.MeasureText(g, ValueText, valueFont, Size.Empty, flags).Width;
internal sealed class BadgeLabel : Label var valueHeight = Math.Max(1, Height - headingHeight - (shortCard ? 0 : S(18)));
{ TextRenderer.DrawText(g, ValueText, valueFont, new Rectangle(x, headingHeight, Math.Max(1, available - unitWidth - S(4)), valueHeight), Brand.Navy, flags | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
internal BadgeLabel() { DoubleBuffered = true; ResizeRedraw = true; } TextRenderer.DrawText(g, UnitText, unitFont, new Rectangle(x + Math.Min(valueWidth, available - unitWidth - S(4)) + S(4), headingHeight, unitWidth, valueHeight), Brand.Muted, flags | TextFormatFlags.VerticalCenter);
protected override void OnPaint(PaintEventArgs e) }
{ if (!shortCard) TextRenderer.DrawText(g, Hint, hintFont, new Rectangle(x, Height - S(17), available, S(17)), Brand.Muted, paintFlags | TextFormatFlags.EndEllipsis);
if (Width < 4 || Height < 4) return; }
if (Parent is { } parent) }
{
var state = e.Graphics.Save(); internal sealed class BadgeLabel : Label
e.Graphics.TranslateTransform(-Left, -Top); {
InvokePaintBackground(parent, new PaintEventArgs(e.Graphics, parent.ClientRectangle)); internal BadgeLabel() { DoubleBuffered = true; ResizeRedraw = true; }
e.Graphics.Restore(state); protected override void OnPaint(PaintEventArgs e)
} {
else e.Graphics.Clear(Brand.Surface); if (Width < 4 || Height < 4) return;
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; if (Parent is { } parent)
using var path = UiGeometry.RoundedRectangle(new(0, 0, Width - 1, Height - 1), (Height - 1) / 2); {
using var fill = new SolidBrush(BackColor); var state = e.Graphics.Save();
e.Graphics.FillPath(fill, path); e.Graphics.TranslateTransform(-Left, -Top);
TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, ForeColor, InvokePaintBackground(parent, new PaintEventArgs(e.Graphics, parent.ClientRectangle));
TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); e.Graphics.Restore(state);
} }
} else e.Graphics.Clear(Brand.Surface);
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
internal sealed class ReadOnlyModeLabel : Control using var path = UiGeometry.RoundedRectangle(new(0, 0, Width - 1, Height - 1), (Height - 1) / 2);
{ using var fill = new SolidBrush(BackColor);
internal ReadOnlyModeLabel() { DoubleBuffered = true; ResizeRedraw = true; BackColor = Color.White; Font = Brand.Font(9.5f); AccessibleName = "当前代理模式(连接中不可修改)"; } e.Graphics.FillPath(fill, path);
protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); } TextRenderer.DrawText(e.Graphics, Text, Font, ClientRectangle, ForeColor,
protected override void OnPaint(PaintEventArgs e) TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
{ }
if (Width < 10 || Height < 10) return; }
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(3, DeviceDpi / 24)); internal sealed class ReadOnlyModeLabel : Control
using var border = new Pen(Color.FromArgb(204, 219, 237)); {
e.Graphics.DrawPath(border, path); internal ReadOnlyModeLabel() { DoubleBuffered = true; ResizeRedraw = true; BackColor = Color.White; Font = Brand.Font(9.5f); AccessibleName = "当前代理模式(连接中不可修改)"; }
var pad = DeviceDpi / 12; protected override void OnTextChanged(EventArgs e) { base.OnTextChanged(e); Invalidate(); }
TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(pad, 0, Width - pad * 2, Height), Brand.Text, protected override void OnPaint(PaintEventArgs e)
TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); {
} if (Width < 10 || Height < 10) return;
} e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
using var path = UiGeometry.RoundedRectangle(new(1, 1, Width - 3, Height - 3), Math.Max(3, DeviceDpi / 24));
using var border = new Pen(Color.FromArgb(204, 219, 237));
e.Graphics.DrawPath(border, path);
var pad = DeviceDpi / 12;
TextRenderer.DrawText(e.Graphics, Text, Font, new Rectangle(pad, 0, Width - pad * 2, Height), Brand.Text,
TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis);
}
}
+127 -84
View File
@@ -1,84 +1,127 @@
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal readonly record struct DashboardGeometry( internal readonly record struct DashboardGeometry(
Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge, Rectangle WelcomeLabel, Rectangle AccountLabel, Rectangle IdentityBadge,
Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard, Rectangle LogoutButton, Rectangle StatusCard, Rectangle NodeCard, Rectangle ModeCard,
Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer, Rectangle[] Metrics, Rectangle TrafficCard, Rectangle TailnetTrafficCard, Rectangle SpeedTrendCard, Rectangle DailyCard, Rectangle ServerTrafficCard, Rectangle Footer,
int ContentHeight, bool Compact, float VerticalScale); int ContentHeight, bool Compact, float VerticalScale);
// Logical pixels converted once, independent of WinForms autoscaling. // Logical pixels converted once, independent of WinForms autoscaling.
internal static class DashboardLayout internal static class DashboardLayout
{ {
internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false) internal static DashboardGeometry Calculate(Size viewport, int dpi, bool showTailnet = false, bool showServerTraffic = false, bool preferCompact = false)
{ {
var scale = Math.Max(1f, dpi / 96f); if (preferCompact || viewport.Width < 720f * dpi / 96f || viewport.Height < 442f * dpi / 96f) return CalculateCompact(viewport, dpi, showTailnet, showServerTraffic);
int S(int n) => (int)Math.Round(n * scale); var scale = Math.Max(1f, dpi / 96f);
// Tailnet is a subdivision of the existing speed area, not another int S(int n) => (int)Math.Round(n * scale);
// dashboard row. Fit the complete canvas even on a small/high-DPI screen. // Tailnet is a subdivision of the existing speed area, not another
var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / ((showServerTraffic ? 718f : 614f) * scale)); // dashboard row. Fit the complete canvas even on a small/high-DPI screen.
int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale)); var verticalScale = Math.Min(1f, Math.Max(1, viewport.Height) / ((showServerTraffic ? 718f : 614f) * scale));
var margin = S(20); int Y(int n) => Math.Max(1, (int)Math.Floor(n * scale * verticalScale));
var gap = Y(10); var margin = S(20);
var columnGap = S(10); var gap = Y(10);
var width = Math.Max(1, viewport.Width - margin * 2); var columnGap = S(10);
var compact = width < S(720); var width = Math.Max(1, viewport.Width - margin * 2);
var half = (width - columnGap) / 2; var compact = width < S(720);
var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30)); var half = (width - columnGap) / 2;
var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24)); var welcome = new Rectangle(margin, Y(8), width - S(132), Y(30));
var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23)); var account = new Rectangle(margin, Y(38), Math.Min(S(275), width - S(230)), Y(24));
var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34)); var identity = new Rectangle(account.Right + S(10), Y(38), S(92), Y(23));
var status = new Rectangle(margin, Y(72), width, Y(76)); var logout = new Rectangle(margin + width - S(104), Y(16), S(104), Y(34));
var node = new Rectangle(margin, status.Bottom + gap, half, Y(72)); var status = new Rectangle(margin, Y(72), width, Y(76));
var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height); var node = new Rectangle(margin, status.Bottom + gap, half, Y(72));
var analyticsTop = mode.Bottom + gap; var mode = new Rectangle(node.Right + columnGap, node.Top, width - half - columnGap, node.Height);
var analyticsHeight = Y(276); var analyticsTop = mode.Bottom + gap;
var leftHeight = showTailnet ? (analyticsHeight - gap) / 2 : analyticsHeight; var analyticsHeight = Y(276);
var traffic = new Rectangle(margin, analyticsTop, half, leftHeight); var trendHeight = Y(120);
var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, analyticsHeight - leftHeight - gap) : Rectangle.Empty; var figuresHeight = analyticsHeight - trendHeight - gap;
var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight); var leftHeight = showTailnet ? (figuresHeight - gap) / 2 : figuresHeight;
Rectangle Metric(Rectangle parent, int column, bool speed) => new( var traffic = new Rectangle(margin, analyticsTop, half, leftHeight);
S(10) + column * ((parent.Width - S(20)) / 2), var tailnet = showTailnet ? new Rectangle(traffic.Left, traffic.Bottom + gap, half, figuresHeight - leftHeight - gap) : Rectangle.Empty;
speed ? Math.Max(Y(38), (parent.Height - Y(82)) / 2) : Y(40), var trend = new Rectangle(margin, analyticsTop + figuresHeight + gap, half, trendHeight);
(parent.Width - S(20)) / 2 - S(1), var daily = new Rectangle(traffic.Right + columnGap, analyticsTop, width - half - columnGap, analyticsHeight);
speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82)); Rectangle Metric(Rectangle parent, int column, bool speed) => new(
// Relative to their matching chart card: totals together; speeds together. S(10) + column * ((parent.Width - S(20)) / 2),
Rectangle[] metrics = [Metric(daily, 0, false), Metric(traffic, 0, true), Metric(traffic, 1, true), Metric(daily, 1, false)]; speed ? Math.Max(Y(38), (parent.Height - Y(82)) / 2) : Y(40),
var serverTraffic = showServerTraffic ? new Rectangle(margin, daily.Bottom + gap, width, Y(94)) : Rectangle.Empty; (parent.Width - S(20)) / 2 - S(1),
var footer = new Rectangle(margin, (showServerTraffic ? serverTraffic.Bottom : daily.Bottom) + gap, width, Y(76)); speed ? Math.Min(Y(82), parent.Height - Y(44)) : Y(82));
return new(welcome, account, identity, logout, status, node, mode, metrics, traffic, // Relative to their matching chart card: totals together; speeds together.
tailnet, daily, serverTraffic, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale); Rectangle Total(int row) => new(S(14), Y(40 + row * 112), daily.Width - S(28), Y(98));
} Rectangle[] metrics = [Total(0), Metric(traffic, 0, true), Metric(traffic, 1, true), Total(1)];
var serverTraffic = showServerTraffic ? new Rectangle(margin, daily.Bottom + gap, width, Y(94)) : Rectangle.Empty;
internal static bool SelfTest() var footer = new Rectangle(margin, (showServerTraffic ? serverTraffic.Bottom : daily.Bottom) + gap, width, Y(76));
{ return new(welcome, account, identity, logout, status, node, mode, metrics, traffic,
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288, 336, 384 }) tailnet, trend, daily, serverTraffic, footer, Math.Min(viewport.Height, footer.Bottom + Y(12)), compact, verticalScale);
foreach (var width in new[] { 600, 620, 739, 760, 780, 900, 1100, 1600 }) }
foreach (var height in new[] { 350, 418, 560, 720 })
foreach (var showTailnet in new[] { false, true }) private static DashboardGeometry CalculateCompact(Size viewport, int dpi, bool showTailnet, bool showServers)
foreach (var showServers in new[] { false, true }) {
{ var scale = Math.Max(1f, dpi / 96f);
var viewport = new Size(width * dpi / 96, height * dpi / 96); int S(int n) => (int)Math.Round(n * scale);
var p = Calculate(viewport, dpi, showTailnet, showServers); var margin = S(8); var gap = S(4);
Rectangle[] cards = showTailnet var width = Math.Max(S(400), viewport.Width - margin * 2);
? [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.TailnetTrafficCard, p.DailyCard, p.Footer] var leftWidth = (int)Math.Round((width-gap)*.61);
: [p.StatusCard, p.NodeCard, p.ModeCard, p.TrafficCard, p.DailyCard, p.Footer]; var welcome = new Rectangle(margin, S(1), width-S(90), S(15));
if (showServers) cards = [..cards, p.ServerTrafficCard]; var account = new Rectangle(margin, S(16), S(175), S(12));
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0)) return false; var identity = new Rectangle(account.Right+gap, S(16), S(58), S(12));
for (var i = 0; i < cards.Length; i++) var logout = new Rectangle(margin+width-S(70), S(3), S(70), S(23));
for (var j = i + 1; j < cards.Length; j++) var status = new Rectangle(margin, S(30), width, S(40));
if (cards[i].IntersectsWith(cards[j])) return false; var node = new Rectangle(margin, S(74), leftWidth, S(42));
if (p.WelcomeLabel.IntersectsWith(p.LogoutButton) || p.AccountLabel.IntersectsWith(p.IdentityBadge)) return false; var mode = new Rectangle(node.Right+gap,node.Top,width-leftWidth-gap,node.Height);
if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false; var footer = new Rectangle(margin, viewport.Height-S(26), width, S(22));
for (var i = 0; i < p.Metrics.Length; i++) var server = showServers ? new Rectangle(margin,footer.Top-gap-S(34),width,S(34)) : Rectangle.Empty;
if (p.Metrics[i].Right > (i == 0 || i == 3 ? p.DailyCard.Width : p.TrafficCard.Width)) return false; var bottom = (showServers?server.Top:footer.Top)-gap;
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false; var analyticsTop=S(120);
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false; var height=Math.Max(S(112),bottom-analyticsTop);
var baseline = Calculate(viewport, dpi, false, showServers); var statsHeight=showTailnet?S(30):S(60);
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false; var traffic=new Rectangle(margin,analyticsTop,leftWidth,statsHeight);
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom var tailnet=showTailnet?new Rectangle(margin,traffic.Bottom+gap,leftWidth,S(30)):Rectangle.Empty;
|| p.DailyCard.Top != p.TrafficCard.Top || p.DailyCard.Bottom != p.TailnetTrafficCard.Bottom)) return false; var trendTop=(showTailnet?tailnet.Bottom:traffic.Bottom)+gap;
if (showServers && (p.ServerTrafficCard.Top <= p.DailyCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false; var trend=new Rectangle(margin,trendTop,leftWidth,analyticsTop+height-trendTop);
} var daily=new Rectangle(mode.Left,analyticsTop,mode.Width,height);
return true; var totalHeight=(daily.Height-S(22))/2;
} Rectangle Total(int row)=>new(S(5),S(20)+row*totalHeight,daily.Width-S(10),totalHeight-S(2));
} var metricWidth=(traffic.Width-S(8))/2;
var metricTop=showTailnet?S(11):S(15);
var metricHeight=traffic.Height-metricTop-S(1);
Rectangle Speed(int col)=>new(S(4)+col*metricWidth,metricTop,metricWidth-S(1),metricHeight);
Rectangle[] metrics=[Total(0),Speed(0),Speed(1),Total(1)];
return new(welcome,account,identity,logout,status,node,mode,metrics,traffic,tailnet,trend,daily,server,footer,
viewport.Height,true,1f);
}
internal static bool SelfTest()
{
foreach (var dpi in new[] { 96, 120, 144, 168, 192, 240, 288, 336, 384 })
foreach (var width in new[] { 480, 600, 620, 739, 760, 780, 900, 1100, 1600 })
foreach (var height in new[] { 312, 350, 418, 560, 720 })
foreach (var showTailnet in new[] { false, true })
foreach (var showServers in new[] { false, true })
{
var viewport = new Size(width * dpi / 96, height * dpi / 96);
var p = Calculate(viewport, dpi, showTailnet, showServers);
Rectangle[] cards = [p.StatusCard,p.NodeCard,p.ModeCard,p.TrafficCard,p.SpeedTrendCard,p.DailyCard,p.Footer];
if(showTailnet)cards=[..cards,p.TailnetTrafficCard];
if(showServers)cards=[..cards,p.ServerTrafficCard];
if (cards.Any(c => c.Left < 0 || c.Right > viewport.Width || c.Bottom > p.ContentHeight || c.Width <= 0 || c.Height<=0)) return false;
for (var i = 0; i < cards.Length; i++)
for (var j = i + 1; j < cards.Length; j++)
if (cards[i].IntersectsWith(cards[j])) return false;
if (p.WelcomeLabel.IntersectsWith(p.LogoutButton) || p.AccountLabel.IntersectsWith(p.IdentityBadge)) return false;
if (p.Metrics[0].IntersectsWith(p.Metrics[3]) || p.Metrics[1].IntersectsWith(p.Metrics[2])) return false;
for (var i = 0; i < p.Metrics.Length; i++)
{
var parent=i==0||i==3?p.DailyCard:p.TrafficCard;
if(p.Metrics[i].Left<0||p.Metrics[i].Top<0||p.Metrics[i].Right>parent.Width||p.Metrics[i].Bottom>parent.Height)return false;
}
if (!showTailnet && p.TailnetTrafficCard != Rectangle.Empty) return false;
if (p.ContentHeight > viewport.Height || p.Footer.Bottom > viewport.Height) return false;
var baseline = Calculate(viewport, dpi, false, showServers);
if (p.DailyCard != baseline.DailyCard || p.Footer != baseline.Footer || p.ContentHeight != baseline.ContentHeight) return false;
if (showTailnet && (p.TailnetTrafficCard.Top <= p.TrafficCard.Bottom || p.SpeedTrendCard.Top<=p.TailnetTrafficCard.Bottom)) return false;
if(p.SpeedTrendCard.Bottom!=p.DailyCard.Bottom)return false;
if (showServers && (p.ServerTrafficCard.Top <= p.DailyCard.Bottom || p.ServerTrafficCard.Bottom >= p.Footer.Top)) return false;
}
return true;
}
}
+92 -83
View File
@@ -1,83 +1,92 @@
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
// UI fixture only: independent supplied values, no adapter/core/route reads. // UI fixture only: independent supplied values, no adapter/core/route reads.
internal Dictionary<string, bool> CheckTailnetTrafficUi() internal Dictionary<string, bool> CheckTailnetTrafficUi()
{ {
var checks = new Dictionary<string, bool>(); var checks = new Dictionary<string, bool>();
var originalSize = ClientSize; var originalSize = ClientSize;
foreach (var size in new[] { new Size(960, 720), new Size(620, 550), new Size(900, 640) }) foreach (var size in new[] { new Size(480, 360), new Size(900, 360), new Size(960, 720), new Size(620, 550), new Size(900, 640) })
{ {
ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height)); ClientSize = new Size(ScaleLogical(size.Width), ScaleLogical(size.Height));
SetTailnetTrafficVisibility(false); LayoutDashboard(); SetTailnetTrafficVisibility(false); LayoutDashboard();
var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size); var baseline = (_trafficCard.Bounds, _dailyCard.Bounds, _footer.Bounds, _dashboardBody.Size);
checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible checks[$"no_tailnet_single_left_{size.Width}"] = !_tailnetTrafficCard.Visible
&& _trafficCard.Top == _dailyCard.Top && _trafficCard.Bottom == _dailyCard.Bottom; && _trafficCard.Top == _dailyCard.Top && _speedTrendCard.Bottom == _dailyCard.Bottom;
SetTailnetTrafficVisibility(true); SetTailnetTrafficVisibility(true);
checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left checks[$"tailnet_only_subdivides_left_{size.Width}"] = _tailnetTrafficCard.Left == _trafficCard.Left
&& _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom && _tailnetTrafficCard.Width == _trafficCard.Width && _tailnetTrafficCard.Top > _trafficCard.Bottom
&& _dailyCard.Top == _trafficCard.Top && _dailyCard.Bottom == _tailnetTrafficCard.Bottom; && _dailyCard.Top == _trafficCard.Top && _dailyCard.Bottom == _speedTrendCard.Bottom;
checks[$"tailnet_never_increases_page_{size.Width}"] = _dailyCard.Bounds == baseline.Item2 checks[$"tailnet_never_increases_page_{size.Width}"] = _dailyCard.Bounds == baseline.Item2
&& _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4 && _footer.Bounds == baseline.Item3 && _dashboardBody.Size == baseline.Item4
&& !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty; && !_dashboardScrollBar.Visible && _dashboardBody.Location == Point.Empty;
checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit(); checks[$"all_card_controls_fit_{size.Width}"] = DashboardControlsFit();
SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(false);
checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1 checks[$"tailnet_hide_restores_geometry_{size.Width}"] = _trafficCard.Bounds == baseline.Item1
&& _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3; && _dailyCard.Bounds == baseline.Item2 && _footer.Bounds == baseline.Item3;
} }
SetTailnetTrafficVisibility(true); ClientSize=new Size(ScaleLogical(480),ScaleLogical(360));
var proxyValue = _uploadMetric.ValueText; _connectionModeCombo.SelectedIndex=1;
var session = (_sessionUp, _sessionDown); if(_manualNodeCombo.Items.Count>0)_manualNodeCombo.SelectedIndex=0;
var curveCount = _trafficChart.PointCount; RefreshSelectionControls(); LayoutDashboard();
DisplayTailnetTraffic(12345, 67890, "独立 UI 样本"); checks["half_size_manual_node_does_not_overlap_mode_selector"] = !_manualNodeCombo.Visible
checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown) || (!_manualNodeCombo.Bounds.IntersectsWith(_connectionModeCombo.Bounds)
&& _trafficChart.PointCount == curveCount; && _manualNodeCombo.Bottom<=_nodeCard.Height);
checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06" _connectionModeCombo.SelectedIndex=0;
&& _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue; SetTailnetTrafficVisibility(true);
checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ") var proxyValue = _uploadMetric.ValueText;
&& _tailnetUploadMetric.Hint == "已计入代理总流量"; var session = (_sessionUp, _sessionDown);
DisplayTailnetTraffic(null, double.NaN, "采样不可用"); var curveCount = _trafficChart.PointCount;
checks["tailnet_missing_samples_not_fake_zero"] = _tailnetUploadMetric.ValueText == "—" DisplayTailnetTraffic(12345, 67890, "独立 UI 样本");
&& _tailnetDownloadMetric.ValueText == "—"; checks["tailnet_never_double_counts_session_or_curve"] = session == (_sessionUp, _sessionDown)
DisplayTailnetTraffic(1, 2, "独立 UI 样本"); && _trafficChart.PointCount == curveCount;
SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(true); checks["tailnet_values_are_independent_controls"] = _tailnetUploadMetric.ValueText == "12.06"
checks["tailnet_hide_clears_previous_numbers"] = _tailnetUploadMetric.ValueText == "—" && _tailnetDownloadMetric.ValueText == "66.3" && _uploadMetric.ValueText == proxyValue;
&& _tailnetDownloadMetric.ValueText == "—"; checks["tailnet_scope_and_already_accounted_are_explicit"] = _tailnetSampleLabel.Text.StartsWith("仅纵横家链路 · ")
checks["only_one_speed_curve_on_right"] = !_trafficCard.Controls.OfType<TrafficChart>().Any() && _tailnetUploadMetric.Hint == "已计入代理总流量";
&& !_tailnetTrafficCard.Controls.OfType<TrafficChart>().Any() DisplayTailnetTraffic(null, double.NaN, "采样不可用");
&& _dailyCard.Controls.OfType<TrafficChart>().Single() == _trafficChart checks["tailnet_missing_samples_not_fake_zero"] = _tailnetUploadMetric.ValueText == "—"
&& _dailyChart.Parent is null && !_dailyChart.Visible; && _tailnetDownloadMetric.ValueText == "—";
UpdateConnectedTransportPresentation(true); DisplayTailnetTraffic(1, 2, "独立 UI 样本");
DisplayTraffic(1024, 2048, "互斥入口样本"); SetTailnetTrafficVisibility(false); SetTailnetTrafficVisibility(true);
DisplayTailnetTraffic(1024, 2048, "互斥入口样本"); checks["tailnet_hide_clears_previous_numbers"] = _tailnetUploadMetric.ValueText == "—"
checks["tailnet_sample_is_not_duplicated_as_public_speed"] = _uploadMetric.ValueText == "—" && _tailnetDownloadMetric.ValueText == "—";
&& _downloadMetric.ValueText == "—" && _uploadMetric.Hint == "未使用公网入口" checks["cumulative_is_numeric_only_proxy_has_speed_curve"] = !_dailyCard.Controls.OfType<TrafficChart>().Any()
&& _tailnetUploadMetric.ValueText == "1" && _tailnetDownloadMetric.ValueText == "2"; && !_trafficCard.Controls.OfType<TrafficChart>().Any()
checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible; && !_tailnetTrafficCard.Controls.OfType<TrafficChart>().Any()
UpdateConnectedTransportPresentation(false); && _speedTrendCard.Controls.OfType<TrafficChart>().Single() == _trafficChart
DisplayTraffic(3072, 4096, "公网样本"); && _dailyChart.Parent is null && !_dailyChart.Visible;
checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3" && _downloadMetric.ValueText == "4"; UpdateConnectedTransportPresentation(true);
checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible; DisplayTraffic(1024, 2048, "互斥入口样本");
using var curve = new TrafficChart(); DisplayTailnetTraffic(1024, 2048, "互斥入口样本");
var end = DateTimeOffset.Now; checks["tailnet_sample_is_not_duplicated_as_public_speed"] = _uploadMetric.ValueText == "—"
for (var i = 0; i <= 720; i++) curve.Add(i, i * 2, end.AddSeconds((i - 720) * 5)); && _downloadMetric.ValueText == "—" && _uploadMetric.Hint == "未使用公网入口"
checks["speed_history_retains_actual_one_hour"] = curve.PointCount == 721; && _tailnetUploadMetric.ValueText == "1" && _tailnetDownloadMetric.ValueText == "2";
curve.SetPeriodMinutes(1); checks["actual_tailnet_transport_shows_section"] = _currentNodeUsesTailnet && _tailnetTrafficVisible;
checks["one_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 13 && curve.PointCount == 721; UpdateConnectedTransportPresentation(false);
curve.SetPeriodMinutes(5); DisplayTraffic(3072, 4096, "公网样本");
checks["five_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 61; checks["public_sample_uses_only_public_speed_section"] = _uploadMetric.ValueText == "3" && _downloadMetric.ValueText == "4";
curve.SetPeriodMinutes(15); checks["public_transport_hides_section"] = !_currentNodeUsesTailnet && !_tailnetTrafficVisible;
checks["fifteen_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 181; using var curve = new TrafficChart();
curve.SetPeriodMinutes(60); var end = DateTimeOffset.Now;
checks["hour_filter_preserves_available_samples"] = curve.VisiblePointCount == 721; for (var i = 0; i <= 720; i++) curve.Add(i, i * 2, end.AddSeconds((i - 720) * 5));
curve.Add(1, 2, end.AddSeconds(5)); checks["speed_history_retains_actual_one_hour"] = curve.PointCount == 721;
checks["old_samples_expire_at_one_hour"] = curve.PointCount == 721; curve.SetPeriodMinutes(1);
curve.Reset(); checks["one_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 13 && curve.PointCount == 721;
checks["speed_history_reset_has_no_fabricated_samples"] = curve.PointCount == 0 && curve.VisiblePointCount == 0; curve.SetPeriodMinutes(5);
ClientSize = originalSize; LayoutDashboard(); checks["five_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 61;
checks["fitted_geometry_448_viewport_dpi_cases"] = DashboardLayout.SelfTest(); curve.SetPeriodMinutes(15);
checks["card_surface_remains_half_transparent"] = CardPanel.SurfaceAlpha == 128; checks["fifteen_minute_filter_uses_actual_samples"] = curve.VisiblePointCount == 181;
return checks; curve.SetPeriodMinutes(60);
} checks["hour_filter_preserves_available_samples"] = curve.VisiblePointCount == 721;
} curve.Add(1, 2, end.AddSeconds(5));
checks["old_samples_expire_at_one_hour"] = curve.PointCount == 721;
curve.Reset();
checks["speed_history_reset_has_no_fabricated_samples"] = curve.PointCount == 0 && curve.VisiblePointCount == 0;
ClientSize = originalSize; LayoutDashboard();
checks["fitted_geometry_448_viewport_dpi_cases"] = DashboardLayout.SelfTest();
checks["card_surface_remains_half_transparent"] = CardPanel.SurfaceAlpha == 128;
return checks;
}
}
+135
View File
@@ -0,0 +1,135 @@
namespace UCVL.VPNPlus;
internal sealed partial class MainForm
{
// A compact logical canvas; native DPI scaling still happens exactly once.
private bool CompactPresentation => ClientSize.Width < ScaleLogical(720) || ClientSize.Height < ScaleLogical(550);
private readonly Font _compactStatusFont=Brand.Font(10,FontStyle.Bold);
private readonly Font _compactChartFont=Brand.Font(6.5f);
private readonly Dictionary<Control, (Font Original, Font? Compact)> _presentationFonts = new();
private bool _presentationFontsDisposed;
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if(!disposing || _presentationFontsDisposed)return;
_presentationFontsDisposed=true;
foreach(var fonts in _presentationFonts.Values)fonts.Compact?.Dispose();
_presentationFonts.Clear();
_compactStatusFont.Dispose();
_compactChartFont.Dispose();
}
private void SetStatusTitleFont(float size)
{
if(CompactPresentation && ReferenceEquals(_statusTitle.Font,_compactStatusFont))return;
if(!CompactPresentation && !ReferenceEquals(_statusTitle.Font,_compactStatusFont)
&& Math.Abs(_statusTitle.Font.SizeInPoints-size)<.1f)return;
var previous=_statusTitle.Font;
_statusTitle.Font=CompactPresentation?_compactStatusFont:Brand.Font(size,FontStyle.Bold);
if(!ReferenceEquals(previous,_compactStatusFont))previous.Dispose();
}
private void ApplyCompactTypography()
{
void Visit(Control parent)
{
foreach (Control control in parent.Controls)
{
if (control is CaptionButton || ReferenceEquals(control,_statusTitle)) continue;
if (!_presentationFonts.TryGetValue(control, out var fonts))
{
var original = control.Font;
fonts = (original, new Font(original.FontFamily, Math.Max(6.5f, original.SizeInPoints * .78f), original.Style));
_presentationFonts.Add(control, fonts);
}
control.Font = CompactPresentation ? fonts.Compact! : fonts.Original;
Visit(control);
}
}
Visit(this);
}
private void LayoutCompactHeader()
{
int S(int n) => ScaleLogical(n);
_brandHeader.Height=S(48);
foreach(Control control in _brandHeader.Controls)
{
if(control.Tag is not Rectangle)continue;
if(control is PictureBox)control.Bounds=new(S(10),S(5),S(34),S(37));
else if(control is Label label && label.Text=="纵横家")control.Bounds=new(S(52),S(5),S(180),S(25));
else control.Bounds=new(S(53),S(28),S(260),S(15));
}
_headerPoem.Visible=false;
LayoutWindowChrome();
}
private void LayoutCompactLogin()
{
int S(int n)=>ScaleLogical(n);
_loginView.Size=new(S(400),S(280));
foreach(Control control in _loginView.Controls)
if(control.Tag is Rectangle r)
control.Bounds=new(S((int)Math.Round(r.X*400d/440)),S((int)Math.Round(r.Y*.72)),
S((int)Math.Round(r.Width*400d/440)),S(Math.Max(14,(int)Math.Round(r.Height*.72))));
// Text boxes and the primary action keep comfortable compact hit areas.
_loginText.Parent!.Bounds=new(S(25),S(65),S(350),S(29));
_passwordText.Parent!.Bounds=new(S(25),S(117),S(350),S(29));
_loginButton.Bounds=new(S(25),S(160),S(350),S(31));
var flags=TextFormatFlags.SingleLine;
var prompt=TextRenderer.MeasureText(_registerPrompt.Text,_registerPrompt.Font,Size.Empty,flags);
var link=TextRenderer.MeasureText(_registerLink.Text,_registerLink.Font,Size.Empty,flags);
var rowWidth=prompt.Width+link.Width+S(16);
var left=(_loginView.Width-rowWidth)/2;
_registerPrompt.Bounds=new(left,S(199),prompt.Width+S(4),S(20));
_registerLink.Bounds=new(_registerPrompt.Right+S(8),S(199),link.Width+S(4),S(20));
foreach(Control control in _loginView.Controls)
{
if(control is Label label && label.Text.StartsWith("浏览器完成注册"))control.Bounds=new(S(20),S(226),S(360),S(18));
}
_loginError.Bounds=new(S(20),S(248),S(360),S(24));
_loginView.Left=Math.Max(S(8),(_content.Width-_loginView.Width)/2);
_loginView.Top=Math.Max(S(8),(_content.Height-_loginView.Height)/2);
}
private void LayoutCompactDashboard(DashboardGeometry layout)
{
int S(int n)=>ScaleLogical(n);
Rectangle R(int x,int y,int w,int h)=>new(S(x),S(y),S(w),S(h));
_statusDot.Bounds=R(10,8,24,24);
_connectButton.Bounds=new(_statusCard.Width-S(68),S(7),S(60),S(26));
_statusTitle.Bounds=new(S(42),S(1),_statusCard.Width-S(116),S(21));
_statusDetail.Bounds=new(S(42),S(22),_statusCard.Width-S(116),S(15));
_nodeIcon.Visible=_modeIcon.Visible=false;
_nodeHeading.Bounds=R(8,0,122,15);
_nodeHeading.Text="工作节点";
_connectionModeCombo.Bounds=new(_nodeCard.Width-S(102),S(1),S(96),S(18));
_manualNodeCombo.Bounds=new(S(8),S(22),_nodeCard.Width-S(16),S(19));
_currentNodeLabel.Bounds=new(S(8),S(23),_nodeCard.Width-S(16),S(17));
_scheduleBadge.Visible=false;
_routeHeading.Bounds=new(S(8),0,_modeCard.Width-S(16),S(14));
_routeCombo.Bounds=new(S(8),S(14),_modeCard.Width-S(16),S(20));
_routeReadOnly.Bounds=_routeCombo.Bounds;
_trafficIcon.Visible=_dailyIcon.Visible=_tailnetTrafficIcon.Visible=false;
_trafficHeading.Bounds=new(S(6),0,_trafficCard.Width-S(12),S(13));
_dailyHeading.Bounds=new(S(7),S(2),_dailyCard.Width-S(14),S(17));
_tailnetTrafficHeading.Bounds=new(S(6),0,_tailnetTrafficCard.Width-S(12),S(13));
if(_tailnetTrafficVisible)
{
var width=(_tailnetTrafficCard.Width-S(8))/2;
_tailnetUploadMetric.Bounds=new(S(4),S(11),width-S(1),S(18));
_tailnetDownloadMetric.Bounds=new(S(4)+width,S(11),width-S(1),S(18));
}
_trendHeading.Bounds=new(S(6),0,_speedTrendCard.Width-S(88),S(15));
_historyRangeCombo.Bounds=new(_speedTrendCard.Width-S(82),0,S(77),S(19));
_trafficChart.Font=_compactChartFont;
_trafficChart.Bounds=new(S(1),S(18),_speedTrendCard.Width-S(3),Math.Max(S(30),_speedTrendCard.Height-S(19)));
_uploadLegend.Visible=_downloadLegend.Visible=_historyStatus.Visible=false;
_sampleLabel.Visible=false;
_planLabel.Bounds=new(0,0,_footer.Width-S(75),S(11));
_expiryLabel.Bounds=new(_footer.Width-S(72),0,S(72),S(11));
_footerCompanySite.Bounds=new(0,S(11),S(210),S(11));
_footerHint.Bounds=new(_footer.Width-S(205),S(11),S(205),S(11));
_footerPoem.Visible=false;
_dashboardBody.Size=_dashboardView.ClientSize;
_dashboardBody.Location=Point.Empty;
}
}
+441 -422
View File
@@ -1,422 +1,441 @@
using System.Text.Json; using System.Text.Json;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed partial class MainForm internal sealed partial class MainForm
{ {
private readonly BadgeLabel _identityBadge = new(); private readonly BadgeLabel _identityBadge = new();
private readonly BadgeLabel _scheduleBadge = new(); private readonly BadgeLabel _scheduleBadge = new();
private readonly Label _sampleLabel = new(); private readonly Label _sampleLabel = new();
private readonly Label _uploadLegend = new(); private readonly Label _uploadLegend = new();
private readonly Label _downloadLegend = new(); private readonly Label _downloadLegend = new();
private readonly Label _historyStatus = new(); private readonly Label _historyStatus = new();
private readonly ReadOnlyModeLabel _routeReadOnly = new(); private readonly ReadOnlyModeLabel _routeReadOnly = new();
private readonly ComboBox _historyRangeCombo = new(); private readonly ComboBox _historyRangeCombo = new();
private readonly Label _footerHint = new(); private readonly Label _footerHint = new();
private readonly Label _footerPoem = new(); private readonly Label _footerPoem = new();
private readonly PictureBox _footerCompanyLogo = new(); private readonly PictureBox _footerCompanyLogo = new();
private readonly Label _footerCompanySite = new(); private readonly Label _footerCompanySite = new();
private readonly CardPanel _nodeCard = new(), _modeCard = new(), _trafficCard = new(), _dailyCard = new(); private readonly CardPanel _nodeCard = new(), _modeCard = new(), _trafficCard = new(), _dailyCard = new();
private readonly ScenicPanel _footer = new() { FooterArtwork = true }; private readonly ScenicPanel _footer = new() { FooterArtwork = true };
private readonly ScenicPanel _dashboardBody = new(); private readonly ScenicPanel _dashboardBody = new();
private readonly VScrollBar _dashboardScrollBar = new(); private readonly VScrollBar _dashboardScrollBar = new();
private readonly MetricCard _usageMetric = new("本期代理流量", DashboardIcon.Database); private readonly MetricCard _usageMetric = new("本期代理流量", DashboardIcon.Database);
private readonly MetricCard _uploadMetric = new("上传速度", DashboardIcon.Upload); private readonly MetricCard _uploadMetric = new("上传速度", DashboardIcon.Upload);
private readonly MetricCard _downloadMetric = new("下载速度", DashboardIcon.Download); private readonly MetricCard _downloadMetric = new("下载速度", DashboardIcon.Download);
private readonly MetricCard _sessionMetric = new("本次代理流量", DashboardIcon.Document); private readonly MetricCard _sessionMetric = new("本次代理流量", DashboardIcon.Document);
private readonly DashboardGlyph _nodeIcon = new(DashboardIcon.Server), _modeIcon = new(DashboardIcon.Settings); private readonly DashboardGlyph _nodeIcon = new(DashboardIcon.Server), _modeIcon = new(DashboardIcon.Settings);
private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History); private readonly DashboardGlyph _trafficIcon = new(DashboardIcon.Chart), _dailyIcon = new(DashboardIcon.History);
private readonly Label _trafficHeading = new(), _dailyHeading = new(); private readonly Label _trafficHeading = new(), _dailyHeading = new(), _trendHeading = new();
private bool _layingOutDashboard; private readonly CardPanel _speedTrendCard = new();
private sealed record SpeedHistoryPeriod(int Minutes, string Label) private bool _layingOutDashboard;
{ private sealed record SpeedHistoryPeriod(int Minutes, string Label)
public override string ToString() => Label; {
internal static readonly SpeedHistoryPeriod[] All = [new(1, "近 1 分钟"), new(5, "近 5 分钟"), new(15, "近 15 分钟"), new(60, "近 1 小时")]; public override string ToString() => Label;
} internal static readonly SpeedHistoryPeriod[] All = [new(1, "近 1 分钟"), new(5, "近 5 分钟"), new(15, "近 15 分钟"), new(60, "近 1 小时")];
}
private void BuildDashboardView()
{ private void BuildDashboardView()
_dashboardView.Dock = DockStyle.Fill; {
_dashboardView.BackColor = Brand.Surface; _dashboardView.Dock = DockStyle.Fill;
_dashboardView.LoginArtwork = true; _dashboardView.BackColor = Brand.Surface;
_dashboardView.AutoScroll = false; _dashboardView.LoginArtwork = true;
_dashboardView.Visible = false; _dashboardView.AutoScroll = false;
_dashboardView.Resize += (_, _) => LayoutDashboard(); _dashboardView.Visible = false;
_content.Controls.Add(_dashboardView); _dashboardView.Resize += (_, _) => LayoutDashboard();
_dashboardBody.BackColor = Brand.Surface; _content.Controls.Add(_dashboardView);
_dashboardBody.ParentArtwork = true; _dashboardBody.BackColor = Brand.Surface;
_dashboardView.Controls.Add(_dashboardBody); _dashboardBody.ParentArtwork = true;
_dashboardView.Controls.Add(_dashboardScrollBar); _dashboardView.Controls.Add(_dashboardBody);
_dashboardScrollBar.AccessibleName = "主界面垂直滚动"; _dashboardView.Controls.Add(_dashboardScrollBar);
_dashboardScrollBar.ValueChanged += (_, _) => _dashboardScrollBar.AccessibleName = "主界面垂直滚动";
{ _dashboardScrollBar.ValueChanged += (_, _) =>
_dashboardBody.Top = -_dashboardScrollBar.Value; {
// Child surfaces use the viewport's fixed backdrop coordinates. _dashboardBody.Top = -_dashboardScrollBar.Value;
// Moving a canvas must repaint them, not bit-blit old transparent pixels. // Child surfaces use the viewport's fixed backdrop coordinates.
_dashboardBody.Invalidate(true); // Moving a canvas must repaint them, not bit-blit old transparent pixels.
}; _dashboardBody.Invalidate(true);
ConfigureLabel(_welcomeLabel, "", Brand.Font(15, FontStyle.Bold), Brand.Navy); };
ConfigureLabel(_accountLabel, "", Brand.Font(9.5f), Brand.Muted); ConfigureLabel(_welcomeLabel, "", Brand.Font(15, FontStyle.Bold), Brand.Navy);
ConfigureLabel(_identityBadge, "", Brand.Font(8.5f), Brand.RoyalBlue); ConfigureLabel(_accountLabel, "", Brand.Font(9.5f), Brand.Muted);
ConfigureLabel(_scheduleBadge, "AI 自动调度", Brand.Font(8, FontStyle.Bold), Brand.RoyalBlue); ConfigureLabel(_identityBadge, "", Brand.Font(8.5f), Brand.RoyalBlue);
foreach (var badge in new[] { _identityBadge, _scheduleBadge }) ConfigureLabel(_scheduleBadge, "AI 自动调度", Brand.Font(8, FontStyle.Bold), Brand.RoyalBlue);
{ foreach (var badge in new[] { _identityBadge, _scheduleBadge })
badge.BackColor = Color.FromArgb(226, 239, 255); {
badge.TextAlign = ContentAlignment.MiddleCenter; badge.BackColor = Color.FromArgb(226, 239, 255);
} badge.TextAlign = ContentAlignment.MiddleCenter;
ConfigureSecondaryButton(_logoutButton, "退出账号", Point.Empty, new(104, 34)); }
_logoutButton.ForeColor = Brand.RoyalBlue; ConfigureSecondaryButton(_logoutButton, "退出账号", Point.Empty, new(104, 34));
_logoutButton.Click += async (_, _) => await LogoutAsync(); _logoutButton.ForeColor = Brand.RoyalBlue;
_dashboardBody.Controls.AddRange([_welcomeLabel, _accountLabel, _identityBadge, _logoutButton]); _logoutButton.Click += async (_, _) => await LogoutAsync();
_dashboardBody.Controls.AddRange([_welcomeLabel, _accountLabel, _identityBadge, _logoutButton]);
ConfigureLabel(_statusTitle, "未连接", Brand.Font(17, FontStyle.Bold), Brand.Text);
ConfigureLabel(_statusDetail, "点击连接,自动选择工作节点", Brand.Font(9.5f), Brand.Muted); ConfigureLabel(_statusTitle, "未连接", Brand.Font(17, FontStyle.Bold), Brand.Text);
_statusDot.ForeColor = Brand.Muted; ConfigureLabel(_statusDetail, "点击连接,自动选择工作节点", Brand.Font(9.5f), Brand.Muted);
_statusCard.ScenicStatus = true; _statusDot.ForeColor = Brand.Muted;
_nodeCard.AccentBar = _modeCard.AccentBar = true; _statusCard.ScenicStatus = true;
_trafficCard.MetricBand = _dailyCard.MetricBand = false; _nodeCard.AccentBar = _modeCard.AccentBar = true;
ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42)); _trafficCard.MetricBand = _dailyCard.MetricBand = false;
_connectButton.Click += async (_, _) => ConfigurePrimaryButton(_connectButton, "连接", Point.Empty, new(130, 42));
{ _connectButton.Click += async (_, _) =>
if (!_busy && !_wantConnected && !_handoverOperating) {
_tailnetPreference.ResetForUserConnect(); if (!_busy && !_wantConnected && !_handoverOperating)
await ToggleConnectionAsync(); _tailnetPreference.ResetForUserConnect();
}; await ToggleConnectionAsync();
_statusCard.Controls.AddRange([_statusDot, _statusTitle, _statusDetail, _connectButton]); };
ConfigureLabel(_nodeHeading, "当前工作节点", Brand.Font(9), Brand.Text); _statusCard.Controls.AddRange([_statusDot, _statusTitle, _statusDetail, _connectButton]);
ConfigureLabel(_routeHeading, "代理模式", Brand.Font(9), Brand.Text); ConfigureLabel(_nodeHeading, "当前工作节点", Brand.Font(9), Brand.Text);
ConfigureLabel(_currentNodeLabel, "连接后自动分配", Brand.Font(12, FontStyle.Bold), Brand.RoyalBlue); ConfigureLabel(_routeHeading, "代理模式", Brand.Font(9), Brand.Text);
_nodeCard.Controls.AddRange([_nodeIcon, _nodeHeading, _currentNodeLabel, _scheduleBadge]); ConfigureLabel(_currentNodeLabel, "连接后自动分配", Brand.Font(12, FontStyle.Bold), Brand.RoyalBlue);
BuildConnectionSelection(); _nodeCard.Controls.AddRange([_nodeIcon, _nodeHeading, _currentNodeLabel, _scheduleBadge]);
ConfigureCombo(_routeCombo, Point.Empty, new(220, 30)); BuildConnectionSelection();
_routeCombo.BackColor = Color.White; ConfigureCombo(_routeCombo, Point.Empty, new(220, 30));
_routeCombo.AccessibleName = "代理模式(连接时不可更改)"; _routeCombo.BackColor = Color.White;
_routeReadOnly.Visible = false; _routeCombo.AccessibleName = "代理模式(连接时不可更改)";
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]); _routeReadOnly.Visible = false;
_modeCard.Controls.AddRange([_modeIcon, _routeHeading, _routeCombo, _routeReadOnly]);
ConfigureLabel(_trafficHeading, "公网入口速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
_trafficCard.AccessibleDescription = "仅当前纵横家使用域名或公网入口的代理速度;Tailscale 入口速度另列,非整机流量。"; ConfigureLabel(_trafficHeading, "公网入口速度", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
ConfigureLabel(_dailyHeading, "速度与累计", Brand.Font(9.5f, FontStyle.Bold), Brand.Text); _trafficCard.AccessibleDescription = "仅当前纵横家使用域名或公网入口的代理速度;Tailscale 入口速度另列,非整机流量。";
ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted); ConfigureLabel(_dailyHeading, "累计流量", Brand.Font(9.5f, FontStyle.Bold), Brand.Text);
_sampleLabel.TextAlign = ContentAlignment.MiddleRight; ConfigureLabel(_sampleLabel, "仅代理流量 · 近 5 分钟", Brand.Font(7.5f), Brand.Muted);
ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue); _sampleLabel.TextAlign = ContentAlignment.MiddleRight;
ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan); ConfigureLabel(_uploadLegend, "● 上传 —", Brand.Font(8), Brand.RoyalBlue);
ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted); ConfigureLabel(_downloadLegend, "● 下载 —", Brand.Font(8), Brand.Cyan);
_historyStatus.AutoEllipsis = true; ConfigureLabel(_historyStatus, "仅本次运行采样 · B/s", Brand.Font(7), Brand.Muted);
_historyStatus.TextAlign = ContentAlignment.MiddleRight; _historyStatus.AutoEllipsis = true;
_historyStatus.AccessibleDescription = "右侧曲线仅为当前客户端实际采集的代理速度。累计数值来自套餐和本次连接,不随速度时间范围改变。"; _historyStatus.TextAlign = ContentAlignment.MiddleRight;
_trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading]); _historyStatus.AccessibleDescription = "代理速度曲线仅为当前客户端实际采集的代理速度;右侧累计区只显示统计数字。";
_dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading, _trafficChart, _uploadLegend, _downloadLegend]); ConfigureLabel(_trendHeading, "代理速度趋势", Brand.Font(8, FontStyle.Bold), Brand.Text);
// Keep backend accounting data available to UpdateProfile, but daily _trafficCard.Controls.AddRange([_trafficIcon, _trafficHeading]);
// byte totals are no longer drawn as a misleading speed history. _dailyCard.Controls.AddRange([_dailyIcon, _dailyHeading]);
_dailyChart.Visible = false; _speedTrendCard.Controls.AddRange([_trendHeading, _trafficChart, _uploadLegend, _downloadLegend]);
ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28)); // Keep backend accounting data available to UpdateProfile, but daily
_historyRangeCombo.BackColor = Color.White; // byte totals are no longer drawn as a misleading speed history.
_historyRangeCombo.Font = Brand.Font(8.5f); _dailyChart.Visible = false;
_historyRangeCombo.DrawMode = DrawMode.OwnerDrawFixed; ConfigureCombo(_historyRangeCombo, Point.Empty, new(120, 28));
_historyRangeCombo.DrawItem += (_, e) => _historyRangeCombo.BackColor = Color.White;
{ _historyRangeCombo.Font = Brand.Font(8.5f);
if (e.Index < 0) return; _historyRangeCombo.DrawMode = DrawMode.OwnerDrawFixed;
var highlight = _historyRangeCombo.DroppedDown && (e.State & DrawItemState.Selected) != 0; _historyRangeCombo.DrawItem += (_, e) =>
using var fill = new SolidBrush(highlight ? Brand.PaleBlue : Color.White); {
e.Graphics.FillRectangle(fill, e.Bounds); if (e.Index < 0) return;
TextRenderer.DrawText(e.Graphics, _historyRangeCombo.Items[e.Index]?.ToString() ?? "", _historyRangeCombo.Font, var highlight = _historyRangeCombo.DroppedDown && (e.State & DrawItemState.Selected) != 0;
e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis); using var fill = new SolidBrush(highlight ? Brand.PaleBlue : Color.White);
e.DrawFocusRectangle(); e.Graphics.FillRectangle(fill, e.Bounds);
}; TextRenderer.DrawText(e.Graphics, _historyRangeCombo.Items[e.Index]?.ToString() ?? "", _historyRangeCombo.Font,
_historyRangeCombo.AccessibleName = "代理实时速度时间范围"; e.Bounds, Brand.Text, TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.EndEllipsis);
_historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All); e.DrawFocusRectangle();
_historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1]; };
_historyRangeCombo.SelectedIndexChanged += (_, _) => _historyRangeCombo.AccessibleName = "代理实时速度时间范围";
{ _historyRangeCombo.Items.AddRange(SpeedHistoryPeriod.All);
if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes); _historyRangeCombo.SelectedItem = SpeedHistoryPeriod.All[1];
}; _historyRangeCombo.SelectedIndexChanged += (_, _) =>
_dailyCard.Controls.AddRange([_historyRangeCombo, _historyStatus]); {
ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted); if (_historyRangeCombo.SelectedItem is SpeedHistoryPeriod period) _trafficChart.SetPeriodMinutes(period.Minutes);
ConfigureLabel(_expiryLabel, "", Brand.Font(8.5f), Brand.Muted); };
ConfigureLabel(_footerHint, "仅限内部使用,不作商业使用。", Brand.Font(9, FontStyle.Bold), Brand.DeepBlue); _speedTrendCard.Controls.AddRange([_historyRangeCombo, _historyStatus]);
_footerHint.TextAlign = ContentAlignment.MiddleRight; ConfigureLabel(_planLabel, "", Brand.Font(8.5f), Brand.Muted);
ConfigureLabel(_footerPoem, "— 科技守护连接 · 让世界更近 —", new Font("KaiTi", 11.5f), Brand.Muted); ConfigureLabel(_expiryLabel, "", Brand.Font(8.5f), Brand.Muted);
_footerPoem.TextAlign = ContentAlignment.MiddleRight; ConfigureLabel(_footerHint, "仅限内部使用,不作商业使用。", Brand.Font(9, FontStyle.Bold), Brand.DeepBlue);
_footerCompanyLogo.Image = LoadCompanyLogo(); _footerHint.TextAlign = ContentAlignment.MiddleRight;
_footerCompanyLogo.SizeMode = PictureBoxSizeMode.Zoom; ConfigureLabel(_footerPoem, "— 科技守护连接 · 让世界更近 —", new Font("KaiTi", 11.5f), Brand.Muted);
ConfigureLabel(_footerCompanySite, "vpn.example.invalid", Brand.Font(8), Brand.Muted); _footerPoem.TextAlign = ContentAlignment.MiddleRight;
_footerCompanyLogo.BackColor = Color.Transparent; _footerCompanyLogo.Image = LoadCompanyLogo();
_footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]); _footerCompanyLogo.SizeMode = PictureBoxSizeMode.Zoom;
foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _dailyCard }) ConfigureLabel(_footerCompanySite, "vpn.example.invalid", Brand.Font(8), Brand.Muted);
{ _footerCompanyLogo.BackColor = Color.Transparent;
card.BackColor = Color.White; _footer.Controls.AddRange([_planLabel, _expiryLabel, _footerHint, _footerPoem, _footerCompanyLogo, _footerCompanySite]);
_dashboardBody.Controls.Add(card); foreach (var card in new CardPanel[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _speedTrendCard, _dailyCard })
} {
foreach (var metric in new[] { _usageMetric, _sessionMetric, _uploadMetric, _downloadMetric }) metric.Embedded = true; card.BackColor = Color.White;
_trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]); _dashboardBody.Controls.Add(card);
_dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]); }
BuildTailnetTrafficCard(); foreach (var metric in new[] { _usageMetric, _sessionMetric, _uploadMetric, _downloadMetric }) metric.Embedded = true;
BuildNodeTrafficMonitor(); _trafficCard.Controls.AddRange([_uploadMetric, _downloadMetric]);
_dashboardBody.Controls.Add(_footer); _dailyCard.Controls.AddRange([_usageMetric, _sessionMetric]);
foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel }) BuildTailnetTrafficCard();
{ BuildNodeTrafficMonitor();
label.AutoEllipsis = true; _dashboardBody.Controls.Add(_footer);
label.TextAlign = ContentAlignment.MiddleLeft; foreach (var label in new[] { _welcomeLabel, _accountLabel, _statusTitle, _statusDetail, _currentNodeLabel, _planLabel, _expiryLabel })
} {
_sessionMetric.SetBytes(0, hint: "本次连接累计"); label.AutoEllipsis = true;
DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟"); label.TextAlign = ContentAlignment.MiddleLeft;
// The dashboard is one fitted page; no hidden vertical or horizontal }
// canvas is introduced by Tailnet, and mouse-wheel cannot shift it. _sessionMetric.SetBytes(0, hint: "本次连接累计");
LayoutDashboard(); DisplayTraffic(null, null, "仅代理流量 · 近 5 分钟");
} // The dashboard is one fitted page; no hidden vertical or horizontal
// canvas is introduced by Tailnet, and mouse-wheel cannot shift it.
private void DisplayTraffic(double? upload, double? download, string sampling) LayoutDashboard();
{ }
var publicUpload = _currentNodeUsesTailnet ? null : upload;
var publicDownload = _currentNodeUsesTailnet ? null : download; private void DisplayTraffic(double? upload, double? download, string sampling)
var hint = _currentNodeUsesTailnet ? "未使用公网入口" : ""; {
_uploadMetric.SetBytes(publicUpload, speed: true, hint: hint); var publicUpload = _currentNodeUsesTailnet ? null : upload;
_downloadMetric.SetBytes(publicDownload, speed: true, hint: hint); var publicDownload = _currentNodeUsesTailnet ? null : download;
_sampleLabel.Text = sampling; var hint = _currentNodeUsesTailnet ? "未使用公网入口" : "";
_uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —"; _uploadMetric.SetBytes(publicUpload, speed: true, hint: hint);
_downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —"; _downloadMetric.SetBytes(publicDownload, speed: true, hint: hint);
// Waiting/handover/error paths also invalidate the separate transport _sampleLabel.Text = sampling;
// view. Valid samples are supplied once by the existing traffic reader. _uploadLegend.Text = upload.HasValue ? $"● 上传 {FormatBytes((long)upload.Value)}/s" : "● 上传 —";
if (!upload.HasValue || !download.HasValue) DisplayTailnetTraffic(null, null, sampling); _downloadLegend.Text = download.HasValue ? $"● 下载 {FormatBytes((long)download.Value)}/s" : "● 下载 —";
} // Waiting/handover/error paths also invalidate the separate transport
// view. Valid samples are supplied once by the existing traffic reader.
private void LayoutDashboard() if (!upload.HasValue || !download.HasValue) DisplayTailnetTraffic(null, null, sampling);
{ }
if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return;
_layingOutDashboard = true; private void LayoutDashboard()
Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _nodeTrafficPanel, _footer]; {
foreach (var container in layoutContainers) container.SuspendLayout(); if (_layingOutDashboard || _dashboardView.ClientSize.Width <= 0) return;
try _layingOutDashboard = true;
{ Control[] layoutContainers = [_dashboardView, _dashboardBody, _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _speedTrendCard, _dailyCard, _nodeTrafficPanel, _footer];
var viewport = _dashboardView.ClientSize; foreach (var container in layoutContainers) container.SuspendLayout();
var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible, _canViewNodeTraffic); try
var titleSize = 17f * Math.Max(.7f, layout.VerticalScale); {
if (Math.Abs(_statusTitle.Font.Size - titleSize) > .1f) ApplyCompactTypography();
{ var viewport = _dashboardView.ClientSize;
var previousTitleFont = _statusTitle.Font; var layout = DashboardLayout.Calculate(viewport, DeviceDpi, _tailnetTrafficVisible, _canViewNodeTraffic, CompactPresentation);
_statusTitle.Font = Brand.Font(titleSize, FontStyle.Bold); var titleSize = CompactPresentation ? 10f : 17f * Math.Max(.7f, layout.VerticalScale);
previousTitleFont.Dispose(); SetStatusTitleFont(titleSize);
} _dashboardScrollBar.Visible = false;
_dashboardScrollBar.Visible = false; _dashboardScrollBar.Value = 0;
_dashboardScrollBar.Value = 0; _dashboardScrollBar.Maximum = 0;
_dashboardScrollBar.Maximum = 0; int Y(int value) => Math.Max(0, (int)Math.Floor(ScaleLogical(value) * layout.VerticalScale));
int Y(int value) => Math.Max(0, (int)Math.Floor(ScaleLogical(value) * layout.VerticalScale)); void Place(Control c, Rectangle r) { c.Bounds = r; }
void Place(Control c, Rectangle r) { c.Bounds = r; } Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), Y(y), ScaleLogical(w), Y(h));
Rectangle R(int x, int y, int w, int h) => new(ScaleLogical(x), Y(y), ScaleLogical(w), Y(h)); Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel);
Place(_welcomeLabel, layout.WelcomeLabel); Place(_accountLabel, layout.AccountLabel); Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton);
Place(_identityBadge, layout.IdentityBadge); Place(_logoutButton, layout.LogoutButton); Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard);
Place(_statusCard, layout.StatusCard); Place(_nodeCard, layout.NodeCard); Place(_modeCard, layout.ModeCard); var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric };
var metrics = new[] { _usageMetric, _uploadMetric, _downloadMetric, _sessionMetric }; for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]);
for (var i = 0; i < 4; i++) Place(metrics[i], layout.Metrics[i]); Place(_trafficCard, layout.TrafficCard); Place(_speedTrendCard, layout.SpeedTrendCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer);
Place(_trafficCard, layout.TrafficCard); Place(_dailyCard, layout.DailyCard); Place(_footer, layout.Footer); Place(_nodeTrafficPanel, layout.ServerTrafficCard);
Place(_nodeTrafficPanel, layout.ServerTrafficCard); LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale);
LayoutTailnetTrafficCard(layout.TailnetTrafficCard, layout.VerticalScale); if (CompactPresentation) { LayoutCompactDashboard(layout); return; }
_statusDot.Bounds = R(24, 15, 42, 46); _nodeIcon.Visible=_modeIcon.Visible=_trafficIcon.Visible=_dailyIcon.Visible=true;
_connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), Y(17), ScaleLogical(130), Y(42)); _uploadLegend.Visible=_downloadLegend.Visible=true;
var textWidth = _connectButton.Left - ScaleLogical(100); _tailnetTrafficIcon.Visible=true;
_statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33)); _scheduleBadge.Visible=!_manualNodeCombo.Visible&&!_selectionUiConnected;
_statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25)); _statusDot.Bounds = R(24, 15, 42, 46);
_nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24); _connectButton.Bounds = new(_statusCard.Width - ScaleLogical(148), Y(17), ScaleLogical(130), Y(42));
_nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23)); var textWidth = _connectButton.Left - ScaleLogical(100);
_nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点"; _statusTitle.Bounds = new(ScaleLogical(84), Y(10), textWidth, Y(33));
_connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), Y(6), ScaleLogical(130), Y(28)); _statusDetail.Bounds = new(ScaleLogical(85), Y(43), textWidth, Y(25));
_manualNodeCombo.Bounds = new(ScaleLogical(54), Y(34), _nodeCard.Width - ScaleLogical(68), Y(28)); _nodeIcon.Bounds = R(26, 23, 24, 24); _modeIcon.Bounds = R(26, 23, 24, 24);
var badgeWidth = ScaleLogical(88); _nodeHeading.Bounds = new(ScaleLogical(54), Y(9), Math.Max(0, _nodeCard.Width - ScaleLogical(205)), Y(23));
var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14); _nodeHeading.Text = layout.Compact ? "工作节点" : "当前工作节点";
_currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34), _connectionModeCombo.Bounds = new(_nodeCard.Width - ScaleLogical(144), Y(6), ScaleLogical(130), Y(28));
_selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27)); _manualNodeCombo.Bounds = new(ScaleLogical(54), Y(34), _nodeCard.Width - ScaleLogical(68), Y(28));
_scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23)); var badgeWidth = ScaleLogical(88);
_routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22)); var badgeX = _nodeCard.Width - badgeWidth - ScaleLogical(14);
_routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28)); _currentNodeLabel.Bounds = new(ScaleLogical(54), Y(34),
_routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28)); _selectionUiConnected ? _nodeCard.Width - ScaleLogical(68) : badgeX - ScaleLogical(60), Y(27));
_trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20); _scheduleBadge.Bounds = new(badgeX, Y(35), badgeWidth, Y(23));
_trafficHeading.Bounds = R(42, 8, 150, 26); _routeHeading.Bounds = new(ScaleLogical(54), Y(8), _modeCard.Width - ScaleLogical(70), Y(22));
_dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26)); _routeCombo.Bounds = new(ScaleLogical(54), Y(33), _modeCard.Width - ScaleLogical(70), Y(28));
_historyRangeCombo.Bounds = new(_dailyCard.Width - ScaleLogical(120), Y(8), ScaleLogical(106), Y(26)); _routeReadOnly.Bounds = new(_routeCombo.Left, _routeCombo.Top, _routeCombo.Width, Y(28));
_trafficChart.Bounds = new(ScaleLogical(10), Y(127), _dailyCard.Width - ScaleLogical(20), Y(105)); _trafficIcon.Bounds = R(15, 10, 20, 20); _dailyIcon.Bounds = R(15, 10, 20, 20);
var legendWidth = (_dailyCard.Width - ScaleLogical(28)) / 2; _trafficHeading.Bounds = R(42, 8, 150, 26);
_uploadLegend.Bounds = new(ScaleLogical(14), Y(234), legendWidth, Y(19)); _dailyHeading.Bounds = new(ScaleLogical(42), Y(8), Math.Max(1, _dailyCard.Width - ScaleLogical(166)), Y(26));
_downloadLegend.Bounds = new(ScaleLogical(14) + legendWidth, Y(234), legendWidth, Y(19)); _trendHeading.Bounds = new(ScaleLogical(10),Y(4),Math.Max(1,_speedTrendCard.Width-ScaleLogical(132)),Y(21));
_historyStatus.Bounds = new(ScaleLogical(14), Y(255), _dailyCard.Width - ScaleLogical(28), Y(17)); _historyRangeCombo.Bounds = new(_speedTrendCard.Width-ScaleLogical(110),Y(3),ScaleLogical(100),Y(24));
_planLabel.Bounds = R(0, 4, 300, 26); _trafficChart.Bounds = new(ScaleLogical(5),Y(28),_speedTrendCard.Width-ScaleLogical(10),Math.Max(Y(38),_speedTrendCard.Height-Y(50)));
_expiryLabel.Bounds = R(306, 4, 132, 26); var legendWidth = (_speedTrendCard.Width-ScaleLogical(16))/2;
_footerCompanyLogo.Bounds = R(0, 34, 32, 34); _uploadLegend.Bounds = new(ScaleLogical(8),_speedTrendCard.Height-Y(20),legendWidth,Y(18));
_footerCompanySite.Bounds = R(0, 41, 220, 22); _downloadLegend.Bounds = new(ScaleLogical(8)+legendWidth,_speedTrendCard.Height-Y(20),legendWidth,Y(18));
_footerHint.Visible = true; _historyStatus.Visible=false;
_footerHint.Bounds = new(ScaleLogical(232), Y(39), Math.Max(1, _footer.Width - ScaleLogical(232)), Y(28)); _planLabel.Bounds = R(0, 4, 300, 26);
_footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780); _expiryLabel.Bounds = R(306, 4, 132, 26);
_footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29)); _footerCompanyLogo.Bounds = R(0, 34, 32, 34);
_dashboardBody.Size = viewport; _footerCompanySite.Bounds = R(0, 41, 220, 22);
_dashboardBody.Location = Point.Empty; _footerHint.Visible = true;
} _footerHint.Bounds = new(ScaleLogical(232), Y(39), Math.Max(1, _footer.Width - ScaleLogical(232)), Y(28));
finally _footerPoem.Visible = !layout.Compact && _footer.Width >= ScaleLogical(780);
{ _footerPoem.Bounds = new(_footer.Width - ScaleLogical(322), Y(5), ScaleLogical(322), Y(29));
foreach (var container in layoutContainers.Reverse()) container.ResumeLayout(false); _dashboardBody.Size = viewport;
_layingOutDashboard = false; _dashboardBody.Location = Point.Empty;
} }
} finally
{
// Isolated synthetic fixture: no stored account, core, system proxy, update query or installation. foreach (var container in layoutContainers.Reverse()) container.ResumeLayout(false);
internal static void RenderPreview() _layingOutDashboard = false;
{ }
using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false }; }
form.Show();
form.ShowDashboard(new Profile // Isolated synthetic fixture: no stored account, core, system proxy, update query or installation.
{ internal static void RenderPreview()
DisplayName = "示例用户", Email = "demo@example.com", IdentityType = "employee", {
Subscription = new SubscriptionInfo { Plan = "员工福利", UsedBytes = 17480516895, DeviceLimit = 3 }, using var form = new MainForm(preview: true) { Opacity = 0, ShowInTaskbar = false };
Nodes = [new NodeInfo { Name = "VPN003", Slug = "preview", Status = "online" }], form.Show();
RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }], form.ShowDashboard(new Profile
UsageHistory = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = DateTime.Today.AddDays(i - 6).ToString("yyyy-MM-dd"), UploadBytes = new long[] { 14000000, 0, 0, 0, 3000000, 35000000, 196000000 }[i], DownloadBytes = new long[] { 28000000, 0, 0, 0, 26000000, 158000000, 126000000 }[i] }).ToList() {
}); DisplayName = "示例用户", Email = "demo@example.com", IdentityType = "employee",
form._refreshTimer.Stop(); Subscription = new SubscriptionInfo { Plan = "员工福利", UsedBytes = 17480516895, DeviceLimit = 3 },
var fixtureRanges = UsageHistoryPeriod.All.ToDictionary(p => p.Key, p => new UsageHistorySeries Nodes = [new NodeInfo { Name = "VPN003", Slug = "preview", Status = "online" }],
{ RouteModes = [new RouteModeInfo { Id = "smart", Name = "AI 智能代理" }],
Bucket = p.Bucket, Note = p.Bucket == "hour" ? "演示数据 · 按上报入账小时;缺口为无明细" : "演示数据 · 月筛选为近30个自然日", UsageHistory = Enumerable.Range(0, 7).Select(i => new DailyUsage { Day = DateTime.Today.AddDays(i - 6).ToString("yyyy-MM-dd"), UploadBytes = new long[] { 14000000, 0, 0, 0, 3000000, 35000000, 196000000 }[i], DownloadBytes = new long[] { 28000000, 0, 0, 0, 26000000, 158000000, 126000000 }[i] }).ToList()
Points = Enumerable.Range(0, p.Count).Select(i => new UsageHistoryPoint });
{ form._refreshTimer.Stop();
Time = p.Bucket == "hour" ? new DateTimeOffset(2026, 9, 9, 21, 0, 0, TimeSpan.FromHours(8)).AddHours(i - p.Count + 1).ToString("O") var fixtureRanges = UsageHistoryPeriod.All.ToDictionary(p => p.Key, p => new UsageHistorySeries
: new DateOnly(2026, 9, 9).AddDays(i - p.Count + 1).ToString("yyyy-MM-dd"), {
UploadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Sin(i * .72) + 1.1) * 60_000_000), Bucket = p.Bucket, Note = p.Bucket == "hour" ? "演示数据 · 按上报入账小时;缺口为无明细" : "演示数据 · 月筛选为近30个自然日",
DownloadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Cos(i * .81) + 1.1) * 84_000_000) Points = Enumerable.Range(0, p.Count).Select(i => new UsageHistoryPoint
}).ToList() {
}); Time = p.Bucket == "hour" ? new DateTimeOffset(2026, 9, 9, 21, 0, 0, TimeSpan.FromHours(8)).AddHours(i - p.Count + 1).ToString("O")
form._currentNodeLabel.Text = "VPN003"; : new DateOnly(2026, 9, 9).AddDays(i - p.Count + 1).ToString("yyyy-MM-dd"),
form.SetConnectionState(true, "已安全连接", "VPN003 · AI 智能代理"); UploadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Sin(i * .72) + 1.1) * 60_000_000),
form.DisplayTraffic(91975, 23357, "21:13:00 · 近 5 分钟"); DownloadBytes = p.Bucket == "hour" && i == 3 ? null : (long)((Math.Cos(i * .81) + 1.1) * 84_000_000)
form._sessionMetric.SetBytes(130180710, hint: "本次连接累计"); }).ToList()
for (var i = 0; i < 60; i++) form._trafficChart.Add((i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024, });
(i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024, DateTimeOffset.Now.AddSeconds((i - 59) * 5)); form._currentNodeLabel.Text = "VPN003";
form.LayoutBrandHeader(); form.LayoutDashboard(); form.SetConnectionState(true, "已安全连接", "VPN003 · AI 智能代理");
var checks = new Dictionary<string, bool> { ["geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest() }; form.DisplayTraffic(91975, 23357, "21:13:00 · 近 5 分钟");
foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value; form._sessionMetric.SetBytes(130180710, hint: "本次连接累计");
void Capture(string suffix) for (var i = 0; i < 60; i++) form._trafficChart.Add((i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024,
{ (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024, DateTimeOffset.Now.AddSeconds((i - 59) * 5));
form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents(); form.LayoutBrandHeader(); form.LayoutDashboard();
using var image = new Bitmap(form.Width, form.Height); var checks = new Dictionary<string, bool> { ["geometry_112_viewport_dpi_cases"] = DashboardLayout.SelfTest() };
form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size)); foreach (var check in UsageHistorySeries.SelfTest()) checks[check.Key] = check.Value;
image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{suffix}.png")); void Capture(string suffix)
} {
Capture("dashboard"); form.PerformLayout(); form.LayoutDashboard(); Application.DoEvents();
form._currentNodeName = NodePresentation.JinanName; using var image = new Bitmap(form.Width, form.Height);
form._currentNodeLabel.Text = form._currentNodeName; form.DrawToBitmap(image, new Rectangle(Point.Empty, image.Size));
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理"); image.Save(Path.Combine(AppContext.BaseDirectory, $"preview-{GetDisplayVersion()}-{suffix}.png"));
Capture("zero3-connected"); }
checks["zero3_connected_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width; Capture("dashboard");
checks["dashboard_controls_within_cards"] = form.DashboardControlsFit(); checks["default_window_width_and_height_halved"] = form.ClientSize==new Size(form.ScaleLogical(480),form.ScaleLogical(360));
checks["footer_slogan_displays_without_company_brand"] = !form._brandHeader.Controls.Contains(form._footerCompanyLogo) checks["cumulative_card_has_only_numeric_metrics"] = !form._dailyCard.Controls.OfType<TrafficChart>().Any()
&& form._footerCompanyLogo.Parent == form._footer && !form._footerCompanyLogo.Visible; && form._usageMetric.Parent==form._dailyCard && form._sessionMetric.Parent==form._dailyCard;
checks["footer_slogan_text_has_no_url"] = form._footerCompanySite.Visible && form._footerCompanySite.Text == "智能连接 · 高效办公" checks["proxy_speed_has_independent_trend_card"] = form._trafficChart.Parent==form._speedTrendCard
&& !form._footerCompanySite.Text.Contains("vpn.", StringComparison.OrdinalIgnoreCase) && form._speedTrendCard.Left==form._trafficCard.Left && form._speedTrendCard.Top>form._trafficCard.Bottom;
&& !form._footerCompanySite.Text.Contains("://", StringComparison.OrdinalIgnoreCase);
checks["official_header_logo_preserved"] = form._brandHeader.Controls.OfType<PictureBox>().Any(logo => logo.Visible && logo.Image is not null form._currentNodeName = NodePresentation.JinanName;
&& logo.SizeMode == PictureBoxSizeMode.Zoom && logo.Tag is Rectangle bounds && bounds == new Rectangle(20, 29, 62, 67) form._currentNodeLabel.Text = form._currentNodeName;
&& logo.Bounds == new Rectangle(form.ScaleLogical(20), form.ScaleLogical(29), form.ScaleLogical(62), form.ScaleLogical(67))); form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
checks["product_header_named_zonghengjia"] = form.Text == "纵横家" && form._brandHeader.Controls.OfType<Label>().Any(label => label.Text == "纵横家"); Capture("zero3-connected");
checks["powered_by_removed_from_login_and_footer"] = !form._footer.Controls.OfType<Label>().Concat(form._loginView.Controls.OfType<Label>()) checks["zero3_connected_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
.Any(label => label.Text.Contains("Powered by", StringComparison.OrdinalIgnoreCase) || label.Text == "优创未来"); checks["dashboard_controls_within_cards"] = form.DashboardControlsFit();
checks["content_uses_local_buffers_not_composited_subtree"] = !form._content.ComposeChildren; checks["footer_slogan_displays_without_company_brand"] = !form._brandHeader.Controls.Contains(form._footerCompanyLogo)
checks["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork; && form._footerCompanyLogo.Parent == form._footer && !form._footerCompanyLogo.Visible;
checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1; checks["footer_slogan_text_has_no_url"] = form._footerCompanySite.Visible && form._footerCompanySite.Text == "智能连接 · 高效办公"
checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._dailyCard; && !form._footerCompanySite.Text.Contains("vpn.", StringComparison.OrdinalIgnoreCase)
checks["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable; && !form._footerCompanySite.Text.Contains("://", StringComparison.OrdinalIgnoreCase);
checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right; checks["official_header_logo_preserved"] = form._brandHeader.Controls.OfType<PictureBox>().Any(logo => logo.Visible && logo.Image is not null
checks["internal_use_notice_visible"] = form._footerHint.Text == "仅限内部使用,不作商业使用。" && form._footerHint.Visible; && logo.SizeMode == PictureBoxSizeMode.Zoom && form._brandHeader.ClientRectangle.Contains(logo.Bounds)
checks["proxy_metrics_values"] = form._usageMetric.UnitText == "GB" && form._uploadMetric.UnitText == "KB/s" && form._sessionMetric.UnitText == "MB"; && logo.Width >= form.ScaleLogical(30) && logo.Right < form._windowChrome!.MinimizeButton.Left);
checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent checks["product_header_named_zonghengjia"] = form.Text == "纵横家" && form._brandHeader.Controls.OfType<Label>().Any(label => label.Text == "纵横家");
&& form._usageMetric.Parent == form._trafficChart.Parent && form._uploadMetric.Parent == form._trafficCard checks["powered_by_removed_from_login_and_footer"] = !form._footer.Controls.OfType<Label>().Concat(form._loginView.Controls.OfType<Label>())
&& form._downloadMetric.Parent == form._trafficCard; .Any(label => label.Text.Contains("Powered by", StringComparison.OrdinalIgnoreCase) || label.Text == "优创未来");
form._historyRangeCombo.SelectedIndex = 0; checks["content_uses_local_buffers_not_composited_subtree"] = !form._content.ComposeChildren;
Capture("history-legacy-unavailable"); checks["dashboard_reuses_login_backdrop"] = form._dashboardView.LoginArtwork && form._dashboardBody.ParentArtwork;
checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible; checks["header_only_has_minimize_button"] = form._brandHeader.Controls.OfType<CaptionButton>().Count() == 1;
form._dailyChart.SetHistory([], fixtureRanges); checks["scenic_asset_is_decoration_only"] = form._brandHeader.BackgroundImage is null && form._trafficChart.Parent == form._speedTrendCard;
var retainedSampleCount = form._trafficChart.PointCount; checks["scenic_artwork_packaged_in_exe"] = ScenicTheme.ArtworkAvailable;
foreach (var period in SpeedHistoryPeriod.All) checks["footer_poem_does_not_overlap_plan"] = !form._footerPoem.Visible || form._footerPoem.Left > form._expiryLabel.Right;
{ checks["internal_use_notice_visible"] = form._footerHint.Text == "仅限内部使用,不作商业使用。" && form._footerHint.Visible;
form._historyRangeCombo.SelectedItem = period; checks["proxy_metrics_values"] = form._usageMetric.UnitText == "GB" && form._uploadMetric.UnitText == "KB/s" && form._sessionMetric.UnitText == "MB";
Capture("speed-" + period.Minutes + "m"); checks["speed_figures_left_curve_and_totals_right"] = form._usageMetric.Parent == form._sessionMetric.Parent
checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes && form._usageMetric.Parent == form._dailyCard && form._trafficChart.Parent == form._speedTrendCard && form._uploadMetric.Parent == form._trafficCard
&& form._trafficChart.PointCount == retainedSampleCount; && form._downloadMetric.Parent == form._trafficCard;
} form._historyRangeCombo.SelectedIndex = 0;
form._dailyChart.SetHistory([], fixtureRanges); Capture("history-legacy-unavailable");
checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60; checks["daily_accounting_curve_no_longer_displayed"] = form._dailyChart.Parent is null && !form._dailyChart.Visible;
form._historyRangeCombo.SelectedIndex = 1; form._dailyChart.SetHistory([], fixtureRanges);
form.Size = form.MinimumSize; var retainedSampleCount = form._trafficChart.PointCount;
Capture("compact"); foreach (var period in SpeedHistoryPeriod.All)
checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width; {
checks["compact_controls_within_cards"] = form.DashboardControlsFit(); form._historyRangeCombo.SelectedItem = period;
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1); Capture("speed-" + period.Minutes + "m");
Application.DoEvents(); checks["speed_filter_" + period.Minutes] = form._trafficChart.PeriodMinutes == period.Minutes
form.LayoutDashboard(); && form._trafficChart.PointCount == retainedSampleCount;
checks["compact_footer_fits_without_scroll"] = !form._dashboardScrollBar.Visible }
&& form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom; form._dailyChart.SetHistory([], fixtureRanges);
checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible; checks["profile_refresh_preserves_speed_filter"] = form._trafficChart.PeriodMinutes == 60;
Capture("compact-scrolled"); form._historyRangeCombo.SelectedIndex = 1;
form._dashboardScrollBar.Value = 0; form.Size = form.MinimumSize;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640)); Capture("compact");
form._currentNodeName = "VPN002"; checks["zero3_compact_name_fits"] = TextRenderer.MeasureText(form._currentNodeName, form._currentNodeLabel.Font).Width <= form._currentNodeLabel.Width;
form._currentNodeLabel.Text = form._currentNodeName; checks["compact_controls_within_cards"] = form.DashboardControlsFit();
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · 已回退到公共节点"); form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
Capture("public-fallback"); Application.DoEvents();
checks["fallback_does_not_show_zero3"] = !form._statusDetail.Text.Contains("Zero3") && form._currentNodeLabel.Text == "VPN002"; form.LayoutDashboard();
form.SetConnectionState(false, "未连接", "点击连接,自动选择工作节点"); checks["compact_footer_fits_without_scroll"] = !form._dashboardScrollBar.Visible
form._currentNodeLabel.Text = "连接后自动分配"; && form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
form._trafficChart.Reset(); form._dailyChart.SetHistory([]); checks["compact_no_horizontal_scrollbar"] = !form._dashboardView.HorizontalScroll.Visible;
Capture("disconnected"); Capture("compact-scrolled");
checks["disconnected_speed_not_stale"] = form._uploadMetric.ValueText == "—" && form._downloadMetric.ValueText == "—"; form._dashboardScrollBar.Value = 0;
form._connectionModeCombo.SelectedIndex = 1; form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form._manualNodeCombo.SelectedIndex = 0; form._currentNodeName = "VPN002";
Capture("manual-selection"); form._currentNodeLabel.Text = form._currentNodeName;
checks["manual_selection_controls_within_card"] = form.DashboardControlsFit(); form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · 已回退到公共节点");
checks["manual_selection_visible_when_disconnected"] = form._manualNodeCombo.Visible && form._manualNodeCombo.Enabled; Capture("public-fallback");
form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理"); checks["fallback_does_not_show_zero3"] = !form._statusDetail.Text.Contains("Zero3") && form._currentNodeLabel.Text == "VPN002";
Capture("manual-connected"); form.SetConnectionState(false, "未连接", "点击连接,自动选择工作节点");
checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible; form._currentNodeLabel.Text = "连接后自动分配";
// Same window dimensions with or without Tailnet: only the left speed form._trafficChart.Reset(); form._dailyChart.SetHistory([]);
// region is subdivided. Synthetic samples do not claim live acceptance. Capture("disconnected");
form._connectionModeCombo.SelectedIndex = 0; checks["disconnected_speed_not_stale"] = form._uploadMetric.ValueText == "—" && form._downloadMetric.ValueText == "—";
form._currentNodeBaseName = "VPN003"; form._connectionModeCombo.SelectedIndex = 1;
form.UpdateConnectedTransportPresentation(true); form._manualNodeCombo.SelectedIndex = 0;
form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理"); Capture("manual-selection");
form._currentNodeLabel.Text = form._currentNodeName; checks["manual_selection_controls_within_card"] = form.DashboardControlsFit();
form._dailyChart.SetHistory([], fixtureRanges); checks["manual_selection_visible_when_disconnected"] = form._manualNodeCombo.Visible && form._manualNodeCombo.Enabled;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640)); form.SetConnectionState(true, "已安全连接", "手动指定节点 · AI 智能代理");
form._trafficChart.Reset(); Capture("manual-connected");
form.ResetTailnetTraffic(); checks["manual_connected_selection_locked"] = !form._connectionModeCombo.Enabled && !form._manualNodeCombo.Visible;
for (var i = 0; i < 60; i++) // Same window dimensions with or without Tailnet: only the left speed
{ // region is subdivided. Synthetic samples do not claim live acceptance.
var up = (i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024; form._connectionModeCombo.SelectedIndex = 0;
var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024; form._currentNodeBaseName = "VPN003";
var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5); form.UpdateConnectedTransportPresentation(true);
form._trafficChart.Add(up, down, sampledAt); form.SetConnectionState(true, "已安全连接", form._currentNodeName + " · AI 智能代理");
} form._currentNodeLabel.Text = form._currentNodeName;
form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟"); form._dailyChart.SetHistory([], fixtureRanges);
form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟"); form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
Capture("tailnet-dashboard"); form._trafficChart.Reset();
checks["tailnet_wide_preview_has_left_two_right_one"] = form._dailyCard.Top == form._trafficCard.Top form.ResetTailnetTraffic();
&& form._dailyCard.Bottom == form._tailnetTrafficCard.Bottom; for (var i = 0; i < 60; i++)
form.Size = form.MinimumSize; {
Capture("tailnet-compact"); var up = (i % 13 == 0 ? 72 : 8 + Math.Sin(i * 1.8) * 4) * 1024;
form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1); var down = (i % 9 == 2 ? 130 : 10 + Math.Sin(i * 2.4) * 8) * 1024;
Capture("tailnet-compact-scrolled"); var sampledAt = DateTimeOffset.Now.AddSeconds((i - 59) * 5);
checks["tailnet_compact_preview_footer_reachable"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom form._trafficChart.Add(up, down, sampledAt);
<= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom; }
form.SetTailnetTrafficVisibility(false); form.DisplayTraffic(23842, 89312, "演示样本 · 近 5 分钟");
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640)); form.DisplayTailnetTraffic(23842, 89312, "演示样本 · 近 5 分钟");
form.ShowLogin(); Capture("login"); Capture("tailnet-dashboard");
checks["login_fields_visible"] = form.LoginFieldsVisibleForTest; checks["tailnet_wide_preview_has_left_two_right_one"] = form._dailyCard.Top == form._trafficCard.Top
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-ui-self-test.json"), JsonSerializer.Serialize(new && form._dailyCard.Bottom == form._speedTrendCard.Bottom;
{ form.Size = form.MinimumSize;
version = GetDisplayVersion(), passed = checks.Values.All(v => v), checks, Capture("tailnet-compact");
dpi = form.DeviceDpi, synthetic_data = true, network_modified = false, installed_client_modified = false form._dashboardScrollBar.Value = Math.Max(0, form._dashboardScrollBar.Maximum - form._dashboardScrollBar.LargeChange + 1);
}, new JsonSerializerOptions { WriteIndented = true })); Capture("tailnet-compact-scrolled");
form.RequestExit(); checks["tailnet_compact_preview_footer_reachable"] = form._footer.RectangleToScreen(form._footer.ClientRectangle).Bottom
if (checks.Values.Any(v => !v)) throw new InvalidOperationException("Dashboard UI self-test failed; inspect dashboard-ui-self-test.json"); <= form._dashboardView.RectangleToScreen(form._dashboardView.ClientRectangle).Bottom;
} form.ClientSize=new Size(form.ScaleLogical(480),form.ScaleLogical(360));
form.SetNodeTrafficPermission(true);
private bool DashboardControlsFit() => new Control[] { _statusCard, _nodeCard, _modeCard, _trafficCard, _tailnetTrafficCard, _dailyCard, _footer } form.LayoutDashboard(); Capture("half-size-tailnet-servers");
.Where(parent => parent.Visible) checks["half_size_tailnet_servers_fit"] = form.DashboardControlsFit() && !form._dashboardScrollBar.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)); && form._nodeTrafficPanel.Bottom<form._footer.Top;
} form.SetNodeTrafficPermission(false);
form.SetTailnetTrafficVisibility(false);
form.ShowLogin(); Capture("half-size-login");
checks["half_size_login_visible"] = form.LoginFieldsVisibleForTest && form.LoginRegistrationAlignedForTest;
form.ClientSize = new Size(form.ScaleLogical(900), form.ScaleLogical(640));
form.ShowLogin(); Capture("login");
checks["login_fields_visible"] = form.LoginFieldsVisibleForTest;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "dashboard-ui-self-test.json"), JsonSerializer.Serialize(new
{
version = GetDisplayVersion(), passed = checks.Values.All(v => v), checks,
dpi = form.DeviceDpi, synthetic_data = true, network_modified = false, installed_client_modified = false
}, new JsonSerializerOptions { WriteIndented = true }));
form.RequestExit();
if (checks.Values.Any(v => !v)) 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 }
.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));
}
+1715 -1711
View File
File diff suppressed because it is too large Load Diff
+41 -3
View File
@@ -13,6 +13,44 @@ internal static class NodeHealthProbe
internal static bool OverallHealthy(IReadOnlyList<bool> results) => internal static bool OverallHealthy(IReadOnlyList<bool> results) =>
results.Count >= 3 && results[2] && (results[0] || results[1]); results.Count >= 3 && results[2] && (results[0] || results[1]);
internal static async Task<bool> AggregateAsync(IReadOnlyList<Task<bool>> probes,
CancellationToken token, Action cancelRemaining)
{
async Task<bool> ResultAsync(Task<bool> probe)
{
try { return await probe.ConfigureAwait(false); }
catch { return false; }
}
// Observe every probe even after an early verdict. Cancellation or a
// late HTTP exception from a losing probe must not escape unobserved.
var observations = probes.Select(ResultAsync).ToArray();
try
{
token.ThrowIfCancellationRequested();
if (observations.Length < 3) return false;
var results = new bool?[3];
var pending = Enumerable.Range(0, 3).ToList();
while (pending.Count > 0)
{
var completed = await Task.WhenAny(pending.Select(index => observations[index]))
.WaitAsync(token).ConfigureAwait(false);
var index = pending.First(index => observations[index] == completed);
results[index] = await completed.ConfigureAwait(false);
pending.Remove(index);
token.ThrowIfCancellationRequested();
// Codex is mandatory; either independent target is sufficient.
// Stop only once that same predicate is proved or impossible.
if (results[2] == false || results[0] == false && results[1] == false) return false;
if (results[2] == true && (results[0] == true || results[1] == true)) return true;
}
return false;
}
finally
{
cancelRemaining();
}
}
internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0) internal static async Task<bool> CheckAsync(CancellationToken token, int proxyPort = 0)
{ {
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token);
@@ -23,17 +61,17 @@ internal static class NodeHealthProbe
}) { Timeout = Timeout.InfiniteTimeSpan }; }) { Timeout = Timeout.InfiniteTimeSpan };
var urls = new[] { "https://www.google.com/generate_204", "https://api.openai.com/v1/models", var urls = new[] { "https://www.google.com/generate_204", "https://api.openai.com/v1/models",
"https://chatgpt.com/backend-api/codex/models" }; "https://chatgpt.com/backend-api/codex/models" };
var results = await Task.WhenAll(urls.Select(async (url, index) => { var probes = urls.Select(async (url, index) => {
try { try {
using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token); using var response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
return Accepts(index, (int)response.StatusCode); return Accepts(index, (int)response.StatusCode);
} }
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; } catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
catch { return false; } catch { return false; }
})); }).ToArray();
// This client exists primarily for ChatGPT/Codex. Google or the OpenAI // This client exists primarily for ChatGPT/Codex. Google or the OpenAI
// REST API remaining reachable must not mask a broken Codex transport. // REST API remaining reachable must not mask a broken Codex transport.
// Require the Codex endpoint plus one independent Internet target. // Require the Codex endpoint plus one independent Internet target.
return OverallHealthy(results); return await AggregateAsync(probes, token, timeout.Cancel);
} }
} }
+185
View File
@@ -0,0 +1,185 @@
using System.Text.Json;
namespace UCVL.VPNPlus;
// Exercises the production aggregator without HTTP, proxies or network changes.
internal static class NodeHealthProbeSelfTest
{
internal static async Task<int> RunAsync()
{
var checks = new Dictionary<string, bool>();
var errors = new Dictionary<string, string>();
async Task Check(string name, Func<Task> test)
{
try { await test(); checks[name] = true; }
catch (Exception error) { checks[name] = false; errors[name] = error.Message; }
}
await Check("http_status_and_codex_requirement_preserved", () => {
Require(NodeHealthProbe.Accepts(0, 200) && NodeHealthProbe.Accepts(0, 204)
&& !NodeHealthProbe.Accepts(0, 201) && !NodeHealthProbe.Accepts(0, 401)
&& NodeHealthProbe.Accepts(1, 401) && !NodeHealthProbe.Accepts(1, 500)
&& NodeHealthProbe.Accepts(2, 499) && !NodeHealthProbe.Accepts(2, 500), "HTTP status policy changed");
Require(NodeHealthProbe.OverallHealthy(new[] { true, false, true })
&& NodeHealthProbe.OverallHealthy(new[] { false, true, true })
&& !NodeHealthProbe.OverallHealthy(new[] { true, true, false })
&& !NodeHealthProbe.OverallHealthy(new[] { false, false, true }), "Codex health predicate changed");
return Task.CompletedTask;
});
await Check("google_and_codex_do_not_wait_for_api", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Required successes did not prove health");
Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled");
});
await Check("api_and_codex_do_not_wait_for_google", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Required successes did not prove health");
Require(fixture.Cancellation.IsCancellationRequested, "Unused HTTP probe was not cancelled");
});
await Check("codex_failure_finishes_with_other_probes_pending", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(false);
Require(!await Finished(result), "Codex failure must prove unhealthy");
Require(fixture.Cancellation.IsCancellationRequested, "Unneeded HTTP probes were not cancelled");
});
await Check("both_independent_failures_do_not_wait_for_codex", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(false); fixture.Api.SetResult(false);
Require(!await Finished(result), "No independent target can prove health");
});
await Check("google_and_api_success_still_waits_for_codex", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Api.SetResult(true);
await StillPending(result);
Require(!fixture.Cancellation.IsCancellationRequested, "Codex was cancelled before its verdict");
fixture.Codex.SetResult(false);
Require(!await Finished(result), "Independent successes cannot mask Codex failure");
});
await Check("codex_success_still_waits_for_independent_proof", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(true);
await StillPending(result);
fixture.Google.SetResult(false); await StillPending(result);
fixture.Api.SetResult(true);
Require(await Finished(result), "An eventual independent success must prove health");
});
await Check("critical_probe_exception_counts_as_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetException(new HttpRequestException("test failure"));
Require(!await Finished(result), "Failed Codex probe must prove unhealthy");
});
await Check("independent_exception_allows_other_independent_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetException(new HttpRequestException("test failure"));
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "One failed independent probe must not hide valid health");
});
await Check("two_independent_exceptions_prove_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetException(new IOException("test failure"));
fixture.Api.SetException(new HttpRequestException("test failure"));
Require(!await Finished(result), "Two failed independent probes must prove unhealthy");
});
await Check("caller_precancellation_is_preserved", async () => {
using var caller = new CancellationTokenSource(); caller.Cancel();
using var fixture = new Probes();
await Cancelled(fixture.Start(caller.Token), caller.Token);
Require(fixture.Cancellation.IsCancellationRequested, "Probe cleanup did not run after cancellation");
});
await Check("caller_cancellation_interrupts_pending_probes", async () => {
using var caller = new CancellationTokenSource();
using var fixture = new Probes();
var result = fixture.Start(caller.Token); caller.Cancel();
await Cancelled(result, caller.Token);
Require(fixture.Cancellation.IsCancellationRequested, "Pending HTTP probes were not cancelled");
});
await Check("late_failure_cannot_change_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established");
fixture.Api.SetException(new HttpRequestException("late unused failure"));
Require(await result, "Late unused failure changed a completed health verdict");
});
await Check("late_success_cannot_change_failure", async () => {
using var fixture = new Probes();
var result = fixture.Start(); fixture.Codex.SetResult(false);
Require(!await Finished(result), "Failure was not established");
fixture.Google.SetResult(true); fixture.Api.SetResult(true);
Require(!await result, "Late successes changed a completed health verdict");
});
await Check("late_caller_cancellation_cannot_change_success", async () => {
using var caller = new CancellationTokenSource();
using var fixture = new Probes();
var result = fixture.Start(caller.Token);
fixture.Google.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established"); caller.Cancel();
Require(await result, "Later cancellation changed a completed health verdict");
});
await Check("cancelled_unused_probe_cannot_change_success", async () => {
using var fixture = new Probes();
var result = fixture.Start();
fixture.Api.SetResult(true); fixture.Codex.SetResult(true);
Require(await Finished(result), "Health was not established");
fixture.Google.SetCanceled(fixture.Cancellation.Token);
Require(await result, "Unused-probe cancellation changed the health verdict");
});
var passed = checks.Values.All(value => value);
var report = JsonSerializer.Serialize(new { kind = "node_health_early_completion", network_used = false,
checks, errors, passed }, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-health-probe-self-test.json"), report);
Console.WriteLine(report);
return passed ? 0 : 1;
}
private static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
private static async Task<bool> Finished(Task<bool> result)
{
try { return await result.WaitAsync(TimeSpan.FromSeconds(1)); }
catch (TimeoutException) { throw new InvalidOperationException("Health verdict waited for an unnecessary pending probe"); }
}
private static async Task StillPending(Task<bool> result)
{
var winner = await Task.WhenAny(result, Task.Delay(40));
Require(winner != result, "Health completed without required evidence");
}
private static async Task Cancelled(Task<bool> result, CancellationToken caller)
{
try { await result.WaitAsync(TimeSpan.FromSeconds(1)); }
catch (OperationCanceledException error) when (caller.IsCancellationRequested && error.CancellationToken == caller) { return; }
throw new InvalidOperationException("Caller cancellation did not propagate with its token");
}
private sealed class Probes : IDisposable
{
private Task<bool>? _running;
internal TaskCompletionSource<bool> Google { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal TaskCompletionSource<bool> Api { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal TaskCompletionSource<bool> Codex { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
internal CancellationTokenSource Cancellation { get; } = new();
internal Task<bool> Start(CancellationToken caller = default) => _running = NodeHealthProbe.AggregateAsync(
new[] { Google.Task, Api.Task, Codex.Task }, caller, Cancellation.Cancel);
public void Dispose()
{
Google.TrySetResult(false); Api.TrySetResult(false); Codex.TrySetResult(false);
if (_running is null) Cancellation.Dispose();
else _ = _running.ContinueWith(task => { _ = task.Exception; Cancellation.Dispose(); },
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
}
+160 -158
View File
@@ -1,158 +1,160 @@
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal sealed class NodeTrafficSnapshot internal sealed class NodeTrafficSnapshot
{ {
[JsonPropertyName("contract")] public int Contract { get; init; } [JsonPropertyName("contract")] public int Contract { get; init; }
[JsonPropertyName("scope")] public string Scope { get; init; } = ""; [JsonPropertyName("scope")] public string Scope { get; init; } = "";
[JsonPropertyName("source")] public string Source { get; init; } = ""; [JsonPropertyName("source")] public string Source { get; init; } = "";
[JsonPropertyName("direction")] public string Direction { get; init; } = ""; [JsonPropertyName("direction")] public string Direction { get; init; } = "";
[JsonPropertyName("counter_since")] public string CounterSince { get; init; } = ""; [JsonPropertyName("counter_since")] public string CounterSince { get; init; } = "";
[JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; } [JsonPropertyName("generated_at")] public DateTimeOffset GeneratedAt { get; init; }
[JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = []; [JsonPropertyName("nodes")] public List<NodeTrafficReading> Nodes { get; init; } = [];
} }
internal sealed class NodeTrafficReading internal sealed class NodeTrafficReading
{ {
[JsonPropertyName("slug")] public string Slug { get; init; } = ""; [JsonPropertyName("slug")] public string Slug { get; init; } = "";
[JsonPropertyName("name")] public string Name { get; init; } = ""; [JsonPropertyName("name")] public string Name { get; init; } = "";
[JsonPropertyName("region")] public string Region { get; init; } = ""; [JsonPropertyName("region")] public string Region { get; init; } = "";
[JsonPropertyName("current_upload_bytes_per_second")] public long? UploadRate { get; init; } [JsonPropertyName("current_upload_bytes_per_second")] public long? UploadRate { get; init; }
[JsonPropertyName("current_download_bytes_per_second")] public long? DownloadRate { get; init; } [JsonPropertyName("current_download_bytes_per_second")] public long? DownloadRate { get; init; }
[JsonPropertyName("total_upload_bytes")] public long? TotalUpload { get; init; } [JsonPropertyName("total_upload_bytes")] public long? TotalUpload { get; init; }
[JsonPropertyName("total_download_bytes")] public long? TotalDownload { get; init; } [JsonPropertyName("total_download_bytes")] public long? TotalDownload { get; init; }
[JsonPropertyName("sampled_at")] public DateTimeOffset? SampledAt { get; init; } [JsonPropertyName("sampled_at")] public DateTimeOffset? SampledAt { get; init; }
[JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; } [JsonPropertyName("interval_seconds")] public double? IntervalSeconds { get; init; }
[JsonPropertyName("stale")] public bool Stale { get; init; } [JsonPropertyName("stale")] public bool Stale { get; init; }
[JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; } [JsonPropertyName("counter_epoch")] public string? CounterEpoch { get; init; }
} }
// Read-only display contract: no personal accounting or route/core mutations. // Read-only display contract: no personal accounting or route/core mutations.
internal static class NodeTrafficPresentation internal static class NodeTrafficPresentation
{ {
internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"]; internal static readonly string[] Slugs = ["aliyun-tokyo-002", "aliyun-siliconvalley-003"];
internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1 internal static bool Valid(NodeTrafficSnapshot value, DateTimeOffset now) => value.Contract == 1
&& value.Scope == "server_host_interface" && value.Source == "linux_host_interface" && value.Scope == "server_host_interface" && value.Source == "linux_host_interface"
&& value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset" && value.Direction == "interface_perspective" && value.CounterSince == "boot_or_interface_reset"
&& value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15) && value.GeneratedAt <= now.AddSeconds(5) && value.GeneratedAt >= now.AddSeconds(-15)
&& value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null) && value.Nodes is { Count: <= 2 } && value.Nodes.All(n => n is not null)
&& value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count && value.Nodes.Select(n => n.Slug).Distinct(StringComparer.Ordinal).Count() == value.Nodes.Count
&& value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal) && value.Nodes.All(n => Slugs.Contains(n.Slug, StringComparer.Ordinal)
&& n.UploadRate is not < 0 && n.DownloadRate is not < 0 && n.UploadRate is not < 0 && n.DownloadRate is not < 0
&& n.TotalUpload is not < 0 && n.TotalDownload is not < 0 && n.TotalUpload is not < 0 && n.TotalDownload is not < 0
&& (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30)); && (n.IntervalSeconds is null || double.IsFinite(n.IntervalSeconds.Value) && n.IntervalSeconds > 0 && n.IntervalSeconds <= 30));
internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale internal static bool Fresh(NodeTrafficReading row, DateTimeOffset now) => !row.Stale
&& row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15) && row.SampledAt is { } sampled && sampled <= now.AddSeconds(5) && sampled >= now.AddSeconds(-15)
&& row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch); && row.IntervalSeconds is > 0 and <= 30 && !string.IsNullOrWhiteSpace(row.CounterEpoch);
internal static string Bytes(long? bytes, bool speed = false) internal static string Bytes(long? bytes, bool speed = false)
{ {
if (bytes is null or < 0) return "—"; if (bytes is null or < 0) return "—";
var value = (double)bytes.Value; var value = (double)bytes.Value;
string[] units = ["B", "KB", "MB", "GB", "TB"]; string[] units = ["B", "KB", "MB", "GB", "TB"];
var unit = 0; var unit = 0;
while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; }
return $"{value:0.##} {units[unit]}" + (speed ? "/s" : ""); return $"{value:0.##} {units[unit]}" + (speed ? "/s" : "");
} }
} }
// One buffered surface, not a table of native child HWNDs. A snapshot swaps // One buffered surface, not a table of native child HWNDs. A snapshot swaps
// atomically on the UI thread and never changes row count or window height. // atomically on the UI thread and never changes row count or window height.
internal sealed class NodeTrafficPanel : CardPanel internal sealed class NodeTrafficPanel : CardPanel
{ {
private NodeTrafficSnapshot? _snapshot; private NodeTrafficSnapshot? _snapshot;
private string _status = "等待服务器采样"; private string _status = "等待服务器采样";
internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); } internal void SetSnapshot(NodeTrafficSnapshot value) { _snapshot = value; _status = "每 5 秒更新"; Invalidate(); }
internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); } internal void Unavailable(string status, bool clear = false) { if (clear) _snapshot = null; _status = status; Invalidate(); }
internal NodeTrafficPanel() => AccessibleName = "VPN 服务器上行下行实时速度与累计流量"; internal NodeTrafficPanel() => AccessibleName = "VPN 服务器上行下行实时速度与累计流量";
internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight) internal static (Rectangle Title, Rectangle[] Rows) TextLayout(Size size, int dpi, int fontHeight)
{ {
var pad = Math.Max(2, 4 * dpi / 96); var pad = Math.Max(2, 4 * dpi / 96);
var contentHeight = Math.Max(0, size.Height - pad * 2); var contentHeight = Math.Max(0, size.Height - pad * 2);
var title = contentHeight >= fontHeight * 3; var title = contentHeight >= fontHeight * 3;
var height = contentHeight / (title ? 3 : 2); var height = contentHeight / (title ? 3 : 2);
Rectangle Line(int row) => new(pad, pad + row * height, Math.Max(0, size.Width - pad * 2), height); Rectangle Line(int row) => new(pad, pad + row * height, Math.Max(0, size.Width - pad * 2), height);
return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]); return (title ? Line(0) : Rectangle.Empty, [Line(title ? 1 : 0), Line(title ? 2 : 1)]);
} }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
base.OnPaint(e); base.OnPaint(e);
var now = DateTimeOffset.UtcNow; var now = DateTimeOffset.UtcNow;
using var font = Brand.Font(7.1f); var compact=Width<720*DeviceDpi/96;
var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height); using var font = Brand.Font(compact?6.5f:7.1f);
var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis; var layout = TextLayout(ClientSize, DeviceDpi, TextRenderer.MeasureText(e.Graphics, "VPN002 上传", font).Height);
if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 主 WAN 网卡 · 累计自网卡启动 / 重置", font, var flags = ChartAxis.PaintFlags | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis;
layout.Title, Brand.Muted, flags); if (!layout.Title.IsEmpty) TextRenderer.DrawText(e.Graphics, "服务器整机流量 · 主 WAN 网卡 · 累计自网卡启动 / 重置", font,
for (var i = 0; i < 2; i++) layout.Title, Brand.Muted, flags);
{ for (var i = 0; i < 2; i++)
var slug = NodeTrafficPresentation.Slugs[i]; {
var row = _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug); var slug = NodeTrafficPresentation.Slugs[i];
var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now) var row = _snapshot?.Nodes.SingleOrDefault(n => n.Slug == slug);
&& NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新"; var fresh = row is not null && _snapshot is not null && NodeTrafficPresentation.Valid(_snapshot, now)
var name = i == 0 ? "VPN002 东京" : "VPN003 美国"; && NodeTrafficPresentation.Fresh(row, now) && _status == "每 5 秒更新";
var up = fresh ? row!.UploadRate : null; var name = i == 0 ? "VPN002 东京" : "VPN003 美国";
var down = fresh ? row!.DownloadRate : null; var up = fresh ? row!.UploadRate : null;
var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss") var down = fresh ? row!.DownloadRate : null;
: row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报"; var status = fresh ? row!.SampledAt!.Value.LocalDateTime.ToString("HH:mm:ss")
var text = $"{name} ↑ {NodeTrafficPresentation.Bytes(up, true)} ↓ {NodeTrafficPresentation.Bytes(down, true)}" : row?.SampledAt is { } oldTime ? $"过期 {oldTime.LocalDateTime:HH:mm:ss}" : "等待上报";
+ $" 累计 ↑ {NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓ {NodeTrafficPresentation.Bytes(row?.TotalDownload)} {status}"; var text = $"{name} ↑ {NodeTrafficPresentation.Bytes(up, true)} ↓ {NodeTrafficPresentation.Bytes(down, true)}"
TextRenderer.DrawText(e.Graphics, text, font, + $" 累计 ↑ {NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓ {NodeTrafficPresentation.Bytes(row?.TotalDownload)} {status}";
layout.Rows[i], Brand.Text, flags); if(compact)text=$"{(i==0?"VPN002 东京":"VPN003 美国")} {(fresh?status:row?.SampledAt is { } age?$"过期{age.LocalDateTime:HH:mm}":"待上报")} ↑{NodeTrafficPresentation.Bytes(up,true)} ↓{NodeTrafficPresentation.Bytes(down,true)} 累计↑{NodeTrafficPresentation.Bytes(row?.TotalUpload)} ↓{NodeTrafficPresentation.Bytes(row?.TotalDownload)}";
} TextRenderer.DrawText(e.Graphics, text, font,
AccessibleDescription = _status + ";速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。"; layout.Rows[i], Brand.Text, flags);
} }
} AccessibleDescription = _status + ";速率为采样区间平均。服务器整机网卡数据,不是本账号代理流量,不计入套餐用量;过期累计保留采样时间。";
}
internal sealed partial class MainForm }
{
private readonly NodeTrafficPanel _nodeTrafficPanel = new(); internal sealed partial class MainForm
private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 }; {
private bool _canViewNodeTraffic, _nodeTrafficReading; private readonly NodeTrafficPanel _nodeTrafficPanel = new();
private DateTimeOffset _nextNodeTrafficAttempt; private readonly System.Windows.Forms.Timer _nodeTrafficTimer = new() { Interval = 5_000 };
private void BuildNodeTrafficMonitor() private bool _canViewNodeTraffic, _nodeTrafficReading;
{ private DateTimeOffset _nextNodeTrafficAttempt;
_nodeTrafficPanel.Visible = false; private void BuildNodeTrafficMonitor()
_dashboardBody.Controls.Add(_nodeTrafficPanel); {
_nodeTrafficTimer.Tick += async (_, _) => await RefreshNodeTrafficAsync(); _nodeTrafficPanel.Visible = false;
_nodeTrafficPanel.Disposed += (_, _) => _nodeTrafficTimer.Dispose(); _dashboardBody.Controls.Add(_nodeTrafficPanel);
} _nodeTrafficTimer.Tick += async (_, _) => await RefreshNodeTrafficAsync();
private void SetNodeTrafficPermission(bool allowed) _nodeTrafficPanel.Disposed += (_, _) => _nodeTrafficTimer.Dispose();
{ }
if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true); private void SetNodeTrafficPermission(bool allowed)
_canViewNodeTraffic = allowed; {
_nodeTrafficPanel.Visible = allowed; if (_canViewNodeTraffic != allowed) _nodeTrafficPanel.Unavailable("等待服务器采样", clear: true);
if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start(); _canViewNodeTraffic = allowed;
else _nodeTrafficTimer.Stop(); _nodeTrafficPanel.Visible = allowed;
LayoutDashboard(); if (allowed && !_preview && !_uiOnly && !_exiting) _nodeTrafficTimer.Start();
} else _nodeTrafficTimer.Stop();
private async Task RefreshNodeTrafficAsync() LayoutDashboard();
{ }
_nodeTrafficPanel.Invalidate(); private async Task RefreshNodeTrafficAsync()
if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting {
|| string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return; _nodeTrafficPanel.Invalidate();
var token = _accessToken; if (!_canViewNodeTraffic || _nodeTrafficReading || _preview || _uiOnly || _exiting
var revision = _sessionRevision; || string.IsNullOrWhiteSpace(_accessToken) || DateTimeOffset.UtcNow < _nextNodeTrafficAttempt) return;
bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token; var token = _accessToken;
_nodeTrafficReading = true; var revision = _sessionRevision;
try bool Current() => !_exiting && !IsDisposed && _canViewNodeTraffic && _sessionRevision == revision && _accessToken == token;
{ _nodeTrafficReading = true;
var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token); try
if (!Current()) return; {
if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。"); var result = await _api.GetNodeTrafficAsync(token, _lifetime.Token);
_nodeTrafficPanel.SetSnapshot(result); if (!Current()) return;
} if (!NodeTrafficPresentation.Valid(result, DateTimeOffset.UtcNow)) throw new IOException("监控契约或时间戳无效。");
catch (ApiException error) when (error.StatusCode is 401 or 403) _nodeTrafficPanel.SetSnapshot(result);
{ }
if (Current()) { _nodeTrafficPanel.Unavailable("监控权限不可用", clear: true); SetNodeTrafficPermission(false); } catch (ApiException error) when (error.StatusCode is 401 or 403)
// An optional monitor must not log out or disconnect the VPN. {
} if (Current()) { _nodeTrafficPanel.Unavailable("监控权限不可用", clear: true); SetNodeTrafficPermission(false); }
catch (ApiException error) when (error.StatusCode is 404 or 405) // An optional monitor must not log out or disconnect the VPN.
{ }
if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); } catch (ApiException error) when (error.StatusCode is 404 or 405)
} {
catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); } if (Current()) { _nextNodeTrafficAttempt = DateTimeOffset.UtcNow.AddMinutes(2); _nodeTrafficPanel.Unavailable("后台尚未提供服务器监控"); }
catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); } }
finally { _nodeTrafficReading = false; } catch (OperationCanceledException) { if (Current()) _nodeTrafficPanel.Unavailable("采样请求超时"); }
} catch (Exception) { if (Current()) _nodeTrafficPanel.Unavailable("服务器采样暂不可用"); }
} finally { _nodeTrafficReading = false; }
}
}
+89 -83
View File
@@ -1,83 +1,89 @@
using System.Text.Json; using System.Text.Json;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
internal static class NodeTrafficSelfTest internal static class NodeTrafficSelfTest
{ {
internal static int Run() internal static int Run()
{ {
var checks = new Dictionary<string, bool>(); var checks = new Dictionary<string, bool>();
string? error = null; string? error = null;
try try
{ {
var now = new DateTimeOffset(2026, 10, 22, 8, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 22, 8, 0, 0, TimeSpan.Zero);
NodeTrafficReading Row(string slug = "aliyun-tokyo-002", bool stale = false, DateTimeOffset? sampled = null, NodeTrafficReading Row(string slug = "aliyun-tokyo-002", bool stale = false, DateTimeOffset? sampled = null,
long? up = 10, long? down = 20, long? totalUp = 30, long? totalDown = 40, double? interval = 5, string? epoch = "fixture") => new() long? up = 10, long? down = 20, long? totalUp = 30, long? totalDown = 40, double? interval = 5, string? epoch = "fixture") => new()
{ Slug = slug, Stale = stale, SampledAt = sampled ?? now, UploadRate = up, DownloadRate = down, { Slug = slug, Stale = stale, SampledAt = sampled ?? now, UploadRate = up, DownloadRate = down,
TotalUpload = totalUp, TotalDownload = totalDown, IntervalSeconds = interval, CounterEpoch = epoch }; TotalUpload = totalUp, TotalDownload = totalDown, IntervalSeconds = interval, CounterEpoch = epoch };
NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface", NodeTrafficSnapshot Snapshot(List<NodeTrafficReading>? rows = null, string scope = "server_host_interface",
string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new() string source = "linux_host_interface", DateTimeOffset? generated = null, string direction = "interface_perspective") => new()
{ Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset", { Contract = 1, Scope = scope, Source = source, Direction = direction, CounterSince = "boot_or_interface_reset",
GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] }; GeneratedAt = generated ?? now, Nodes = rows ?? [Row(), Row(NodeTrafficPresentation.Slugs[1])] };
bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now); bool Valid(NodeTrafficSnapshot value) => NodeTrafficPresentation.Valid(value, now);
checks["exact_two_authorized_server_contract"] = Valid(Snapshot()); checks["exact_two_authorized_server_contract"] = Valid(Snapshot());
checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([])); checks["empty_authorized_set_is_not_fake_servers"] = Valid(Snapshot([]));
checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")])); checks["other_nodes_rejected"] = !Valid(Snapshot([Row("phone")]));
checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()])); checks["duplicate_node_rejected"] = !Valid(Snapshot([Row(), Row()]));
checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()])); checks["too_many_rows_rejected"] = !Valid(Snapshot([Row(), Row(), Row()]));
checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate")); checks["proxy_accounting_cannot_be_mislabelled_host"] = !Valid(Snapshot(scope: "server_proxy_aggregate"));
checks["unknown_source_rejected"] = !Valid(Snapshot(source: "unknown")); checks["unknown_source_rejected"] = !Valid(Snapshot(source: "unknown"));
checks["wrong_direction_rejected"] = !Valid(Snapshot(direction: "client_perspective")); checks["wrong_direction_rejected"] = !Valid(Snapshot(direction: "client_perspective"));
checks["stale_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(-16))); checks["stale_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(-16)));
checks["future_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(6))); checks["future_envelope_rejected"] = !Valid(Snapshot(generated: now.AddSeconds(6)));
checks["negative_upload_rejected"] = !Valid(Snapshot([Row(up: -1)])); checks["negative_upload_rejected"] = !Valid(Snapshot([Row(up: -1)]));
checks["negative_download_rejected"] = !Valid(Snapshot([Row(down: -1)])); checks["negative_download_rejected"] = !Valid(Snapshot([Row(down: -1)]));
checks["negative_total_rejected"] = !Valid(Snapshot([Row(totalUp: -1)])); checks["negative_total_rejected"] = !Valid(Snapshot([Row(totalUp: -1)]));
checks["nonfinite_interval_rejected"] = !Valid(Snapshot([Row(interval: double.NaN)])); checks["nonfinite_interval_rejected"] = !Valid(Snapshot([Row(interval: double.NaN)]));
checks["unbounded_interval_rejected"] = !Valid(Snapshot([Row(interval: 31)])); checks["unbounded_interval_rejected"] = !Valid(Snapshot([Row(interval: 31)]));
checks["fresh_sample_is_current"] = NodeTrafficPresentation.Fresh(Row(), now); checks["fresh_sample_is_current"] = NodeTrafficPresentation.Fresh(Row(), now);
checks["backend_stale_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(stale: true), now); checks["backend_stale_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(stale: true), now);
checks["client_checks_sample_age_independently"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(-16)), now); checks["client_checks_sample_age_independently"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(-16)), now);
checks["future_sample_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(6)), now); checks["future_sample_is_not_live"] = !NodeTrafficPresentation.Fresh(Row(sampled: now.AddSeconds(6)), now);
checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now); checks["first_counter_has_no_invented_rate"] = !NodeTrafficPresentation.Fresh(Row(up: null, down: null, interval: null), now);
checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now); checks["reset_epoch_required"] = !NodeTrafficPresentation.Fresh(Row(epoch: null), now);
checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—"; checks["missing_is_dash_not_zero"] = NodeTrafficPresentation.Bytes(null, true) == "—";
checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0 B/s"; checks["measured_zero_retained"] = NodeTrafficPresentation.Bytes(0, true) == "0 B/s";
checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200 KB/s"; checks["rate_uses_bytes_not_bits"] = NodeTrafficPresentation.Bytes(204800, true) == "200 KB/s";
checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB"; checks["cumulative_has_no_speed_suffix"] = NodeTrafficPresentation.Bytes(204800) == "200 KB";
checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest(); checks["all_geometry_monitor_tailnet_cases_fit"] = DashboardLayout.SelfTest();
using (var font = Brand.Font(7.1f)) using (var font = Brand.Font(6.5f))
{ using (var graphics = Graphics.FromHwnd(IntPtr.Zero))
var measuredHeight = TextRenderer.MeasureText("VPN002 上传", font).Height; {
foreach (var dpi in new[] { 96, 120, 144, 192, 336, 384 }) // Measure a real display context, then normalize once from its
{ // actual DPI. Default MeasureText may already be at 200% DPI.
var view = new Size(620 * dpi / 96, 350 * dpi / 96); var measuredHeight = TextRenderer.MeasureText(graphics, "VPN002 上传", font).Height;
var panel = DashboardLayout.Calculate(view, dpi, true, true).ServerTrafficCard; var sourceDpi = graphics.DpiY;
var text = NodeTrafficPanel.TextLayout(panel.Size, dpi, (int)Math.Ceiling(measuredHeight * dpi / 96d)); foreach (var dpi in new[] { 96, 120, 144, 192, 336, 384 })
checks["minimum_two_text_rows_fit_" + dpi] = text.Rows.Length == 2 foreach (var logicalView in new[] { new Size(480, 312), new Size(620, 350) })
&& text.Rows.All(row => row.Height >= measuredHeight * dpi / 96d && row.Bottom <= panel.Height) {
&& !text.Rows[0].IntersectsWith(text.Rows[1]); var view = new Size(logicalView.Width * dpi / 96, logicalView.Height * dpi / 96);
} var panel = DashboardLayout.Calculate(view, dpi, true, true).ServerTrafficCard;
} var targetFontHeight = (int)Math.Ceiling(measuredHeight * dpi / (double)sourceDpi);
foreach (var tailnet in new[] { false, true }) var text = NodeTrafficPanel.TextLayout(panel.Size, dpi, targetFontHeight);
{ checks[$"minimum_two_text_rows_fit_{logicalView.Width}x{logicalView.Height}_{dpi}"] = text.Rows.Length == 2
var view = new Size(960, 612); && text.Rows.All(row => row.Height >= targetFontHeight && row.Bottom <= panel.Height)
var layout = DashboardLayout.Calculate(view, 96, tailnet, true); && !text.Rows[0].IntersectsWith(text.Rows[1]);
checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom }
&& layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom }
&& (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom); foreach (var tailnet in new[] { false, true })
checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height {
&& layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top; var view = new Size(960, 612);
} var layout = DashboardLayout.Calculate(view, 96, tailnet, true);
var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!; checks["server_rows_below_real_speed_" + tailnet] = layout.ServerTrafficCard.Top > layout.DailyCard.Bottom
checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic; && layout.ServerTrafficCard.Top > layout.TrafficCard.Bottom
} && (!tailnet || layout.ServerTrafficCard.Top > layout.TailnetTrafficCard.Bottom);
catch (Exception exception) { error = exception.GetType().Name; } checks["no_extra_window_height_or_scroll_" + tailnet] = layout.Footer.Bottom <= view.Height
var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value); && layout.ContentHeight <= view.Height && layout.ServerTrafficCard.Bottom < layout.Footer.Top;
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"), }
JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract and fixed-height geometry only", var oldProfile = JsonSerializer.Deserialize<Profile>("{\"email\":\"fixture@example.invalid\"}")!;
network_modified = false, credentials_loaded = false, production_sample_observed = false }, checks["older_backend_omission_does_not_enable_monitor"] = !oldProfile.CanViewNodeTraffic;
new JsonSerializerOptions { WriteIndented = true })); }
return passed ? 0 : 84; catch (Exception exception) { error = exception.GetType().Name; }
} var passed = error is null && checks.Count >= 30 && checks.Values.All(value => value);
} File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "node-traffic-self-test.json"),
JsonSerializer.Serialize(new { passed, checks, error, scope = "offline contract and fixed-height geometry only",
network_modified = false, credentials_loaded = false, production_sample_observed = false },
new JsonSerializerOptions { WriteIndented = true }));
return passed ? 0 : 84;
}
}
+5
View File
@@ -28,7 +28,12 @@ internal static class Program
if (args.Length == 1 && args[0] == "--chart-freshness-self-test") if (args.Length == 1 && args[0] == "--chart-freshness-self-test")
return ChartFreshnessSelfTest.Run(); return ChartFreshnessSelfTest.Run();
if (args.Length == 1 && args[0] == "--node-traffic-self-test") if (args.Length == 1 && args[0] == "--node-traffic-self-test")
{
ApplicationConfiguration.Initialize();
return NodeTrafficSelfTest.Run(); return NodeTrafficSelfTest.Run();
}
if (args.Length == 1 && args[0] == "--node-health-probe-self-test")
return NodeHealthProbeSelfTest.RunAsync().GetAwaiter().GetResult();
if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test") if (args.Length == 1 && args[0] == "--nextgen-lifecycle-self-test")
{ {
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
+6 -4
View File
@@ -1,6 +1,6 @@
# 纵横家 Windows 0.3.1 开源源码 # 纵横家 Windows 0.3.2 开源源码
基于已冻结的 0.3.1 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。 基于已冻结的 0.3.2 r1 第一方 Windows Forms / .NET 8 源码整理。此导出不是原安装包的逐字节副本:删除许可来源不明的可选登录插图及内部运维历史,保留原创山水缺图 fallback;端点为示例配置。原候选测试报告不能当作本导出的构建或生产验收证明。
## 构建 ## 构建
@@ -17,6 +17,8 @@ dotnet publish VPNPlus.csproj -c Release -r win-x64 --self-contained true
公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。 公司自有代码适用 LICENSE;公司 Logo/商标保留来源识别用途、不授予品牌权利;第三方许可文本在 licenses/ 中,原 THIRD_PARTY_NOTICES.md 保持原文。
本次 0.3.1 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。 本次 0.3.2 同步连接排序与内网恢复提示、可取消连接、会话代际及学习同步退避、固定高度单页与实时速度显示。内网恢复不静默中断长连接;需要明确重连。此清洁源码以原创山水替代许可不明的可选人物插图,真实内部端点替换为示例。原安装包测试结论不自动转移为此导出的网络或安装验收。
0.3.1:固定画布实时速率、主WAN采样显示、节点延迟和粘性连接维护。整机WAN监控与个人套餐分开;未部署的后台、账户限速、真实网络和实窗结论不转移到此清洁源码。 0.3.2:固定画布实时速率、主WAN采样显示、节点延迟和粘性连接维护。整机WAN监控与个人套餐分开;未部署的后台、账户限速、真实网络和实窗结论不转移到此清洁源码。
0.3.2:启动时重叠执行只读路径验证与本机DNS准备,健康判定取得必要证据后结束等待,并调整紧凑窗口布局。保留Codex必要健康条件、授权、路由提交锁与原有超时。离线和合成界面测试不代表实机启动提速、生产安装、持续业务会话或完整网络验收。
+38
View File
@@ -0,0 +1,38 @@
namespace UCVL.VPNPlus;
internal static class StartupLearningWarmup
{
// The readiness callback starts only transport proof. The setup owner keeps
// its lifecycle lock until DNS/network setup succeeds; rule commits wait on
// that existing lock. Setup time never spends the post-setup learning budget.
internal static async Task RunAsync(Func<Action<CancellationToken>, Task> setup,
Func<CancellationToken, Task> learn, CancellationToken token, TimeProvider? clock = null)
{
token.ThrowIfCancellationRequested();
using var budget = new CancellationTokenSource(Timeout.InfiniteTimeSpan, clock ?? TimeProvider.System);
CancellationTokenSource? learning = null;
Task? work = null;
try
{
await setup(epoch => {
if (learning is not null) throw new InvalidOperationException("Startup learning already began.");
learning = CancellationTokenSource.CreateLinkedTokenSource(token, epoch, budget.Token);
learning.Token.ThrowIfCancellationRequested();
work = learn(learning.Token);
});
token.ThrowIfCancellationRequested();
if (work is null) return;
budget.CancelAfter(TimeSpan.FromSeconds(15));
await work;
token.ThrowIfCancellationRequested();
}
finally
{
// A failed setup must leave no outstanding proof/commit task. Drain
// cancellation without replacing the original setup/learning error.
learning?.Cancel();
if (work is not null) try { await work; } catch { }
learning?.Dispose();
}
}
}
+196 -195
View File
@@ -1,195 +1,196 @@
using System.Drawing.Drawing2D; using System.Drawing.Drawing2D;
namespace UCVL.VPNPlus; namespace UCVL.VPNPlus;
// Reads only existing proxy-outbound counters; never the physical adapter. // Reads only existing proxy-outbound counters; never the physical adapter.
internal sealed class TrafficChart : Control internal sealed class TrafficChart : Control
{ {
private readonly TrafficChartTimeline _timeline; private readonly TrafficChartTimeline _timeline;
private TimeSpan _period = TimeSpan.FromMinutes(5); private TimeSpan _period = TimeSpan.FromMinutes(5);
internal int PeriodMinutes => (int)_period.TotalMinutes; internal int PeriodMinutes => (int)_period.TotalMinutes;
internal int PointCount => _timeline.PointCount; internal int PointCount => _timeline.PointCount;
internal int VisiblePointCount => VisiblePoints().Length; internal int VisiblePointCount => VisiblePoints().Length;
internal bool HasFreshSample => _timeline.HasFreshSample; internal bool HasFreshSample => _timeline.HasFreshSample;
internal DateTimeOffset? LastSampleAt => _timeline.LastSampleAt; internal DateTimeOffset? LastSampleAt => _timeline.LastSampleAt;
internal DateTimeOffset TimelineEnd => _timeline.End; internal DateTimeOffset TimelineEnd => _timeline.End;
internal void SetPeriodMinutes(int minutes) internal void SetPeriodMinutes(int minutes)
{ {
if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes)); if (minutes is not (1 or 5 or 15 or 60)) throw new ArgumentOutOfRangeException(nameof(minutes));
_period = TimeSpan.FromMinutes(minutes); _period = TimeSpan.FromMinutes(minutes);
Invalidate(); Invalidate();
} }
private TrafficChartTimeline.Sample[] VisiblePoints() => _timeline.Visible(_period); private TrafficChartTimeline.Sample[] VisiblePoints() => _timeline.Visible(_period);
internal TrafficChart(Func<DateTimeOffset>? clock = null) internal TrafficChart(Func<DateTimeOffset>? clock = null)
{ {
_timeline = new TrafficChartTimeline(clock); _timeline = new TrafficChartTimeline(clock);
DoubleBuffered = true; DoubleBuffered = true;
SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.Opaque, false); SetStyle(ControlStyles.Opaque, false);
BackColor = Color.Transparent; BackColor = Color.Transparent;
Font = Brand.Font(7.3f); Font = Brand.Font(7.3f);
} }
internal void Add(double up, double down, DateTimeOffset? time = null) internal void Add(double up, double down, DateTimeOffset? time = null)
{ {
_timeline.Add(up, down, time); _timeline.Add(up, down, time);
Invalidate(); Invalidate();
} }
// Called by the existing sampling timer even when the reader is busy or // Called by the existing sampling timer even when the reader is busy or
// returns no counters. Neither method invents a zero-speed sample or bytes. // returns no counters. Neither method invents a zero-speed sample or bytes.
internal void AdvanceClock(DateTimeOffset? now = null) { _timeline.AdvanceClock(now); Invalidate(); } internal void AdvanceClock(DateTimeOffset? now = null) { _timeline.AdvanceClock(now); Invalidate(); }
internal void MarkUnavailable(DateTimeOffset? now = null) { _timeline.MarkUnavailable(now); Invalidate(); } internal void MarkUnavailable(DateTimeOffset? now = null) { _timeline.MarkUnavailable(now); Invalidate(); }
internal void Reset() { _timeline.Reset(); Invalidate(); } internal void Reset() { _timeline.Reset(); Invalidate(); }
protected override void OnPaint(PaintEventArgs e) protected override void OnPaint(PaintEventArgs e)
{ {
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 => Math.Max(p.Up, p.Down)));
var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true); var chart = ChartAxis.Draw(e.Graphics, ClientRectangle, Font, DeviceDpi, peak, speed: true);
if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return; if (chart.Plot.Width < 1 || chart.Plot.Height < 1) return;
var end = _timeline.End; var end = _timeline.End;
ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]); ChartAxis.TimeLabels(e.Graphics, chart.Plot, Font, [end.Subtract(_period).ToString("HH:mm"), end.Subtract(_period / 2).ToString("HH:mm"), end.ToString("HH:mm")]);
if (points.Length == 0) if (points.Length == 0)
{ {
TextRenderer.DrawText(e.Graphics, LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted, TextRenderer.DrawText(e.Graphics, LastSampleAt.HasValue ? "采样暂不可用" : "等待代理流量采样", Font, Rectangle.Round(chart.Plot), Brand.Muted,
ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); ChartAxis.PaintFlags | TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
return; return;
} }
foreach (var segment in points.GroupBy(point => point.Segment)) foreach (var segment in points.GroupBy(point => point.Segment))
{ {
var samples = segment.ToArray(); var samples = segment.ToArray();
PointF[] Line(bool up) => samples.Select(p => new PointF( PointF[] Line(bool up) => samples.Select(p => new PointF(
chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width, chart.Plot.Left + (float)Math.Clamp(1 - (end - p.Time).TotalSeconds / _period.TotalSeconds, 0, 1) * chart.Plot.Width,
chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray(); chart.Plot.Bottom - (float)((up ? p.Up : p.Down) / chart.Maximum) * chart.Plot.Height)).ToArray();
ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1); ChartAxis.Curve(e.Graphics, Line(true), Brand.RoyalBlue, DeviceDpi, dots: samples.Length == 1);
ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: samples.Length == 1); ChartAxis.Curve(e.Graphics, Line(false), Brand.Cyan, DeviceDpi, dots: samples.Length == 1);
} }
if (!HasFreshSample) if (!HasFreshSample)
TextRenderer.DrawText(e.Graphics, "采样暂不可用", Font, Rectangle.Round(chart.Plot), Brand.Muted, TextRenderer.DrawText(e.Graphics, "采样暂不可用", Font, Rectangle.Round(chart.Plot), Brand.Muted,
ChartAxis.PaintFlags | TextFormatFlags.Right | TextFormatFlags.Top | TextFormatFlags.SingleLine); ChartAxis.PaintFlags | TextFormatFlags.Right | TextFormatFlags.Top | TextFormatFlags.SingleLine);
} }
} }
// Pure presentation history: no proxy/adapter reads, cumulative byte totals or // Pure presentation history: no proxy/adapter reads, cumulative byte totals or
// timers. An injected clock makes missing-sample behavior deterministic in tests. // timers. An injected clock makes missing-sample behavior deterministic in tests.
internal sealed class TrafficChartTimeline internal sealed class TrafficChartTimeline
{ {
internal readonly record struct Sample(DateTimeOffset Time, double Up, double Down, long Segment); internal readonly record struct Sample(DateTimeOffset Time, double Up, double Down, long Segment);
internal static readonly TimeSpan MaximumSampleAge = TimeSpan.FromSeconds(15); internal static readonly TimeSpan MaximumSampleAge = TimeSpan.FromSeconds(15);
private static readonly TimeSpan Retention = TimeSpan.FromMinutes(60); private static readonly TimeSpan Retention = TimeSpan.FromMinutes(60);
private readonly Queue<Sample> _points = new(); private readonly Queue<Sample> _points = new();
private readonly Func<DateTimeOffset> _clock; private readonly Func<DateTimeOffset> _clock;
private DateTimeOffset? _end, _lastSampleAt; private DateTimeOffset? _end, _lastSampleAt;
private bool _gapPending, _unavailable = true; private bool _gapPending, _unavailable = true;
private long _segment; private long _segment;
internal TrafficChartTimeline(Func<DateTimeOffset>? clock = null) => _clock = clock ?? (() => DateTimeOffset.Now); internal TrafficChartTimeline(Func<DateTimeOffset>? clock = null) => _clock = clock ?? (() => DateTimeOffset.Now);
internal int PointCount => _points.Count; internal int PointCount => _points.Count;
internal DateTimeOffset End => _end ?? _clock(); internal DateTimeOffset End => _end ?? _clock();
internal DateTimeOffset? LastSampleAt => _lastSampleAt; internal DateTimeOffset? LastSampleAt => _lastSampleAt;
internal bool HasFreshSample => !_unavailable && _lastSampleAt is { } last && End - last <= MaximumSampleAge; internal bool HasFreshSample => !_unavailable && _lastSampleAt is { } last && End - last <= MaximumSampleAge;
private void MoveEnd(DateTimeOffset at) private void MoveEnd(DateTimeOffset at)
{ {
if (!_end.HasValue || at > _end.Value) _end = at; if (!_end.HasValue || at > _end.Value) _end = at;
while (_points.Count > 3600 || (_points.Count > 0 && End - _points.Peek().Time > Retention)) _points.Dequeue(); while (_points.Count > 3600 || (_points.Count > 0 && End - _points.Peek().Time > Retention)) _points.Dequeue();
} }
internal void AdvanceClock(DateTimeOffset? now = null) internal void AdvanceClock(DateTimeOffset? now = null)
{ {
MoveEnd(now ?? _clock()); MoveEnd(now ?? _clock());
if (_lastSampleAt is { } last && End - last > MaximumSampleAge) if (_lastSampleAt is { } last && End - last > MaximumSampleAge)
_gapPending = _unavailable = true; _gapPending = _unavailable = true;
} }
internal void MarkUnavailable(DateTimeOffset? now = null) internal void MarkUnavailable(DateTimeOffset? now = null)
{ {
AdvanceClock(now); AdvanceClock(now);
_gapPending = _unavailable = true; _gapPending = _unavailable = true;
} }
internal bool Add(double up, double down, DateTimeOffset? time = null) internal bool Add(double up, double down, DateTimeOffset? time = null)
{ {
var at = time ?? _clock(); var at = time ?? _clock();
if (!double.IsFinite(up) || !double.IsFinite(down) || up < 0 || down < 0) if (!double.IsFinite(up) || !double.IsFinite(down) || up < 0 || down < 0)
{ {
MarkUnavailable(at); MarkUnavailable(at);
return false; return false;
} }
// Late/duplicate callbacks must not move the axis backwards, inject a // Late/duplicate callbacks must not move the axis backwards, inject a
// second point or turn a newer good sample into an unavailable one. // second point or turn a newer good sample into an unavailable one.
if (_lastSampleAt is { } previous && at <= previous) return false; if (_lastSampleAt is { } previous && at <= previous) return false;
if (_lastSampleAt is { } last && (_gapPending || at - last > MaximumSampleAge)) _segment++; if (_lastSampleAt is { } last && (_gapPending || at - last > MaximumSampleAge)) _segment++;
_points.Enqueue(new Sample(at, up, down, _segment)); _points.Enqueue(new Sample(at, up, down, _segment));
_lastSampleAt = at; _lastSampleAt = at;
_gapPending = _unavailable = false; _gapPending = _unavailable = false;
MoveEnd(at); MoveEnd(at);
return true; return true;
} }
internal Sample[] Visible(TimeSpan period) => _points.Where(point => End - point.Time <= period).ToArray(); internal Sample[] Visible(TimeSpan period) => _points.Where(point => End - point.Time <= period).ToArray();
internal void Reset() internal void Reset()
{ {
_points.Clear(); _points.Clear();
_end = _lastSampleAt = null; _end = _lastSampleAt = null;
_gapPending = false; _gapPending = false;
_unavailable = true; _unavailable = true;
_segment = 0; _segment = 0;
} }
} }
internal static class ChartAxis internal static class ChartAxis
{ {
internal const TextFormatFlags PaintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping; internal const TextFormatFlags PaintFlags = TextFormatFlags.PreserveGraphicsTranslateTransform | TextFormatFlags.PreserveGraphicsClipping;
internal static (RectangleF Plot, double Maximum) Draw(Graphics g, Rectangle bounds, Font font, int dpi, double peak, bool speed) internal static (RectangleF Plot, double Maximum) Draw(Graphics g, Rectangle bounds, Font font, int dpi, double peak, bool speed)
{ {
var scale = dpi / 96f; var scale = dpi / 96f;
var unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d; var unit = peak >= 1024d * 1024 * 1024 ? 1024d * 1024 * 1024 : peak >= 1024d * 1024 ? 1024d * 1024 : peak >= 1024 ? 1024d : 1d;
var unitName = unit >= 1024d * 1024 * 1024 ? "GB" : unit >= 1024d * 1024 ? "MB" : unit >= 1024 ? "KB" : "B"; var unitName = unit >= 1024d * 1024 * 1024 ? "GB" : unit >= 1024d * 1024 ? "MB" : unit >= 1024 ? "KB" : "B";
var raw = Math.Max(1, peak / unit) * 1.15; var raw = Math.Max(1, peak / unit) * 1.15;
var power = Math.Pow(10, Math.Floor(Math.Log10(raw))); var power = Math.Pow(10, Math.Floor(Math.Log10(raw)));
var normal = raw / power; var normal = raw / power;
var maximum = (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * power; var maximum = (normal <= 1 ? 1 : normal <= 2 ? 2 : normal <= 2.5 ? 2.5 : normal <= 5 ? 5 : 10) * power;
var fontHeight = TextRenderer.MeasureText(g, "0", font).Height; var fontHeight = TextRenderer.MeasureText(g, "0", font).Height;
var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, maximum.ToString("0.#"), font).Width + 5 * scale); var left = Math.Max(31 * scale, TextRenderer.MeasureText(g, maximum.ToString("0.#"), font).Width + 5 * scale);
var plot = new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale)); var plot = new RectangleF(left, fontHeight + 1, Math.Max(1, bounds.Width - left - 9 * scale), Math.Max(1, bounds.Height - fontHeight * 2 - 7 * scale));
g.SmoothingMode = SmoothingMode.AntiAlias; g.SmoothingMode = SmoothingMode.AntiAlias;
TextRenderer.DrawText(g, unitName + (speed ? "/s" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); var compactAxis = plot.Height < fontHeight * 3;
using var grid = new Pen(Color.FromArgb(218, 230, 245), Math.Max(1, scale * .6f)) { DashStyle = DashStyle.Dash }; TextRenderer.DrawText(g, unitName + (speed ? "/s" : "") + (compactAxis ? $" · {maximum:0.#}" : ""), font, new Rectangle(0, 0, bounds.Width, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding);
for (var i = 0; i <= 2; i++) using var grid = new Pen(Color.FromArgb(218, 230, 245), Math.Max(1, scale * .6f)) { DashStyle = DashStyle.Dash };
{ for (var i = 0; i <= 2; i++)
var y = plot.Bottom - plot.Height * i / 2; {
g.DrawLine(grid, plot.Left, y, plot.Right, y); var y = plot.Bottom - plot.Height * i / 2;
TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding); g.DrawLine(grid, plot.Left, y, plot.Right, y);
} if (!compactAxis || i == 0) TextRenderer.DrawText(g, (maximum * i / 2).ToString("0.#"), font, new Rectangle(0, (int)y - fontHeight / 2, (int)left - 4, fontHeight), Brand.Muted, PaintFlags | TextFormatFlags.Right | TextFormatFlags.NoPadding);
for (var i = 0; i <= 6; i++) }
{ for (var i = 0; i <= 6; i++)
var x = plot.Left + plot.Width * i / 6; {
g.DrawLine(grid, x, plot.Top, x, plot.Bottom); var x = plot.Left + plot.Width * i / 6;
} g.DrawLine(grid, x, plot.Top, x, plot.Bottom);
return (plot, maximum * unit); }
} return (plot, maximum * unit);
}
internal static void TimeLabels(Graphics g, RectangleF plot, Font font, string[] labels)
{ internal static void TimeLabels(Graphics g, RectangleF plot, Font font, string[] labels)
for (var i = 0; i < labels.Length; i++) {
{ for (var i = 0; i < labels.Length; i++)
var width = TextRenderer.MeasureText(g, labels[i], font).Width; {
var x = plot.Left + i * plot.Width / Math.Max(1, labels.Length - 1); var width = TextRenderer.MeasureText(g, labels[i], font).Width;
// Align edge labels inside the chart rather than cutting their final digits. var x = plot.Left + i * plot.Width / Math.Max(1, labels.Length - 1);
var left = i == 0 ? x : i == labels.Length - 1 ? x - width : x - width / 2; // Align edge labels inside the chart rather than cutting their final digits.
TextRenderer.DrawText(g, labels[i], font, new Point((int)left, (int)plot.Bottom + 3), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding); var left = i == 0 ? x : i == labels.Length - 1 ? x - width : x - width / 2;
} TextRenderer.DrawText(g, labels[i], font, new Point((int)left, (int)plot.Bottom + 3), Brand.Muted, PaintFlags | TextFormatFlags.NoPadding);
} }
}
internal static void Curve(Graphics g, PointF[] points, Color color, int dpi, bool dots)
{ internal static void Curve(Graphics g, PointF[] points, Color color, int dpi, bool dots)
if (points.Length == 0) return; {
var scale = dpi / 96f; if (points.Length == 0) return;
using var pen = new Pen(color, 1.8f * scale) { LineJoin = LineJoin.Round }; var scale = dpi / 96f;
if (points.Length > 1) g.DrawLines(pen, points); using var pen = new Pen(color, 1.8f * scale) { LineJoin = LineJoin.Round };
if (!dots) return; if (points.Length > 1) g.DrawLines(pen, points);
using var brush = new SolidBrush(color); if (!dots) return;
var radius = 2.5f * scale; using var brush = new SolidBrush(color);
foreach (var p in points) g.FillEllipse(brush, p.X - radius, p.Y - radius, radius * 2, radius * 2); var radius = 2.5f * scale;
} foreach (var p in points) g.FillEllipse(brush, p.X - radius, p.Y - radius, radius * 2, radius * 2);
} }
}
+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.1</Version> <Version>0.3.2</Version>
<AssemblyVersion>0.3.1.0</AssemblyVersion> <AssemblyVersion>0.3.2.0</AssemblyVersion>
<FileVersion>0.3.1.0</FileVersion> <FileVersion>0.3.2.0</FileVersion>
<InformationalVersion>0.3.1</InformationalVersion> <InformationalVersion>0.3.2</InformationalVersion>
<Product>纵横家</Product> <Product>纵横家</Product>
<Company>优创未来(UCVL)</Company> <Company>优创未来(UCVL)</Company>
<Description>纵横家 Windows 智能网络客户端</Description> <Description>纵横家 Windows 智能网络客户端</Description>
+28 -31
View File
@@ -196,37 +196,32 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
if (preferred is not null && !TailnetTransport.SameAuthorizedFallback(preferred, original)) if (preferred is not null && !TailnetTransport.SameAuthorizedFallback(preferred, original))
throw new InvalidOperationException("Tailscale 恢复入口与已授权线路不匹配。"); throw new InvalidOperationException("Tailscale 恢复入口与已授权线路不匹配。");
await InitializeAsync(cancellationToken); await InitializeAsync(cancellationToken);
await _lifecycle.WaitAsync(cancellationToken); await StartupLearningWarmup.RunAsync(async beginLearning => {
try await _lifecycle.WaitAsync(cancellationToken);
{ try
await StopCoreAsync(); {
_baseConfigJson = configJson; await StopCoreAsync();
_tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson; _baseConfigJson = configJson;
_preferredTailnetConfigJson = preferred; _tailnetFallbackConfigJson = preferred is not null ? original : tailnetFallbackConfigJson;
_routeMode = routeMode; _preferredTailnetConfigJson = preferred;
_nodeSlug = nodeSlug; _routeMode = routeMode;
await StartCoreAsync(cancellationToken); _nodeSlug = nodeSlug;
} await StartCoreAsync(cancellationToken, routeMode == "smart" ? beginLearning : null);
catch }
{ catch
await StopCoreAsync().ConfigureAwait(false); {
throw; await StopCoreAsync().ConfigureAwait(false);
} throw;
finally }
{ finally { _lifecycle.Release(); }
_lifecycle.Release(); if (_routeMode == "smart") StatusMessage?.Invoke("正在验证本地直连与代理路径…");
} }, warmupToken =>
if (_routeMode == "smart") // Keep the same targets, direct/proxy proof and lifecycle-gated
{ // commits. Only their read-only transport work overlaps DNS setup.
// The same three fixed health destinations, but first validate their real Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
// physical direct path. Never mark all server candidate domains as proxy.
StatusMessage?.Invoke("正在验证本地直连与代理路径…");
using var warmup = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _learningEpoch.Token);
warmup.CancelAfter(TimeSpan.FromSeconds(15));
await Task.WhenAll(new[] { "chatgpt.com", "api.openai.com", "www.google.com" }.Select(target =>
ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http", ScheduleLearningAsync(new LearningObservation { Target=target, Port=443, AccessKind="http",
Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmup.Token))); Node=_nodeSlug, Scope=PrivateAuxiliaryRuntime.IsPrivate(_baseConfigJson ?? "{}") ? "private_auxiliary" : "public" }, warmupToken))),
} cancellationToken);
} }
internal async Task StopAsync() internal async Task StopAsync()
@@ -262,7 +257,8 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
finally { _lifecycle.Release(); } finally { _lifecycle.Release(); }
} }
private async Task StartCoreAsync(CancellationToken cancellationToken) private async Task StartCoreAsync(CancellationToken cancellationToken,
Action<CancellationToken>? beginStartupLearning = null)
{ {
EnsureRuntime(); EnsureRuntime();
if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。"); if (string.IsNullOrWhiteSpace(_baseConfigJson)) throw new InvalidOperationException("线路配置为空。");
@@ -365,6 +361,7 @@ internal sealed class XrayManager : IDisposable, IAsyncDisposable, IHandoverRunt
// 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);
beginStartupLearning?.Invoke(_learningEpoch.Token);
await ProxyDnsPolicy.EnableAsync(_baseConfigJson, cancellationToken); await ProxyDnsPolicy.EnableAsync(_baseConfigJson, cancellationToken);
StatusMessage?.Invoke("正在等待 Windows 网络与 DNS 就绪…"); StatusMessage?.Invoke("正在等待 Windows 网络与 DNS 就绪…");
await WaitForDnsReadyAsync(cancellationToken); await WaitForDnsReadyAsync(cancellationToken);
@@ -0,0 +1,209 @@
using System.Text.Json;
using UCVL.VPNPlus;
var checks = new Dictionary<string, bool>();
TaskCompletionSource Signal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
// The real coordinator receives controlled external setup/probe phases. The
// semaphore is the same boundary used by XrayManager to defer rule commits.
using (var epoch = new CancellationTokenSource())
using (var lifecycle = new SemaphoreSlim(1, 1))
{
var tunReady = Signal(); var nrptStarted = Signal(); var finishNrpt = Signal();
var proofFinished = false; var committed = false; var setupFinished = false;
var clock = new ManualClock();
var run = StartupLearningWarmup.RunAsync(async begin => {
await lifecycle.WaitAsync();
try
{
await tunReady.Task;
begin(epoch.Token);
nrptStarted.SetResult();
await finishNrpt.Task;
setupFinished = true;
}
finally { lifecycle.Release(); }
}, async token => {
proofFinished = true;
await lifecycle.WaitAsync(token);
try { token.ThrowIfCancellationRequested(); committed = setupFinished; }
finally { lifecycle.Release(); }
}, CancellationToken.None, clock);
checks["learning_does_not_start_before_tun_ipv4_ready"] = !proofFinished;
tunReady.SetResult(); await nrptStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
checks["readonly_proof_overlaps_pending_nrpt"] = proofFinished;
checks["rule_commit_waits_for_setup_lifecycle_release"] = !committed;
finishNrpt.SetResult(); await run.WaitAsync(TimeSpan.FromSeconds(3));
checks["completed_proof_commits_after_setup"] = committed;
}
{
var clock = new ManualClock(); var setupEntered = Signal(); var finishSetup = Signal();
var learningStarted = Signal(); var cancelled = false;
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(CancellationToken.None); setupEntered.SetResult(); await finishSetup.Task;
}, async token => {
learningStarted.SetResult();
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { cancelled = true; }
}, CancellationToken.None, clock);
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromMinutes(1));
checks["setup_does_not_consume_post_setup_learning_budget"] = !cancelled;
finishSetup.SetResult(); await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
await learningStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromMilliseconds(14_999));
checks["learning_retains_fifteen_seconds_after_setup"] = !cancelled && !run.IsCompleted;
clock.Advance(TimeSpan.FromMilliseconds(1));
await run.WaitAsync(TimeSpan.FromSeconds(3));
checks["learning_stops_at_post_setup_budget"] = cancelled;
}
{
var learningCalls = 0;
await StartupLearningWarmup.RunAsync(_ => Task.CompletedTask,
_ => { learningCalls++; return Task.CompletedTask; }, CancellationToken.None, new ManualClock());
checks["setup_without_smart_readiness_never_starts_learning"] = learningCalls == 0;
}
foreach (var reason in new[] { "setup_failure", "caller_cancel", "epoch_cancel" })
{
using var caller = new CancellationTokenSource(); using var epoch = new CancellationTokenSource();
var setupEntered = Signal(); var finishSetup = Signal(); var stopped = false; var active = false;
var failure = new IOException("synthetic setup failure"); Exception? observed = null;
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(epoch.Token); setupEntered.SetResult();
await finishSetup.Task.WaitAsync(caller.Token);
if (reason == "setup_failure") throw failure;
}, async token => {
active = true;
try { await Task.Delay(Timeout.Infinite, token); }
finally { active = false; stopped = true; }
}, caller.Token, new ManualClock());
await setupEntered.Task.WaitAsync(TimeSpan.FromSeconds(3));
if (reason == "caller_cancel") caller.Cancel();
if (reason == "epoch_cancel") epoch.Cancel();
finishSetup.TrySetResult();
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (Exception error) { observed = error; }
checks[reason + "_drains_learning_without_late_work"] = stopped && !active;
checks[reason + "_preserves_original_failure"] = reason == "setup_failure"
? ReferenceEquals(observed, failure) : observed is OperationCanceledException;
}
// Failed NRPT setup cancels the same epoch while still holding the lifecycle
// lock. A proof already waiting to commit must not escape cleanup or apply late.
using (var epoch = new CancellationTokenSource())
using (var lifecycle = new SemaphoreSlim(1, 1))
{
var proofFinished = false; var committed = false; var drained = false;
var failure = new IOException("synthetic NRPT failure"); Exception? observed = null;
try
{
await StartupLearningWarmup.RunAsync(async begin => {
await lifecycle.WaitAsync();
try
{
begin(epoch.Token);
epoch.Cancel();
throw failure;
}
finally { lifecycle.Release(); }
}, async token => {
proofFinished = true;
try
{
await lifecycle.WaitAsync(token);
try { token.ThrowIfCancellationRequested(); committed = true; }
finally { lifecycle.Release(); }
}
finally { drained = true; }
}, CancellationToken.None, new ManualClock());
}
catch (Exception error) { observed = error; }
checks["failed_nrpt_cancels_pending_rule_commit"] = proofFinished && drained && !committed;
checks["pending_commit_cancellation_preserves_setup_error"] = ReferenceEquals(observed, failure);
}
{
var clock = new ManualClock();
using var caller = new CancellationTokenSource(TimeSpan.FromSeconds(45), clock);
var learningStopped = false; var setupStarted = Signal();
var run = StartupLearningWarmup.RunAsync(async begin => {
begin(CancellationToken.None); setupStarted.SetResult();
await Task.Delay(Timeout.Infinite, caller.Token);
}, async token => {
try { await Task.Delay(Timeout.Infinite, token); }
finally { learningStopped = true; }
}, caller.Token, clock);
await setupStarted.Task.WaitAsync(TimeSpan.FromSeconds(3));
clock.Advance(TimeSpan.FromSeconds(45));
var cancelled = false;
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
checks["caller_forty_five_second_bound_remains_active_during_setup"] = cancelled && learningStopped;
}
{
using var caller = new CancellationTokenSource(); caller.Cancel(); var setupCalled = false;
try { await StartupLearningWarmup.RunAsync(_ => { setupCalled = true; return Task.CompletedTask; },
_ => Task.CompletedTask, caller.Token, new ManualClock()); }
catch (OperationCanceledException) { }
checks["cancelled_caller_does_not_start_setup"] = !setupCalled;
}
// Production learning handlers absorb cancellation after cleaning up their own
// probes. The startup owner must still propagate the user's cancelled connect.
{
using var caller = new CancellationTokenSource();
var clock = new ManualClock(); var learnerFinishedNormally = false;
var run = StartupLearningWarmup.RunAsync(begin => {
begin(CancellationToken.None); return Task.CompletedTask;
}, async token => {
try { await Task.Delay(Timeout.Infinite, token); }
catch (OperationCanceledException) { learnerFinishedNormally = true; }
}, caller.Token, clock);
await clock.Armed.Task.WaitAsync(TimeSpan.FromSeconds(3));
caller.Cancel();
var cancelled = false;
try { await run.WaitAsync(TimeSpan.FromSeconds(3)); } catch (OperationCanceledException) { cancelled = true; }
checks["caller_cancellation_propagates_when_learning_swallows_it"] = cancelled && learnerFinishedNormally;
}
var report = new { passed = checks.Values.All(v => v), checks, production_coordinator = true,
simulated_external_phases = true, network_modified = false, production_client_started = false };
Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }));
return report.passed ? 0 : 91;
sealed class ManualClock : TimeProvider
{
private readonly List<ManualTimer> timers = [];
internal long ElapsedTicks { get; private set; }
internal TaskCompletionSource Armed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
{
var timer = new ManualTimer(this, callback, state); lock (timers) timers.Add(timer);
timer.Change(dueTime, period); return timer;
}
internal void Advance(TimeSpan elapsed)
{
ManualTimer[] snapshot; lock (timers) { ElapsedTicks += elapsed.Ticks; snapshot = timers.ToArray(); }
foreach (var timer in snapshot) timer.FireIfDue();
}
private sealed class ManualTimer(ManualClock clock, TimerCallback callback, object? state) : ITimer
{
private long? due; private bool disposed;
public bool Change(TimeSpan dueTime, TimeSpan period)
{
if (disposed) return false;
due = dueTime == Timeout.InfiniteTimeSpan ? null : clock.ElapsedTicks + dueTime.Ticks;
if (dueTime == TimeSpan.FromSeconds(15)) clock.Armed.TrySetResult();
return true;
}
internal void FireIfDue()
{
if (!disposed && due is { } value && value <= clock.ElapsedTicks)
{ due = null; callback(state); }
}
public void Dispose() { disposed = true; due = null; }
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
}
}
@@ -0,0 +1,19 @@
<Project>
<PropertyGroup>
<BaseIntermediateOutputPath>obj/startup-learning-warmup/</BaseIntermediateOutputPath>
</PropertyGroup>
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
<OutputPath>bin/startup-learning-warmup/</OutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Include="StartupLearningWarmupHarness.cs" />
<Compile Include="../StartupLearningWarmup.cs" />
</ItemGroup>
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>
+13
View File
@@ -0,0 +1,13 @@
# 纵横家 Windows 0.3.2
正式、非强制更新,保留现有账号、授权和连接选择策略。
- 缩短连接启动的串行等待:TUN/IPv4 就绪后,将只读直连验证与隧道 DNS 设置并行;规则仍在设置成功后提交。
- 连接健康检查满足原有条件后立即完成,不再等待无关的第三个探测;仍要求 Codex 与另一独立目标通过验证。
- 主窗口默认宽、高各为原来的一半;累计流量仅显示统计数字,代理速度保留趋势图。公网、Tailscale 入口速度和服务器监控继续区分。
- 沿用内网 IP 优先、不可达后回退域名且本次连接保持回退入口的策略。不会启停、登录或修改 Tailscale。
验证包含同包离线回归、合成界面及隔离文件升级/恢复;保持当前运行连接,没有执行生产覆盖安装或真实 TUN 重连。因此本版不承诺固定连接秒数,也不将隔离验证写成生产联网验收。
安装包未进行 Authenticode 签名,更新需要 Windows 管理员授权。
既有共享账户限速执行层仍未启用,本版不宣称已启用跨服务器共享限速。