-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
488 lines (388 loc) · 13.1 KB
/
Copy pathProgram.cs
File metadata and controls
488 lines (388 loc) · 13.1 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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
using MiniLaunch; // Help
using MiniLaunch.Profiles;
using MiniLaunch.UI;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using MiniLaunch.Core;
internal static class Program
{
[STAThread]
private static void Main()
{
const string mutexName = "MiniLaunch_SingleInstance";
bool createdNew;
using var mutex = new Mutex(false, mutexName, out createdNew);
if (!createdNew)
{
MessageBox.Show(
"MiniLaunch is already running.\n\nUse the tray icon to access it.",
"MiniLaunch",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += (sender, args) =>
{
HandleException(args.Exception);
};
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
if (args.ExceptionObject is Exception ex)
{
HandleException(ex);
}
};
try
{
SetupLogging();
ApplicationConfiguration.Initialize();
var modules = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t =>
typeof(IAppModule).IsAssignableFrom(t) &&
!t.IsAbstract && // 🔥 FIX
!t.IsInterface && // 🔥 SAFETY
t.GetConstructor(Type.EmptyTypes) != null // 🔥 SAFETY
)
.Select(t => (IAppModule)Activator.CreateInstance(t)!)
.ToList();
// 🔥 ADD THIS BLOCK
foreach (var module in modules)
{
Log.WriteCategory("INIT", $"loaded module | {module.Type}");
}
Log.WriteCategory("INIT", $"total modules | {modules.Count}");
var profileService = new ProfileService(modules);
ProfilePaths.Ensure();
Application.Run(new MiniLaunchContext(profileService));
}
catch (Exception ex)
{
HandleException(ex);
}
}
// ---------------- SETUP LOG FILE ----------------
private static void SetupLogging()
{
try
{
string folder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MiniLaunch");
Directory.CreateDirectory(folder);
string logFile = Path.Combine(folder, "debug.log");
string prevFile = Path.Combine(folder, "debug.prev.log");
const long maxSize = 1_048_576; // 1 MB
if (File.Exists(logFile))
{
var info = new FileInfo(logFile);
if (info.Length > maxSize)
{
if (File.Exists(prevFile))
File.Delete(prevFile);
File.Move(logFile, prevFile);
}
}
// ✅ ONLY write a simple startup marker
Log.Write("========================================");
Log.Write($"MiniLaunch START {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
Log.Write("========================================");
}
catch
{
// never crash
}
}
private static void HandleException(Exception ex)
{
try
{
string folder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MiniLaunch");
Directory.CreateDirectory(folder);
string file = Path.Combine(folder, "crash.log");
string message =
$"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}]\n" +
$"Type: {ex.GetType().FullName}\n" +
$"Message: {ex.Message}\n" +
$"Stack:\n{ex.StackTrace}\n\n";
File.AppendAllText(file, message);
MessageBox.Show(
"MiniLaunch encountered an unexpected error and needs to close.\n\n" +
"A crash log has been saved to:\n\n" +
file,
"MiniLaunch Error",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch { }
}
}
// ---------------- CONTEXT ----------------
public class MiniLaunchContext : ApplicationContext
{
private readonly NotifyIcon _tray;
private readonly ProfileService _profileService;
private readonly FileSystemWatcher _watcher;
private static string AppDataDir =>
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"MiniLaunch");
private static string DefaultProfilePath =>
Path.Combine(AppDataDir, "default_profile.txt");
private static string SuppressFlagPath =>
Path.Combine(Path.GetTempPath(), "MiniLaunch_suppress_startup.flag");
public MiniLaunchContext(ProfileService profileService)
{
_profileService = profileService;
_tray = new NotifyIcon
{
Icon = AppIcons.App,
ContextMenuStrip = BuildMenu(),
Visible = true,
Text = "MiniLaunch"
};
if (File.Exists(SuppressFlagPath))
File.Delete(SuppressFlagPath);
else
ShowStartupNotification();
_tray.DoubleClick += (_, _) => RunDefaultProfile();
_tray.MouseUp += (_, e) =>
{
if (e.Button == MouseButtons.Right)
RefreshMenu();
};
Microsoft.Win32.SystemEvents.SessionSwitch += OnSessionSwitch;
Microsoft.Win32.SystemEvents.SessionEnding += OnSessionEnding;
_watcher = new FileSystemWatcher(ProfilePaths.ProfilesDir, "*.json")
{
NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite
};
_watcher.Created += OnProfilesChanged;
_watcher.Deleted += OnProfilesChanged;
_watcher.Renamed += OnProfilesChanged;
_watcher.Changed += OnProfilesChanged;
_watcher.EnableRaisingEvents = true;
}
private void RunDefaultProfile()
{
var profiles = _profileService.GetProfileNames();
if (profiles.Count == 0)
return;
Directory.CreateDirectory(AppDataDir);
if (File.Exists(DefaultProfilePath))
{
var name = File.ReadAllText(DefaultProfilePath);
if (profiles.Contains(name))
{
Run(name);
return;
}
}
var newDefault = profiles[0];
File.WriteAllText(DefaultProfilePath, newDefault);
Run(newDefault);
}
private void ShowStartupNotification()
{
_tray.ShowBalloonTip(
3000,
"MiniLaunch is running",
"Use the tray menu to capture or run profiles.",
ToolTipIcon.Info);
}
private void OnSessionSwitch(object? sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == Microsoft.Win32.SessionSwitchReason.SessionUnlock)
RecreateTrayIcon();
}
private void OnSessionEnding(object? sender, Microsoft.Win32.SessionEndingEventArgs e)
{
_tray.Visible = false;
}
private void RecreateTrayIcon()
{
try
{
_tray.Visible = false;
var timer = new System.Windows.Forms.Timer { Interval = 50 };
timer.Tick += (_, _) =>
{
timer.Stop();
timer.Dispose();
_tray.Icon = AppIcons.App;
_tray.Visible = true;
};
timer.Start();
}
catch { }
}
private void OnProfilesChanged(object sender, FileSystemEventArgs e)
{
try
{
_tray?.GetType()
.GetMethod("BeginInvoke", BindingFlags.Instance | BindingFlags.NonPublic)
?.Invoke(_tray, new object[] { new Action(RefreshMenu) });
}
catch
{
RefreshMenu();
}
}
private ContextMenuStrip BuildMenu()
{
var builder = new TrayMenuBuilder(
_profileService,
Capture,
Run,
RenameProfile,
DeleteProfile,
_profileService.EditProfile,
ShowAbout,
ShowHelp,
Exit
);
return builder.Build();
}
private void Capture()
{
using (var form = new CaptureProfileForm())
{
if (form.ShowDialog() != DialogResult.OK)
return;
var name = form.ProfileName;
var existing = _profileService.GetProfileNames();
if (existing.Any(p => string.Equals(p, name, StringComparison.OrdinalIgnoreCase)))
{
var result = MessageBox.Show(
$"A profile named '{name}' already exists.\n\nDo you want to overwrite it?",
"Confirm Overwrite",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
return;
}
// 🔥 ONLY debug needed here
WindowHelpers.DebugForegroundWindow();
// ✅ Use central capture pipeline
var profile = _profileService.CaptureProfile();
_profileService.SaveProfile(profile, name);
Directory.CreateDirectory(AppDataDir);
if (!File.Exists(DefaultProfilePath))
File.WriteAllText(DefaultProfilePath, name);
RefreshMenu();
MessageBox.Show(
$"Profile '{name}' captured.",
"MiniLaunch",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void Run(string name)
{
try
{
var profile = _profileService.LoadProfile(name);
_profileService.RunProfile(profile);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "MiniLaunch Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RenameProfile(string oldName)
{
var newName = Prompt.Show($"Rename profile '{oldName}' to:", "Rename Profile");
if (string.IsNullOrWhiteSpace(newName) || newName == oldName)
return;
var existing = _profileService.GetProfileNames();
var match = existing.FirstOrDefault(p =>
string.Equals(p, newName, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
var result = MessageBox.Show(
$"A profile named '{newName}' already exists.\n\nDo you want to overwrite it?",
"Confirm Overwrite",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
return;
_profileService.DeleteProfile(match);
}
try
{
_profileService.RenameProfile(oldName, newName);
if (File.Exists(DefaultProfilePath))
{
var current = File.ReadAllText(DefaultProfilePath);
if (string.Equals(current, oldName, StringComparison.OrdinalIgnoreCase))
File.WriteAllText(DefaultProfilePath, newName);
}
RefreshMenu();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "MiniLaunch Error");
}
}
private void DeleteProfile(string name)
{
var result = MessageBox.Show(
$"Delete profile '{name}'?",
"Confirm Delete",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning);
if (result != DialogResult.Yes)
return;
try
{
_profileService.DeleteProfile(name);
if (File.Exists(DefaultProfilePath))
{
var current = File.ReadAllText(DefaultProfilePath);
if (current == name)
File.Delete(DefaultProfilePath);
}
RefreshMenu();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "MiniLaunch Error");
}
}
private void ShowAbout()
{
new AboutForm().ShowDialog();
}
private string GetSupportedAppsText()
{
var apps = _profileService.GetSupportedAppNames();
return "Supported Applications:\n- " + string.Join("\n- ", apps);
}
// 🔥 UPDATED HELP METHOD
private void ShowHelp()
{
var supportedApps = GetSupportedAppsText();
var text = HelpContent.Get(supportedApps);
new HelpForm(text).ShowDialog();
}
private void Exit()
{
Microsoft.Win32.SystemEvents.SessionSwitch -= OnSessionSwitch;
Microsoft.Win32.SystemEvents.SessionEnding -= OnSessionEnding;
_watcher.Dispose();
_tray.Visible = false;
_tray.Dispose();
Application.Exit();
}
private void RefreshMenu()
{
_tray.ContextMenuStrip = BuildMenu();
}
}