-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDialogManager.cs
More file actions
455 lines (397 loc) · 13.7 KB
/
Copy pathDialogManager.cs
File metadata and controls
455 lines (397 loc) · 13.7 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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace BootstrapMate
{
/// <summary>
/// csharpdialog integration for user-facing progress UI during enrollment.
/// Gracefully degrades to headless mode if csharpdialog is not available.
/// </summary>
public class DialogManager : IDisposable
{
private static DialogManager? _instance;
private static readonly object _lock = new object();
// csharpdialog paths
private readonly string _dialogPath = @"C:\Program Files\csharpDialog\dialog.exe";
private readonly string _defaultCommandFile;
// State
private Process? _dialogProcess;
private string _commandFilePath;
private bool _isAvailable;
private bool _isRunning;
private int _totalItems;
private int _completedItems;
private bool _disposed;
public static DialogManager Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
_instance ??= new DialogManager();
}
}
return _instance;
}
}
private DialogManager()
{
_defaultCommandFile = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"ManagedBootstrap", "dialog_commands.txt"
);
_commandFilePath = _defaultCommandFile;
_isAvailable = File.Exists(_dialogPath);
if (!_isAvailable)
{
Logger.Debug($"csharpdialog not found at {_dialogPath} - running in headless mode");
}
}
/// <summary>
/// Check if csharpdialog is available
/// </summary>
public bool IsDialogAvailable() => _isAvailable;
/// <summary>
/// Initialize and launch the dialog window
/// </summary>
public void Initialize(
string title,
string message,
int totalPackages,
string? icon = null,
bool fullScreen = false,
bool kioskMode = false)
{
if (!_isAvailable)
{
Logger.Debug("Dialog not available, skipping initialization");
return;
}
// Reset state
_totalItems = totalPackages;
_completedItems = 0;
// Ensure command file directory exists
var commandDir = Path.GetDirectoryName(_commandFilePath);
if (!string.IsNullOrEmpty(commandDir) && !Directory.Exists(commandDir))
{
Directory.CreateDirectory(commandDir);
}
// Clear command file
ClearCommandFile();
// Build dialog arguments as a safe list (avoids quoting/escaping issues)
var argList = new List<string>
{
"--title", title,
"--message", message,
"--progress", "0",
"--progresstext", "Preparing...",
"--commandfile", _commandFilePath,
"--button1", "Please Wait",
};
if (!string.IsNullOrEmpty(icon))
{
argList.Add("--icon");
argList.Add(icon);
}
if (fullScreen)
{
argList.Add("--fullscreen");
}
if (kioskMode)
{
argList.Add("--kiosk");
}
Logger.Info($"Dialog args: {string.Join(" ", argList)}");
// Launch dialog process
LaunchDialog(argList);
}
/// <summary>
/// Add a new list item with initial status
/// </summary>
public void AddListItem(string name, DialogStatus status = DialogStatus.Pending, string statusText = "")
{
var command = BuildListItemCommand("add", name, status, statusText);
WriteCommand(command);
Logger.Debug($"Dialog: Added list item '{name}' with status {status}");
}
/// <summary>
/// Update an existing list item's status
/// </summary>
public void UpdateListItem(string name, DialogStatus status, string statusText = "")
{
var command = BuildListItemCommand("update", name, status, statusText);
WriteCommand(command);
// Track completion for progress
if (status == DialogStatus.Success || status == DialogStatus.Fail)
{
_completedItems++;
var progressPercent = _totalItems > 0 ? (_completedItems * 100) / _totalItems : 0;
UpdateProgress(progressPercent);
}
}
/// <summary>
/// Update the progress bar value (0-100)
/// </summary>
public void UpdateProgress(int percent)
{
WriteCommand($"progress: {Math.Clamp(percent, 0, 100)}");
}
/// <summary>
/// Update the progress bar text
/// </summary>
public void UpdateProgressText(string text)
{
WriteCommand($"progresstext: {text}");
}
/// <summary>
/// Update the dialog title
/// </summary>
public void UpdateTitle(string title)
{
WriteCommand($"title: {title}");
}
/// <summary>
/// Update the dialog message
/// </summary>
public void UpdateMessage(string message)
{
WriteCommand($"message: {message}");
}
/// <summary>
/// Mark progress as complete
/// </summary>
public void Complete(string message = "Setup Complete")
{
UpdateProgressText(message);
WriteCommand("progress: 100");
WriteCommand("button1text: Done");
Logger.Info("Dialog: Marked as complete");
}
/// <summary>
/// Close the dialog window
/// </summary>
public void Close()
{
if (!_isRunning) return;
WriteCommand("quit");
// Give dialog time to close gracefully
System.Threading.Thread.Sleep(500);
TerminateDialog();
}
/// <summary>
/// Force terminate the dialog (for error scenarios)
/// </summary>
public void TerminateDialog()
{
if (!_isRunning || _dialogProcess == null) return;
try
{
if (!_dialogProcess.HasExited)
{
_dialogProcess.Kill();
}
}
catch (Exception ex)
{
Logger.Debug($"Error terminating dialog: {ex.Message}");
}
finally
{
_dialogProcess?.Dispose();
_dialogProcess = null;
_isRunning = false;
Logger.Debug("Dialog process terminated");
}
}
#region Convenience Methods for Package Processing
/// <summary>
/// Helper for package download phase
/// </summary>
public void NotifyDownloadStarted(string packageName)
{
UpdateListItem(packageName, DialogStatus.Wait, "Downloading...");
UpdateProgressText($"Downloading {packageName}...");
}
/// <summary>
/// Helper for package installation phase
/// </summary>
public void NotifyInstallStarted(string packageName)
{
UpdateListItem(packageName, DialogStatus.Wait, "Installing...");
UpdateProgressText($"Installing {packageName}...");
}
/// <summary>
/// Helper for package success
/// </summary>
public void NotifyPackageSuccess(string packageName)
{
UpdateListItem(packageName, DialogStatus.Success, "Installed");
}
/// <summary>
/// Helper for package failure
/// </summary>
public void NotifyPackageFailure(string packageName, string error)
{
UpdateListItem(packageName, DialogStatus.Fail, error);
}
/// <summary>
/// Helper for package skipped
/// </summary>
public void NotifyPackageSkipped(string packageName, string reason = "Already installed")
{
UpdateListItem(packageName, DialogStatus.Success, reason);
}
/// <summary>
/// Helper for phase transition
/// </summary>
public void NotifyPhaseStarted(string phase)
{
UpdateProgressText($"Phase: {phase}");
Logger.WriteSection($"Processing {phase} packages");
}
#endregion
#region Private Methods
private void LaunchDialog(List<string> argList)
{
if (_isRunning)
{
Logger.Warning("Dialog already running, skipping launch");
return;
}
try
{
// UseShellExecute=true launches dialog.exe via the shell at the interactive
// user's token level (not elevated), which is required for WPF transparency/
// fullscreen compositing to work correctly when this process runs elevated.
// Requires Arguments string (ArgumentList is only available with UseShellExecute=false).
var startInfo = new ProcessStartInfo
{
FileName = _dialogPath,
Arguments = BuildArgumentString(argList),
UseShellExecute = true,
CreateNoWindow = false,
};
_dialogProcess = Process.Start(startInfo);
if (_dialogProcess != null)
{
_isRunning = true;
Logger.Info("csharpdialog launched successfully");
}
else
{
Logger.Error("Failed to start csharpdialog process");
}
}
catch (Exception ex)
{
Logger.Error($"Failed to launch csharpdialog: {ex.Message}");
_isRunning = false;
}
}
/// <summary>
/// Converts a list of arguments to a properly quoted Windows command-line string.
/// Each argument containing spaces or quotes is wrapped in double-quotes with
/// internal quotes escaped per Windows command-line conventions.
/// </summary>
private static string BuildArgumentString(List<string> args)
{
var parts = new System.Text.StringBuilder();
foreach (var arg in args)
{
if (parts.Length > 0)
parts.Append(' ');
bool needsQuotes = arg.Contains(' ') || arg.Contains('"') || arg.Length == 0;
if (needsQuotes)
{
parts.Append('"');
// Escape backslashes and quotes per Windows rules
int backslashes = 0;
foreach (char c in arg)
{
if (c == '\\') { backslashes++; }
else if (c == '"') { parts.Append('\\', backslashes + 1); parts.Append('"'); backslashes = 0; }
else { parts.Append('\\', backslashes); parts.Append(c); backslashes = 0; }
}
parts.Append('\\', backslashes);
parts.Append('"');
}
else
{
parts.Append(arg);
}
}
return parts.ToString();
}
private void WriteCommand(string command)
{
if (!_isAvailable || !_isRunning) return;
try
{
// Append command with newline
File.AppendAllText(_commandFilePath, command + Environment.NewLine, Encoding.UTF8);
}
catch (Exception ex)
{
Logger.Debug($"Failed to write dialog command: {ex.Message}");
}
}
private void ClearCommandFile()
{
try
{
File.WriteAllText(_commandFilePath, string.Empty, Encoding.UTF8);
}
catch (Exception ex)
{
Logger.Debug($"Failed to clear command file: {ex.Message}");
}
}
private string BuildListItemCommand(string action, string title, DialogStatus status, string statusText)
{
var command = $"listitem: {action}, title: {title}, status: {status.ToString().ToLowerInvariant()}";
if (!string.IsNullOrEmpty(statusText))
{
command += $", statustext: {statusText}";
}
return command;
}
#endregion
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed) return;
if (disposing)
{
TerminateDialog();
}
_disposed = true;
}
~DialogManager()
{
Dispose(false);
}
#endregion
}
/// <summary>
/// Dialog status indicators matching csharpdialog/SwiftDialog
/// </summary>
public enum DialogStatus
{
None,
Pending,
Wait,
Success,
Fail,
Error,
Progress
}
}