-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
364 lines (330 loc) · 13.4 KB
/
MainForm.cs
File metadata and controls
364 lines (330 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Windows.Forms;
using CUIckScan.Services;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
namespace CUIckScan;
public sealed class MainForm : Form
{
private const int GripSize = 6;
private readonly WebView2 _webView;
private bool _isMaximized;
private bool _navigateStarted;
private Rectangle _restoreBounds;
private volatile bool _closeApprovedByReact;
/// <summary>Set by Program.cs after construction so the form can prompt save-on-close.</summary>
public ScanApiHost? ApiHost { get; set; }
public MainForm()
{
Text = "CUIck Scan";
FormBorderStyle = FormBorderStyle.None;
StartPosition = FormStartPosition.CenterScreen;
MinimumSize = new Size(960, 600);
Size = new Size(1280, 800);
BackColor = Color.FromArgb(19, 20, 26);
DoubleBuffered = true;
LoadAppIcon();
// Padding creates a thin border around WebView2 that the form owns,
// so WndProc can handle WM_NCHITTEST for resize grips on the edges.
Padding = new Padding(GripSize);
_webView = new WebView2
{
Dock = DockStyle.Fill,
DefaultBackgroundColor = Color.FromArgb(19, 20, 26),
};
Controls.Add(_webView);
}
public async void NavigateTo(string url)
{
if (_navigateStarted) return;
_navigateStarted = true;
CrashLog.Debug($"NavigateTo called with url={url}");
try
{
var udFolder = Path.Combine(Path.GetTempPath(), "CUIckScan_WebView2");
CrashLog.Debug($"WebView2 userDataFolder={udFolder}");
var env = await CoreWebView2Environment.CreateAsync(
userDataFolder: udFolder);
CrashLog.Debug("CoreWebView2Environment created — calling EnsureCoreWebView2Async...");
await _webView.EnsureCoreWebView2Async(env);
CrashLog.Debug($"CoreWebView2 initialized — BrowserVersion={_webView.CoreWebView2.Environment.BrowserVersionString}");
#if !DEBUG
// In release builds, enable devtools only when --debug flag is passed
_webView.CoreWebView2.Settings.AreDevToolsEnabled = CrashLog.DebugMode;
#endif
_webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false;
_webView.CoreWebView2.Settings.IsStatusBarEnabled = false;
_webView.CoreWebView2.Settings.IsZoomControlEnabled = false;
// Debug: track navigation lifecycle
_webView.CoreWebView2.NavigationStarting += (s, e) =>
{
CrashLog.Debug($"WebView2 NavigationStarting: Uri={e.Uri}");
// Allowlist: only permit http/https to 127.0.0.1 or localhost
if (!Uri.TryCreate(e.Uri, UriKind.Absolute, out var uri)
|| (uri.Scheme != "http" && uri.Scheme != "https")
|| (uri.Host != "127.0.0.1" && uri.Host != "localhost"))
{
e.Cancel = true;
CrashLog.Warn($"Blocked navigation to: {e.Uri}");
}
};
_webView.CoreWebView2.NavigationCompleted += (s, e) =>
CrashLog.Debug($"WebView2 NavigationCompleted: IsSuccess={e.IsSuccess}, HttpStatusCode={e.HttpStatusCode}, WebErrorStatus={e.WebErrorStatus}");
_webView.CoreWebView2.DOMContentLoaded += (s, e) =>
CrashLog.Debug($"WebView2 DOMContentLoaded: NavigationId={e.NavigationId}");
_webView.CoreWebView2.ContentLoading += (s, e) =>
CrashLog.Debug($"WebView2 ContentLoading: NavigationId={e.NavigationId}, IsErrorPage={e.IsErrorPage}");
_webView.CoreWebView2.ProcessFailed += (s, e) =>
CrashLog.Error($"WebView2 ProcessFailed: Kind={e.ProcessFailedKind}, Reason={e.Reason}");
// Block all new window requests (defense-in-depth against window.open)
_webView.CoreWebView2.NewWindowRequested += (s, e) =>
{
e.Handled = true;
CrashLog.Warn($"Blocked new window request: {e.Uri}");
};
_webView.CoreWebView2.WebMessageReceived += OnWebMessageReceived;
CrashLog.Debug($"Navigating WebView2 to {url}");
_webView.CoreWebView2.Navigate(url);
}
catch (Exception ex)
{
CrashLog.Error("WebView2 initialization failed", ex);
MessageBox.Show(
"WebView2 failed to initialize. The application will try to start in fallback mode.\n\n" +
"If this persists, try deleting the CUIckScan_WebView2 folder in your temp directory.",
"CUIckScan — Initialization Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// --- Load application icon for title bar and taskbar ---
private void LoadAppIcon()
{
var candidates = new[]
{
Path.Combine(AppContext.BaseDirectory, "Resources", "app.ico"),
Path.Combine(AppContext.BaseDirectory, "app.ico"),
Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "Resources", "app.ico"),
};
foreach (var path in candidates)
{
if (!File.Exists(path)) continue;
try
{
var oldIcon = Icon;
Icon = new Icon(path);
oldIcon?.Dispose(); // M13: Dispose previous icon to prevent GDI handle leak
return;
}
catch (Exception ex) { CrashLog.Debug($"Failed to load icon from {path}: {ex.Message}"); }
}
}
// --- Native dialog helpers (called from API threads) ---
public string? ShowFolderDialog(string? description = null, string? initialPath = null)
{
string? result = null;
Invoke(() =>
{
using var dialog = new FolderBrowserDialog
{
Description = description ?? "Select folder",
UseDescriptionForTitle = true,
ShowNewFolderButton = true,
};
if (!string.IsNullOrEmpty(initialPath) && Directory.Exists(initialPath))
dialog.InitialDirectory = initialPath;
if (dialog.ShowDialog(this) == DialogResult.OK)
result = dialog.SelectedPath;
});
return result;
}
public string? ShowOpenFileDialog(string? title = null, string? filter = null, string? initialDir = null)
{
string? result = null;
Invoke(() =>
{
using var dialog = new OpenFileDialog
{
Title = title ?? "Open file",
Filter = filter ?? "All files (*.*)|*.*",
RestoreDirectory = true,
};
if (!string.IsNullOrEmpty(initialDir) && Directory.Exists(initialDir))
dialog.InitialDirectory = initialDir;
if (dialog.ShowDialog(this) == DialogResult.OK)
result = dialog.FileName;
});
return result;
}
public string? ShowSaveFileDialog(string? title = null, string? filter = null, string? defaultName = null, string? initialDir = null)
{
string? result = null;
Invoke(() =>
{
using var dialog = new SaveFileDialog
{
Title = title ?? "Save file",
Filter = filter ?? "CSV files (*.csv)|*.csv|All files (*.*)|*.*",
RestoreDirectory = true,
};
if (!string.IsNullOrEmpty(defaultName))
dialog.FileName = defaultName;
if (!string.IsNullOrEmpty(initialDir) && Directory.Exists(initialDir))
dialog.InitialDirectory = initialDir;
if (dialog.ShowDialog(this) == DialogResult.OK)
result = dialog.FileName;
});
return result;
}
// --- Close handler: prompt to save scan database ---
protected override void OnFormClosing(FormClosingEventArgs e)
{
// If React already handled the close prompt, skip the native dialog
if (_closeApprovedByReact)
{
base.OnFormClosing(e);
return;
}
// Fallback for Alt+F4, taskbar close, Windows shutdown — use native prompt
if (ApiHost != null && !ApiHost.PromptSaveOnClose())
{
e.Cancel = true;
return;
}
base.OnFormClosing(e);
}
// --- WebView2 message handler ---
private void OnWebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
try
{
var json = e.WebMessageAsJson;
using var doc = JsonDocument.Parse(json);
var action = doc.RootElement.GetProperty("action").GetString();
switch (action)
{
case "minimize":
Invoke(() => WindowState = FormWindowState.Minimized);
break;
case "maximize":
Invoke(ToggleMaximize);
break;
case "close":
Invoke(Close);
break;
case "forceClose":
Invoke(() =>
{
_closeApprovedByReact = true;
Close();
});
break;
case "switchToFallback":
Invoke(() =>
{
var exePath = Environment.ProcessPath;
if (exePath != null)
{
CrashLog.Log("Debug: switching to FallbackForm UI...");
Process.Start(exePath, "--debug --fallback");
}
_closeApprovedByReact = true;
Close();
});
break;
case "drag":
Invoke(() =>
{
ReleaseCapture();
SendMessage(Handle, 0x00A1, 0x0002, 0);
});
break;
case "titlebar-dblclick":
Invoke(ToggleMaximize);
break;
}
}
catch (Exception ex) { CrashLog.Debug($"WebMessage handling error: {ex.GetType().Name}: {ex.Message}"); }
}
private void ToggleMaximize()
{
if (_isMaximized)
{
Padding = new Padding(GripSize);
Bounds = _restoreBounds;
_isMaximized = false;
}
else
{
_restoreBounds = Bounds;
Padding = new Padding(0); // no grip when maximized
Bounds = Screen.FromControl(this).WorkingArea;
_isMaximized = true;
}
NotifyWindowState();
}
/// <summary>Update the window title (taskbar) and notify the React titlebar.</summary>
public void SetTitleText(string? openedDbName)
{
var title = string.IsNullOrEmpty(openedDbName)
? "CUIck Scan"
: $"CUIck Scan \u2014 {openedDbName}";
try
{
Invoke(() =>
{
Text = title;
try
{
_webView.CoreWebView2?.PostWebMessageAsJson(
JsonSerializer.Serialize(new { type = "titleUpdate", openedDbName = openedDbName ?? "" }));
}
catch { }
});
}
catch { }
}
private void NotifyWindowState()
{
try
{
var state = _isMaximized ? "maximized" : "normal";
_webView.CoreWebView2?.PostWebMessageAsJson(
$"{{\"type\":\"windowState\",\"state\":\"{state}\"}}");
}
catch { }
}
// --- WM_NCHITTEST: resize grips on the padding area ---
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0084 && !_isMaximized) // WM_NCHITTEST
{
// Use nint to avoid OverflowException on 64-bit multi-monitor setups
var lp = (nint)m.LParam;
var screenPt = new Point(unchecked((short)(lp & 0xFFFF)), unchecked((short)((lp >> 16) & 0xFFFF)));
var pt = PointToClient(screenPt);
var w = ClientSize.Width;
var h = ClientSize.Height;
if (pt.Y < GripSize)
{
if (pt.X < GripSize) { m.Result = (IntPtr)13; return; } // HTTOPLEFT
if (pt.X >= w - GripSize) { m.Result = (IntPtr)14; return; } // HTTOPRIGHT
m.Result = (IntPtr)12; return; // HTTOP
}
if (pt.Y >= h - GripSize)
{
if (pt.X < GripSize) { m.Result = (IntPtr)16; return; } // HTBOTTOMLEFT
if (pt.X >= w - GripSize) { m.Result = (IntPtr)17; return; } // HTBOTTOMRIGHT
m.Result = (IntPtr)15; return; // HTBOTTOM
}
if (pt.X < GripSize) { m.Result = (IntPtr)10; return; } // HTLEFT
if (pt.X >= w - GripSize) { m.Result = (IntPtr)11; return; } // HTRIGHT
}
base.WndProc(ref m);
}
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[DllImport("user32.dll")]
private static extern nint SendMessage(IntPtr hWnd, int msg, nint wParam, nint lParam);
}