-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
686 lines (597 loc) · 25.8 KB
/
MainWindow.xaml.cs
File metadata and controls
686 lines (597 loc) · 25.8 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using ModernWpf.Controls;
using NodaStack.Pages;
namespace NodaStack
{
public partial class MainWindow : Window
{
// Services
private ProjectManager projectManager;
private ConfigurationManager configManager;
private LogManager logManager;
// System Tray
private System.Windows.Forms.NotifyIcon _notifyIcon;
// Pages
private DashboardPage _dashboardPage;
private MonitoringPage _monitoringPage;
private BackupPage _backupPage;
private SettingsPage _settingsPage;
// État des services (Centralisé ici pour l'instant)
private bool apacheIsRunning = false;
private bool phpIsRunning = false;
private bool mysqlIsRunning = false;
private bool phpmyadminIsRunning = false;
private bool mailhogIsRunning = false;
// Flag to control shutdown vs minimize
private bool _isExiting = false;
public MainWindow()
{
InitializeComponent();
// Init Managers
configManager = new ConfigurationManager();
projectManager = new ProjectManager();
logManager = new LogManager();
// Apply Settings
var config = configManager.GetConfiguration();
// Theme
ThemeManager.Initialize(false);
if (config.Settings.DarkMode)
{
ThemeManager.IsDarkTheme = true;
}
// Projects Path
if (!string.IsNullOrEmpty(config.Settings.ProjectsPath))
{
projectManager.UpdateProjectsPath(config.Settings.ProjectsPath);
}
// Init System Tray
InitializeSystemTray();
// Init Pages
try
{
_dashboardPage = new DashboardPage(projectManager);
_dashboardPage.ServiceToggleRequested += DashboardPage_ServiceToggleRequested;
_monitoringPage = new MonitoringPage();
_backupPage = new BackupPage();
_settingsPage = new SettingsPage();
}
catch (Exception ex)
{
MessageBox.Show($"Error initializing pages: {ex.Message}\n{ex.InnerException?.Message}", "Startup Error");
// Continue or exit? If pages fail, app is broken.
}
// Start Minimized
if (config.Settings.StartMinimized)
{
this.WindowState = WindowState.Minimized;
this.Hide();
}
// Initial Check
CheckInitialContainerStatus();
// Auto Update Check
_ = CheckForUpdatesSilent();
}
private async Task CheckForUpdatesSilent()
{
try
{
var updateManager = new UpdateManager();
var (hasUpdate, info) = await updateManager.CheckForUpdatesAsync();
if (hasUpdate && info != null)
{
var result = MessageBox.Show($"A new version ({info.Version}) of NodaStack is available.\nInstall it now?",
"Update Available",
MessageBoxButton.YesNo,
MessageBoxImage.Information);
if (result == MessageBoxResult.Yes)
{
// Select Settings in NavView
NavView.SelectedItem = NavView.SettingsItem;
ContentFrame.Navigate(_settingsPage);
// Wait a bit for UI to load then trigger
await Task.Delay(500);
_settingsPage.StartAutoUpdate();
}
}
}
catch { /* Silent fail */ }
}
private void InitializeSystemTray()
{
_notifyIcon = new System.Windows.Forms.NotifyIcon();
try
{
// Load icon using absolute path from BaseDirectory to support installed version
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string iconPath = Path.Combine(baseDir, "Assets", "NodaStackLogo.ico");
if (File.Exists(iconPath))
{
_notifyIcon.Icon = new System.Drawing.Icon(iconPath);
}
else if (File.Exists("Assets/NodaStackLogo.ico")) // Fallback for dev
{
_notifyIcon.Icon = new System.Drawing.Icon("Assets/NodaStackLogo.ico");
}
else
{
// Ultimate fallback: Use the application's own executable icon
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
if (!string.IsNullOrEmpty(exePath))
{
_notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(exePath);
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Failed to load tray icon: " + ex.Message);
}
if (_notifyIcon.Icon != null)
{
_notifyIcon.Visible = true;
}
_notifyIcon.Text = "NodaStack - Local Server Environment";
_notifyIcon.DoubleClick += (s, args) =>
{
Show();
WindowState = WindowState.Normal;
Activate();
};
var contextMenu = new System.Windows.Forms.ContextMenuStrip();
contextMenu.Items.Add("Open Dashboard", null, (s, e) => { Show(); WindowState = WindowState.Normal; Activate(); });
contextMenu.Items.Add("-");
contextMenu.Items.Add("Exit NodaStack", null, (s, e) => { CleanupAndExit(); });
_notifyIcon.ContextMenuStrip = contextMenu;
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
Hide();
}
base.OnStateChanged(e);
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
// Only minimize if option is enabled AND the tray icon is actually working/visible
if (!_isExiting && configManager.GetConfiguration().Settings.MinimizeToTray && _notifyIcon.Visible)
{
e.Cancel = true;
this.Hide();
// Show a notification balloon tip to inform user
if (configManager.GetConfiguration().Settings.ShowTrayNotifications)
{
_notifyIcon.ShowBalloonTip(3000, "NodaStack Minimized", "NodaStack is running in the background.", System.Windows.Forms.ToolTipIcon.Info);
}
}
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
base.OnClosed(e);
Application.Current.Shutdown();
}
private void CleanupAndExit()
{
_isExiting = true;
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
Application.Current.Shutdown();
}
private void NavView_Loaded(object sender, RoutedEventArgs e)
{
NavView.SelectedItem = NavView.MenuItems[0];
}
private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.IsSettingsSelected)
{
ContentFrame.Navigate(_settingsPage);
}
else if (args.SelectedItem is NavigationViewItem item)
{
switch (item.Tag.ToString())
{
case "dashboard":
ContentFrame.Navigate(_dashboardPage);
UpdateDashboardState(); // Refresh UI
break;
case "monitoring":
ContentFrame.Navigate(_monitoringPage);
break;
case "backups":
ContentFrame.Navigate(_backupPage);
break;
}
}
}
private async void DashboardPage_ServiceToggleRequested(object? sender, string service)
{
switch (service)
{
case "apache": await ToggleApache(); break;
case "php": await TogglePhp(); break;
case "mysql": await ToggleMysql(); break;
case "phpmyadmin": await TogglePma(); break;
case "mailhog": await ToggleMailHog(); break;
}
}
private void UpdateDashboardState()
{
_dashboardPage.UpdateServiceStatus("apache", apacheIsRunning);
_dashboardPage.UpdateServiceStatus("php", phpIsRunning);
_dashboardPage.UpdateServiceStatus("mysql", mysqlIsRunning);
_dashboardPage.UpdateServiceStatus("phpmyadmin", phpmyadminIsRunning);
_dashboardPage.UpdateServiceStatus("mailhog", mailhogIsRunning);
}
private async Task StopContainer(string containerName)
{
await RunProcessAsync($"docker stop {containerName}");
await RunProcessAsync($"docker rm -f {containerName}");
}
private async Task ToggleApache()
{
var config = configManager.GetConfiguration();
if (!apacheIsRunning)
{
var absoluteProjectsPath = Path.GetFullPath(projectManager.ProjectsPath);
await StopContainer("nodastack_apache"); // Nettoyage préventif
bool success = await RunProcessAsync($"docker run -d --restart=unless-stopped -p {config.ApachePort}:80 -v \"{absoluteProjectsPath}:/var/www/html\" --name nodastack_apache nodastack_apache");
if (success)
{
await Task.Delay(1000);
if (await IsContainerRunning("nodastack_apache"))
{
apacheIsRunning = true;
}
else
{
apacheIsRunning = false;
string logs = await GetProcessOutputAsync("docker logs --tail 5 nodastack_apache");
MessageBox.Show($"Apache failed to start. Logs:\n{logs}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Failed to execute start command for Apache.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
await StopContainer("nodastack_apache");
apacheIsRunning = false;
}
UpdateDashboardState();
}
private async Task TogglePhp()
{
var config = configManager.GetConfiguration();
if (!phpIsRunning)
{
var absoluteProjectsPath = Path.GetFullPath(projectManager.ProjectsPath);
await StopContainer("nodastack_php");
bool success = await RunProcessAsync($"docker run -d --restart=unless-stopped -p {config.PhpPort}:8000 -v \"{absoluteProjectsPath}:/var/www/html\" --name nodastack_php nodastack_php");
if (success)
{
await Task.Delay(1000);
if (await IsContainerRunning("nodastack_php"))
{
phpIsRunning = true;
}
else
{
phpIsRunning = false;
string logs = await GetProcessOutputAsync("docker logs --tail 5 nodastack_php");
MessageBox.Show($"PHP failed to start. Logs:\n{logs}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Failed to execute start command for PHP.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
await StopContainer("nodastack_php");
phpIsRunning = false;
}
UpdateDashboardState();
}
private async Task ToggleMysql()
{
var config = configManager.GetConfiguration();
if (!mysqlIsRunning)
{
await StopContainer("nodastack_mysql");
bool success = await RunProcessAsync($"docker run -d --restart=unless-stopped -p {config.MySqlPort}:3306 -e MYSQL_ROOT_PASSWORD=root --name nodastack_mysql nodastack_mysql");
if (success)
{
await Task.Delay(2000);
if (await IsContainerRunning("nodastack_mysql"))
{
mysqlIsRunning = true;
}
else
{
mysqlIsRunning = false;
string logs = await GetProcessOutputAsync("docker logs --tail 5 nodastack_mysql");
MessageBox.Show($"MySQL failed to start. Logs:\n{logs}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Failed to execute start command for MySQL.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
await StopContainer("nodastack_mysql");
mysqlIsRunning = false;
}
UpdateDashboardState();
}
private async Task TogglePma()
{
var config = configManager.GetConfiguration();
if (!phpmyadminIsRunning)
{
await StopContainer("nodastack_phpmyadmin");
bool success = await RunProcessAsync($"docker run -d --restart=unless-stopped -p {config.PhpMyAdminPort}:80 --name nodastack_phpmyadmin --link nodastack_mysql -e PMA_HOST=nodastack_mysql nodastack_phpmyadmin");
if (success)
{
await Task.Delay(1000);
if (await IsContainerRunning("nodastack_phpmyadmin"))
{
phpmyadminIsRunning = true;
}
else
{
phpmyadminIsRunning = false;
string logs = await GetProcessOutputAsync("docker logs --tail 5 nodastack_phpmyadmin");
MessageBox.Show($"phpMyAdmin failed to start. Logs:\n{logs}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Failed to execute start command for phpMyAdmin.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
await StopContainer("nodastack_phpmyadmin");
phpmyadminIsRunning = false;
}
UpdateDashboardState();
}
private async Task ToggleMailHog()
{
var config = configManager.GetConfiguration();
if (!mailhogIsRunning)
{
await StopContainer("nodastack_mailhog");
// MailHog uses ports 1025 (SMTP) and 8025 (Web UI)
bool success = await RunProcessAsync($"docker run -d --restart=unless-stopped -p {config.MailHogSmtpPort}:1025 -p {config.MailHogWebPort}:8025 --name nodastack_mailhog mailhog/mailhog");
if (success)
{
await Task.Delay(1000);
if (await IsContainerRunning("nodastack_mailhog"))
{
mailhogIsRunning = true;
}
else
{
mailhogIsRunning = false;
string logs = await GetProcessOutputAsync("docker logs --tail 5 nodastack_mailhog");
MessageBox.Show($"MailHog failed to start. Logs:\n{logs}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Failed to execute start command for MailHog. Ensure you have internet connection to pull 'mailhog/mailhog' image.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
await StopContainer("nodastack_mailhog");
mailhogIsRunning = false;
}
UpdateDashboardState();
}
private async Task<bool> RunProcessAsync(string command)
{
return await Task.Run(async () =>
{
try
{
var psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C {command}",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var p = new Process())
{
p.StartInfo = psi;
p.Start();
if (p.StandardOutput == null || p.StandardError == null)
{
p.WaitForExit();
return p.ExitCode == 0;
}
var stdoutTask = p.StandardOutput.ReadToEndAsync();
var stderrTask = p.StandardError.ReadToEndAsync();
await Task.WhenAll(stdoutTask, stderrTask);
p.WaitForExit();
if (p.ExitCode != 0)
{
string error = await stderrTask;
Debug.WriteLine($"Command failed: {command}. Error: {error}");
return false;
}
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return false;
}
});
}
public async Task BuildDockerImages(IProgress<string> progress = null)
{
// Determine root path (where Docker folder is)
string appDir = AppDomain.CurrentDomain.BaseDirectory;
string projectRoot = Path.GetFullPath(Path.Combine(appDir, "..", "..", "..", "..")); // Adjust based on build depth
// If not found, try current dir (portable mode)
if (!Directory.Exists(Path.Combine(projectRoot, "Docker")))
{
projectRoot = Directory.GetCurrentDirectory();
}
if (!Directory.Exists(Path.Combine(projectRoot, "Docker")))
{
MessageBox.Show($"Docker folder not found in {projectRoot}", "Error");
return;
}
try
{
progress?.Report("Building Apache image...");
if (!await RunProcessAsync($"docker build -t nodastack_apache \"{Path.Combine(projectRoot, "Docker", "apache")}\""))
throw new Exception("Failed to build Apache image");
progress?.Report("Building PHP image...");
if (!await RunProcessAsync($"docker build -t nodastack_php \"{Path.Combine(projectRoot, "Docker", "php")}\""))
throw new Exception("Failed to build PHP image");
progress?.Report("Building MySQL image...");
if (!await RunProcessAsync($"docker build -t nodastack_mysql \"{Path.Combine(projectRoot, "Docker", "mysql")}\""))
throw new Exception("Failed to build MySQL image");
progress?.Report("Building phpMyAdmin image...");
if (!await RunProcessAsync($"docker build -t nodastack_phpmyadmin \"{Path.Combine(projectRoot, "Docker", "phpmyadmin")}\""))
throw new Exception("Failed to build phpMyAdmin image");
if (Directory.Exists(Path.Combine(projectRoot, "Docker", "mailhog")))
{
progress?.Report("Building MailHog image...");
if (!await RunProcessAsync($"docker build -t nodastack_mailhog \"{Path.Combine(projectRoot, "Docker", "mailhog")}\""))
throw new Exception("Failed to build MailHog image");
}
progress?.Report("All images built successfully!");
}
catch (Exception ex)
{
progress?.Report($"Error: {ex.Message}");
throw; // Re-throw to be caught by caller if needed
}
}
private async void CheckInitialContainerStatus()
{
try
{
// Check Apache
if (await IsContainerRunning("nodastack_apache")) apacheIsRunning = true;
// Check PHP
if (await IsContainerRunning("nodastack_php")) phpIsRunning = true;
// Check MySQL
if (await IsContainerRunning("nodastack_mysql")) mysqlIsRunning = true;
// Check PMA
if (await IsContainerRunning("nodastack_phpmyadmin")) phpmyadminIsRunning = true;
// Check MailHog
if (await IsContainerRunning("nodastack_mailhog")) mailhogIsRunning = true;
}
catch (Exception ex)
{
Debug.WriteLine("Error checking container status: " + ex.Message);
}
UpdateDashboardState();
}
private async Task<bool> IsContainerRunning(string containerName)
{
// Use 'docker ps' filtering by name to see if it's running
// output will be the container name if running, empty otherwise
string output = await GetProcessOutputAsync($"docker ps -q -f name={containerName}");
return !string.IsNullOrWhiteSpace(output);
}
private async Task<string> GetProcessOutputAsync(string command)
{
return await Task.Run(async () =>
{
try
{
var psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/C {command}",
RedirectStandardOutput = true,
RedirectStandardError = true, // Redirect error too to avoid popping up
UseShellExecute = false,
CreateNoWindow = true
};
using (var p = new Process())
{
p.StartInfo = psi;
p.Start();
var stdoutTask = p.StandardOutput.ReadToEndAsync();
var stderrTask = p.StandardError.ReadToEndAsync();
await Task.WhenAll(stdoutTask, stderrTask);
p.WaitForExit();
return (await stdoutTask).Trim();
}
}
catch { return ""; }
});
}
public void CheckForUpdatesManually(object sender, RoutedEventArgs e)
{
MessageBox.Show("Update check stub.", "Info");
}
public async Task DownloadAndInstallUpdate()
{
await Task.Delay(100);
MessageBox.Show("Update install stub.", "Info");
}
private void OpenConfiguration()
{
var configWindow = new ConfigurationWindow(configManager);
configWindow.Owner = this;
configWindow.ShowDialog();
}
private void OpenMonitoring()
{
var monitoringWindow = new MonitoringWindow();
monitoringWindow.Owner = this;
monitoringWindow.Show();
}
private void OpenBackups()
{
var backupWindow = new BackupWindow();
backupWindow.Owner = this;
backupWindow.ShowDialog();
}
public void ReloadConfiguration()
{
configManager.LoadConfiguration();
var config = configManager.GetConfiguration();
// Update Project Manager path
projectManager.UpdateProjectsPath(config.Settings.ProjectsPath);
// Refresh Dashboard Project List
_dashboardPage.RefreshProjects_Click(null, null);
}
public void CreateProject_Click(object sender, RoutedEventArgs e)
{
projectManager.CreateProject("NewProject_" + DateTime.Now.Ticks);
}
public void ViewApache_Direct(ProjectInfo project)
{
var config = configManager.GetConfiguration();
try { Process.Start(new ProcessStartInfo($"http://localhost:{config.ApachePort}/{project.Name}") { UseShellExecute = true }); } catch { }
}
}
}