XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEExtension.NetCore.XFEConsole

新增第二调试模式及自研艺术字字体

为 XFEConsole 增加第二调试模式,支持远程工具箱通过密码鉴权连接调试服务器,核心类包括 XFEConsoleProgramServer、XFEConsoleTerminalClient、XFEConsoleTerminalInfo,实现安全握手、终端元数据、事件回调和多终端并发。静态 API 增加 UseXFEConsoleServer,StopXFEConsole 支持关闭所有连接,输出逻辑统一支持多端广播。原有类升级适配 CyberComm 5.2.0,支持异步和更强错误处理。新增 RemoteDebugSelfTest.cs 自动化测试新旧模式。移除 Figgle/FIGlet 依赖,全部艺术字字体自研实现,API 统一,支持多种渲染算法,文档和测试同步更新。依赖升级,版本提升至 2.6.0。

86ee80c
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

14 个文件 +1165 -197
Modified .github/workflows/publish-packages.yml +4 -2
@@ -2,6 +2,8 @@ name: Publish Packages
2 2
3 3 on:
4 4 push:
5 branches-ignore:
6 - "**"
5 7 tags:
6 8 - "v*"
7 9 workflow_dispatch:
@@ -78,7 +80,7 @@ jobs:
78 80 - name: Publish to GitHub Packages
79 81 shell: pwsh
80 82 env:
81 GITHUB_PACKAGES_TOKEN: ${{ secrets.GH_PACKAGES_TOKEN }}
83 GH_PACKAGES_TOKEN: ${{ secrets.GH_PACKAGES_TOKEN }}
82 84 run: |
83 85 $packages = Get-ChildItem -Path "${{ env.PACKAGE_OUTPUT_DIR }}" -Filter *.nupkg -File
84 86 if (-not $packages) {
@@ -88,7 +90,7 @@ jobs:
88 90 foreach ($package in $packages) {
89 91 dotnet nuget push $package.FullName `
90 92 --source "https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json" `
91 --api-key "$env:GITHUB_PACKAGES_TOKEN" `
93 --api-key "$env:GH_PACKAGES_TOKEN" `
92 94 --skip-duplicate
93 95 }
94 96
Modified README.md +18 -5
@@ -109,7 +109,7 @@ For custom loops, compose `XFETerminalSession`, `XFETerminalCanvas`, and `XFETer
109 109
110 110 ### Colored title art
111 111
112 In addition to the backward-compatible 5x5 pixel font, the library now bundles more than 250 FIGlet fonts. Common choices are exposed through `Standard`, `Big`, `Slant`, `AnsiShadow`, `Doom`, `Epic`, `Gothic`, `Ivrit`, `Modular`, `Ogre`, `Rectangles`, `Relief`, `Isometric`, and `Larry3D`; `FigletFontName` accepts any name returned by `AvailableFigletFonts`.
112 The repository implements 17 fonts itself and has no third-party font-package dependency: `Pixel`, `Standard`, `Big`, `Small`, `Slant`, `AnsiShadow`, `SmallShadow`, `Doom`, `Epic`, `Gothic`, `Ivrit`, `Modular`, `Ogre`, `Rectangles`, `Relief`, `Isometric`, and `Larry3D`. They are generated from the built-in glyph matrix by independent line-connection, double-line, block, module, mirror, relief, shadow, and isometric algorithms. `AvailableFonts` returns the complete enum list.
113 113
114 114 Fonts and effects are independent and composable. `OutlineWidth` creates a real outer stroke, while `ExtrudeDepth` and the eight `ExtrudeDirection` values create layered 3D extrusion. Fill, outline, and extrusion have separate palette/color controls. `Outline` supplies a one-cell default stroke and `ThreeDimensional` supplies a three-cell down-right extrusion.
115 115
@@ -141,16 +141,16 @@ string terminalReady = XFEConsole.GenerateTitleArt("XFE", new XFETerminalTitleAr
141 141
142 142 XFEConsole.WriteTitleArt("HELLO", new XFETerminalTitleArtOptions
143 143 {
144 FigletFontName = "Banner3D",
144 Font = XFETerminalArtFont.Larry3D,
145 145 Palette = XFETerminalArtPalette.Ocean,
146 146 Compatibility = XFETerminalCompatibility.Auto
147 147 });
148 148
149 foreach (string fontName in XFETerminalTitleArt.AvailableFigletFonts)
150 Console.WriteLine(fontName);
149 foreach (XFETerminalArtFont font in XFETerminalTitleArt.AvailableFonts)
150 Console.WriteLine(font);
151 151 ```
152 152
153 Modern mode uses Unicode effect characters and ANSI true color, including distinct colors within a single row. Legacy mode switches effects to ASCII and uses `ConsoleColor` when writing directly. FIGlet fonts primarily cover Latin letters, digits, and common punctuation; unsupported CJK or emoji text falls back to a frame that preserves the original characters.
153 Modern mode uses Unicode effect characters and ANSI true color, including distinct colors within a single row. Legacy mode switches effects to ASCII and uses `ConsoleColor` when writing directly. Built-in glyphs cover Latin letters, digits, and common punctuation; unsupported CJK or emoji text falls back to a frame that preserves the original characters.
154 154
155 155 Run the feature demos and deterministic checks with:
156 156
@@ -177,6 +177,19 @@ bool connected = await XFEConsole.UseXFEConsole("ws://192.168.1.100:3280/", "MyA
177 177
178 178 Once connected, all `Console.WriteLine` and `Console.Write` output is automatically forwarded to the remote console.
179 179
180 ### Mode 2: Let the Toolbox Connect to the Program
181
182 ```csharp
183 // Run the debug program as the server. Remote toolboxes must use the same password.
184 XFEConsoleProgramServer server = await XFEConsole.UseXFEConsoleServer(
185 port: 3280,
186 localOnly: false,
187 password: "your-password",
188 programName: "MyApp");
189 ```
190
191 Enable "Mode 2" in the toolbox console settings, enter `ws://server-address:3280/` and the same password, then start the console. Keep `localOnly` set to `true` for same-machine debugging. Across networks, use `ws` only on a trusted LAN or VPN; public deployments should place the endpoint behind a TLS reverse proxy and connect with `wss`.
192
180 193 ### Properties
181 194
182 195 ```csharp
Modified README_zh.md +18 -5
@@ -122,7 +122,7 @@ await XFETerminalGame.RunAsync((game, cancellationToken) =>
122 122
123 123 ### 彩色标题艺术字
124 124
125 除兼容旧版的 5x5 点阵字体外,现已内置 250 多种 FIGlet 字体。常用字体可通过 `Standard`、`Big`、`Slant`、`AnsiShadow`、`Doom`、`Epic`、`Gothic`、`Ivrit`、`Modular`、`Ogre`、`Rectangles`、`Relief`、`Isometric`、`Larry3D` 等枚举直接选择;也可用 `FigletFontName` 按名称访问完整字体库。`AvailableFigletFonts` 返回所有可用名称。
125 仓库内自研实现了 17 种字体,不依赖任何第三方字体包:`Pixel`、`Standard`、`Big`、`Small`、`Slant`、`AnsiShadow`、`SmallShadow`、`Doom`、`Epic`、`Gothic`、`Ivrit`、`Modular`、`Ogre`、`Rectangles`、`Relief`、`Isometric` 和 `Larry3D`。这些字体由内置字形矩阵经过线框连接、双线、块面、模块、镜像、浮雕、阴影和等距投影等独立算法生成,`AvailableFonts` 返回全部字体枚举。
126 126
127 127 字体与效果可以自由组合:`OutlineWidth` 生成真正的外描边,`ExtrudeDepth` 和八种 `ExtrudeDirection` 生成多层立体挤出;正面、描边和挤出层分别由 `Color`/`Palette`、`OutlineColor`、`ExtrudeColor` 控制。`Outline` 样式默认生成 1 格描边,`ThreeDimensional` 默认生成 3 格右下挤出。
128 128
@@ -156,16 +156,16 @@ string terminalReady = XFEConsole.GenerateTitleArt("XFE", new XFETerminalTitleAr
156 156 // 直接显示;Auto 自动区分新旧终端
157 157 XFEConsole.WriteTitleArt("HELLO", new XFETerminalTitleArtOptions
158 158 {
159 FigletFontName = "Banner3D", // 完整字体目录中的任意名称
159 Font = XFETerminalArtFont.Larry3D,
160 160 Palette = XFETerminalArtPalette.Ocean,
161 161 Compatibility = XFETerminalCompatibility.Auto
162 162 });
163 163
164 foreach (string fontName in XFETerminalTitleArt.AvailableFigletFonts)
165 Console.WriteLine(fontName);
164 foreach (XFETerminalArtFont font in XFETerminalTitleArt.AvailableFonts)
165 Console.WriteLine(font);
166 166 ```
167 167
168 现代模式使用 Unicode 效果字符与 ANSI 真彩色,并允许一行内分别呈现正面、描边和立体层颜色;传统模式自动改用 ASCII 效果字符,直接显示时映射至 `ConsoleColor`,不会把转义字符打印到旧终端。FIGlet 字体主要覆盖英文、数字和常用标点;不支持的中文、Emoji 等字符会自动使用保留原文字的边框样式。
168 现代模式使用 Unicode 效果字符与 ANSI 真彩色,并允许一行内分别呈现正面、描边和立体层颜色;传统模式自动改用 ASCII 效果字符,直接显示时映射至 `ConsoleColor`,不会把转义字符打印到旧终端。内置字形覆盖英文、数字和常用标点;不支持的中文、Emoji 等字符会自动使用保留原文字的边框样式。
169 169
170 170 示例项目提供 `self-test`、`art`、`progress` 和 `game` 四个入口:
171 171
@@ -192,6 +192,19 @@ bool connected = await XFEConsole.UseXFEConsole("ws://192.168.1.100:3280/", "MyA
192 192
193 193 连接后,所有 `Console.WriteLine` 和 `Console.Write` 的输出都会被自动转发到远程控制台。
194 194
195 ### 第二调试模式:由工具箱主动连接程序
196
197 ```csharp
198 // 调试程序作为服务器运行;远程工具箱需要相同密码才能接收输出
199 XFEConsoleProgramServer server = await XFEConsole.UseXFEConsoleServer(
200 port: 3280,
201 localOnly: false,
202 password: "your-password",
203 programName: "MyApp");
204 ```
205
206 在工具箱的控制台设置中启用“第二调试模式”,填写 `ws://服务器地址:3280/` 和相同密码后启动即可。仅在同一台计算机调试时将 `localOnly` 保持为 `true`;跨网络使用 `ws` 时建议通过可信局域网或 VPN,公网场景应在 TLS 反向代理后使用 `wss`。
207
195 208 ### 属性配置
196 209
197 210 ```csharp
Modified XFEExtension.NetCore.XFEConsole.Test/Program.cs +38 -36
@@ -7,6 +7,9 @@ switch (command)
7 7 case "self-test":
8 8 RunSelfTests();
9 9 break;
10 case "remote-debug-self-test":
11 await RemoteDebugSelfTest.RunAsync();
12 break;
10 13 case "art":
11 14 ShowArt();
12 15 break;
@@ -22,7 +25,8 @@ switch (command)
22 25 default:
23 26 Console.WriteLine("XFEConsole feature demo");
24 27 Console.WriteLine(" self-test Run deterministic API checks");
25 Console.WriteLine(" art Show every title-art style");
28 Console.WriteLine(" remote-debug-self-test Verify server mode authentication and throughput");
29 Console.WriteLine(" art Show every title-art style and built-in font");
26 30 Console.WriteLine(" progress Show inline + Windows Terminal taskbar progress");
27 31 Console.WriteLine(" game Run a keyboard/mouse canvas demo (Esc exits)");
28 32 Console.WriteLine(" log Run the original parallel logging stress demo");
@@ -40,7 +44,7 @@ static void RunSelfTests()
40 44 ("RGB style", () => Contains("38;2;1;2;3", new XFETerminalStyle { Foreground = XFETerminalColor.FromRgb(1, 2, 3) }.ToSequence())),
41 45 ("Legacy title art", TestLegacyTitleArt),
42 46 ("Every title art style", TestEveryTitleArtStyle),
43 ("FIGlet font catalog", TestFigletFontCatalog),
47 ("Built-in font catalog", TestBuiltInFontCatalog),
44 48 ("Outlined title art", TestOutlinedTitleArt),
45 49 ("3D title art", TestThreeDimensionalTitleArt),
46 50 ("Layered title art color", TestLayeredTitleArtColor),
@@ -103,40 +107,44 @@ static void TestModernTitleArt()
103 107 Contains("▓", art);
104 108 }
105 109
106 static void TestFigletFontCatalog()
110 static void TestBuiltInFontCatalog()
107 111 {
108 if (XFETerminalTitleArt.AvailableFigletFonts.Count < 250)
109 throw new InvalidOperationException("Expected at least 250 bundled FIGlet fonts.");
110 foreach (var font in new[] { "Doom", "Epic", "Gothic", "Modular", "Rectangles", "Relief" })
112 Equal(Enum.GetValues<XFETerminalArtFont>().Length, XFETerminalTitleArt.AvailableFonts.Count);
113 var legacyResults = new HashSet<string>(StringComparer.Ordinal);
114 var modernResults = new HashSet<string>(StringComparer.Ordinal);
115 foreach (var font in XFETerminalTitleArt.AvailableFonts)
111 116 {
112 if (!XFETerminalTitleArt.IsFigletFontAvailable(font))
113 throw new InvalidOperationException($"Expected FIGlet font {font}.");
117 var legacy = XFETerminalTitleArt.GeneratePlain("XFE", new XFETerminalTitleArtOptions
118 {
119 Font = font,
120 Style = XFETerminalArtStyle.Compact,
121 Compatibility = XFETerminalCompatibility.Legacy
122 });
123 var modern = XFETerminalTitleArt.GeneratePlain("XFE", new XFETerminalTitleArtOptions
124 {
125 Font = font,
126 Style = XFETerminalArtStyle.Compact,
127 Compatibility = XFETerminalCompatibility.Modern
128 });
129 if (string.IsNullOrWhiteSpace(legacy) || string.IsNullOrWhiteSpace(modern))
130 throw new InvalidOperationException($"{font} rendered an empty string.");
131 DoesNotContain("\x1b", legacy);
132 DoesNotContain("\x1b", modern);
133 if (!legacyResults.Add(legacy))
134 throw new InvalidOperationException($"{font} did not produce a distinct legacy visual result.");
135 if (!modernResults.Add(modern))
136 throw new InvalidOperationException($"{font} did not produce a distinct visual result.");
114 137 }
115 if (!XFETerminalTitleArt.IsFigletFontAvailable("banner-3d"))
116 throw new InvalidOperationException("Normalized FIGlet font lookup failed.");
117 138
118 139 var art = XFETerminalTitleArt.GeneratePlain("XFE", new XFETerminalTitleArtOptions
119 140 {
120 141 Font = XFETerminalArtFont.Epic,
121 142 Style = XFETerminalArtStyle.Compact,
122 Compatibility = XFETerminalCompatibility.Legacy
143 Compatibility = XFETerminalCompatibility.Modern
123 144 });
124 Contains("_", art);
145 Contains("═", art);
125 146 if (art.Split(Environment.NewLine).Length < 5)
126 throw new InvalidOperationException("Epic did not render as multi-line FIGlet art.");
127
128 var custom = XFETerminalTitleArt.GeneratePlain("XFE", new XFETerminalTitleArtOptions
129 {
130 FigletFontName = "banner-3d",
131 Compatibility = XFETerminalCompatibility.Legacy
132 });
133 if (string.IsNullOrWhiteSpace(custom))
134 throw new InvalidOperationException("Custom FIGlet font rendered an empty string.");
135
136 Throws<ArgumentException>(() => XFETerminalTitleArt.GeneratePlain("XFE", new XFETerminalTitleArtOptions
137 {
138 FigletFontName = "does-not-exist"
139 }));
147 throw new InvalidOperationException("Epic did not render as multi-line built-in art.");
140 148 }
141 149
142 150 static void TestOutlinedTitleArt()
@@ -258,17 +266,11 @@ static void ShowArt()
258 266 });
259 267 }
260 268
261 foreach (var font in new[]
262 {
263 XFETerminalArtFont.AnsiShadow,
264 XFETerminalArtFont.Doom,
265 XFETerminalArtFont.Epic,
266 XFETerminalArtFont.Gothic,
267 XFETerminalArtFont.Modular,
268 XFETerminalArtFont.Relief
269 })
269 Console.WriteLine($"\nAll built-in fonts ({XFETerminalTitleArt.AvailableFonts.Count})");
270 for (var index = 0; index < XFETerminalTitleArt.AvailableFonts.Count; index++)
270 271 {
271 Console.WriteLine($"\nFIGlet {font}");
272 var font = XFETerminalTitleArt.AvailableFonts[index];
273 Console.WriteLine($"\n[{index + 1}/{XFETerminalTitleArt.AvailableFonts.Count}] {font}");
272 274 XFETerminalTitleArt.Write("XFE", new XFETerminalTitleArtOptions
273 275 {
274 276 Font = font,
Added XFEExtension.NetCore.XFEConsole.Test/RemoteDebugSelfTest.cs +143 -0
@@ -0,0 +1,143 @@
1 using System.Diagnostics;
2 using System.Net;
3 using System.Net.Sockets;
4 using XFEExtension.NetCore.FormatExtension;
5 using XFEExtension.NetCore.XFEConsole;
6
7 internal static class RemoteDebugSelfTest
8 {
9 private const int MessageCount = 5_000;
10
11 public static async Task RunAsync()
12 {
13 var port = GetAvailablePort();
14 await using var server = new XFEConsoleProgramServer(port, true, "correct-password", "RemoteTestProgram", "program-1");
15 await server.StartAsync();
16
17 await VerifyWrongPasswordIsRejectedAsync(port);
18 var messagesPerSecond = await VerifyAuthenticatedOutputAsync(server, port);
19 await VerifyStaticConsoleServerApiAsync();
20 await VerifyOriginalProgramClientModeAsync();
21
22 Console.WriteLine("PASS wrong password rejected");
23 Console.WriteLine("PASS authenticated terminal metadata");
24 Console.WriteLine($"PASS {MessageCount:N0} remote output messages at {messagesPerSecond:N0} messages/second");
25 Console.WriteLine("PASS XFEConsole.UseXFEConsoleServer output redirection");
26 Console.WriteLine("PASS original program-client mode compatibility");
27 }
28
29 private static async Task VerifyWrongPasswordIsRejectedAsync(int port)
30 {
31 await using var terminal = new XFEConsoleTerminalClient($"ws://localhost:{port}/", "wrong-password", "RejectedTerminal", "terminal-rejected");
32 var accepted = await terminal.ConnectAsync(TimeSpan.FromSeconds(5));
33 if (accepted)
34 throw new InvalidOperationException("The server accepted an incorrect password.");
35 if (string.IsNullOrWhiteSpace(terminal.AuthenticationFailureReason))
36 throw new InvalidOperationException("The server did not return an authentication failure reason.");
37 }
38
39 private static async Task<double> VerifyAuthenticatedOutputAsync(XFEConsoleProgramServer server, int port)
40 {
41 await using var terminal = new XFEConsoleTerminalClient($"ws://localhost:{port}/", "correct-password", "TestToolbox", "terminal-1");
42 var received = 0;
43 var receivedAll = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
44 terminal.MessageReceived += (_, message) =>
45 {
46 var dictionary = new XFEDictionary(message);
47 if (dictionary["IsLine"] != "true" || dictionary["Text"] is null)
48 receivedAll.TrySetException(new InvalidDataException("Received an invalid console output message."));
49 if (Interlocked.Increment(ref received) == MessageCount)
50 receivedAll.TrySetResult();
51 };
52
53 if (!await terminal.ConnectAsync(TimeSpan.FromSeconds(5)))
54 throw new InvalidOperationException($"Authentication failed: {terminal.AuthenticationFailureReason}");
55 if (terminal.RemoteProgramName != "RemoteTestProgram" || terminal.RemoteProgramId != "program-1")
56 throw new InvalidOperationException("The authenticated program metadata is incorrect.");
57
58 var stopwatch = Stopwatch.StartNew();
59 for (var index = 0; index < MessageCount; index++)
60 await server.OutputMessage($"line-{index}", true);
61 await receivedAll.Task.WaitAsync(TimeSpan.FromSeconds(20));
62 stopwatch.Stop();
63
64 if (received != MessageCount)
65 throw new InvalidOperationException($"Expected {MessageCount} messages but received {received}.");
66 return MessageCount / stopwatch.Elapsed.TotalSeconds;
67 }
68
69 private static async Task VerifyStaticConsoleServerApiAsync()
70 {
71 var port = GetAvailablePort();
72 var originalShowInDebug = XFEConsole.ShowInDebug;
73 var originalShowInLocalConsole = XFEConsole.ShowInLocalConsole;
74 XFEConsole.ShowInDebug = false;
75 XFEConsole.ShowInLocalConsole = false;
76 try
77 {
78 await XFEConsole.UseXFEConsoleServer(port, true, "static-password", "StaticProgram", "static-program");
79 await using var terminal = new XFEConsoleTerminalClient($"ws://localhost:{port}/", "static-password");
80 var received = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
81 terminal.MessageReceived += (_, message) => received.TrySetResult(message);
82 if (!await terminal.ConnectAsync(TimeSpan.FromSeconds(5)))
83 throw new InvalidOperationException("The static XFEConsole server rejected the correct password.");
84
85 Console.WriteLine("static-server-output");
86 var dictionary = new XFEDictionary(await received.Task.WaitAsync(TimeSpan.FromSeconds(5)));
87 if (dictionary["Text"]?.Contains("static-server-output", StringComparison.Ordinal) != true)
88 throw new InvalidOperationException("Console.Out was not redirected to the program server.");
89 }
90 finally
91 {
92 await XFEConsole.StopXFEConsole();
93 XFEConsole.ShowInDebug = originalShowInDebug;
94 XFEConsole.ShowInLocalConsole = originalShowInLocalConsole;
95 }
96 }
97
98 private static async Task VerifyOriginalProgramClientModeAsync()
99 {
100 var port = GetAvailablePort();
101 var connected = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
102 var received = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
103 var server = new XFEConsoleTerminalServer(port, true, "original-password");
104 server.Connected += (_, _) => connected.TrySetResult();
105 server.MessageReceived += (_, message) => received.TrySetResult(message);
106 await server.StartAsync();
107 try
108 {
109 var rejectedClosed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
110 var rejectedClient = new XFEConsoleProgramClient($"ws://localhost:{port}/", "RejectedProgram", "rejected-program", "wrong-password");
111 rejectedClient.Client.ConnectionClosedHandler = cancellationToken =>
112 {
113 rejectedClosed.TrySetResult();
114 return ValueTask.CompletedTask;
115 };
116 await rejectedClient.Connect();
117 await rejectedClosed.Task.WaitAsync(TimeSpan.FromSeconds(5));
118 if (connected.Task.IsCompleted)
119 throw new InvalidOperationException("The original terminal server authenticated an incorrect password.");
120
121 var client = new XFEConsoleProgramClient($"ws://localhost:{port}/", "OriginalProgram", "original-program", "original-password");
122 if (!await client.Connect())
123 throw new InvalidOperationException("The original program client could not connect.");
124 await connected.Task.WaitAsync(TimeSpan.FromSeconds(5));
125 await client.OutputMessage("original-mode-output", true);
126 var dictionary = new XFEDictionary(await received.Task.WaitAsync(TimeSpan.FromSeconds(5)));
127 if (dictionary["Text"] != "original-mode-output")
128 throw new InvalidOperationException("The original program-client output was not preserved.");
129 await client.Client.DisconnectAsync();
130 }
131 finally
132 {
133 await server.StopAsync();
134 }
135 }
136
137 private static int GetAvailablePort()
138 {
139 using var listener = new TcpListener(IPAddress.Loopback, 0);
140 listener.Start();
141 return ((IPEndPoint)listener.LocalEndpoint).Port;
142 }
143 }
Modified XFEExtension.NetCore.XFEConsole/Terminal/XFETerminalTitleArt.cs +351 -80
@@ -1,7 +1,4 @@
1 using Figgle;
2 using Figgle.Fonts;
3 1 using System.Globalization;
4 using System.Reflection;
5 2 using System.Text;
6 3
7 4 namespace XFEExtension.NetCore.XFEConsole.Terminal;
@@ -30,43 +27,43 @@ public enum XFETerminalArtStyle
30 27 }
31 28
32 29 /// <summary>
33 /// 常用的终端艺术字体。除 <see cref="Pixel"/> 外均由 FIGlet 字体提供。
30 /// XFEConsole 自研的终端艺术字体。
34 31 /// </summary>
35 32 public enum XFETerminalArtFont
36 33 {
37 34 /// <summary>XFEConsole 内置的 5x5 点阵字体。</summary>
38 35 Pixel,
39 /// <summary>FIGlet Standard。</summary>
36 /// <summary>经典线框字体。</summary>
40 37 Standard,
41 /// <summary>FIGlet Big。</summary>
38 /// <summary>双倍尺寸块状字体。</summary>
42 39 Big,
43 /// <summary>FIGlet Small。</summary>
40 /// <summary>紧凑块状字体。</summary>
44 41 Small,
45 /// <summary>FIGlet Slant。</summary>
42 /// <summary>倾斜线框字体。</summary>
46 43 Slant,
47 /// <summary>ANSI Shadow 风格;映射至 FIGlet Shadow。</summary>
44 /// <summary>ANSI 实心阴影字体。</summary>
48 45 AnsiShadow,
49 /// <summary>FIGlet Shadow Small。</summary>
46 /// <summary>紧凑阴影字体。</summary>
50 47 SmallShadow,
51 /// <summary>FIGlet Doom。</summary>
48 /// <summary>厚重的 Doom 风格字体。</summary>
52 49 Doom,
53 /// <summary>FIGlet Epic。</summary>
50 /// <summary>双线 Epic 风格字体。</summary>
54 51 Epic,
55 /// <summary>FIGlet Gothic。</summary>
52 /// <summary>尖角哥特字体。</summary>
56 53 Gothic,
57 /// <summary>FIGlet Ivrit。</summary>
54 /// <summary>从右向左镜像布局字体。</summary>
58 55 Ivrit,
59 /// <summary>FIGlet Modular。</summary>
56 /// <summary>模块化单元字体。</summary>
60 57 Modular,
61 /// <summary>FIGlet Ogre。</summary>
58 /// <summary>圆润 Ogre 风格字体。</summary>
62 59 Ogre,
63 /// <summary>FIGlet Rectangles。</summary>
60 /// <summary>矩形单元字体。</summary>
64 61 Rectangles,
65 /// <summary>FIGlet Relief。</summary>
62 /// <summary>浮雕高光字体。</summary>
66 63 Relief,
67 /// <summary>FIGlet Isometric1。</summary>
64 /// <summary>等距投影字体。</summary>
68 65 Isometric,
69 /// <summary>FIGlet Larry3d。</summary>
66 /// <summary>Larry 风格立体字体。</summary>
70 67 Larry3D
71 68 }
72 69
@@ -127,12 +124,6 @@ public sealed class XFETerminalTitleArtOptions
127 124 /// <summary>艺术字体;默认使用兼容原有版本的内置点阵字体。</summary>
128 125 public XFETerminalArtFont Font { get; set; } = XFETerminalArtFont.Pixel;
129 126
130 /// <summary>
131 /// 任意 FIGlet 字体名。设置后优先于 <see cref="Font"/>;可从
132 /// <see cref="XFETerminalTitleArt.AvailableFigletFonts"/> 获取全部名称。
133 /// </summary>
134 public string? FigletFontName { get; set; }
135
136 127 /// <summary>内置配色。</summary>
137 128 public XFETerminalArtPalette Palette { get; set; } = XFETerminalArtPalette.Cyan;
138 129
@@ -199,16 +190,6 @@ public static class XFETerminalTitleArt
199 190 public int Height => Rows.Length;
200 191 }
201 192
202 private static readonly PropertyInfo[] FigletFontProperties = typeof(FiggleFonts)
203 .GetProperties(BindingFlags.Public | BindingFlags.Static)
204 .Where(property => property.PropertyType == typeof(FiggleFont) && property.GetMethod is not null)
205 .OrderBy(property => property.Name, StringComparer.OrdinalIgnoreCase)
206 .ToArray();
207
208 private static readonly Dictionary<string, FiggleFont> FigletFontCache = new(StringComparer.OrdinalIgnoreCase);
209
210 private static readonly object FigletFontCacheLock = new();
211
212 193 private static readonly IReadOnlyDictionary<char, string> Glyphs = new Dictionary<char, string>
213 194 {
214 195 ['A'] = "0111010001111111000110001",
@@ -311,9 +292,9 @@ public static class XFETerminalTitleArt
311 292 ]
312 293 };
313 294
314 /// <summary>取得全部可通过 <see cref="XFETerminalTitleArtOptions.FigletFontName"/> 使用的 FIGlet 字体名。</summary>
315 public static IReadOnlyList<string> AvailableFigletFonts { get; } =
316 Array.AsReadOnly(FigletFontProperties.Select(property => property.Name).ToArray());
295 /// <summary>取得本仓库实现的全部艺术字体。</summary>
296 public static IReadOnlyList<XFETerminalArtFont> AvailableFonts { get; } =
297 Array.AsReadOnly(Enum.GetValues<XFETerminalArtFont>());
317 298
318 299 /// <summary>
319 300 /// 生成适合当前终端直接输出的艺术字。现代模式可能包含 ANSI 颜色序列。
@@ -366,11 +347,6 @@ public static class XFETerminalTitleArt
366 347 return ToPlainText(Render(text, options, IsModern(options.Compatibility)));
367 348 }
368 349
369 /// <summary>
370 /// 检查指定 FIGlet 字体名是否可用。比较时忽略大小写、空格、连字符和下划线。
371 /// </summary>
372 public static bool IsFigletFontAvailable(string? fontName) => FindFigletFontProperty(fontName) is not null;
373
374 350 /// <summary>
375 351 /// 直接向终端显示艺术字。传统模式会通过 ConsoleColor 为正面、描边和挤出层着色。
376 352 /// </summary>
@@ -407,12 +383,11 @@ public static class XFETerminalTitleArt
407 383 {
408 384 rows = RenderFramed(text, modern);
409 385 }
410 else if (options.Font != XFETerminalArtFont.Pixel || !string.IsNullOrWhiteSpace(options.FigletFontName))
386 else if (options.Font != XFETerminalArtFont.Pixel)
411 387 {
412 var font = ResolveFigletFont(options);
413 rows = text.Any(character => !char.IsWhiteSpace(character) && !font.Contains(character))
388 rows = text.ToUpperInvariant().Any(character => !Glyphs.ContainsKey(character))
414 389 ? RenderFramed(text, modern)
415 : NormalizeRows(font.Render(text));
390 : RenderBuiltInFont(text, options.Font, options.LetterSpacing, modern);
416 391 }
417 392 else
418 393 {
@@ -512,48 +487,346 @@ public static class XFETerminalTitleArt
512 487 _ => throw new ArgumentOutOfRangeException(nameof(direction))
513 488 };
514 489
515 private static FiggleFont ResolveFigletFont(XFETerminalTitleArtOptions options)
490 private static IReadOnlyList<string> RenderBuiltInFont(
491 string text,
492 XFETerminalArtFont font,
493 int letterSpacing,
494 bool modern)
516 495 {
517 var requestedName = string.IsNullOrWhiteSpace(options.FigletFontName)
518 ? FontName(options.Font)
519 : options.FigletFontName;
520 var property = FindFigletFontProperty(requestedName) ??
521 throw new ArgumentException($"找不到 FIGlet 字体“{requestedName}”。请从 AvailableFigletFonts 选择字体。", nameof(options));
496 var compact = BuildTextMatrix(text, 1, 1, letterSpacing);
497 return font switch
498 {
499 XFETerminalArtFont.Standard => RenderConnectionMask(compact, modern, false, false),
500 XFETerminalArtFont.Big => RenderSolidMask(BuildTextMatrix(text, 2, 2, letterSpacing), modern ? '█' : '#'),
501 XFETerminalArtFont.Small => RenderSolidMask(compact, modern ? '▪' : '*'),
502 XFETerminalArtFont.Slant => SlantRows(RenderConnectionMask(compact, modern, false, false)),
503 XFETerminalArtFont.AnsiShadow => AddInlineShadow(
504 RenderSolidMask(BuildTextMatrix(text, 2, 1, letterSpacing), modern ? '█' : '#'),
505 modern ? '░' : '.', 1, 1),
506 XFETerminalArtFont.SmallShadow => AddInlineShadow(
507 RenderSolidMask(compact, modern ? '■' : '#'), modern ? '░' : '.', 1, 1),
508 XFETerminalArtFont.Doom => RenderDoomMask(BuildTextMatrix(text, 2, 1, letterSpacing), modern),
509 XFETerminalArtFont.Epic => RenderConnectionMask(compact, modern, true, false),
510 XFETerminalArtFont.Gothic => RenderGothicMask(compact, modern),
511 XFETerminalArtFont.Ivrit => RenderConnectionMask(
512 BuildTextMatrix(text, 1, 1, letterSpacing, reverse: true, mirror: true), modern, false, false),
513 XFETerminalArtFont.Modular => RenderTokenMask(compact, modern ? "▦" : "O"),
514 XFETerminalArtFont.Ogre => RenderConnectionMask(compact, modern, false, true),
515 XFETerminalArtFont.Rectangles => RenderTokenMask(compact, modern ? "▣" : "[]"),
516 XFETerminalArtFont.Relief => AddInlineShadow(
517 RenderSolidMask(BuildTextMatrix(text, 2, 1, letterSpacing), modern ? '▓' : '%'),
518 modern ? '░' : '.', 1, 1),
519 XFETerminalArtFont.Isometric => RenderIsometricMask(compact, modern),
520 XFETerminalArtFont.Larry3D => SlantRows(AddInlineShadow(
521 RenderSolidMask(BuildTextMatrix(text, 2, 1, letterSpacing), modern ? '█' : '#'),
522 modern ? '╲' : '\\', 2, 1)),
523 _ => throw new ArgumentOutOfRangeException(nameof(font))
524 };
525 }
526
527 private static bool[,] BuildTextMatrix(
528 string text,
529 int scaleX,
530 int scaleY,
531 int letterSpacing,
532 bool reverse = false,
533 bool mirror = false)
534 {
535 var normalized = text.ToUpperInvariant();
536 if (reverse)
537 normalized = new string(normalized.Reverse().ToArray());
538
539 var glyphWidth = GlyphWidth * scaleX;
540 var width = normalized.Length * glyphWidth + Math.Max(0, normalized.Length - 1) * letterSpacing;
541 var matrix = new bool[GlyphHeight * scaleY, width];
542 var offsetX = 0;
543 foreach (var character in normalized)
544 {
545 var glyph = Glyphs[character];
546 for (var glyphY = 0; glyphY < GlyphHeight; glyphY++)
547 for (var glyphX = 0; glyphX < GlyphWidth; glyphX++)
548 {
549 var sourceX = mirror ? GlyphWidth - glyphX - 1 : glyphX;
550 if (glyph[glyphY * GlyphWidth + sourceX] != '1')
551 continue;
552 for (var yScale = 0; yScale < scaleY; yScale++)
553 for (var xScale = 0; xScale < scaleX; xScale++)
554 matrix[glyphY * scaleY + yScale, offsetX + glyphX * scaleX + xScale] = true;
555 }
556 offsetX += glyphWidth + letterSpacing;
557 }
558 return matrix;
559 }
522 560
523 lock (FigletFontCacheLock)
561 private static IReadOnlyList<string> RenderSolidMask(bool[,] matrix, char character)
562 {
563 var height = matrix.GetLength(0);
564 var width = matrix.GetLength(1);
565 var rows = new string[height];
566 for (var y = 0; y < height; y++)
524 567 {
525 if (FigletFontCache.TryGetValue(property.Name, out var cached))
526 return cached;
527 var font = (FiggleFont?)property.GetValue(null) ??
528 throw new InvalidOperationException($"无法加载 FIGlet 字体“{property.Name}”。");
529 FigletFontCache[property.Name] = font;
530 return font;
568 var builder = new StringBuilder(width);
569 for (var x = 0; x < width; x++)
570 builder.Append(matrix[y, x] ? character : ' ');
571 rows[y] = builder.ToString().TrimEnd();
531 572 }
573 return rows;
532 574 }
533 575
534 private static PropertyInfo? FindFigletFontProperty(string? fontName)
576 private static IReadOnlyList<string> RenderConnectionMask(
577 bool[,] matrix,
578 bool modern,
579 bool doubleLine,
580 bool rounded)
535 581 {
536 if (string.IsNullOrWhiteSpace(fontName))
537 return null;
538 var normalized = NormalizeFontName(fontName);
539 return FigletFontProperties.FirstOrDefault(property => NormalizeFontName(property.Name) == normalized);
582 var height = matrix.GetLength(0);
583 var width = matrix.GetLength(1);
584 var rows = new string[height];
585 for (var y = 0; y < height; y++)
586 {
587 var builder = new StringBuilder(width);
588 for (var x = 0; x < width; x++)
589 builder.Append(matrix[y, x] ? ConnectionCharacter(matrix, x, y, modern, doubleLine, rounded) : ' ');
590 rows[y] = builder.ToString().TrimEnd();
591 }
592 return rows;
540 593 }
541 594
542 private static string NormalizeFontName(string fontName) =>
543 new(fontName.Where(character => character is not (' ' or '-' or '_')).Select(char.ToUpperInvariant).ToArray());
595 private static char ConnectionCharacter(
596 bool[,] matrix,
597 int x,
598 int y,
599 bool modern,
600 bool doubleLine,
601 bool rounded)
602 {
603 var bits = (IsFilled(matrix, x, y - 1) ? 1 : 0) |
604 (IsFilled(matrix, x + 1, y) ? 2 : 0) |
605 (IsFilled(matrix, x, y + 1) ? 4 : 0) |
606 (IsFilled(matrix, x - 1, y) ? 8 : 0);
607 if (!modern && doubleLine)
608 return bits switch
609 {
610 0 => 'O',
611 1 or 4 or 5 => 'H',
612 2 or 8 or 10 => '=',
613 _ => '#'
614 };
615 if (!modern && rounded)
616 return bits switch
617 {
618 0 => 'o',
619 1 or 4 or 5 => '!',
620 2 or 8 or 10 => '~',
621 _ => '+'
622 };
623 if (!modern)
624 return bits switch
625 {
626 0 => 'o',
627 1 or 4 or 5 => '|',
628 2 or 8 or 10 => '-',
629 _ => '+'
630 };
631 if (rounded)
632 return bits switch
633 {
634 0 => '●',
635 1 => '╵',
636 2 => '╶',
637 3 => '╰',
638 4 => '╷',
639 5 => '│',
640 6 => '╭',
641 7 => '├',
642 8 => '╴',
643 9 => '╯',
644 10 => '─',
645 11 => '┴',
646 12 => '╮',
647 13 => '┤',
648 14 => '┬',
649 _ => '┼'
650 };
651 if (doubleLine)
652 return bits switch
653 {
654 0 => '◆',
655 1 => '╵',
656 2 => '╶',
657 3 => '╚',
658 4 => '╷',
659 5 => '║',
660 6 => '╔',
661 7 => '╠',
662 8 => '╴',
663 9 => '╝',
664 10 => '═',
665 11 => '╩',
666 12 => '╗',
667 13 => '╣',
668 14 => '╦',
669 _ => '╬'
670 };
671 return bits switch
672 {
673 0 => '●',
674 1 => '╵',
675 2 => '╶',
676 3 => '└',
677 4 => '╷',
678 5 => '│',
679 6 => '┌',
680 7 => '├',
681 8 => '╴',
682 9 => '┘',
683 10 => '─',
684 11 => '┴',
685 12 => '┐',
686 13 => '┤',
687 14 => '┬',
688 _ => '┼'
689 };
690 }
544 691
545 private static string FontName(XFETerminalArtFont font) => font switch
692 private static IReadOnlyList<string> RenderDoomMask(bool[,] matrix, bool modern)
546 693 {
547 XFETerminalArtFont.Pixel => throw new ArgumentException("Pixel 不是 FIGlet 字体。", nameof(font)),
548 XFETerminalArtFont.AnsiShadow => "Shadow",
549 XFETerminalArtFont.SmallShadow => "ShadowSmall",
550 XFETerminalArtFont.Isometric => "Isometric1",
551 XFETerminalArtFont.Larry3D => "Larry3d",
552 _ => font.ToString()
553 };
694 var height = matrix.GetLength(0);
695 var width = matrix.GetLength(1);
696 var rows = new string[height];
697 for (var y = 0; y < height; y++)
698 {
699 var builder = new StringBuilder(width);
700 for (var x = 0; x < width; x++)
701 {
702 if (!matrix[y, x])
703 {
704 builder.Append(' ');
705 continue;
706 }
707 var character = !IsFilled(matrix, x - 1, y) ? modern ? '▌' : '/' :
708 !IsFilled(matrix, x + 1, y) ? modern ? '▐' : '\\' :
709 !IsFilled(matrix, x, y - 1) ? modern ? '▀' : '_' :
710 !IsFilled(matrix, x, y + 1) ? modern ? '▄' : '_' : modern ? '█' : '#';
711 builder.Append(character);
712 }
713 rows[y] = builder.ToString().TrimEnd();
714 }
715 return rows;
716 }
717
718 private static IReadOnlyList<string> RenderGothicMask(bool[,] matrix, bool modern)
719 {
720 var height = matrix.GetLength(0);
721 var width = matrix.GetLength(1);
722 var rows = new string[height];
723 for (var y = 0; y < height; y++)
724 {
725 var builder = new StringBuilder(width);
726 for (var x = 0; x < width; x++)
727 {
728 if (!matrix[y, x])
729 {
730 builder.Append(' ');
731 continue;
732 }
733 var horizontal = IsFilled(matrix, x - 1, y) || IsFilled(matrix, x + 1, y);
734 var vertical = IsFilled(matrix, x, y - 1) || IsFilled(matrix, x, y + 1);
735 builder.Append((horizontal, vertical) switch
736 {
737 (true, true) => modern ? '✣' : '+',
738 (true, false) => modern ? '━' : '-',
739 (false, true) => modern ? '┃' : '|',
740 _ => (x + y) % 2 == 0 ? '/' : '\\'
741 });
742 }
743 rows[y] = builder.ToString().TrimEnd();
744 }
745 return rows;
746 }
747
748 private static IReadOnlyList<string> RenderTokenMask(bool[,] matrix, string token)
749 {
750 var height = matrix.GetLength(0);
751 var width = matrix.GetLength(1);
752 var empty = new string(' ', token.Length);
753 var rows = new string[height];
754 for (var y = 0; y < height; y++)
755 {
756 var builder = new StringBuilder(width * token.Length);
757 for (var x = 0; x < width; x++)
758 builder.Append(matrix[y, x] ? token : empty);
759 rows[y] = builder.ToString().TrimEnd();
760 }
761 return rows;
762 }
763
764 private static IReadOnlyList<string> RenderIsometricMask(bool[,] matrix, bool modern)
765 {
766 var height = matrix.GetLength(0);
767 var width = matrix.GetLength(1);
768 var rows = new List<string>(height * 2);
769 var top = modern ? "╱╲" : "/\\";
770 var bottom = modern ? "╲╱" : "\\/";
771 for (var y = 0; y < height; y++)
772 {
773 var indentation = new string(' ', (height - y - 1) * 2);
774 var topBuilder = new StringBuilder(indentation);
775 var bottomBuilder = new StringBuilder(indentation);
776 for (var x = 0; x < width; x++)
777 {
778 topBuilder.Append(matrix[y, x] ? top : " ");
779 bottomBuilder.Append(matrix[y, x] ? bottom : " ");
780 }
781 rows.Add(topBuilder.ToString().TrimEnd());
782 rows.Add(bottomBuilder.ToString().TrimEnd());
783 }
784 return rows;
785 }
786
787 private static IReadOnlyList<string> AddInlineShadow(
788 IReadOnlyList<string> sourceRows,
789 char shadowCharacter,
790 int offsetX,
791 int offsetY)
792 {
793 var height = sourceRows.Count + offsetY;
794 var width = sourceRows.Max(row => row.Length) + offsetX;
795 var canvas = new char[height, width];
796 for (var y = 0; y < height; y++)
797 for (var x = 0; x < width; x++)
798 canvas[y, x] = ' ';
799
800 for (var y = 0; y < sourceRows.Count; y++)
801 for (var x = 0; x < sourceRows[y].Length; x++)
802 if (sourceRows[y][x] != ' ')
803 canvas[y + offsetY, x + offsetX] = shadowCharacter;
804 for (var y = 0; y < sourceRows.Count; y++)
805 for (var x = 0; x < sourceRows[y].Length; x++)
806 if (sourceRows[y][x] != ' ')
807 canvas[y, x] = sourceRows[y][x];
808
809 var rows = new string[height];
810 for (var y = 0; y < height; y++)
811 {
812 var builder = new StringBuilder(width);
813 for (var x = 0; x < width; x++)
814 builder.Append(canvas[y, x]);
815 rows[y] = builder.ToString().TrimEnd();
816 }
817 return rows;
818 }
819
820 private static IReadOnlyList<string> SlantRows(IReadOnlyList<string> rows)
821 {
822 var result = new string[rows.Count];
823 for (var y = 0; y < rows.Count; y++)
824 result[y] = new string(' ', rows.Count - y - 1) + rows[y];
825 return result;
826 }
554 827
555 private static IReadOnlyList<string> NormalizeRows(string rendered) =>
556 TrimEmptyRows(rendered.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n').Select(row => row.TrimEnd()).ToArray());
828 private static bool IsFilled(bool[,] matrix, int x, int y) =>
829 y >= 0 && y < matrix.GetLength(0) && x >= 0 && x < matrix.GetLength(1) && matrix[y, x];
557 830
558 831 private static IReadOnlyList<string> TrimEmptyRows(IReadOnlyList<string> sourceRows)
559 832 {
@@ -807,8 +1080,6 @@ public static class XFETerminalTitleArt
807 1080 throw new ArgumentOutOfRangeException(nameof(options.OutlineWidth), "描边宽度必须在 0 到 8 之间。");
808 1081 if (options.ExtrudeDepth is < 0 or > 32)
809 1082 throw new ArgumentOutOfRangeException(nameof(options.ExtrudeDepth), "立体挤出深度必须在 0 到 32 之间。");
810 if (options.FigletFontName is { Length: > 128 } || options.FigletFontName?.Any(char.IsControl) == true)
811 throw new ArgumentException("FIGlet 字体名无效。", nameof(options.FigletFontName));
812 1083 ValidateEffectCharacter(options.OutlineCharacter, nameof(options.OutlineCharacter));
813 1084 ValidateEffectCharacter(options.ExtrudeCharacter, nameof(options.ExtrudeCharacter));
814 1085 }
Modified XFEExtension.NetCore.XFEConsole/XFEConsole.cs +50 -12
@@ -54,6 +54,10 @@ public static class XFEConsole
54 54 /// </summary>
55 55 public static List<XFEConsoleProgramClient> ClientList { get; set; } = [];
56 56 /// <summary>
57 /// 当前由调试程序托管的远程控制台服务器列表。
58 /// </summary>
59 public static List<XFEConsoleProgramServer> ProgramServerList { get; set; } = [];
60 /// <summary>
57 61 /// 当前控制台输出流
58 62 /// </summary>
59 63 public static XFEConsoleTextWriter? CurrentConsoleTextWriter { get; set; }
@@ -117,6 +121,28 @@ public static class XFEConsole
117 121 /// <returns>是否连接成功</returns>
118 122 public static async Task<bool> UseXFEConsole(int port = 3280, string password = "") => await UseXFEConsole($"ws://localhost:{port}/", AppDomain.CurrentDomain.FriendlyName, Guid.NewGuid().ToString(), password);
119 123 /// <summary>
124 /// 以服务器模式使用 XFE 控制台,允许工具箱主动连接当前调试程序。
125 /// </summary>
126 /// <param name="port">监听端口。</param>
127 /// <param name="localOnly">是否仅允许本机工具箱连接;远程调试时应设为 false。</param>
128 /// <param name="password">工具箱连接密码。</param>
129 /// <param name="programName">显示在工具箱中的程序名称。</param>
130 /// <param name="programId">程序唯一标识。</param>
131 /// <returns>已启动的调试程序服务器。</returns>
132 public static async Task<XFEConsoleProgramServer> UseXFEConsoleServer(
133 int port = 3280,
134 bool localOnly = true,
135 string password = "",
136 string? programName = null,
137 string? programId = null)
138 {
139 SetConsoleOutput();
140 var server = new XFEConsoleProgramServer(port, localOnly, password, programName, programId);
141 await server.StartAsync().ConfigureAwait(false);
142 ProgramServerList.Add(server);
143 return server;
144 }
145 /// <summary>
120 146 /// 使用XFE控制台日志
121 147 /// </summary>
122 148 public static void UseXFEConsoleLog(XFEConsoleLogOptions? xFEConsoleLogOptions = null)
@@ -156,8 +182,13 @@ public static class XFEConsole
156 182 {
157 183 if (CurrentConsoleTextWriter is not null)
158 184 Console.SetOut(CurrentConsoleTextWriter.OriginalTextWriter);
159 foreach (var client in ClientList)
160 await client.Client.CloseCyberCommClient();
185 foreach (var client in ClientList.ToArray())
186 await client.Client.DisconnectAsync().ConfigureAwait(false);
187 foreach (var server in ProgramServerList.ToArray())
188 await server.StopAsync().ConfigureAwait(false);
189 ClientList.Clear();
190 ProgramServerList.Clear();
191 CurrentConsoleTextWriter = null;
161 192 }
162 193 /// <summary>
163 194 /// 设置XFE控制台
@@ -165,6 +196,11 @@ public static class XFEConsole
165 196 /// <returns></returns>
166 197 public static void SetConsoleOutput()
167 198 {
199 if (Console.Out is XFEConsoleTextWriter currentWriter)
200 {
201 CurrentConsoleTextWriter = currentWriter;
202 return;
203 }
168 204 CurrentConsoleTextWriter = new(Console.Out);
169 205 Console.SetOut(CurrentConsoleTextWriter);
170 206 }
@@ -210,8 +246,7 @@ public static class XFEConsole
210 246 Debug.WriteLine(objectInfo);
211 247 if (ShowInLocalConsole)
212 248 await (CurrentConsoleTextWriter?.OriginalTextWriter.WriteLineAsync(objectInfo) ?? Task.CompletedTask);
213 foreach (var client in ClientList)
214 await client.OutputMessage(objectInfo, true);
249 await OutputToRemoteConsolesAsync(objectInfo, true).ConfigureAwait(false);
215 250 }
216 251 /// <summary>
217 252 /// 向已连接的XFE控制台输出一条消息
@@ -233,8 +268,7 @@ public static class XFEConsole
233 268 {
234 269 CurrentConsoleTextWriter?.OriginalTextWriter.WriteLine(text);
235 270 }
236 foreach (var client in ClientList)
237 client.OutputMessage($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", true).Wait();
271 OutputToRemoteConsolesAsync($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", true).GetAwaiter().GetResult();
238 272 }
239 273 /// <summary>
240 274 /// 向已连接的XFE控制台输出一条消息
@@ -256,8 +290,7 @@ public static class XFEConsole
256 290 {
257 291 CurrentConsoleTextWriter?.OriginalTextWriter.Write(text);
258 292 }
259 foreach (var client in ClientList)
260 client.OutputMessage($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", false).Wait();
293 OutputToRemoteConsolesAsync($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", false).GetAwaiter().GetResult();
261 294 }
262 295 /// <summary>
263 296 /// 向已连接的XFE控制台输出一条消息
@@ -279,8 +312,7 @@ public static class XFEConsole
279 312 {
280 313 await (CurrentConsoleTextWriter?.OriginalTextWriter.WriteLineAsync(text) ?? Task.CompletedTask);
281 314 }
282 foreach (var client in ClientList)
283 await client.OutputMessage($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", true);
315 await OutputToRemoteConsolesAsync($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", true).ConfigureAwait(false);
284 316 }
285 317 /// <summary>
286 318 /// 向已连接的XFE控制台输出一条消息
@@ -303,10 +335,16 @@ public static class XFEConsole
303 335 {
304 336 await (CurrentConsoleTextWriter?.OriginalTextWriter.WriteAsync(text) ?? Task.CompletedTask);
305 337 }
306 foreach (var client in ClientList)
307 await client.OutputMessage($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", false);
338 await OutputToRemoteConsolesAsync($"[color {ConvertConsoleColorToString(Console.ForegroundColor)} {ConvertConsoleColorToString(Console.BackgroundColor)}]{text}", false).ConfigureAwait(false);
308 339 }
309 340 }
341 private static async Task OutputToRemoteConsolesAsync(string message, bool isLine)
342 {
343 foreach (var client in ClientList.ToArray())
344 await client.OutputMessage(message, isLine).ConfigureAwait(false);
345 foreach (var server in ProgramServerList.ToArray())
346 await server.OutputMessage(message, isLine).ConfigureAwait(false);
347 }
310 348 /// <summary>
311 349 /// 将控制台颜色转为颜色代码
312 350 /// </summary>
Modified XFEExtension.NetCore.XFEConsole/XFEConsoleProgramClient.cs +21 -29
@@ -1,7 +1,5 @@
1 1 using System.Diagnostics;
2 2 using XFEExtension.NetCore.CyberComm;
3 using XFEExtension.NetCore.FormatExtension;
4 using XFEExtension.NetCore.TaskExtension;
5 3
6 4 namespace XFEExtension.NetCore.XFEConsole;
7 5
@@ -17,11 +15,20 @@ namespace XFEExtension.NetCore.XFEConsole;
17 15 /// <param name="password">密码</param>
18 16 public class XFEConsoleProgramClient(string ipAddress, string clientName, string clientID, string password)
19 17 {
20 private event EndTaskTrigger<bool>? ConnectTrigger;
21 18 /// <summary>
22 19 /// 客户端
23 20 /// </summary>
24 public CyberCommClient Client { get; set; } = new(ipAddress);
21 public CyberCommClient Client { get; set; } = new(new CyberCommClientOptions
22 {
23 ServerUri = new Uri(ipAddress, UriKind.Absolute),
24 Reconnect = new CyberCommReconnectOptions { Enabled = false, MaxAttempts = 0 },
25 RequestHeaders = new Dictionary<string, string>
26 {
27 [nameof(ClientName)] = clientName,
28 [nameof(Password)] = password,
29 [nameof(ClientID)] = clientID
30 }
31 });
25 32 /// <summary>
26 33 /// 客户端名称
27 34 /// </summary>
@@ -40,34 +47,19 @@ public class XFEConsoleProgramClient(string ipAddress, string clientName, string
40 47 /// <returns></returns>
41 48 public async Task<bool> Connect()
42 49 {
43 Client.Connected += Client_Connected;
44 Client.MessageReceived += Client_MessageReceived;
45 Client.ClientWebSocket.Options.SetRequestHeader(nameof(ClientName), ClientName);
46 Client.ClientWebSocket.Options.SetRequestHeader(nameof(Password), Password);
47 Client.ClientWebSocket.Options.SetRequestHeader(nameof(ClientID), ClientID);
48 _ = Client.StartCyberCommClient();
49 if (Client.IsConnected)
50 return true;
51 return await new XFEWaitTask<bool>(ref ConnectTrigger!);
52 }
53
54 private static void Client_MessageReceived(object? sender, CyberCommClientEventArgs e)
55 {
56 switch (e.MessageType)
50 try
57 51 {
58 case BackMessageType.Text:
59 case BackMessageType.Binary:
60 break;
61 case BackMessageType.Error:
62 Debug.WriteLine(e.Exception);
63 break;
64 default:
65 throw new ArgumentOutOfRangeException();
52 Client.ErrorHandler = exception => Debug.WriteLine(exception);
53 await Client.ConnectAsync().ConfigureAwait(false);
54 return Client.IsConnected;
55 }
56 catch (Exception exception)
57 {
58 Debug.WriteLine(exception);
59 return false;
66 60 }
67 61 }
68 62
69 private void Client_Connected(object? sender, EventArgs e) => ConnectTrigger?.Invoke(true);
70
71 63 /// <summary>
72 64 /// 输出控制台消息
73 65 /// </summary>
@@ -79,7 +71,7 @@ public class XFEConsoleProgramClient(string ipAddress, string clientName, string
79 71 try
80 72 {
81 73 if (Client.IsConnected)
82 await Client.SendTextMessage(new XFEDictionary("IsLine", isLine ? "true" : "false", "Text", message));
74 await Client.SendTextAsync(XFEConsoleProtocol.CreateOutputMessage(message, isLine));
83 75 }
84 76 catch { }
85 77 }
Modified XFEExtension.NetCore.XFEConsole/XFEConsoleProgramServer.cs +210 -1
Added XFEExtension.NetCore.XFEConsole/XFEConsoleProtocol.cs +27 -0
@@ -0,0 +1,27 @@
1 using XFEExtension.NetCore.FormatExtension;
2
3 namespace XFEExtension.NetCore.XFEConsole;
4
5 internal static class XFEConsoleProtocol
6 {
7 public const string MessageTypeKey = "MessageType";
8 public const string AuthenticationMessage = "Authentication";
9 public const string AuthenticatedKey = "Authenticated";
10 public const string ReasonKey = "Reason";
11 public const string ProgramNameKey = "ProgramName";
12 public const string ProgramIdKey = "ProgramID";
13 public const string TerminalNameHeader = "TerminalName";
14 public const string TerminalIdHeader = "TerminalID";
15 public const string PasswordHeader = "Password";
16
17 public static string CreateAuthenticationMessage(bool authenticated, string reason, string programName, string programId) =>
18 new XFEDictionary(
19 MessageTypeKey, AuthenticationMessage,
20 AuthenticatedKey, authenticated ? "true" : "false",
21 ReasonKey, reason,
22 ProgramNameKey, programName,
23 ProgramIdKey, programId);
24
25 public static string CreateOutputMessage(string message, bool isLine) =>
26 new XFEDictionary("IsLine", isLine ? "true" : "false", "Text", message);
27 }
Modified XFEExtension.NetCore.XFEConsole/XFEConsoleTerminalClient.cs +196 -1
Added XFEExtension.NetCore.XFEConsole/XFEConsoleTerminalInfo.cs +27 -0
@@ -0,0 +1,27 @@
1 using XFEExtension.NetCore.CyberComm;
2
3 namespace XFEExtension.NetCore.XFEConsole;
4
5 /// <summary>
6 /// 连接到调试程序服务器的终端信息。
7 /// </summary>
8 public sealed class XFEConsoleTerminalInfo
9 {
10 internal XFEConsoleTerminalInfo(string terminalName, string terminalId, CyberCommServerEventArgs eventArgs)
11 {
12 TerminalName = terminalName;
13 TerminalId = terminalId;
14 EventArgs = eventArgs;
15 }
16
17 /// <summary>终端名称。</summary>
18 public string TerminalName { get; }
19
20 /// <summary>终端唯一标识。</summary>
21 public string TerminalId { get; }
22
23 /// <summary>终端的远程 IP 地址。</summary>
24 public string IPAddress => EventArgs.IPAddress;
25
26 internal CyberCommServerEventArgs EventArgs { get; }
27 }
Modified XFEExtension.NetCore.XFEConsole/XFEConsoleTerminalServer.cs +58 -21
@@ -51,10 +51,7 @@ public class XFEConsoleTerminalServer
51 51 {
52 52 Password = password;
53 53 Server = localOnly ? new CyberCommServer($"http://localhost:{port}/") : new CyberCommServer(port);
54 Server.ServerStarted += Server_ServerStarted;
55 Server.ClientConnected += Server_ClientConnected;
56 Server.ConnectionClosed += Server_ConnectionClosed;
57 Server.MessageReceived += Server_MessageReceived;
54 ConfigureServer();
58 55 }
59 56 /// <summary>
60 57 /// XFE控制台终端服务器
@@ -65,34 +62,62 @@ public class XFEConsoleTerminalServer
65 62 {
66 63 Password = password;
67 64 Server = new CyberCommServer(ipAddress);
68 Server.ServerStarted += Server_ServerStarted;
69 Server.ClientConnected += Server_ClientConnected;
70 Server.ConnectionClosed += Server_ConnectionClosed;
71 Server.MessageReceived += Server_MessageReceived;
65 ConfigureServer();
72 66 }
73 67
74 private void Server_MessageReceived(object? sender, CyberCommServerEventArgs e)
68 private void ConfigureServer()
75 69 {
70 Server.StartedHandler = cancellationToken =>
71 {
72 Server_ServerStarted();
73 return ValueTask.CompletedTask;
74 };
75 Server.WebSocketConnectedHandler = async (eventArgs, cancellationToken) =>
76 await Server_ClientConnected(eventArgs).ConfigureAwait(false);
77 Server.WebSocketClosedHandler = (eventArgs, cancellationToken) =>
78 {
79 Server_ConnectionClosed(eventArgs);
80 return ValueTask.CompletedTask;
81 };
82 Server.WebSocketMessageHandler = (eventArgs, cancellationToken) =>
83 {
84 Server_MessageReceived(eventArgs);
85 return ValueTask.CompletedTask;
86 };
87 }
88
89 private void Server_MessageReceived(CyberCommServerEventArgs e)
90 {
91 XFEConsoleClientInfo? clientInfo;
92 lock (ClientInfoDictionary)
93 ClientInfoDictionary.TryGetValue(e.CurrentWebSocket, out clientInfo);
94 if (clientInfo is null)
95 return;
96
76 97 switch (e.MessageType)
77 98 {
78 99 case BackMessageType.Text:
79 MessageReceived?.Invoke(ClientInfoDictionary[e.CurrentWebSocket], e.TextMessage!);
100 MessageReceived?.Invoke(clientInfo, e.TextMessage!);
80 101 break;
81 102 case BackMessageType.Binary:
82 103 break;
83 104 case BackMessageType.Error:
84 ErrorOccurred?.Invoke(ClientInfoDictionary[e.CurrentWebSocket], e.Exception!);
105 ErrorOccurred?.Invoke(clientInfo, e.Exception!);
85 106 break;
86 107 }
87 108 }
88 109
89 private void Server_ConnectionClosed(object? sender, CyberCommServerEventArgs e)
110 private void Server_ConnectionClosed(CyberCommServerEventArgs e)
90 111 {
91 if (!ClientInfoDictionary.Remove(e.CurrentWebSocket, out var clientInfo)) return;
112 XFEConsoleClientInfo? clientInfo;
113 lock (ClientInfoDictionary)
114 {
115 if (!ClientInfoDictionary.Remove(e.CurrentWebSocket, out clientInfo)) return;
116 }
92 117 Disconnected?.Invoke(this, clientInfo);
93 118 }
94 119
95 private async void Server_ClientConnected(object? sender, CyberCommServerEventArgs e)
120 private async Task Server_ClientConnected(CyberCommServerEventArgs e)
96 121 {
97 122 try
98 123 {
@@ -101,11 +126,14 @@ public class XFEConsoleTerminalServer
101 126 var password = e.WSHeader["Password"]!;
102 127 var clientName = e.WSHeader["ClientName"]!;
103 128 var clientUuid = e.WSHeader["ClientID"]!;
104 if (password != Password) return;
105 var clientInfo = new XFEConsoleClientInfo(clientName, clientUuid, password, e);
106 ClientInfoDictionary.Add(e.CurrentWebSocket, clientInfo);
107 Connected?.Invoke(this, clientInfo);
108 return;
129 if (password == Password)
130 {
131 var clientInfo = new XFEConsoleClientInfo(clientName, clientUuid, password, e);
132 lock (ClientInfoDictionary)
133 ClientInfoDictionary.Add(e.CurrentWebSocket, clientInfo);
134 Connected?.Invoke(this, clientInfo);
135 return;
136 }
109 137 }
110 138 }
111 139 catch { }
@@ -123,7 +151,7 @@ public class XFEConsoleTerminalServer
123 151 }
124 152 }
125 153
126 private void Server_ServerStarted(object? sender, EventArgs e)
154 private void Server_ServerStarted()
127 155 {
128 156 ClientInfoDictionary = [];
129 157 ServerStarted?.Invoke(this);
@@ -134,6 +162,15 @@ public class XFEConsoleTerminalServer
134 162 /// <returns></returns>
135 163 public async Task StartServer()
136 164 {
137 await Server.StartCyberCommServer();
165 await Server.StartAsync().ConfigureAwait(false);
166 await Server.RunAsync().ConfigureAwait(false);
138 167 }
168 /// <summary>
169 /// 启动服务器并在监听就绪后返回。
170 /// </summary>
171 public Task StartAsync(CancellationToken cancellationToken = default) => Server.StartAsync(cancellationToken);
172 /// <summary>
173 /// 停止服务器并关闭当前连接。
174 /// </summary>
175 public Task StopAsync(CancellationToken cancellationToken = default) => Server.StopAsync(cancellationToken);
139 176 }
Modified XFEExtension.NetCore.XFEConsole/XFEExtension.NetCore.XFEConsole.csproj +4 -5
@@ -4,7 +4,7 @@
4 4 <TargetFramework>net10.0</TargetFramework>
5 5 <ImplicitUsings>enable</ImplicitUsings>
6 6 <Nullable>enable</Nullable>
7 <Version>2.5.0</Version>
7 <Version>2.6.0</Version>
8 8 <Authors>XFEstudio</Authors>
9 9 <Company>寰宇朽力网络科技</Company>
10 10 <Description>XFEConsole 提供远程调试输出、日志、Windows Terminal/VT 控制、交互画布、进度条和标题艺术字功能</Description>
@@ -13,9 +13,9 @@
13 13 <PackageIcon>logoIcon.png</PackageIcon>
14 14 <PackageReadmeFile>README.md</PackageReadmeFile>
15 15 <RepositoryUrl>https://github.com/XFEstudio/XFEExtension.NetCore.XFEConsole.git</RepositoryUrl>
16 <PackageTags>XFE;Console;Test;Output;Remote;WindowsTerminal;ANSI;VT;Progress;TUI;ASCIIArt;FIGlet;</PackageTags>
16 <PackageTags>XFE;Console;Test;Output;Remote;WindowsTerminal;ANSI;VT;Progress;TUI;ASCIIArt;</PackageTags>
17 17 <PackageReleaseNotes>
18 标题艺术字新增 250 多种 FIGlet 字体、可配置外描边、多层 3D 挤出、分层颜色与旧终端 ASCII 降级
18 标题艺术字新增多种自研字体、可配置外描边、多层 3D 挤出、分层颜色与旧终端 ASCII 降级,不引入第三方字体包;新增工具箱主动连接调试程序服务器的第二调试模式、密码握手,并迁移至 CyberComm 5.2.0 新 API
19 19 </PackageReleaseNotes>
20 20 <PackageLicenseFile>LICENSE</PackageLicenseFile>
21 21 <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
@@ -44,8 +44,7 @@
44 44 </ItemGroup>
45 45
46 46 <ItemGroup>
47 <PackageReference Include="Figgle.Fonts" Version="0.6.6" />
48 <PackageReference Include="XFEExtension.NetCore" Version="4.2.*" />
47 <PackageReference Include="XFEExtension.NetCore" Version="5.2.0" />
49 48 </ItemGroup>
50 49
51 50 </Project>