-
Notifications
You must be signed in to change notification settings - Fork 4
/
MainWindow.xaml.cs
1349 lines (1289 loc) · 54.5 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 System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
using System.Diagnostics;
using System.Threading;
using ModernWpf;
using System.Net;
using System.Text.RegularExpressions;
using RazzTools;
using GitHub;
using System.Data;
namespace ValheimServerWarden
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//private List<ValheimServer> servers;
private bool suppressLog = false;
private bool editing = false;
private System.Windows.Forms.NotifyIcon notifyIcon;
private WindowState storedWindowState;
private DateTime lastUpdateCheck;
private List<ServerDetailsWindow> serverDetailWindows;
private List<ServerLogWindow> serverLogWindows;
private List<LogEntry> logEntries;
private FileSystemWatcher shutdownWatcher;
private string ServerJsonPath
{
get
{
return "valheim_servers.json";
}
}
private string LogPath
{
get
{
return "vswlog.txt";
}
}
public MainWindow()
{
InitializeComponent();
if (Properties.Settings.Default.UpgradeRequired)
{
Properties.Settings.Default.Upgrade();
Properties.Settings.Default.UpgradeRequired = false;
Properties.Settings.Default.Save();
}
if (Properties.Settings.Default.MainWindowWidth > 0)
{
Width = Properties.Settings.Default.MainWindowWidth;
}
if (Properties.Settings.Default.MainWindowHeight > 0)
{
Height = Properties.Settings.Default.MainWindowHeight;
}
LogEntry.NormalColor = ((SolidColorBrush)this.Foreground).Color;
logEntries = new List<LogEntry>();
serverDetailWindows = new List<ServerDetailsWindow>();
serverLogWindows = new List<ServerLogWindow>();
if (Properties.Settings.Default.AppTheme.Equals("Dark"))
{
radThemeDark.IsChecked = true;
}
else
{
radThemeLight.IsChecked = true;
radThemeLight_Checked(null, null);
}
if (Properties.Settings.Default.WriteAppLog)
{
System.IO.File.WriteAllText(LogPath, "");
}
txtLog.Document.Blocks.Clear();
logMessage($"Version {typeof(MainWindow).Assembly.GetName().Version}");
CheckServerPath();
txtServerPath.Text = Properties.Settings.Default.ServerFilePath;
txtSteamCmdPath.Text = Properties.Settings.Default.SteamCMDPath;
foreach (var i in Enum.GetValues(typeof(ValheimServer.ServerInstallMethod)))
{
cmbServerType.Items.Add(Enum.GetName(typeof(ValheimServer.ServerInstallMethod), i));
}
cmbServerType.SelectedIndex = Properties.Settings.Default.ServerInstallType;
chkAutoCheckUpdate.IsChecked = Properties.Settings.Default.AutoCheckUpdate;
chkLog.IsChecked = Properties.Settings.Default.WriteAppLog;
chkRunningServerCheck.IsChecked = Properties.Settings.Default.RunningServerCheck;
chkStopOnClose.IsChecked = Properties.Settings.Default.StopOnClose;
chkStartMinimized.IsChecked = Properties.Settings.Default.StartMinimized;
if (Properties.Settings.Default.AutoCheckUpdate)
{
checkForUpdate();
}
Console.CancelKeyPress += Console_CancelKeyPress;
//dgServers.ContextMenuOpening += dgServers_ContextMenuOpening;
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.BalloonTipText = "VSW has been minimized. Click the tray icon to restore.";
notifyIcon.BalloonTipClicked += NotifyIcon_Click;
notifyIcon.Text = "Valheim Server Warden";
this.notifyIcon.Icon = ValheimServerWarden.Properties.Resources.vsw2;
notifyIcon.MouseClick += NotifyIcon_MouseClick;
System.Windows.Forms.ContextMenuStrip cm = new System.Windows.Forms.ContextMenuStrip();
System.Windows.Forms.ToolStripMenuItem menuQuit = new System.Windows.Forms.ToolStripMenuItem();
menuQuit.Text = "Quit";
menuQuit.Click += NotifyMenuQuit_Click;
cm.Items.Add(menuQuit);
notifyIcon.ContextMenuStrip = cm;
storedWindowState = WindowState.Normal;
if (Properties.Settings.Default.RunningServerCheck)
{
checkForRunningServers();
}
if (File.Exists(this.ServerJsonPath))
{
try
{
ValheimServer[] savedServers = JsonSerializer.Deserialize<ValheimServer[]>(File.ReadAllText(this.ServerJsonPath));
foreach (ValheimServer s in savedServers)
{
attachServerEventListeners(s);
//servers.Add(s);
if (s.Autostart)
{
s.Start();
}
}
}
catch (Exception ex)
{
logMessage($"Error reading saved servers: {ex.Message}", LogEntryType.Error);
}
}
dgServers.ItemsSource = ValheimServer.Servers;//servers;
RefreshDataGrid();
if (File.Exists("shutdown.now")) File.Delete("shutdown.now");
shutdownWatcher = new();
shutdownWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.FileName;
shutdownWatcher.Filter = "shutdown.now";
shutdownWatcher.Path = System.AppDomain.CurrentDomain.BaseDirectory;
shutdownWatcher.EnableRaisingEvents = true;
shutdownWatcher.Created += ShutdownWatcher_Created;
shutdownWatcher.Renamed += ShutdownWatcher_Created;
}
private void ShutdownWatcher_Created(object sender, FileSystemEventArgs e)
{
try
{
logMessage("Shutdown file detected, initiating shutdown of server(s).");
ShutdownAndQuit();
}
catch (Exception ex)
{
logMessage($"Error while stopping servers for shutdown: {ex.Message}");
}
}
private void ShutdownAndQuit()
{
try
{
foreach (var server in ValheimServer.Servers)
{
if (server.Status != ValheimServer.ServerStatus.Stopped && server.Status != ValheimServer.ServerStatus.Stopping)
{
server.Stopped += Server_StoppedShutdownCheck;
server.Stop();
} else if (server.Status == ValheimServer.ServerStatus.Stopping)
{
server.Stopped += Server_StoppedShutdownCheck;
}
}
}
catch (Exception ex)
{
logMessage($"Error while stopping servers for shutdown: {ex.Message}");
}
}
private void Server_StoppedShutdownCheck(object sender, ServerStoppedEventArgs e)
{
var allStopped = true;
foreach (var s in ValheimServer.Servers)
{
if (s.Status != ValheimServer.ServerStatus.Stopped)
{
allStopped = false;
break;
}
}
this.Dispatcher.Invoke(() =>
{
if (allStopped) Close();
});
}
private void NotifyMenuQuit_Click(object sender, EventArgs e)
{
foreach (var server in ValheimServer.Servers)
{
if (server.Running)
{
logMessage($"Stop all running servers before exiting.", LogEntryType.Error);
Show();
WindowState = storedWindowState;
return;
}
}
Close();
}
private void NotifyIcon_Click(object sender, EventArgs e)
{
Show();
Activate();
WindowState = storedWindowState;
}
private void NotifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
Show();
Activate();
WindowState = storedWindowState;
}
else
{
//context menu?
}
}
private void dgServers_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
try
{
((System.Windows.Media.Animation.Storyboard)FindResource("WorkingStoryboard")).Begin();
serversMenuStart.Visibility = Visibility.Collapsed;
serversMenuStop.Visibility = Visibility.Collapsed;
serversMenuWorking.Visibility = Visibility.Collapsed;
serversMenuRemove.Visibility = Visibility.Collapsed;
serversMenuDetails.Visibility = Visibility.Collapsed;
serversMenuLog.Visibility = Visibility.Collapsed;
serversmenuSep1.Visibility = Visibility.Collapsed;
serversmenuSep2.Visibility = Visibility.Collapsed;
serversmenuSep3.Visibility = Visibility.Collapsed;
if (dgServers.SelectedIndex == -1)
{
/*serversMenuStart.IsEnabled = false;
serversMenuStart.Icon = FindResource("StartGrey");
serversMenuStop.IsEnabled = false;
serversMenuStop.Icon = FindResource("StopGrey");
serversMenuRemove.IsEnabled = false;
serversMenuRemove.Icon = FindResource("RemoveGrey");
serversMenuDetails.IsEnabled = false;
serversMenuLog.IsEnabled = false;*/
return;
}
ValheimServer server = ((ValheimServer)dgServers.SelectedItem);
//serversMenuDetails.IsEnabled = true;
//serversMenuLog.IsEnabled = (File.Exists(server.LogRawName));
serversMenuDetails.Visibility = Visibility.Visible;
if (File.Exists(server.LogRawName))
{
serversMenuLog.Visibility = Visibility.Visible;
}
else
{
serversMenuLog.Visibility = Visibility.Collapsed;
}
serversmenuSep1.Visibility = Visibility.Visible;
serversmenuSep2.Visibility = Visibility.Visible;
serversmenuSep3.Visibility = Visibility.Visible;
if (server.Status == ValheimServer.ServerStatus.Running)
{
/*serversMenuStart.IsEnabled = false;
serversMenuStart.Icon = FindResource("StartGrey");
serversMenuStop.IsEnabled = true;
serversMenuStop.Icon = FindResource("Stop");
serversMenuRemove.IsEnabled = false;
serversMenuRemove.Icon = FindResource("RemoveGrey");*/
serversMenuStart.Visibility = Visibility.Collapsed;
serversMenuStop.Visibility = Visibility.Visible;
serversMenuRemove.Visibility = Visibility.Collapsed;
serversmenuSep2.Visibility = Visibility.Collapsed;
}
else if (server.Status == ValheimServer.ServerStatus.Stopped)
{
/*serversMenuStart.IsEnabled = true;
serversMenuStart.Icon = FindResource("Start");
serversMenuStop.IsEnabled = false;
serversMenuStop.Icon = FindResource("StopGrey");
serversMenuRemove.IsEnabled = true;
serversMenuRemove.Icon = FindResource("Remove");*/
serversMenuStart.Visibility = Visibility.Visible;
serversMenuStop.Visibility = Visibility.Collapsed;
serversMenuRemove.Visibility = Visibility.Visible;
serversmenuSep2.Visibility = Visibility.Visible;
serversmenuSep3.Visibility = Visibility.Visible;
}
else
{
serversMenuStart.Visibility = Visibility.Collapsed;
serversMenuStop.Visibility = Visibility.Collapsed;
serversMenuWorking.Visibility = Visibility.Visible;
if (server.Status == ValheimServer.ServerStatus.Starting)
{
serversMenuWorking.Header = "Starting...";
}
else if (server.Status == ValheimServer.ServerStatus.Stopping)
{
serversMenuWorking.Header = "Stopping...";
}
else if (server.Status == ValheimServer.ServerStatus.Updating)
{
serversMenuWorking.Header = "Updating...";
}
serversMenuRemove.Visibility = Visibility.Collapsed;
serversmenuSep2.Visibility = Visibility.Collapsed;
}
}
catch (Exception ex)
{
logMessage($"Error opening context menu: {ex.Message}", LogEntryType.Error);
}
}
private void CheckServerPath()
{
try
{
string path = Properties.Settings.Default.ServerFilePath;
bool searchNeeded = true;
if (path.Length > 0 && File.Exists(path))
{
searchNeeded = false;
}
if (searchNeeded)
{
logMessage("Valid path for Valheim dedicated server not set.");
string steampath = @"Program Files (x86)\Steam\steam.exe";
string fullSteamPath = "";
string filePath = $@"Program Files (x86)\Steam\steamapps\common\Valheim dedicated server\{ValheimServer.ExecutableName}";
bool serverfound = false;
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (File.Exists($@"{drive.Name}{steampath}"))
{
fullSteamPath = $@"{drive.Name}{steampath}";
}
string testpath = $@"{drive.Name}{filePath}";
if (File.Exists(testpath))
{
logMessage($"Dedicated server path found at {drive.Name}{filePath}");
Properties.Settings.Default.ServerFilePath = drive.Name + filePath;
Properties.Settings.Default.Save();
serverfound = true;
break;
}
}
if (!serverfound)
{
if (fullSteamPath != null)
{
var mmb = new ModernMessageBox(this);
mmb.SetButtonText(new NameValueCollection() { { "Yes", "Steam" }, { "No", "SteamCMD" }, { "Cancel", "Manual" } });
var confirmResult = mmb.Show("VSW couldn't find the Valheim dedicated server installed, but it found Steam. Do you want to install the dedicated server via Steam, SteamCMD, or manually select your installation location?",
"Install dedicated server?", MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.Cancel);
if (confirmResult == MessageBoxResult.Yes)
{
mmb = new ModernMessageBox(this);
mmb.Show("Once the dedicated server finishes installing, restart this app and it will hopefully detect the dedicated server location.",
"Restart Required", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
Process.Start(fullSteamPath, $"-applaunch {ValheimServer.SteamID}");
logMessage("Please restart this app once the Valheim dedicated server finishes installing.");
Properties.Settings.Default.ServerInstallType = (int)ValheimServer.ServerInstallMethod.Steam;
Properties.Settings.Default.Save();
return;
}
else if (confirmResult == MessageBoxResult.No)
{
var steamCmdWindow = new InstallSteamCmdWindow();
steamCmdWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
if (steamCmdWindow.ShowDialog().GetValueOrDefault())
{
logMessage("Valheim dedicated server installed via SteamCMD.");
return;
}
}
}
else
{
var mmb = new ModernMessageBox(this);
mmb.SetButtonText(new NameValueCollection() { { "OK", "SteamCMD" }, { "Cancel", "Manual" } });
var confirmResult = mmb.Show("VSW couldn't find the Valheim dedicated server installation. Do you want to install the dedicated server via SteamCMD or manually select your installation location?",
"Install dedicated server?", MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel);
if (confirmResult == MessageBoxResult.OK)
{
var steamCmdWindow = new InstallSteamCmdWindow();
steamCmdWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
if (steamCmdWindow.ShowDialog().GetValueOrDefault())
{
logMessage("Valheim dedicated server installed via SteamCMD.");
return;
}
}
}
}
logMessage("Valid path for dedicated server not found. Please set manually in settings.");
Properties.Settings.Default.ServerInstallType = (int)ValheimServer.ServerInstallMethod.Manual;
Properties.Settings.Default.Save();
}
}
catch (Exception ex)
{
logMessage($"Error checking for dedicated server path: {ex.Message}");
}
}
private void btnServerPath_Click(object sender, RoutedEventArgs e)
{
var openFolderDialog = new System.Windows.Forms.FolderBrowserDialog();
if (txtServerPath.Text != "")
{
var serverpath = new FileInfo(txtServerPath.Text).Directory.FullName;
if (Directory.Exists(serverpath))
{
openFolderDialog.SelectedPath = serverpath;
}
}
openFolderDialog.UseDescriptionForTitle = true;
openFolderDialog.Description = "Default server installation folder";
var result = openFolderDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
var folderName = openFolderDialog.SelectedPath;
/*if (folderName+ "\\valheim_server.exe" == txtServerPath.Text)
{
return;
}*/
if (!File.Exists($@"{folderName}\{ValheimServer.ExecutableName}") && cmbServerType.SelectedIndex == (int)ValheimServer.ServerInstallMethod.SteamCMD && File.Exists(Properties.Settings.Default.SteamCMDPath))
{
var mmb = new ModernMessageBox(this);
var install = mmb.Show($"{ValheimServer.ExecutableName} was not found in {folderName}, do you want to install it via SteamCMD?",
"Install Valheim dedicated server?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (install == MessageBoxResult.Yes)
{
try
{
var process = new Process();
process.StartInfo.FileName = Properties.Settings.Default.SteamCMDPath;
process.StartInfo.Arguments = $"+login anonymous +force_install_dir \"{folderName}\" +app_update {ValheimServer.SteamID} +quit";
//process.EnableRaisingEvents = true;
//process.Exited += SteamCmdProcess_Exited;
process.Start();
process.WaitForExit();
}
catch (Exception ex)
{
logMessage($"Error installing dedicated server: {ex.Message}", LogEntryType.Error);
}
}
}
folderName += $@"\{ValheimServer.ExecutableName}";
txtServerPath.Text = folderName;
Properties.Settings.Default.ServerFilePath = folderName;
Properties.Settings.Default.Save();
}
/*System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
if (txtServerPath.Text.Length > 0)
{
string filepath = txtServerPath.Text;
openFileDialog.CheckFileExists = true;
if (File.Exists(filepath))
{
openFileDialog.InitialDirectory = (new FileInfo(filepath)).DirectoryName;
}
}
openFileDialog.Filter = "Server executable|valheim_server.exe";
openFileDialog.Title = "Select where valheim_server.exe is installed";
System.Windows.Forms.DialogResult result = openFileDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string fileName = openFileDialog.FileName;
if (fileName.Equals(txtServerPath.Text))
{
return;
}
if (!File.Exists(fileName))
{
var mmb = new ModernMessageBox(this);
mmb.Show("Please select the location of valheim_server.exe.",
"Invalid Folder", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK);
return;
}
txtServerPath.Text = fileName;
Properties.Settings.Default.ServerFilePath = fileName;
Properties.Settings.Default.Save();
}*/
}
private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
Debug.WriteLine("Console_CancelKeyPress");
if (e.SpecialKey == ConsoleSpecialKey.ControlC)
Debug.WriteLine("Control c event!");
e.Cancel = true;
}
private void Window_Closed(object sender, EventArgs e)
{
SaveServers();
notifyIcon.Dispose();
notifyIcon = null;
foreach (ValheimServer server in ValheimServer.Servers)
{
if (server.Status == ValheimServer.ServerStatus.Running || server.Status == ValheimServer.ServerStatus.Starting)
{
server.Stop();
}
}
for (int i=0; i < this.serverDetailWindows.Count; i++)
{
this.serverDetailWindows[i].Close();
}
for (int i = 0; i < this.serverLogWindows.Count; i++)
{
this.serverLogWindows[i].Close();
}
}
private void SaveServers()
{
try
{
File.WriteAllTextAsync(this.ServerJsonPath, JsonSerializer.Serialize(ValheimServer.Servers));
}
catch (Exception ex)
{
logMessage($"Error writing servers to json: {ex.Message}", LogEntryType.Error);
}
}
private void attachServerEventListeners(ValheimServer server)
{
try
{
//server.OutputDataReceived += Server_OutputDataReceived;
//server.ErrorDataReceived += Server_OutputDataReceived;
server.LoggedMessage += ((object sender, LoggedMessageEventArgs e) => {
this.Dispatcher.Invoke(() =>
{
var server = (ValheimServer)sender;
logMessage(server.DisplayName+": "+e.LogEntry.Message, e.LogEntry.Type);
});
});
server.Stopped += Server_Stopped;
server.Started += Server_Started;
server.Starting += Server_StartingStopping;
server.StartFailed += Server_StartFailed;
server.Stopping += Server_StartingStopping;
server.StopFailed += Server_StopFailed;
server.PlayerConnected += Server_PlayerConnected;
server.PlayerDisconnected += Server_PlayerDisconnected;
}
catch (Exception ex)
{
logMessage($"Error attaching event listeners: {ex.Message}", LogEntryType.Error);
}
}
private void Server_StartingStopping(object sender, EventArgs e)
{
this.Dispatcher.Invoke(() =>
{
try
{
dgServers.CancelEdit();
dgServers.IsReadOnly = true;
RefreshDataGrid();
} catch (Exception ex)
{
logMessage($"Error refreshing server list on start/stop: {ex.Message}");
}
});
}
private void Server_StopFailed(object sender, ServerErrorEventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
dgServers.IsReadOnly = false;
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error responding to server stop failed event: {ex.Message}", LogEntryType.Error);
}
}
private void Server_StartFailed(object sender, ServerErrorEventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
dgServers.IsReadOnly = false;
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error responding to server start failed event: {ex.Message}", LogEntryType.Error);
}
}
private void Server_Started(object sender, EventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
dgServers.IsReadOnly = false;
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error responding to server started event: {ex.Message}", LogEntryType.Error);
}
}
private void Server_PlayerDisconnected(object sender, PlayerEventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error responding to PlayerDisconnected event: {ex.Message}",LogEntryType.Error);
}
}
private void Server_PlayerConnected(object sender, PlayerEventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error responding to PlayerConnected event: {ex.Message}", LogEntryType.Error);
}
}
private void serversMenuAdd_Click(object sender, RoutedEventArgs e)
{
try
{
ValheimServer s = new ValheimServer();
s.InstallMethod = (ValheimServer.ServerInstallMethod)Properties.Settings.Default.ServerInstallType;
attachServerEventListeners(s);
//servers.Add(s);
RefreshDataGrid();
dgServers.SelectedItem = s;
dgServers.BeginEdit();
}
catch (Exception ex)
{
logMessage($"Error adding new server: {ex.Message}", LogEntryType.Error);
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// setting cancel to true will cancel the close request
// so the application is not closed
/*e.Cancel = true;
this.Hide();
base.OnClosing(e);*/
try
{
foreach (ValheimServer server in ValheimServer.Servers)
{
if (server.Running)
{
e.Cancel = true;
if (Properties.Settings.Default.StopOnClose)
{
logMessage($"Stopping all servers for app exit.");
WindowState = WindowState.Minimized;
ShutdownAndQuit();
} else
{
logMessage($"Server {server.DisplayName} is still running. Please stop all servers before exiting.", LogEntryType.Error);
}
}
else
{
Properties.Settings.Default.MainWindowWidth = Width;
Properties.Settings.Default.MainWindowHeight = Height;
Properties.Settings.Default.Save();
}
}
if (!e.Cancel) SaveServers();
}
catch (Exception ex) {
logMessage($"Error while closing: {ex.Message}", LogEntryType.Error);
}
}
private void dgServers_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
try
{
ValheimServer server = (ValheimServer)e.Row.Item;
/*if (e.Column.Header.Equals("Name"))
{
string newName = ((TextBox)e.EditingElement).Text;
foreach (ValheimServer s in servers)
{
if (server != s && s.Name.Equals(newName))
{
logMessage($"A server named {newName} already exists. Please choose another name.", LogEntryType.Error);
e.Cancel = true;
return;
}
}
}
else*/ if (e.Column.Header.Equals("Password"))
{
string newPass = ((TextBox)e.EditingElement).Text;
if (newPass.Length == 0)
{
logMessage("Warning: Servers must have passwords unless modded to remove that requirement.");
}
else if (newPass.Length < 5)
{
logMessage("Passwords must be at least 5 characters long.", LogEntryType.Error);
((TextBox)e.EditingElement).Text = server.Password;
e.Cancel = true;
return;
}
else if (server.World.Contains(newPass)) {
logMessage("Your password cannot be contained in your World name.", LogEntryType.Error);
((TextBox)e.EditingElement).Text = server.Password;
e.Cancel = true;
return;
}
}
//force the edit to end so the dataGrid can get refreshed again. if there's only one item in the datagrid, it never leaves editing.
tabsMain.Focus();
}
catch (Exception ex)
{
logMessage($"Error responding to CellEditEnding event: {ex.Message}", LogEntryType.Error);
}
}
private void dgServers_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
try
{
editing = false;
}
catch (Exception ex)
{
logMessage($"Error responding to RowEditEnding event: {ex.Message}", LogEntryType.Error);
}
}
private void serversMenuStart_Click(object sender, RoutedEventArgs e)
{
try
{
ValheimServer server = ((ValheimServer)dgServers.SelectedItem);
server.Start();
}
catch (Exception ex)
{
logMessage($"Error starting server from context menu: {ex.Message}",LogEntryType.Error);
}
}
private void serversMenuStop_Click(object sender, RoutedEventArgs e)
{
try
{
ValheimServer server = ((ValheimServer)dgServers.SelectedItem);
server.Stop();
}
catch (Exception ex)
{
logMessage($"Error stopping server: {ex.Message}", LogEntryType.Error);
}
}
private void Server_Stopped(object sender, ServerStoppedEventArgs e)
{
try
{
var server = (ValheimServer)sender;
this.Dispatcher.Invoke(() =>
{
dgServers.IsReadOnly = false;
RefreshDataGrid();
});
}
catch (Exception ex)
{
logMessage($"Error handling server exited event: {ex.Message}", LogEntryType.Error);
}
}
public void logMessage(string msg)
{
logMessage(msg, LogEntryType.Normal);
}
public void logMessage(string msg, LogEntryType lt)
{
logMessage(new LogEntry(msg, lt));
}
public void logMessage(LogEntry entry)
{
logEntries.Add(entry);
this.Dispatcher.Invoke(() =>
{
if (!suppressLog)
{
try
{
if (txtLog.Document.Blocks.Count > 0)
{
txtLog.Document.Blocks.InsertBefore(txtLog.Document.Blocks.FirstBlock, (Block)entry);
}
else
{
txtLog.Document.Blocks.Add((Block)entry);
}
if (entry.Message.Contains('\n'))
{
lblLastMessage.Content = entry.Message.Split('\n')[0];
}
else
{
lblLastMessage.Content = entry.Message;
}
lblLastMessage.Foreground = new SolidColorBrush(entry.Color);
if (entry.Type == LogEntryType.Normal)
{
lblLastMessage.FontWeight = FontWeights.Normal;
}
else
{
lblLastMessage.FontWeight = FontWeights.Bold;
}
} catch (Exception ex)
{
logMessage($"Error logging message: {ex.Message}");
}
}
});
if (Properties.Settings.Default.WriteAppLog)
{
try
{
StreamWriter writer = System.IO.File.AppendText(LogPath);
writer.WriteLine(entry.TimeStamp + ": " + entry.Message);
writer.Close();
} catch (Exception ex)
{
logMessage($"Error writing to log file: {ex.Message}");
}
}
}
private void Window_StateChanged(object sender, EventArgs e)
{
if (WindowState == WindowState.Minimized)
{
{
Hide();
if (notifyIcon != null)
{
if (Properties.Settings.Default.ShowMinimizeMessage)
{
notifyIcon.ShowBalloonTip(2000);
Properties.Settings.Default.ShowMinimizeMessage = false;
Properties.Settings.Default.Save();
}
}
}
}
else
{
storedWindowState = WindowState;
}
}
private void dgServers_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
editing = true;
}
private void RefreshDataGrid()
{
this.Dispatcher.Invoke(() =>
{
try
{
if (!editing)
{
dgServers.Items.Refresh();
}
}
catch (Exception ex)
{
logMessage($"Error refreshing server grid: {ex.Message}", LogEntryType.Error);
}
});
}
private void serversMenuRemove_Click(object sender, RoutedEventArgs e)
{
ValheimServer server = (ValheimServer)dgServers.SelectedItem;
var mmb = new ModernMessageBox(this);
var confirmResult = mmb.Show($"Are you sure you want to remove {server.DisplayName}?",
"Remove Server", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
if (confirmResult == MessageBoxResult.Yes)
{
//servers.Remove(server);
server.Dispose();
RefreshDataGrid();
}
}
private void radThemeDark_Checked(object sender, RoutedEventArgs e)
{
if (!Properties.Settings.Default.AppTheme.Equals("Dark"))
{
Properties.Settings.Default.AppTheme = "Dark";
Properties.Settings.Default.Save();
}
ChangeTheme(ApplicationTheme.Dark);
}
private void radThemeLight_Checked(object sender, RoutedEventArgs e)
{
if (!Properties.Settings.Default.AppTheme.Equals("Light"))
{
Properties.Settings.Default.AppTheme = "Light";
Properties.Settings.Default.Save();
}
ChangeTheme(ApplicationTheme.Light);
}
private void ChangeTheme(ApplicationTheme theme)
{
ThemeManager.Current.ApplicationTheme = theme;
//ThemeManager.Current.AccentColor = Colors.Orange;
LogEntry.NormalColor = ((SolidColorBrush)this.Foreground).Color;
if (logEntries.Count > 0)