| 1 | using System.Text.Json; |
| 2 | using Microsoft.Web.WebView2.Core; |
| 3 | using Microsoft.Web.WebView2.WinForms; |
| 4 | |
| 5 | namespace Cage.Windows; |
| 6 | |
| 7 | internal sealed class MainWindow : Form |
| 8 | { |
| 9 | private WebView2 web = new() { Dock = DockStyle.Fill, Visible = false }; |
| 10 | private readonly NativeInput nativeInput; |
| 11 | private readonly Label message = new() { AutoSize = true, MaximumSize = new Size(720, 0), Text = "正在启动 Cage 工作台…", Margin = new Padding(12) }; |
| 12 | private readonly FlowLayoutPanel status = new() { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, Padding = new Padding(48), WrapContents = false }; |
| 13 | private readonly Button retry = new() { Text = "重试连接", AutoSize = true, Visible = false }; |
| 14 | private readonly Button existing = new() { Text = "打开现有环境保存文件", AutoSize = true, Visible = false }; |
| 15 | private readonly Button complete = new() { Text = "保存后停止环境并完成更新", AutoSize = true, Visible = false }; |
| 16 | private readonly NotifyIcon tray; |
| 17 | private readonly AppUpdater updater; |
| 18 | private int expectedPort; |
| 19 | private bool controllerNeedsUpdate, allowQuit, bootstrapping, webFailed; |
| 20 | private bool completingSmoke; |
| 21 | private string smokePhase = "starting"; |
| 22 | private readonly CancellationTokenSource lifetime = new(); |
| 23 | private readonly Dictionary<string, (string[] Paths, DateTime Expires)> fileSelections = new(); |
| 24 | |
| 25 | public MainWindow() |
| 26 | { |
| 27 | nativeInput = new NativeInput(value => Script("window.dispatchEvent(new CustomEvent('cage-native-input',{detail:" + JsonSerializer.Serialize(value) + "}));")); |
| 28 | AutoScaleMode = AutoScaleMode.Dpi; AutoScaleDimensions = new SizeF(96, 96); |
| 29 | Text = "Cage"; |
| 30 | StartPosition = FormStartPosition.CenterScreen; BackColor = Color.FromArgb(247, 247, 247); |
| 31 | Icon = Icon.ExtractAssociatedIcon(Environment.ProcessPath!) ?? SystemIcons.Application; |
| 32 | status.Controls.AddRange([message, retry, existing, complete]); |
| 33 | Controls.Add(web); Controls.Add(status); |
| 34 | Controls.Add(nativeInput); |
| 35 | retry.Click += async (_, _) => { |
| 36 | if (webFailed || web.CoreWebView2 == null) await Initialize(true); else await Bootstrap(); |
| 37 | }; |
| 38 | existing.Click += async (_, _) => await Bootstrap("--existing"); |
| 39 | complete.Click += async (_, _) => { |
| 40 | if (ConfirmStop()) await Bootstrap("--complete-update"); |
| 41 | }; |
| 42 | var trayMenu = new TrayMenu(); |
| 43 | trayMenu.Items.Add("打开 Cage", null, (_, _) => RestoreWindow()); |
| 44 | trayMenu.Items.Add("检查应用更新…", null, (_, _) => updater!.Handle("check")); |
| 45 | trayMenu.Items.Add("关于 Cage", null, (_, _) => MessageBox.Show(this, $"Cage {AppUpdater.Version}\n本机隔离编码工作区", "关于 Cage")); |
| 46 | trayMenu.Items.Add(new ToolStripSeparator()); |
| 47 | trayMenu.Items.Add("退出 Cage…", null, (_, _) => RequestQuit()); |
| 48 | trayMenu.Opening += (_, _) => (chrome ?? new WindowChrome(BackColor, ForeColor, false)).ApplyMenu(trayMenu); |
| 49 | tray = new NotifyIcon { Icon = Icon, Text = "Cage", Visible = true, ContextMenuStrip = trayMenu }; |
| 50 | tray.DoubleClick += (_, _) => RestoreWindow(); |
| 51 | updater = new AppUpdater(PublishUpdate, () => { allowQuit = true; Close(); }, () => _ = Bootstrap()); |
| 52 | Shown += async (_, _) => { |
| 53 | if (Program.SmokeOutput != null) _ = SmokeDeadline(); |
| 54 | await Initialize(); |
| 55 | }; |
| 56 | Resize += (_, _) => PublishVisibility(); VisibleChanged += (_, _) => PublishVisibility(); |
| 57 | FormClosing += (_, e) => { |
| 58 | SaveWindowPlacement(); |
| 59 | if (!allowQuit && e.CloseReason is not (CloseReason.WindowsShutDown or CloseReason.TaskManagerClosing)) { e.Cancel = true; Hide(); } |
| 60 | }; |
| 61 | FormClosed += (_, _) => { lifetime.Cancel(); updater.Dispose(); tray.Dispose(); trayMenu.Dispose(); web.Dispose(); }; |
| 62 | } |
| 63 | |
| 64 | protected override void OnLoad(EventArgs e) |
| 65 | { |
| 66 | base.OnLoad(e); |
| 67 | WindowPlacement? saved = null; |
| 68 | try { saved = JsonSerializer.Deserialize<WindowPlacement>(File.ReadAllText(Path.Combine(Backend.Root, "window-placement.json"))); } |
| 69 | catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { } |
| 70 | var work = Screen.FromHandle(Handle).WorkingArea; |
| 71 | MinimumSize = WindowLayout.Minimum(work, DeviceDpi); |
| 72 | StartPosition = FormStartPosition.Manual; |
| 73 | Bounds = WindowLayout.Bounds(work, DeviceDpi, saved); |
| 74 | if (saved?.Maximized == true) WindowState = FormWindowState.Maximized; |
| 75 | } |
| 76 | |
| 77 | private void SaveWindowPlacement() |
| 78 | { |
| 79 | var bounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; |
| 80 | if (bounds.Width <= 0 || bounds.Height <= 0) return; |
| 81 | try |
| 82 | { |
| 83 | Directory.CreateDirectory(Backend.Root); |
| 84 | File.WriteAllText(Path.Combine(Backend.Root, "window-placement.json"), |
| 85 | JsonSerializer.Serialize(new WindowPlacement(bounds.X, bounds.Y, bounds.Width, bounds.Height, DeviceDpi, |
| 86 | WindowState == FormWindowState.Maximized))); |
| 87 | } |
| 88 | catch (Exception error) when (error is IOException or UnauthorizedAccessException) { } |
| 89 | } |
| 90 | |
| 91 | protected override bool ProcessCmdKey(ref Message msg, Keys keyData) |
| 92 | { |
| 93 | var action = keyData switch { |
| 94 | Keys.Control | Keys.O => "openProject", |
| 95 | Keys.Control | Keys.T => "newTab", |
| 96 | Keys.Control | Keys.Shift | Keys.Enter => "newTerminal", |
| 97 | Keys.Control | Keys.W => "closeTab", |
| 98 | Keys.Control | Keys.Oemcomma => "settings", |
| 99 | _ => null, |
| 100 | }; |
| 101 | if (action == null) return base.ProcessCmdKey(ref msg, keyData); |
| 102 | Action(action); return true; |
| 103 | } |
| 104 | |
| 105 | private WindowChrome? chrome; |
| 106 | |
| 107 | private void ApplyWindowChrome() |
| 108 | { |
| 109 | if (IsHandleCreated) |
| 110 | chrome?.Apply(Handle, MainMenuStrip); |
| 111 | if (tray?.ContextMenuStrip != null) |
| 112 | chrome?.ApplyMenu(tray.ContextMenuStrip); |
| 113 | } |
| 114 | |
| 115 | protected override void OnHandleCreated(EventArgs e) |
| 116 | { |
| 117 | base.OnHandleCreated(e); |
| 118 | ApplyWindowChrome(); |
| 119 | } |
| 120 | |
| 121 | protected override void OnSystemColorsChanged(EventArgs e) |
| 122 | { |
| 123 | base.OnSystemColorsChanged(e); |
| 124 | ApplyWindowChrome(); |
| 125 | } |
| 126 | |
| 127 | private bool ConfirmStop() => MessageBox.Show(this, |
| 128 | "请先保存编辑器中的文件并结束正在运行的工作。继续后 Cage 会停止环境、安装已验证的更新并重新启动。", |
| 129 | "保存并停止环境后安装重启", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK; |
| 130 | |
| 131 | public void RestoreWindow() { Show(); if (WindowState == FormWindowState.Minimized) WindowState = FormWindowState.Normal; Activate(); PublishVisibility(); } |
| 132 | private void RequestQuit() |
| 133 | { |
| 134 | RestoreWindow(); |
| 135 | if (web.Visible) Action("quit"); |
| 136 | else { allowQuit = true; Close(); } |
| 137 | } |
| 138 | private void Action(string name) => Script("window.cageNativeAction?.(" + JsonSerializer.Serialize(name) + ")"); |
| 139 | private void PublishVisibility() => Script($"window.cageWindowVisible = {(Visible && WindowState != FormWindowState.Minimized ? "true" : "false")}; window.dispatchEvent(new Event('cage-window-visibility'));"); |
| 140 | private void PublishUpdate(Dictionary<string, object?> state) { |
| 141 | if (state.TryGetValue("phase", out var phase) && phase as string == "failed") _ = Backend.Report("App update failed: " + state.GetValueOrDefault("message")); |
| 142 | Script("window.dispatchEvent(new CustomEvent('cage-app-update',{detail:" + JsonSerializer.Serialize(state) + "}));"); |
| 143 | } |
| 144 | private async void Script(string script) |
| 145 | { |
| 146 | if (web.IsDisposed || web.CoreWebView2 == null || IsDisposed) return; |
| 147 | try { await web.ExecuteScriptAsync(script); } |
| 148 | catch (InvalidOperationException) { } |
| 149 | catch (System.Runtime.InteropServices.COMException) { } |
| 150 | } |
| 151 | private void Error(string text) |
| 152 | { |
| 153 | _ = Backend.Report(text); |
| 154 | message.Text = text; status.Show(); status.BringToFront(); retry.Show(); web.Hide(); |
| 155 | } |
| 156 | |
| 157 | private async Task Initialize(bool recreate = false) |
| 158 | { |
| 159 | smokePhase = "initializing_webview"; |
| 160 | retry.Enabled = false; |
| 161 | try |
| 162 | { |
| 163 | if (recreate) |
| 164 | { |
| 165 | Controls.Remove(web); web.Dispose(); |
| 166 | web = new WebView2 { Dock = DockStyle.Fill, Visible = false }; |
| 167 | Controls.Add(web); status.BringToFront(); |
| 168 | } |
| 169 | var environment = await CoreWebView2Environment.CreateAsync(null, Path.Combine(Backend.Root, "webview2")); |
| 170 | await web.EnsureCoreWebView2Async(environment); |
| 171 | smokePhase = "webview_initialized"; |
| 172 | var core = web.CoreWebView2; |
| 173 | core.Settings.AreDevToolsEnabled = false; core.Settings.AreDefaultContextMenusEnabled = false; |
| 174 | core.Settings.IsStatusBarEnabled = false; core.Settings.IsZoomControlEnabled = false; |
| 175 | core.Settings.AreBrowserAcceleratorKeysEnabled = false; |
| 176 | core.Settings.IsPasswordAutosaveEnabled = false; core.Settings.IsGeneralAutofillEnabled = false; |
| 177 | core.NavigationStarting += (_, e) => { if (!UpdatePolicy.IsWorkbench(e.Uri, expectedPort)) e.Cancel = true; }; |
| 178 | core.NewWindowRequested += (_, e) => e.Handled = true; |
| 179 | core.DownloadStarting += (_, e) => e.Cancel = true; |
| 180 | core.PermissionRequested += (_, e) => e.State = CoreWebView2PermissionState.Deny; |
| 181 | core.WebMessageReceived += Receive; |
| 182 | core.ProcessFailed += (_, _) => { webFailed = true; Error("工作台显示进程已退出。后台任务保留,可重试连接。"); }; |
| 183 | core.NavigationCompleted += (_, e) => { |
| 184 | if (!e.IsSuccess) { |
| 185 | var reason = e.WebErrorStatus.ToString() switch { |
| 186 | "Timeout" => "等待本机后台响应超时", |
| 187 | "CannotConnect" => "本机后台没有接受连接,可能尚未启动或已经退出", |
| 188 | "ConnectionAborted" or "ConnectionReset" => "本机工作台连接在加载完成前中断", |
| 189 | _ => "内置网页组件未能加载本机工作台(错误类型 " + e.WebErrorStatus + ")", |
| 190 | }; |
| 191 | Error("打开工作台失败:" + reason + "。请点击“重试连接”;仍失败时请保留此错误提示并反馈给维护者。后台任务不会因此自动结束。"); return; |
| 192 | } |
| 193 | status.Hide(); web.Show(); web.Focus(); PublishVisibility(); |
| 194 | }; |
| 195 | await core.AddScriptToExecuteOnDocumentCreatedAsync(BridgeScript); |
| 196 | if (Program.SmokeOutput != null) await core.AddScriptToExecuteOnDocumentCreatedAsync(SmokeDiagnosticsScript); |
| 197 | webFailed = false; |
| 198 | await Bootstrap(); |
| 199 | } |
| 200 | catch (WebView2RuntimeNotFoundException) |
| 201 | { |
| 202 | Error("缺少 Microsoft Edge WebView2 Runtime。请运行 Cage 安装程序安装随附运行时后重试。"); |
| 203 | webFailed = true; |
| 204 | } |
| 205 | catch (Exception error) { webFailed = true; Error("无法初始化工作台:" + error.Message); } |
| 206 | finally { retry.Enabled = true; } |
| 207 | } |
| 208 | |
| 209 | private async Task SmokeDeadline() |
| 210 | { |
| 211 | try { await Task.Delay(TimeSpan.FromSeconds(120), lifetime.Token); await CompleteSmoke(false, "工作台未在自检期限内确认就绪"); } |
| 212 | catch (OperationCanceledException) { } |
| 213 | } |
| 214 | |
| 215 | private async Task CompleteSmoke(bool nativeBridgeReady = true, string? failure = null) |
| 216 | { |
| 217 | if (Program.SmokeOutput == null || completingSmoke) return; |
| 218 | completingSmoke = true; |
| 219 | JsonElement? page = null; |
| 220 | var pageURL = web.Source?.GetLeftPart(UriPartial.Path); |
| 221 | var environment = web.CoreWebView2?.Environment; |
| 222 | var webviewVersion = environment?.BrowserVersionString; |
| 223 | using var shutdown = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); |
| 224 | shutdown.CancelAfter(TimeSpan.FromSeconds(20)); |
| 225 | var errors = new List<string>(); |
| 226 | int? prepareExit = null; |
| 227 | string? prepareStatus = null; |
| 228 | if (failure != null) errors.Add(failure); |
| 229 | try |
| 230 | { |
| 231 | if (!nativeBridgeReady && web.CoreWebView2 != null) |
| 232 | { |
| 233 | try |
| 234 | { |
| 235 | var snapshot = await web.CoreWebView2.ExecuteScriptAsync("({title:document.title,ready:document.readyState,text:(document.body?.innerText||'').slice(0,4096),errors:window.__cageSmokeErrors||[]})"); |
| 236 | page = JsonDocument.Parse(snapshot).RootElement.Clone(); |
| 237 | await using var capture = File.Create(Path.ChangeExtension(Program.SmokeOutput, ".png")); |
| 238 | await web.CoreWebView2.CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat.Png, capture); |
| 239 | } |
| 240 | catch (Exception error) { errors.Add("无法保存工作台画面:" + error.Message); } |
| 241 | } |
| 242 | var controllers = Backend.CaptureSmokeControllers(); |
| 243 | try |
| 244 | { |
| 245 | if (nativeBridgeReady) smokePhase = "stopping_backend"; |
| 246 | var (exit, data) = await Backend.Json(["prepare-update", "--json"], shutdown.Token, TimeSpan.FromSeconds(20)); |
| 247 | prepareExit = exit; |
| 248 | prepareStatus = data.Text("status") is "prepared" or "stop_required" or "error" ? data.Text("status") : "unexpected"; |
| 249 | if (exit != 0 || data.Text("status") != "prepared") throw new IOException("自检结束时无法确认后台已停止"); |
| 250 | await Task.WhenAll(controllers.Select(process => process.WaitForExitAsync(shutdown.Token))); |
| 251 | } |
| 252 | finally { foreach (var process in controllers) process.Dispose(); } |
| 253 | } |
| 254 | catch (Exception error) { errors.Add(error.Message); } |
| 255 | |
| 256 | |
| 257 | if (environment != null) |
| 258 | { |
| 259 | var exited = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); |
| 260 | void BrowserExited(object? sender, CoreWebView2BrowserProcessExitedEventArgs args) => exited.TrySetResult(); |
| 261 | environment.BrowserProcessExited += BrowserExited; |
| 262 | try |
| 263 | { |
| 264 | if (nativeBridgeReady && errors.Count == 0) smokePhase = "stopping_browser"; |
| 265 | web.Dispose(); |
| 266 | await exited.Task.WaitAsync(shutdown.Token); |
| 267 | } |
| 268 | catch (Exception error) { errors.Add("自检浏览器尚未退出:" + error.Message); } |
| 269 | finally { environment.BrowserProcessExited -= BrowserExited; } |
| 270 | } |
| 271 | try |
| 272 | { |
| 273 | if (nativeBridgeReady && errors.Count == 0) smokePhase = "completed"; |
| 274 | File.WriteAllText(Program.SmokeOutput, JsonSerializer.Serialize(new { |
| 275 | success = nativeBridgeReady && errors.Count == 0, nativeBridgeReady, version = AppUpdater.Version, |
| 276 | phase = smokePhase, nativeStatus = message.Text, prepareExit, prepareStatus, errors, page, |
| 277 | pageURL, webviewVersion, |
| 278 | windowBounds = Bounds, workingArea = Screen.FromHandle(Handle).WorkingArea, deviceDpi = DeviceDpi, |
| 279 | nativeMenuBar = MainMenuStrip != null, |
| 280 | })); |
| 281 | } |
| 282 | catch (Exception error) { Error(error.Message); } |
| 283 | finally { allowQuit = true; BeginInvoke(Close); } |
| 284 | } |
| 285 | |
| 286 | private async Task Bootstrap(params string[] options) |
| 287 | { |
| 288 | if (bootstrapping || web.CoreWebView2 == null) return; |
| 289 | bootstrapping = true; |
| 290 | message.Text = "正在连接 Cage 工作台…"; status.Show(); status.BringToFront(); |
| 291 | retry.Hide(); existing.Hide(); complete.Hide(); |
| 292 | try |
| 293 | { |
| 294 | smokePhase = "starting_backend"; |
| 295 | var (exit, data) = await Backend.Json(["desktop", "--json", ..options], lifetime.Token); |
| 296 | smokePhase = "backend_returned"; |
| 297 | if (exit != 0) throw new IOException(data.Text("message") is { Length: > 0 } detail ? detail : "工作台未能启动"); |
| 298 | controllerNeedsUpdate = data.Text("status") != "ready"; |
| 299 | if (data.Text("status") == "upgrade_pending") |
| 300 | { |
| 301 | message.Text = data.Text("message"); existing.Show(); complete.Show(); return; |
| 302 | } |
| 303 | var entry = UpdatePolicy.Entry(data.Text("url")); expectedPort = entry.Port; |
| 304 | smokePhase = "loading_workbench"; |
| 305 | Text = controllerNeedsUpdate ? "Cage(更新待完成)" : "Cage"; |
| 306 | web.CoreWebView2.Navigate(entry.AbsoluteUri); |
| 307 | } |
| 308 | catch (OperationCanceledException) { if (!lifetime.IsCancellationRequested) Error("启动工作台失败:等待本机后台响应超时。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。"); } |
| 309 | catch (Exception error) { |
| 310 | _ = Backend.Report("Workbench startup failed: " + error); |
| 311 | Error(error.Message.Any(c => c is >= '\u4E00' and <= '\u9FFF') ? error.Message : "启动工作台失败:本机后台未返回可识别的原因(错误类型 " + error.GetType().Name + ")。请点击“重试连接”;仍失败时请保留此提示并反馈给维护者。"); |
| 312 | } |
| 313 | finally { bootstrapping = false; } |
| 314 | } |
| 315 | |
| 316 | private object RememberFiles(string[] paths) |
| 317 | { |
| 318 | if (paths.Length is 0 or > 100) throw new InvalidDataException("请选择 1 至 100 个文件"); |
| 319 | foreach (var path in paths) |
| 320 | { |
| 321 | if (!Path.IsPathFullyQualified(path) || path.StartsWith(@"\\", StringComparison.Ordinal)) throw new InvalidDataException("请选择本机文件"); |
| 322 | var file = new FileInfo(path); |
| 323 | if (!file.Exists || (file.Attributes & (FileAttributes.Directory | FileAttributes.ReparsePoint)) != 0) |
| 324 | throw new InvalidDataException("请选择普通文件,暂不支持文件夹或链接"); |
| 325 | if (file.Length > 2L * 1024 * 1024 * 1024) throw new InvalidDataException("每个文件不能超过 2 GB"); |
| 326 | } |
| 327 | var now = DateTime.UtcNow; |
| 328 | foreach (var key in fileSelections.Where(item => item.Value.Expires <= now).Select(item => item.Key).ToArray()) fileSelections.Remove(key); |
| 329 | if (fileSelections.Count >= 16) fileSelections.Remove(fileSelections.MinBy(item => item.Value.Expires).Key); |
| 330 | var selection = Guid.NewGuid().ToString(); |
| 331 | fileSelections[selection] = (paths, now.AddMinutes(10)); |
| 332 | return new { fileSelection = selection, count = paths.Length }; |
| 333 | } |
| 334 | |
| 335 | private async void Receive(object? sender, CoreWebView2WebMessageReceivedEventArgs e) |
| 336 | { |
| 337 | |
| 338 | |
| 339 | if (!UpdatePolicy.IsWorkbench(e.Source, expectedPort)) return; |
| 340 | string id = ""; |
| 341 | try |
| 342 | { |
| 343 | var message = e.WebMessageAsJson; |
| 344 | using var envelope = JsonDocument.Parse(message); |
| 345 | var body = envelope.RootElement; |
| 346 | id = body.Text("id"); |
| 347 | if (!Guid.TryParse(id, out _)) return; |
| 348 | |
| 349 | |
| 350 | if (message.Length > 30 * 1024 * 1024) throw new InvalidDataException("请求内容过大,请减少图片或文本内容后重试"); |
| 351 | var request = body.GetProperty("request"); |
| 352 | object? result; |
| 353 | switch (request.Text("action")) |
| 354 | { |
| 355 | case "remoteInput": result = nativeInput.ProcessRequest(request, web, web.ZoomFactor); break; |
| 356 | case "exportDiagnostics": |
| 357 | using (var picker = new SaveFileDialog { Title = "导出诊断包", Filter = "诊断包 (*.zip)|*.zip", FileName = "cage-diagnostics.zip", DefaultExt = "zip", AddExtension = true }) |
| 358 | { |
| 359 | if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } |
| 360 | var connection = request.Text("connection_id"); |
| 361 | var exported = await Backend.Json(["diagnostics", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, picker.FileName], lifetime.Token, TimeSpan.FromSeconds(60)); |
| 362 | if (exported.Exit != 0) throw new IOException(exported.Data.Text("message")); |
| 363 | result = exported.Data; |
| 364 | } |
| 365 | break; |
| 366 | case "workbenchReady": |
| 367 | if (controllerNeedsUpdate) throw new IOException("后台版本尚未同步,更新未完成"); |
| 368 | updater.MarkReady(); result = true; _ = CompleteSmoke(); break; |
| 369 | case "appUpdate": result = updater.Handle(request.Text("operation")); break; |
| 370 | case "importTheme": |
| 371 | using (var picker = new OpenFileDialog { Filter = "Cage 主题 (*.json)|*.json", Title = "导入主题", Multiselect = false }) |
| 372 | { |
| 373 | if (picker.ShowDialog(this) != DialogResult.OK) { result = ""; break; } |
| 374 | using var stream = File.OpenRead(picker.FileName); |
| 375 | if (stream.Length > 256 * 1024) throw new InvalidDataException("主题文件不能超过 256 KB"); |
| 376 | using var reader = new StreamReader(stream, new System.Text.UTF8Encoding(false, true)); |
| 377 | result = reader.ReadToEnd(); |
| 378 | } |
| 379 | break; |
| 380 | case "exportTheme": |
| 381 | var themeText = request.Text("text"); |
| 382 | if (System.Text.Encoding.UTF8.GetByteCount(themeText) > 256 * 1024) throw new InvalidDataException("主题文件不能超过 256 KB"); |
| 383 | var themeDocument = JsonDocument.Parse(themeText).RootElement; |
| 384 | if (themeDocument.Text("format") != "cage-theme" || themeDocument.GetProperty("version").GetInt32() != 1) throw new InvalidDataException("主题文件格式无效"); |
| 385 | using (var picker = new SaveFileDialog { Filter = "Cage 主题 (*.json)|*.json", Title = "导出主题", FileName = Path.GetFileName(request.Text("filename")), DefaultExt = "json", AddExtension = true }) |
| 386 | { |
| 387 | if (picker.ShowDialog(this) != DialogResult.OK) { result = false; break; } |
| 388 | File.WriteAllText(picker.FileName, themeText, new System.Text.UTF8Encoding(false)); result = true; |
| 389 | } |
| 390 | break; |
| 391 | case "shareLocalProject": |
| 392 | { |
| 393 | var connection = request.Text("connection_id"); |
| 394 | var accessMode = request.Text("mode"); |
| 395 | if (connection.Length == 0 || accessMode is not ("read" or "write")) throw new InvalidDataException("请在云端工作台重新选择项目"); |
| 396 | using var picker = new FolderBrowserDialog { |
| 397 | Description = accessMode == "write" ? "云端 Cage 可以读取、修改和删除所选项目中的文件。" : "云端 Cage 可以读取所选项目中的文件。", |
| 398 | UseDescriptionForTitle = true, ShowNewFolderButton = false |
| 399 | }; |
| 400 | if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } |
| 401 | var response = await Backend.Json(["share-project", "--json", "--connection", connection, accessMode, picker.SelectedPath], lifetime.Token, TimeSpan.FromSeconds(90)); |
| 402 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 403 | result = response.Data; break; |
| 404 | } |
| 405 | case "chooseFolder": |
| 406 | using (var picker = new FolderBrowserDialog { Description = request.Text("purpose") == "environmentStorage" ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true }) |
| 407 | result = picker.ShowDialog(this) == DialogResult.OK ? picker.SelectedPath : ""; |
| 408 | break; |
| 409 | case "clipboardRead": result = Clipboard.ContainsText() ? Clipboard.GetText() : ""; break; |
| 410 | case "clipboardRevision": result = SharedClipboard.Revision; break; |
| 411 | case "clipboardSyncCancel": SharedClipboard.Cancel(); result = true; break; |
| 412 | case "clipboardSyncRead": result = await SharedClipboard.Read(request, lifetime.Token); break; |
| 413 | case "clipboardSyncWrite": result = await SharedClipboard.Write(request, lifetime.Token); break; |
| 414 | case "clipboardSyncRelease": result = await SharedClipboard.Release(request, lifetime.Token); break; |
| 415 | case "desktopFileAction": |
| 416 | { |
| 417 | var fileRequestID = request.Text("id"); |
| 418 | if (!Guid.TryParse(fileRequestID, out _)) throw new InvalidDataException("文件打开标识无效"); |
| 419 | var connection = request.Text("connection_id"); |
| 420 | var response = await Backend.Json(["desktop-file", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, fileRequestID], lifetime.Token, TimeSpan.FromMinutes(30)); |
| 421 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 422 | result = response.Data; break; |
| 423 | } |
| 424 | case "saveBrowserDownload": |
| 425 | case "browserDownloadAction": |
| 426 | { |
| 427 | var downloadID = request.Text("id"); |
| 428 | if (!Guid.TryParse(downloadID, out _)) throw new InvalidDataException("下载标识无效"); |
| 429 | var operation = request.Text("action") == "saveBrowserDownload" ? "save" : request.Text("operation"); |
| 430 | if (operation is not ("save" or "open" or "reveal")) throw new InvalidDataException("下载操作无效"); |
| 431 | var connection = request.Text("connection_id"); |
| 432 | var arguments = new List<string> { "browser-file", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, operation, downloadID }; |
| 433 | if (operation == "save") |
| 434 | { |
| 435 | var fileName = Path.GetFileName(request.Text("name")); |
| 436 | foreach (var character in Path.GetInvalidFileNameChars()) fileName = fileName.Replace(character, '_'); |
| 437 | using var picker = new SaveFileDialog { Title = "将下载另存为到本机", FileName = fileName, OverwritePrompt = true, AddExtension = false }; |
| 438 | if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } |
| 439 | arguments.Add(picker.FileName); |
| 440 | } |
| 441 | var response = await Backend.Json(arguments.ToArray(), lifetime.Token, TimeSpan.FromMinutes(30)); |
| 442 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 443 | result = response.Data; break; |
| 444 | } |
| 445 | case "clipboardReadContent": |
| 446 | if (Clipboard.ContainsFileDropList()) result = RememberFiles(Clipboard.GetFileDropList().Cast<string>().ToArray()); |
| 447 | else if (Clipboard.ContainsImage()) |
| 448 | { |
| 449 | using var clipboardImage = Clipboard.GetImage() ?? throw new InvalidDataException("无法读取剪贴板图片"); |
| 450 | if ((long)clipboardImage.Width * clipboardImage.Height > 40_000_000) throw new InvalidDataException("图片不能超过 4000 万像素"); |
| 451 | using var imageStream = new MemoryStream(); |
| 452 | clipboardImage.Save(imageStream, System.Drawing.Imaging.ImageFormat.Png); |
| 453 | if (imageStream.Length > 20 * 1024 * 1024) throw new InvalidDataException("图片不能超过 20 MB"); |
| 454 | result = new { png = Convert.ToBase64String(imageStream.ToArray()) }; |
| 455 | } |
| 456 | else result = new { text = Clipboard.ContainsText() ? Clipboard.GetText() : "" }; |
| 457 | break; |
| 458 | case "chooseGuestMedia": |
| 459 | using (var picker = new OpenFileDialog { Title = "选择 Windows 11 x64 安装镜像", Filter = "Windows ISO (*.iso)|*.iso", Multiselect = false }) |
| 460 | result = picker.ShowDialog(this) == DialogResult.OK ? picker.FileName : ""; |
| 461 | break; |
| 462 | case "guestInstallReference": |
| 463 | var reference = request.Text("kind") switch { |
| 464 | "windows-media" => "https://www.microsoft.com/software-download/windows11", |
| 465 | "editor-license" => "https://aka.ms/vscode-server-license", |
| 466 | _ => throw new InvalidDataException("未知的安装参考页面") |
| 467 | }; |
| 468 | System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(reference) { UseShellExecute = true }); |
| 469 | result = true; break; |
| 470 | case "chooseUploadFiles": |
| 471 | using (var picker = new OpenFileDialog { Title = "选择本机文件", Multiselect = request.TryGetProperty("multiple", out var multiple) && multiple.ValueKind == JsonValueKind.True, CheckFileExists = true }) |
| 472 | result = picker.ShowDialog(this) == DialogResult.OK ? RememberFiles(picker.FileNames) : new { canceled = true }; |
| 473 | break; |
| 474 | case "uploadHostFiles": |
| 475 | { |
| 476 | var target = request.Text("target"); |
| 477 | var uploadID = request.Text("id"); |
| 478 | if (target is not ("browser" or "desktop" or "terminal") || !(target == "terminal" ? System.Text.RegularExpressions.Regex.IsMatch(uploadID, "^[a-f0-9]{16}$") : Guid.TryParse(uploadID, out _))) throw new InvalidDataException("文件上传目标无效"); |
| 479 | if (!fileSelections.Remove(request.Text("selection"), out var selected) || selected.Expires <= DateTime.UtcNow) |
| 480 | throw new InvalidDataException("文件选择已过期,请重新复制或选择文件"); |
| 481 | var connection = request.Text("connection_id"); |
| 482 | var arguments = new List<string> { "upload-files", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, target, uploadID }; |
| 483 | arguments.AddRange(selected.Paths); |
| 484 | var response = await Backend.Json(arguments.ToArray(), lifetime.Token, TimeSpan.FromMinutes(30)); |
| 485 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| 486 | result = response.Data; |
| 487 | break; |
| 488 | } |
| 489 | case "clipboardWrite": |
| 490 | if (request.Text("text") is { Length: > 0 } text) Clipboard.SetText(text); else Clipboard.Clear(); |
| 491 | result = true; break; |
| 492 | case "appearance": |
| 493 | var mode = request.Text("mode"); var background = request.Text("background"); |
| 494 | if (mode is not ("system" or "light" or "dark") || !System.Text.RegularExpressions.Regex.IsMatch(background, "^#[0-9a-fA-F]{6}$")) |
| 495 | throw new InvalidDataException("外观参数无效"); |
| 496 | var foreground = request.Text("foreground"); |
| 497 | BackColor = ColorTranslator.FromHtml(background); web.DefaultBackgroundColor = BackColor; |
| 498 | var ink = System.Text.RegularExpressions.Regex.IsMatch(foreground, "^#[0-9a-fA-F]{6}$") |
| 499 | ? ColorTranslator.FromHtml(foreground) : WindowChrome.ContrastingText(BackColor); |
| 500 | chrome = new WindowChrome(BackColor, ink, request.Text("variant") == "dark"); |
| 501 | ApplyWindowChrome(); |
| 502 | web.CoreWebView2.Profile.PreferredColorScheme = mode == "dark" ? CoreWebView2PreferredColorScheme.Dark : mode == "light" ? CoreWebView2PreferredColorScheme.Light : CoreWebView2PreferredColorScheme.Auto; |
| 503 | result = true; break; |
| 504 | case "accountDevice": |
| 505 | if (request.Text("operation") != "status") throw new InvalidDataException("此平台暂不支持快捷登录"); |
| 506 | result = new { supported = false }; break; |
| 507 | case "refreshSession": |
| 508 | var (exit, data) = await Backend.Json(controllerNeedsUpdate ? ["desktop", "--json", "--existing"] : ["desktop", "--json"], lifetime.Token); |
| 509 | if (exit != 0) throw new IOException("工作台会话恢复失败"); |
| 510 | result = new { url = UpdatePolicy.Entry(data.Text("url")).AbsoluteUri }; break; |
| 511 | case "reconnect": result = true; _ = Bootstrap(); break; |
| 512 | case "quitNow": result = true; allowQuit = true; BeginInvoke(Close); break; |
| 513 | default: throw new InvalidDataException("未知原生操作"); |
| 514 | } |
| 515 | if (!web.IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, result })); |
| 516 | } |
| 517 | catch (Exception error) |
| 518 | { |
| 519 | _ = Backend.Report(error.ToString()); |
| 520 | if (id.Length != 0 && !IsDisposed && !web.IsDisposed) web.CoreWebView2.PostWebMessageAsJson(JsonSerializer.Serialize(new { id, error = error.Message })); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | private const string SmokeDiagnosticsScript = """ |
| 525 | (() => { |
| 526 | if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return; |
| 527 | const errors = []; |
| 528 | Object.defineProperty(window, '__cageSmokeErrors', { value: errors }); |
| 529 | const ownPath = value => { |
| 530 | try { const url = new URL(value, location.href); return url.origin === location.origin ? url.pathname : ''; } |
| 531 | catch { return ''; } |
| 532 | }; |
| 533 | const scrub = value => { |
| 534 | let text = String(value || ''); |
| 535 | for (const input of document.querySelectorAll('input,textarea')) |
| 536 | if (input.value) text = text.split(input.value).join('[form-value]'); |
| 537 | return text.replace(/https?:\/\/[^\s"'<>`]+/g, value => ownPath(value) || '[external]') |
| 538 | .replace(/[?#][^\s"'<>)]*/g, '[redacted]').slice(0, 768); |
| 539 | }; |
| 540 | const stack = error => String(error?.stack || '').split('\n').slice(1) |
| 541 | .filter(line => line.includes(location.origin + '/')).slice(0, 6).map(scrub); |
| 542 | const record = value => { if (errors.length < 8) errors.push(value); }; |
| 543 | addEventListener('error', event => { |
| 544 | if (event.target instanceof HTMLScriptElement || event.target instanceof HTMLLinkElement) { |
| 545 | const source = ownPath(event.target.src || event.target.href); |
| 546 | if (source) record({ type: 'module-load', source }); |
| 547 | return; |
| 548 | } |
| 549 | const source = ownPath(event.filename || location.href); |
| 550 | if (source) record({ type: 'error', source, message: scrub(event.message), stack: stack(event.error) }); |
| 551 | }, true); |
| 552 | addEventListener('unhandledrejection', event => { |
| 553 | const frames = stack(event.reason); |
| 554 | // Primitive/cross-origin rejections are counted without exporting arbitrary values. |
| 555 | record({ type: 'unhandledrejection', message: frames.length ? scrub(event.reason?.message) : 'Unhandled rejection', stack: frames }); |
| 556 | }); |
| 557 | })(); |
| 558 | """; |
| 559 | |
| 560 | private const string BridgeScript = """ |
| 561 | (() => { |
| 562 | if (window !== window.top || location.protocol !== 'http:' || location.hostname !== 'localhost') return; |
| 563 | window.cageNativeIMEAvailable = true; |
| 564 | const pending = new Map(); |
| 565 | const fileActions = new Set([ |
| 566 | 'uploadHostFiles', 'chooseUploadFiles', 'clipboardSyncRead', 'clipboardSyncWrite', |
| 567 | 'saveBrowserDownload', 'browserDownloadAction', 'desktopFileAction', 'exportDiagnostics', |
| 568 | 'importTheme', 'exportTheme', 'shareLocalProject', 'chooseFolder', 'chooseGuestMedia', |
| 569 | ]); |
| 570 | chrome.webview.addEventListener('message', ({data}) => { |
| 571 | const item = pending.get(data.id); if (!item) return; |
| 572 | pending.delete(data.id); clearTimeout(item.timer); |
| 573 | data.error ? item.reject(new Error(data.error)) : item.resolve(data.result); |
| 574 | }); |
| 575 | const cage = {postMessage(request) { return new Promise((resolve, reject) => { |
| 576 | const id = crypto.randomUUID(); |
| 577 | // File commands have a 30-minute backend deadline. Leave time for |
| 578 | // the native file dialog and the final subprocess response. |
| 579 | const timer = setTimeout(() => { pending.delete(id); reject(new Error('原生操作超时,请重试')); }, fileActions.has(request.action) ? 3600000 : 240000); |
| 580 | pending.set(id, {resolve, reject, timer}); chrome.webview.postMessage({id, request}); |
| 581 | }); }}; |
| 582 | Object.defineProperty(window, 'webkit', {value: {messageHandlers: {cage}}, writable: false}); |
| 583 | })(); |
| 584 | """; |
| 585 | } |