-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
601 lines (532 loc) · 22.5 KB
/
MainWindow.xaml.cs
File metadata and controls
601 lines (532 loc) · 22.5 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
using System;
using System.ComponentModel;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using GameRegionGuard.Models;
using GameRegionGuard.Services;
namespace GameRegionGuard
{
public partial class MainWindow
{
private CancellationTokenSource _cancellationTokenSource;
private bool _isOperationRunning;
private volatile bool _isClosing;
private bool _isDarkTheme;
public MainWindow()
{
InitializeComponent();
Logger.LogEntryAdded += OnLogEntryAdded;
// Reflect the user's last chosen theme.
_isDarkTheme = AppSettingsService.IsDarkTheme;
UpdateThemeButtonContent();
Logger.Info("Main window initialized");
}
private void OnBlockingModeChanged(object sender, RoutedEventArgs e)
{
if (RadioSpecificApp == null || AppPathPanel == null) return;
if (RadioSpecificApp.IsChecked == true)
{
AppPathPanel.IsEnabled = true;
Logger.Debug("Switched to Specific Application mode");
}
else
{
AppPathPanel.IsEnabled = false;
if (TxtAppPath != null) TxtAppPath.Text = string.Empty;
Logger.Debug("Switched to System-wide mode");
}
}
private void BtnBrowse_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*",
Title = "Select Game Executable"
};
if (dialog.ShowDialog() == true)
{
TxtAppPath.Text = dialog.FileName;
Logger.Info($"Selected application: {dialog.FileName}");
}
}
private async void BtnInstall_Click(object sender, RoutedEventArgs e)
{
Logger.Info("Install button clicked");
var mode = RadioSystemWide.IsChecked == true
? BlockingMode.SystemWide
: BlockingMode.SpecificApplication;
string appPath = null;
if (mode == BlockingMode.SpecificApplication)
{
appPath = TxtAppPath.Text;
if (string.IsNullOrWhiteSpace(appPath))
{
MessageBox.Show(
"Please select an application executable.",
"No Application Selected",
MessageBoxButton.OK,
MessageBoxImage.Warning);
Logger.Warning("Installation cancelled: No application selected");
return;
}
if (!File.Exists(appPath))
{
MessageBox.Show(
$"The selected file does not exist:\n\n{appPath}",
"File Not Found",
MessageBoxButton.OK,
MessageBoxImage.Error);
Logger.Error($"Installation cancelled: File not found - {appPath}");
return;
}
}
var confirmMessage = mode == BlockingMode.SystemWide
? "This will block all Russian IP ranges system-wide.\n\n" +
"This means you may not be able to access services hosted in that region.\n\n" +
"This may take a few minutes to process.\n\n" +
"Do you want to continue?"
: $"This will block Russian IP ranges only for:\n\n{Path.GetFileName(appPath)}\n\n" +
"This may take a few minutes to process.\n\n" +
"Do you want to continue?";
var result = MessageBox.Show(
confirmMessage,
"Confirm Installation",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result != MessageBoxResult.Yes)
{
Logger.Info("Installation cancelled by user at confirmation");
return;
}
await RunInstallationAsync(mode, appPath);
}
private async Task RunInstallationAsync(BlockingMode mode, string appPath)
{
_cancellationTokenSource = new CancellationTokenSource();
_isOperationRunning = true;
SetUIState(false);
try
{
Logger.Info($"Starting installation - Mode: {mode}, Path: {appPath ?? "N/A"}");
UpdateProgress(0, "Downloading Russian IP ranges...");
var downloadService = new IPDownloadService();
var ipRanges = await downloadService.DownloadIPRangesAsync(_cancellationTokenSource.Token);
if (ipRanges == null || ipRanges.Count == 0)
{
MessageBox.Show(
"Failed to download IP ranges. Please check your internet connection.",
"Download Failed",
MessageBoxButton.OK,
MessageBoxImage.Error);
Logger.Error("Installation failed: No IP ranges downloaded");
return;
}
Logger.Info($"Downloaded {ipRanges.Count} IP ranges");
var firewallService = new FirewallService();
var progress = new Progress<(int current, int total, string message)>(report =>
{
try
{
var percent = report.total > 0
? (int)((double)report.current / report.total * 100)
: 0;
UpdateProgress(percent, report.message);
}
catch
{
// Ignore UI progress failures.
}
});
UpdateProgress(5, $"Creating {ipRanges.Count} firewall rules...");
var installResult = await firewallService.InstallRulesAsync(
ipRanges,
mode,
appPath,
progress,
_cancellationTokenSource.Token);
if (installResult.WasCancelled)
{
Logger.Warning($"Installation cancelled. Completed: {installResult.SuccessCount}/{installResult.TotalRules}");
UpdateProgress(100, $"Installation cancelled ({installResult.SuccessCount}/{installResult.TotalRules})");
if (!_isClosing)
{
MessageBox.Show(
$"Installation was cancelled.\n\n" +
$"Rules created: {installResult.SuccessCount}\n" +
$"Skipped (already existed): {installResult.SkippedCount}\n" +
$"Cancelled before completion.",
"Installation Cancelled",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
}
else if (installResult.FailedCount == 0)
{
Logger.Info($"Installation completed successfully. Created: {installResult.SuccessCount}, Skipped: {installResult.SkippedCount}");
if (!_isClosing)
{
MessageBox.Show(
$"Installation completed successfully!\n\n" +
$"Rules created: {installResult.SuccessCount}\n" +
$"Skipped (already existed): {installResult.SkippedCount}\n\n" +
$"Blocking rules have been installed.",
"Installation Complete",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
UpdateProgress(100, "Installation complete");
}
else
{
Logger.Warning($"Installation completed with errors. Success: {installResult.SuccessCount}, Failed: {installResult.FailedCount}");
if (!_isClosing)
{
MessageBox.Show(
$"Installation completed with some errors.\n\n" +
$"Rules created: {installResult.SuccessCount}\n" +
$"Skipped (already existed): {installResult.SkippedCount}\n" +
$"Failed: {installResult.FailedCount}\n\n" +
$"Check the log for details.",
"Installation Complete with Warnings",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
UpdateProgress(100, $"Complete: {installResult.SuccessCount} created, {installResult.FailedCount} failed");
}
}
catch (OperationCanceledException)
{
Logger.Info("Installation cancelled via cancellation token");
UpdateProgress(100, "Installation cancelled");
}
catch (Exception ex)
{
Logger.Error($"Installation error: {ex.Message}\n{ex.StackTrace}");
if (!_isClosing)
{
MessageBox.Show(
$"Installation failed:\n\n{ex.Message}\n\nCheck the log file for details.",
"Installation Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
UpdateProgress(0, "Installation failed");
}
}
finally
{
_isOperationRunning = false;
SetUIState(true);
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}
}
private async void BtnRemove_Click(object sender, RoutedEventArgs e)
{
Logger.Info("Remove button clicked");
// Ask for removal mode
var modeResult = MessageBox.Show(
"What do you want to remove?\n\n" +
"YES = Remove ALL blocking rules (system-wide and all applications)\n" +
"NO = Remove rules for a specific application only",
"Select Removal Mode",
MessageBoxButton.YesNoCancel,
MessageBoxImage.Question);
if (modeResult == MessageBoxResult.Cancel)
{
Logger.Info("Removal cancelled at mode selection");
return;
}
BlockingMode removeMode;
string appPath = null;
if (modeResult == MessageBoxResult.Yes)
{
removeMode = BlockingMode.SystemWide;
Logger.Info("User selected system-wide removal");
}
else
{
removeMode = BlockingMode.SpecificApplication;
var dialog = new OpenFileDialog
{
Filter = "Executable Files (*.exe)|*.exe|All Files (*.*)|*.*",
Title = "Select Application to Remove Rules For"
};
if (dialog.ShowDialog() != true)
{
Logger.Info("Removal cancelled: No application selected");
return;
}
appPath = dialog.FileName;
Logger.Info($"User selected application for removal: {appPath}");
}
var confirmMessage = removeMode == BlockingMode.SystemWide
? "This will remove ALL Russian IP blocking rules (system-wide and all application-specific rules).\n\nAre you sure?"
: $"This will remove all Russian IP blocking rules for:\n\n{Path.GetFileName(appPath)}\n\nAre you sure?";
var confirmResult = MessageBox.Show(
confirmMessage,
"Confirm Removal",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (confirmResult != MessageBoxResult.Yes)
{
Logger.Info("Removal cancelled by user at confirmation");
return;
}
await RunRemovalAsync(removeMode, appPath);
}
private async Task RunRemovalAsync(BlockingMode mode, string appPath)
{
_cancellationTokenSource = new CancellationTokenSource();
_isOperationRunning = true;
SetUIState(false);
try
{
Logger.Info($"Starting rule removal - Mode: {mode}, Path: {appPath ?? "N/A"}");
var firewallService = new FirewallService();
var progress = new Progress<(int current, int total, string message)>(report =>
{
var percent = report.total > 0
? (int)((double)report.current / report.total * 100)
: 0;
UpdateProgress(percent, report.message);
});
UpdateProgress(0, "Searching for firewall rules to remove...");
var removeResult = await firewallService.RemoveRulesAsync(
mode,
appPath,
progress,
_cancellationTokenSource.Token);
if (removeResult.SuccessCount == 0)
{
Logger.Info("No rules found to remove");
if (!_isClosing)
{
MessageBox.Show(
"No blocking rules were found to remove.",
"Nothing to Remove",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
else if (removeResult.FailedCount == 0)
{
Logger.Info($"Removal completed successfully. Removed: {removeResult.SuccessCount}");
if (!_isClosing)
{
MessageBox.Show(
$"Removal completed successfully!\n\nRules removed: {removeResult.SuccessCount}",
"Removal Complete",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
else
{
Logger.Warning($"Removal completed with errors. Success: {removeResult.SuccessCount}, Failed: {removeResult.FailedCount}");
if (!_isClosing)
{
MessageBox.Show(
$"Removal completed with some errors.\n\n" +
$"Removed: {removeResult.SuccessCount}\n" +
$"Failed: {removeResult.FailedCount}\n\n" +
$"Check the log for details.",
"Removal Complete with Warnings",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
}
UpdateProgress(100, "Removal complete");
}
catch (Exception ex)
{
Logger.Error($"Removal error: {ex.Message}\n{ex.StackTrace}");
if (!_isClosing)
{
MessageBox.Show(
$"Removal failed:\n\n{ex.Message}\n\nCheck the log file for details.",
"Removal Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
UpdateProgress(0, "Removal failed");
}
}
finally
{
_isOperationRunning = false;
SetUIState(true);
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}
}
private void BtnCancel_Click(object sender, RoutedEventArgs e)
{
if (_cancellationTokenSource != null && !_cancellationTokenSource.Token.IsCancellationRequested)
{
var result = MessageBox.Show(
"Are you sure you want to cancel the operation?\n\n" +
"Rules created so far will remain in place.",
"Confirm Cancellation",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result == MessageBoxResult.Yes)
{
Logger.Warning("User requested cancellation");
_cancellationTokenSource.Cancel();
BtnCancel.IsEnabled = false;
UpdateProgress(ProgressBar?.Value ?? 0, "Cancelling...");
}
}
}
private void BtnCopyLogs_Click(object sender, RoutedEventArgs e)
{
try
{
Clipboard.SetText(TxtLog.Text);
Logger.Info("Logs copied to clipboard");
}
catch (Exception ex)
{
Logger.Error($"Failed to copy logs: {ex.Message}");
MessageBox.Show(
$"Failed to copy logs:\n\n{ex.Message}",
"Copy Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
private void BtnSaveLogs_Click(object sender, RoutedEventArgs e)
{
try
{
var dialog = new SaveFileDialog
{
Filter = "Log Files (*.log)|*.log|Text Files (*.txt)|*.txt|All Files (*.*)|*.*",
FileName = $"GameRegionGuard_{DateTime.Now:yyyyMMdd_HHmmss}.log",
Title = "Save Log File"
};
if (dialog.ShowDialog() == true)
{
File.WriteAllText(dialog.FileName, TxtLog.Text);
Logger.Info($"Logs saved to: {dialog.FileName}");
MessageBox.Show(
$"Logs saved to:\n{dialog.FileName}",
"Saved",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
catch (Exception ex)
{
Logger.Error($"Failed to save logs: {ex.Message}");
MessageBox.Show(
$"Failed to save logs:\n\n{ex.Message}",
"Save Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
private void SafeUI(Action action)
{
if (_isClosing) return;
try
{
if (Dispatcher == null || Dispatcher.HasShutdownStarted || Dispatcher.HasShutdownFinished) return;
if (Dispatcher.CheckAccess())
{
action();
}
else
{
Dispatcher.BeginInvoke(action);
}
}
catch (InvalidOperationException)
{
// Dispatcher is unavailable (shutdown in progress).
}
catch (TaskCanceledException)
{
// Ignored.
}
}
private void SetUIState(bool enabled)
{
SafeUI(() =>
{
if (BtnInstall != null) BtnInstall.IsEnabled = enabled;
if (BtnRemove != null) BtnRemove.IsEnabled = enabled;
if (BtnBrowse != null) BtnBrowse.IsEnabled = enabled && RadioSpecificApp?.IsChecked == true;
if (RadioSystemWide != null) RadioSystemWide.IsEnabled = enabled;
if (RadioSpecificApp != null) RadioSpecificApp.IsEnabled = enabled;
if (BtnCancel != null) BtnCancel.IsEnabled = !enabled;
});
}
private void UpdateProgress(double percent, string message)
{
var clamped = Math.Max(0, Math.Min(100, percent));
SafeUI(() =>
{
if (ProgressBar != null) ProgressBar.Value = clamped;
if (TxtProgressPercent != null) TxtProgressPercent.Text = $"{clamped:F0}%";
if (TxtProgressStatus != null) TxtProgressStatus.Text = message;
});
}
private void OnLogEntryAdded(object sender, string logMessage)
{
SafeUI(() =>
{
if (TxtLog == null) return;
TxtLog.AppendText(logMessage + Environment.NewLine);
// The TextBox is hosted inside an outer ScrollViewer for styling.
// Scroll the container so the latest log line is always visible.
LogScrollViewer?.ScrollToBottom();
});
}
private void BtnToggleTheme_Click(object sender, RoutedEventArgs e)
{
var newDark = !_isDarkTheme;
if (!ThemeService.ApplyTheme(newDark))
{
Logger.Warning("Theme switch failed.");
return;
}
_isDarkTheme = newDark;
AppSettingsService.SetTheme(newDark);
AppSettingsService.Save();
UpdateThemeButtonContent();
Logger.Info($"Theme switched to {(newDark ? "Dark" : "Light")}");
}
private void UpdateThemeButtonContent()
{
if (BtnToggleTheme == null) return;
BtnToggleTheme.Content = _isDarkTheme ? "White Theme" : "Dark Theme";
}
protected override void OnClosing(CancelEventArgs e)
{
_isClosing = true;
// Prevent late UI updates from background tasks during shutdown.
if (_isOperationRunning && _cancellationTokenSource != null && !_cancellationTokenSource.IsCancellationRequested)
{
try
{
Logger.Warning("Application closing - cancelling running operation");
_cancellationTokenSource.Cancel();
}
catch
{
// Ignored.
}
}
base.OnClosing(e);
}
protected override void OnClosed(EventArgs e)
{
Logger.LogEntryAdded -= OnLogEntryAdded;
base.OnClosed(e);
}
}
}