-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
1300 lines (1120 loc) · 51 KB
/
MainWindow.xaml.cs
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using GongSolutions.Wpf.DragDrop;
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using Serilog;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
namespace Elite_Dangerous_Addon_Launcher_V2
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
#region Private Fields
public List<string> processList = new List<string>();
private string _applicationVersion;
private bool _isChecking = false;
private string _appVersion;
private bool _isLoading = true;
// The row that will be dragged.
private DataGridRow _rowToDrag;
private string logpath;
// Store the position where the mouse button is clicked.
private Point _startPoint;
private bool isDarkTheme = false;
private SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
private Settings settings;
#endregion Private Fields
#region Public Properties
public string ApplicationVersion
{
get { return _appVersion; }
set
{
if (_appVersion != value)
{
_appVersion = value;
OnPropertyChanged(nameof(ApplicationVersion));
}
}
}
#endregion Public Properties
#region Public Constructors
public MainWindow(string profileName = null)
{
InitializeComponent();
LoggingConfig.Configure();
if (!string.IsNullOrEmpty(profileName))
{
// Use the profileName to load the appropriate profile
//LoadProfile(profileName);
}
// Copy user settings from previous application version if necessary
if (Properties.Settings.Default.UpdateSettings)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpdateSettings = false;
Properties.Settings.Default.Save();
}
this.SizeToContent = SizeToContent.Manual;
this.Width = Properties.Settings.Default.MainWindowSize.Width;
this.Height = Properties.Settings.Default.MainWindowSize.Height;
this.Top = Properties.Settings.Default.MainWindowLocation.Y;
this.Left = Properties.Settings.Default.MainWindowLocation.X;
// Assign the event handler to the Loaded event
this.Loaded += MainWindow_Loaded;
var version = Assembly.GetExecutingAssembly().GetName().Version;
ApplicationVersion = $"{version.Major}.{version.Minor}.{version.Build}"; // format as desired
// Set the data context to AppState instance
this.DataContext = AppState.Instance;
CloseAllAppsCheckbox.IsChecked = Properties.Settings.Default.CloseAllAppsOnExit;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
Properties.Settings.Default.MainWindowSize = new System.Drawing.Size((int)this.Width, (int)this.Height);
Properties.Settings.Default.MainWindowLocation = new System.Drawing.Point((int)this.Left, (int)this.Top);
Properties.Settings.Default.Save();
}
protected override void OnContentRendered(EventArgs e)
{
base.OnContentRendered(e);
if (Properties.Settings.Default.MainWindowLocation == new System.Drawing.Point(0, 0))
{
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
}
#endregion Public Constructors
#region Public Methods
public event PropertyChangedEventHandler PropertyChanged;
public Profile CurrentProfile { get; set; }
public List<Profile> OtherProfiles
{
get
{
if (Profiles == null || CurrentProfile == null)
{
return new List<Profile>();
}
var otherProfiles = Profiles.Except(new List<Profile> { CurrentProfile }).ToList();
Debug.WriteLine($"OtherProfiles: {string.Join(", ", otherProfiles.Select(p => p.Name))}");
return otherProfiles;
}
}
public List<Profile> Profiles { get; set; }
public void DragOver(IDropInfo dropInfo)
{
MyApp sourceItem = dropInfo.Data as MyApp;
MyApp targetItem = dropInfo.TargetItem as MyApp;
if (sourceItem != null && targetItem != null)
{
dropInfo.DropTargetAdorner = DropTargetAdorners.Highlight;
dropInfo.Effects = DragDropEffects.Move;
SaveProfilesAsync();
}
}
public async Task LoadProfilesAsync(string profileName = null)
{
try
{
string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string filePath = Path.Combine(localFolder, "profiles.json");
if (File.Exists(filePath))
{
// Read the file to a string
string json = await File.ReadAllTextAsync(filePath);
// Deserialize the JSON string to a list of profiles
List<Profile> loadedProfiles = JsonConvert.DeserializeObject<List<Profile>>(json);
// Convert list to ObservableCollection
var profiles = new ObservableCollection<Profile>(loadedProfiles);
// Set the loaded profiles to AppState.Instance.Profiles
AppState.Instance.Profiles = profiles;
if (profileName != null)
{
// If profileName argument is provided, select that profile
AppState.Instance.CurrentProfile = AppState.Instance.Profiles.FirstOrDefault(p => p.Name == profileName);
Cb_Profiles.SelectedItem = AppState.Instance.Profiles.FirstOrDefault(p => p.Name == profileName);
}
else
{
// Set the CurrentProfile to the default profile (or first one if no default exists)
AppState.Instance.CurrentProfile = AppState.Instance.Profiles.FirstOrDefault(p => p.IsDefault)
?? AppState.Instance.Profiles.FirstOrDefault();
Cb_Profiles.SelectedItem = AppState.Instance.Profiles.FirstOrDefault(p => p.IsDefault);
}
SubscribeToAppEvents(AppState.Instance.CurrentProfile);
}
else
{
// The profiles file doesn't exist, initialize Profiles with an empty collection
AppState.Instance.Profiles = new ObservableCollection<Profile>();
}
}
catch (Exception ex)
{
// Handle other exceptions
}
}
public async Task SaveProfilesAsync()
{
// Serialize the profiles into a JSON string
var profilesJson = JsonConvert.SerializeObject(AppState.Instance.Profiles);
// Create a file called "profiles.json" in the local folder
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "profiles.json");
// Write the JSON string to the file
await File.WriteAllTextAsync(path, profilesJson);
}
public void UpdateDataGrid()
{
// Assuming 'AddonDataGrid' is the name of your DataGrid control
if (AppState.Instance.CurrentProfile != null)
{
// Set DataGrid's ItemsSource to the apps of the currently selected profile
AddonDataGrid.ItemsSource = AppState.Instance.CurrentProfile.Apps;
}
else
{
// No profile is selected. Clear the data grid.
AddonDataGrid.ItemsSource = null;
}
}
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion Public Methods
#region Private Methods
private void AddonDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
// Write the MyApp instances to the data source here, e.g.: SaveAppStateToFile();
}
private void ApplyTheme(string themeName)
{
var darkThemeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml");
var lightThemeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml");
var themeUri = themeName == "Dark" ? darkThemeUri : lightThemeUri;
var existingTheme = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == themeUri);
if (existingTheme == null)
{
existingTheme = new ResourceDictionary() { Source = themeUri };
Application.Current.Resources.MergedDictionaries.Add(existingTheme);
}
// Remove the current theme
var currentTheme = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == (themeName == "Dark" ? lightThemeUri : darkThemeUri));
if (currentTheme != null)
{
Application.Current.Resources.MergedDictionaries.Remove(currentTheme);
}
}
private void Bt_AddApp_Click_1(object sender, RoutedEventArgs e)
{
if (AppState.Instance.CurrentProfile != null)
{
AddApp addAppWindow = new AddApp()
{
MainPageReference = this,
SelectedProfile = AppState.Instance.CurrentProfile,
};
// Set the owner and startup location
addAppWindow.Owner = this; // Or replace 'this' with reference to the main window
addAppWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
addAppWindow.Show();
AddonDataGrid.ItemsSource = AppState.Instance.CurrentProfile.Apps;
}
else
{
// Handle the case when no profile is selected.
}
}
private void Bt_AddProfile_Click_1(object sender, RoutedEventArgs e)
{
var window = new AddProfileDialog();
// Center the dialog within the owner window
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Owner = this; // Or replace 'this' with reference to the main window
if (window.ShowDialog() == true)
{
string profileName = window.ProfileName;
var newProfile = new Profile { Name = profileName };
AppState.Instance.Profiles.Add(newProfile);
AppState.Instance.CurrentProfile = newProfile;
_ = SaveProfilesAsync();
UpdateDataGrid();
}
}
private async void Bt_RemoveProfile_Click_1(object sender, RoutedEventArgs e)
{
Profile profileToRemove = (Profile)Cb_Profiles.SelectedItem;
if (profileToRemove != null)
{
CustomDialog dialog = new CustomDialog("Are you sure you want to delete this profile?");
dialog.Owner = Application.Current.MainWindow;
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
dialog.ShowDialog();
if (dialog.Result == MessageBoxResult.Yes)
{
AppState.Instance.Profiles.Remove(profileToRemove);
// Check if another profile can be selected
if (AppState.Instance.Profiles.Any())
{
// Select the next profile, or the first one if no next profile exists
AppState.Instance.CurrentProfile = AppState.Instance.Profiles.FirstOrDefault(p => p != profileToRemove) ?? AppState.Instance.Profiles.First();
// If no profile is set as default, set the current profile as the default
if (!AppState.Instance.Profiles.Any(p => p.IsDefault))
{
AppState.Instance.CurrentProfile.IsDefault = true;
DefaultCheckBox.IsChecked = true;
}
}
else
{
// No profiles left, so set CurrentProfile to null
AppState.Instance.CurrentProfile = null;
}
_ = SaveProfilesAsync();
UpdateDataGrid();
}
}
}
private void Btn_Edit_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
MyApp appToEdit = button.CommandParameter as MyApp;
if (appToEdit != null)
{
AddApp addAppWindow = new AddApp();
addAppWindow.AppToEdit = appToEdit; // Set the AppToEdit to the app you want to edit
addAppWindow.MainPageReference = this; // Assuming this is done from MainWindow, else replace 'this' with the instance of MainWindow
// Set the owner and startup location
addAppWindow.Owner = this; // Or replace 'this' with reference to the main window
addAppWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
addAppWindow.Title = "Edit App";
addAppWindow.ShowDialog();
}
}
public void ShowWhatsNewIfUpdated()
{
// Get the current assembly version.
var assemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
// Get the last seen version from the application settings.
var lastSeenVersion = Properties.Settings.Default.LastSeenVersion;
// If the last seen version is empty (which it will be the first time this method is run)
// or if the assembly version is greater than the last seen version, show the what's new dialog.
if (string.IsNullOrEmpty(lastSeenVersion) || new Version(lastSeenVersion) < assemblyVersion)
{
ShowWhatsNew();
// Update the last seen version in the application settings.
Properties.Settings.Default.LastSeenVersion = assemblyVersion.ToString();
// Save the application settings.
Properties.Settings.Default.Save();
}
}
public void ShowWhatsNew()
{
WhatsNewWindow whatsNewWindow = new WhatsNewWindow();
// Set the text to what's new
Paragraph titleParagraph = new Paragraph();
titleParagraph.Inlines.Add(new Bold(new Run("New for this version")));
whatsNewWindow.WhatsNewText.Document.Blocks.Add(titleParagraph);
List list = new List();
ListItem listItem1 = new ListItem(new Paragraph(new Run("Fixed bug with renaming profiles causing a crash")));
list.ListItems.Add(listItem1);
// ListItem listItem2 = new ListItem(new Paragraph(new Run("Profile Options for import/export and copy/rename/delete")));
// list.ListItems.Add(listItem2);
whatsNewWindow.WhatsNewText.Document.Blocks.Add(list);
whatsNewWindow.Owner = this; // Set owner to this MainWindow
whatsNewWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner; // Center the window over its owner
whatsNewWindow.ShowDialog();
}
private void Btn_Launch_Click(object sender, RoutedEventArgs e)
{
// Code to launch all enabled apps
Log.Information("Launching all enabled apps..");
foreach (var app in AppState.Instance.CurrentProfile.Apps)
{
if (app.IsEnabled)
{
Btn_Launch.IsEnabled = false;
LaunchApp(app);
Log.Information("Launching {AppName}..", app.Name);
}
}
}
private void Cb_Profiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (Cb_Profiles.SelectedItem is Profile selectedProfile)
{
// Select the currently selected profile
AppState.Instance.CurrentProfile = selectedProfile;
if (AppState.Instance.CurrentProfile != null)
{
UpdateDataGrid();
DefaultCheckBox.IsChecked = selectedProfile.IsDefault;
if (!_isLoading) // Change here
{
_isChecking = true;
CheckEdLaunchInProfile();
_isChecking = false;
}
}
}
}
private void CheckBox_Unchecked(object sender, RoutedEventArgs e) // this is the checkbox fo r the defaul profile
{
var checkBox = (CheckBox)sender;
var app = (MyApp)checkBox.Tag;
if (app != null)
{
app.IsEnabled = false;
_ = SaveProfilesAsync();
}
}
private async void CloseAllAppsCheckbox_Checked(object sender, RoutedEventArgs e)
{
AppState.Instance.CloseAllAppsOnExit = true;
settings.CloseAllAppsOnExit = true;
await SaveSettingsAsync(settings);
}
private async void CloseAllAppsCheckbox_Unchecked(object sender, RoutedEventArgs e)
{
AppState.Instance.CloseAllAppsOnExit = false;
settings.CloseAllAppsOnExit = false;
await SaveSettingsAsync(settings);
}
private void CopyToProfileSubMenuItem_Click(object sender, RoutedEventArgs e)
{
// Get the clicked MenuItem
var menuItem = (MenuItem)sender;
// Get the bounded MyApp item
var boundedApp = (MyApp)((MenuItem)e.OriginalSource).DataContext;
// Get the selected profile
var selectedProfile = (Profile)menuItem.Tag;
// Now you can copy boundedApp to selectedProfile.
}
private void DefaultCheckbox_Checked(object sender, RoutedEventArgs e)
{
if (Cb_Profiles.SelectedItem is Profile selectedProfile)
{
var previouslyDefaultProfile = AppState.Instance.Profiles.FirstOrDefault(p => p.IsDefault);
if (previouslyDefaultProfile != null)
{
previouslyDefaultProfile.IsDefault = false;
}
selectedProfile.IsDefault = true;
_ = SaveProfilesAsync();
}
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
// get the button that raised the event
var button = (Button)sender;
CustomDialog dialog = new CustomDialog("Are you sure?");
dialog.Owner = Application.Current.MainWindow;
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
dialog.ShowDialog();
if (dialog.Result == MessageBoxResult.Yes)
{
// retrieve the item associated with this button
var appToDelete = (MyApp)button.DataContext;
// remove the item from the collection
try
{
AppState.Instance.CurrentProfile.Apps.Remove(appToDelete);
Log.Information($"App {appToDelete.Name} deleted..", appToDelete.Name);
}
catch (Exception ex)
{
// handle exception
Log.Error(ex, "An error occurred trying to delete an app..");
}
_ = SaveProfilesAsync();
}
}
private void LaunchApp(MyApp app) // function to launch enabled applications
{
// set up a list to track which apps we launched
// different apps have different args, so lets set up a string to hold them
string args;
// TARGET requires a path to a script, if that path has spaces, we need to quote them -
// set a string called quote we can use to top and tail
const string quote = "\"";
var path = $"{app.Path}/{app.ExeName}";
// are we launching TARGET?
if (string.Equals(app.ExeName, "targetgui.exe", StringComparison.OrdinalIgnoreCase))
{
// -r is to specify a script
args = "-r " + quote + app.Args + quote;
}
else
{
// ok its not target, leave the arguments as is
args = app.Args;
}
if (File.Exists(path)) // worth checking the app we want to launch actually exists...
{
try
{
var info = new ProcessStartInfo(path);
info.Arguments = args;
info.UseShellExecute = true;
info.WorkingDirectory = app.Path;
Process proc = Process.Start(info);
proc.EnableRaisingEvents = true;
processList.Add(proc.ProcessName);
// processList.Add(proc.ProcessName); <-- You'll need to define processList first
if (proc.ProcessName == "EDLaunch")
{
proc.Exited += new EventHandler(ProcessExitHandler);
}
Thread.Sleep(50);
proc.Refresh();
}
catch
{
// oh dear, something went horribly wrong..
UpdateStatus($"An error occurred trying to launch {app.Name}..");
}
}
else
{
if (!string.IsNullOrEmpty(app.WebAppURL))
{
string target = app.WebAppURL;
Process proc = Process.Start(new ProcessStartInfo(target) { UseShellExecute = true });
// If the app we're launching is via the steam URL, we anticipate that EDLaunch will run
if (target.Equals("steam://rungameid/359320", StringComparison.OrdinalIgnoreCase))
{
// Small delay to give time for the EDLaunch process to start after Steam starts
Thread.Sleep(2000);
// Find the EDLaunch process and attach the event handler
Process edLaunchProc = Process.GetProcessesByName("EDLaunch").FirstOrDefault();
if (edLaunchProc != null)
{
edLaunchProc.EnableRaisingEvents = true;
edLaunchProc.Exited += new EventHandler(ProcessExitHandler);
}
}
UpdateStatus("Launching " + app.Name);
}
else
{
UpdateStatus($"Unable to launch {app.Name}..");
}
}
UpdateStatus("All apps launched, waiting for EDLaunch Exit..");
// notifyIcon1.BalloonTipText = "All Apps running, waiting for exit"; <-- You'll need to
// define notifyIcon1 first
this.WindowState = WindowState.Minimized;
}
private async Task<Settings> LoadSettingsAsync()
{
string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string settingsFilePath = Path.Combine(localFolder, "settings.json");
Settings settings;
if (File.Exists(settingsFilePath))
{
string json = await File.ReadAllTextAsync(settingsFilePath);
settings = JsonConvert.DeserializeObject<Settings>(json);
}
else
{
// If the settings file doesn't exist, use defaults
settings = new Settings { Theme = "Default" };
}
Log.Information("Settings loaded: {Settings}", settings);
return settings;
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
_isLoading = true;
await LoadProfilesAsync(App.ProfileName);
settings = await LoadSettingsAsync();
isDarkTheme = settings.Theme == "Dark";
ApplyTheme(settings.Theme);
AppState.Instance.CloseAllAppsOnExit = settings.CloseAllAppsOnExit;
// Check if there are no profiles and invoke AddProfileDialog if none exist
if (AppState.Instance.Profiles == null || AppState.Instance.Profiles.Count == 0)
{
var window = new AddProfileDialog();
// Center the dialog within the owner window
window.WindowStartupLocation = WindowStartupLocation.CenterOwner;
window.Owner = this; // Or replace 'this' with reference to the main window
if (window.ShowDialog() == true)
{
string profileName = window.ProfileName;
var newProfile = new Profile { Name = profileName, IsDefault = true };
// Unmark any existing default profiles
foreach (var profile in AppState.Instance.Profiles)
{
profile.IsDefault = false;
}
AppState.Instance.Profiles.Add(newProfile);
AppState.Instance.CurrentProfile = newProfile;
await SaveProfilesAsync();
UpdateDataGrid();
}
}
if (App.AutoLaunch)
{
foreach (var app in AppState.Instance.CurrentProfile.Apps)
{
if (app.IsEnabled)
{
LaunchApp(app);
}
}
}
_isLoading = false;
if (_isChecking == false)
{
_isChecking = true;
CheckEdLaunchInProfile();
_isChecking = false;
}
ShowWhatsNewIfUpdated();
}
private void ModifyTheme(Uri newThemeUri)
{
var appResources = Application.Current.Resources;
var oldTheme = appResources.MergedDictionaries.FirstOrDefault(d => d.Source.ToString().Contains("MaterialDesignTheme.Light.xaml") || d.Source.ToString().Contains("MaterialDesignTheme.Dark.xaml"));
if (oldTheme != null)
{
appResources.MergedDictionaries.Remove(oldTheme);
}
appResources.MergedDictionaries.Insert(0, new ResourceDictionary { Source = newThemeUri });
}
private void MyApp_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(MyApp.IsEnabled) || e.PropertyName == nameof(MyApp.Order))
{
_ = SaveProfilesAsync();
}
}
// maybe redundant now
private void OnProfileChanged(Profile oldProfile, Profile newProfile)
{
UnsubscribeFromAppEvents(oldProfile);
SubscribeToAppEvents(newProfile);
}
private void ProcessExitHandler(object sender, EventArgs e) //triggered when EDLaunch exits
{
Application.Current.Dispatcher.Invoke(() =>
{
Btn_Launch.IsEnabled = true;
bool closeAllApps = CloseAllAppsCheckbox.IsChecked == true;
// if EDLaunch has quit, does the user want us to kill all the apps?
if (closeAllApps)
{
Log.Information("CloseAllAppsOnExit is enabled, closing all apps..");
try
{
foreach (string p in processList)
{
Log.Information("Closing {0}", p);
foreach (Process process in Process.GetProcessesByName(p))
{
// Temp is a document which you need to kill.
if (process.ProcessName.Contains(p))
process.CloseMainWindow();
}
}
}
catch
{
// if something went wrong, don't raise an exception
Log.Error("An error occurred trying to close all apps..");
}
// doesn't seem to want to kill VoiceAttack nicely..
try
{
Process[] procs = Process.GetProcessesByName("VoiceAttack");
foreach (var proc in procs) { proc.Kill(); } //sadly this means next time it starts, it will complain it was shutdown in an unclean fashion
}
catch
{
// if something went wrong, don't raise an exception
}
// Elite Dangerous Odyssey Materials Helper is a little strange, let's deal with its
// multiple running processes..
try
{
Process[] procs = Process.GetProcessesByName("Elite Dangerous Odyssey Materials Helper");
foreach (var proc in procs) { proc.CloseMainWindow(); }
}
catch
{
// if something went wrong, don't raise an exception
}
// sleep for 5 seconds then quit
for (int i = 5; i != 0; i--)
{
Thread.Sleep(1000);
}
Environment.Exit(0);
}
});
}
private async Task SaveSettingsAsync(Settings settings)
{
string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
string settingsFilePath = Path.Combine(localFolder, "settings.json");
string json = JsonConvert.SerializeObject(settings);
await File.WriteAllTextAsync(settingsFilePath, json);
}
private void SubscribeToAppEvents(Profile profile)
{
if (profile != null)
{
foreach (var app in profile.Apps)
{
app.PropertyChanged += MyApp_PropertyChanged;
}
}
}
private void ToggleThemeButton_Click(object sender, RoutedEventArgs e)
{
isDarkTheme = !isDarkTheme;
settings.Theme = isDarkTheme ? "Dark" : "Light"; // <-- Add this
_ = SaveSettingsAsync(settings);
var darkThemeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Dark.xaml");
var lightThemeUri = new Uri("pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml");
var themeUri = isDarkTheme ? darkThemeUri : lightThemeUri;
System.Diagnostics.Debug.WriteLine("Before toggle:");
foreach (var dictionary in Application.Current.Resources.MergedDictionaries)
{
System.Diagnostics.Debug.WriteLine($" - {dictionary.Source}");
}
var existingTheme = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == themeUri);
if (existingTheme == null)
{
existingTheme = new ResourceDictionary() { Source = themeUri };
Application.Current.Resources.MergedDictionaries.Add(existingTheme);
}
// Remove the current theme
var currentTheme = Application.Current.Resources.MergedDictionaries.FirstOrDefault(d => d.Source == (isDarkTheme ? lightThemeUri : darkThemeUri));
if (currentTheme != null)
{
Application.Current.Resources.MergedDictionaries.Remove(currentTheme);
}
System.Diagnostics.Debug.WriteLine("After toggle:");
foreach (var dictionary in Application.Current.Resources.MergedDictionaries)
{
System.Diagnostics.Debug.WriteLine($" - {dictionary.Source}");
}
_ = SaveSettingsAsync(settings);
}
private void UnsubscribeFromAppEvents(Profile profile)
{
if (profile != null)
{
foreach (var app in profile.Apps)
{
app.PropertyChanged -= MyApp_PropertyChanged;
}
}
}
private void UpdateStatus(string status)
{
// Define how you update the status in your application
}
#endregion Private Methods
public static async Task<List<string>> ScanComputerForEdLaunch()
{
List<string> foundPaths = new List<string>();
string targetFolder = "Elite Dangerous";
string targetFile = "edlaunch.exe";
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
SearchProgressWindow progressWindow = new SearchProgressWindow();
progressWindow.Owner = Application.Current.MainWindow;
progressWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
progressWindow.Closing += (s, e) => tokenSource.Cancel();
progressWindow.Show(); // Show the window before starting the task
await Task.Run(() =>
{
try
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (token.IsCancellationRequested)
break;
if (drive.DriveType == DriveType.Fixed)
{
try
{
string driveRoot = drive.RootDirectory.ToString();
if (TraverseDirectories(driveRoot, targetFolder, targetFile, foundPaths, progressWindow, 7, token))
{
break;
}
}
catch (UnauthorizedAccessException)
{
// If we don't have access to the directory, skip it
}
catch (IOException)
{
// If another error occurs, skip it
}
}
}
}
catch (OperationCanceledException)
{
// If operation is canceled, return
return;
}
}, token);
if (progressWindow.IsVisible)
progressWindow.Close();
return foundPaths;
}
public static bool TraverseDirectories(string root, string targetFolder, string targetFile, List<string> foundPaths, SearchProgressWindow window, int maxDepth, CancellationToken token, int currentDepth = 0)
{
// Array of directories to exclude
string[] excludeDirs = {
"windows",
"users",
"OneDriveTemp",
"ProgramData",
"$Recycle.Bin",
"OneDrive"
};
if (token.IsCancellationRequested)
return false;
// Make sure not to exceed maximum depth
if (currentDepth > maxDepth) return false;
foreach (string dir in Directory.GetDirectories(root))
{
// Check for excluded directories
bool isExcluded = false;
foreach (string excludeDir in excludeDirs)
{
if (dir.ToLower().Contains(excludeDir.ToLower()))
{
isExcluded = true;
break;
}
}
if (isExcluded || token.IsCancellationRequested)
{
continue;
}
try
{
string dirName = new DirectoryInfo(dir).Name;
if (dirName.Equals(targetFolder, StringComparison.OrdinalIgnoreCase))
{
// The folder has the name we're looking for, now we just need to check if
// the file is there
foreach (string file in Directory.GetFiles(dir))
{
if (Path.GetFileName(file).Equals(targetFile, StringComparison.OrdinalIgnoreCase))
{
foundPaths.Add(file);
return true; // File has been found
}
}
}
// Trim the path for display in the UI
string trimmedPath = dir;
if (dir.Count(f => f == '\\') > 2)
{
var parts = dir.Split('\\');
trimmedPath = string.Join("\\", parts.Take(3)) + "\\...";
}
window.Dispatcher.Invoke(() =>
{
window.searchStatusTextBlock.Text = $"Checking: {trimmedPath}";
});
// Move on to the next level
bool found = TraverseDirectories(dir, targetFolder, targetFile, foundPaths, window, maxDepth, token, currentDepth + 1);
if (found)
{
return true; // File has been found in a subdirectory, so we stop the search
}
}
catch (UnauthorizedAccessException)
{
// If we don't have access to the directory, skip it
}