Repository navigation
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1249 lines (1119 loc) · 52.4 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
1249 lines (1119 loc) · 52.4 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
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 Microsoft.UI;
using Microsoft.UI.Composition.SystemBackdrops;
using Microsoft.UI.Dispatching;
using Microsoft.UI.Input;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Animation;
using ProxiLock.Models;
using ProxiLock.Services;
using Windows.Graphics;
using WinRT.Interop;
using System.Collections.ObjectModel;
using System.Runtime.InteropServices;
namespace ProxiLock;
public sealed partial class MainWindow : Window
{
/// <summary>
/// Opacity of a policy page that does not match the selected lock mode. Dimmed enough to
/// read as "not active", still light enough to read what the page contains.
/// </summary>
private const double DisabledSectionOpacity = 0.45;
private readonly AppServices _services;
private readonly DispatcherQueueTimer _usbTimer;
private readonly DispatcherQueueTimer _bluetoothTimer;
private readonly DispatcherQueueTimer _applyTimer;
private bool _initialized;
private bool _allowClose;
private bool _resourcesShutdown;
private int _suppressAutoSaveDepth;
/// <summary>
/// True while programmatic control updates are in flight. Reference-counted because
/// these scopes nest (e.g. loading settings triggers a list refresh), and a plain flag
/// would be cleared by the inner scope while the outer one is still running.
/// </summary>
private bool _suppressAutoSave => _suppressAutoSaveDepth > 0;
private readonly struct SuppressScope : IDisposable
{
private readonly MainWindow _owner;
public SuppressScope(MainWindow owner)
{
_owner = owner;
owner._suppressAutoSaveDepth++;
}
public void Dispose() => _owner._suppressAutoSaveDepth--;
}
private bool _usbRefreshRunning;
private bool _bluetoothScanning;
private bool _titleBarRegionFailed;
private string _titleBarRegionSignature = string.Empty;
private string _usbSignature = string.Empty;
private BluetoothDeviceInfo? _selectedBluetooth;
private UsbDeviceInfo? _selectedUsb;
// Keep the last successfully persisted device selection separate from the row that is
// currently highlighted. A save can fail (for example while the settings file is
// temporarily unavailable), and in that case the transient row must not remain in the
// UI as if it had become the active credential.
private string? _committedBluetoothAddress;
private string? _committedUsbInstanceId;
private Button? _paneToggleButton;
private IntPtr _windowHandle;
public MainWindow(AppServices services)
{
_services = services;
InitializeComponent();
UpdateNavigationPaneVisuals(SettingsNavigationView.IsPaneOpen);
SetDefaultWindowPlacement();
AppWindow.Title = "设置 - ProxiLock";
// Match BetterLyrics' borderless settings-window chrome while keeping
// the standard system buttons and drag behavior.
AppWindow.TitleBar.ExtendsContentIntoTitleBar = true;
AppWindow.TitleBar.PreferredTheme = TitleBarTheme.UseDefaultAppMode;
AppWindow.TitleBar.PreferredHeightOption = TitleBarHeightOption.Standard;
AppWindow.TitleBar.BackgroundColor = Colors.Transparent;
AppWindow.TitleBar.InactiveBackgroundColor = Colors.Transparent;
AppWindow.TitleBar.ButtonBackgroundColor = Colors.Transparent;
AppWindow.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
// Deliberately leave the hover/pressed button colours unset so they keep the
// system defaults. Forcing them transparent removed all feedback, leaving no way
// to tell whether a click had landed on minimise/maximise/close.
AppWindow.TitleBar.ButtonHoverBackgroundColor = null;
AppWindow.TitleBar.ButtonPressedBackgroundColor = null;
try
{
SystemBackdrop = new DesktopAcrylicBackdrop();
}
catch
{
// Older Windows 10 builds can lack Mica; the normal page brush remains.
}
// AppWindow does not automatically inherit ApplicationIcon for unpackaged WinUI apps.
// Set the shell/title-bar icon explicitly from the published root asset.
var iconPath = Path.Combine(AppContext.BaseDirectory, "icon.ico");
if (File.Exists(iconPath))
{
try { AppWindow.SetIcon(iconPath); } catch { /* shell icon is best-effort */ }
}
AppWindow.Closing += AppWindow_Closing;
_usbTimer = DispatcherQueue.CreateTimer();
_usbTimer.Interval = TimeSpan.FromSeconds(5);
_usbTimer.Tick += (_, _) => RefreshUsbList();
_bluetoothTimer = DispatcherQueue.CreateTimer();
_bluetoothTimer.Interval = TimeSpan.FromMilliseconds(600);
_bluetoothTimer.Tick += (_, _) => RefreshBluetoothList();
// Text fields re-validate on every keystroke; coalesce those edits into one
// apply so a single value does not trigger a config write per character.
_applyTimer = DispatcherQueue.CreateTimer();
_applyTimer.Interval = TimeSpan.FromMilliseconds(400);
_applyTimer.IsRepeating = false;
_applyTimer.Tick += (_, _) =>
{
_applyTimer.Stop();
ApplyCurrentSettings();
};
// The extended title bar supplies a default drag region that swallows pointer
// input along the top strip. The navigation pane toggle button sits inside that
// strip, so declare its rectangle as an interactive passthrough region. The
// button is template-instantiated and may not exist yet at Loaded time, so
// retry on full layout changes until it resolves; once found, only its own
// position changes (window resize, pane toggle) need to be re-measured.
RootGrid.Loaded += (_, _) => AttachPaneToggleWatcher();
SettingsNavigationView.SizeChanged += (_, _) => TryApplyTitleBarRegions();
// Theme-derived brushes are assigned in code, so re-apply them if the system
// flips between light and dark while the window is open.
RootGrid.ActualThemeChanged += (_, _) =>
{
UpdateStatus(_services.LockCoordinator?.IsLocked == true);
};
}
private void SetDefaultWindowPlacement()
{
var requested = new SizeInt32(1816, 1060);
try
{
var displayArea = DisplayArea.GetFromWindowId(AppWindow.Id, DisplayAreaFallback.Nearest);
var workArea = displayArea.WorkArea;
// Keep a margin so the window reads as a floating window, but never
// request more than the display can actually show.
var width = Math.Max(1, Math.Min(workArea.Width, Math.Min(requested.Width, Math.Max(720, workArea.Width - 120))));
var height = Math.Max(1, Math.Min(workArea.Height, Math.Min(requested.Height, Math.Max(520, workArea.Height - 120))));
var size = new SizeInt32(width, height);
AppWindow.Resize(size);
// AppWindow uses physical pixels while XAML uses effective pixels. Account
// for display scaling before deciding whether the navigation pane fits.
var dpi = GetDpiForWindow(WinRT.Interop.WindowNative.GetWindowHandle(this));
var scale = dpi == 0 ? 1d : dpi / 96d;
var paneOpen = width / scale >= 860;
SettingsNavigationView.IsPaneOpen = paneOpen;
UpdateNavigationPaneVisuals(paneOpen);
var x = workArea.X + Math.Max(0, (workArea.Width - size.Width) / 2);
var y = workArea.Y + Math.Max(0, (workArea.Height - size.Height) / 2);
AppWindow.Move(new PointInt32(x, y));
}
catch
{
// Window placement is best-effort during very early shell startup.
AppWindow.Resize(requested);
}
}
public void InitializeRuntime()
{
if (_initialized) return;
_initialized = true;
_services.LockCoordinator.LockStateChanged += LockCoordinator_LockStateChanged;
LoadSettings(_services.Settings);
StartupWarningBar.Message = _services.StartupWarning;
StartupWarningBar.IsOpen = _services.StartupWarning is not null;
RefreshUsbList();
UpdateStatus(_services.LockCoordinator.IsLocked);
// Settings and controls are fully initialized before policy evaluation is armed.
// This avoids locking from stale pre-launch idle time during startup.
_services.LockCoordinator.Arm();
}
/// <summary>Allows the application to close the shell during an explicit exit.</summary>
public void AllowClose() => _allowClose = true;
public void ShowShell()
{
if (_windowHandle == IntPtr.Zero)
_windowHandle = WindowNative.GetWindowHandle(this);
ShowWindow(_windowHandle, SwShow);
// Reserve the WMI-backed device scan for the time the list is actually visible.
if (!_usbTimer.IsRunning) _usbTimer.Start();
RefreshUsbList();
UpdateBluetoothRefreshState();
}
public void HideShell()
{
// Nothing in the shell is observable while it is hidden; stop the periodic
// scans instead of enumerating disks and refreshing a list nobody can see.
_usbTimer.Stop();
_bluetoothTimer.Stop();
if (_windowHandle == IntPtr.Zero)
_windowHandle = WindowNative.GetWindowHandle(this);
ShowWindow(_windowHandle, SwHide);
}
/// <summary>
/// Keeps the Bluetooth list live while it is on screen. Without this the list froze
/// when the ten-second scan ended: signal strength stopped updating and devices that
/// went out of range stayed listed. It refreshes only while the radio is actually
/// collecting data, i.e. during an explicit scan or under the Bluetooth policy.
/// </summary>
private void UpdateBluetoothRefreshState()
{
var visible = _windowHandle != IntPtr.Zero && IsWindowVisible(_windowHandle);
var radioActive = _bluetoothScanning
|| _services.Settings?.LockMode == LockMode.Bluetooth;
if (visible && radioActive)
{
if (!_bluetoothTimer.IsRunning) _bluetoothTimer.Start();
}
else
{
_bluetoothTimer.Stop();
}
}
/// <summary>Stops UI timers and event subscriptions before process teardown.</summary>
public void ShutdownResources()
{
if (_resourcesShutdown) return;
FlushPendingSettings();
_resourcesShutdown = true;
_usbTimer.Stop();
_bluetoothTimer.Stop();
_applyTimer.Stop();
if (_initialized)
_services.LockCoordinator.LockStateChanged -= LockCoordinator_LockStateChanged;
}
/// <summary>
/// Applies a pending text edit before teardown. The debounce timer is intentionally
/// short for normal typing, but stopping it during exit used to lose the final edit.
/// This method is safe to call more than once and is a no-op when the dispatcher is no
/// longer available.
/// </summary>
public void FlushPendingSettings()
{
if (_resourcesShutdown || !_initialized || !_applyTimer.IsRunning) return;
try
{
if (!DispatcherQueue.HasThreadAccess) return;
_applyTimer.Stop();
ApplyCurrentSettings();
}
catch
{
// Teardown must continue even if a last-chance save cannot be completed.
}
}
private void LoadSettings(AppSettings settings)
{
using var suppress = new SuppressScope(this);
_committedBluetoothAddress = settings.Bluetooth.DeviceAddress;
_committedUsbInstanceId = settings.Usb.DeviceInstanceId;
NoneRadio.IsChecked = settings.LockMode == LockMode.None;
BluetoothRadio.IsChecked = settings.LockMode == LockMode.Bluetooth;
UsbRadio.IsChecked = settings.LockMode == LockMode.Usb;
IdleRadio.IsChecked = settings.LockMode == LockMode.Idle;
BluetoothThresholdBox.Text = settings.Bluetooth.Threshold?.ToString() ?? string.Empty;
IdleMinutesBox.Text = settings.Idle.Minutes.ToString();
AutoStartCheckBox.IsChecked = settings.AutoStart;
UpdateModeUi(settings.LockMode);
SetSectionVisibility("Mode");
if (settings.LockMode == LockMode.Bluetooth) _ = RefreshBluetoothAsync();
}
private void SettingsNavigationView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (args.SelectedItem is NavigationViewItem item && item.Tag is string tag)
SetSectionVisibility(tag);
}
private void SettingsNavigationView_PaneOpening(NavigationView sender, object args)
{
UpdateNavigationPaneVisuals(isPaneOpen: true);
}
private void SettingsNavigationView_PaneClosing(NavigationView sender, object args)
{
UpdateNavigationPaneVisuals(isPaneOpen: false);
}
private void UpdateNavigationPaneVisuals(bool isPaneOpen)
{
// The header is useful only when the pane has enough room for its logo and text.
PaneHeader.Visibility = isPaneOpen ? Visibility.Visible : Visibility.Collapsed;
var itemMargins = isPaneOpen
? new[]
{
new Thickness(1, 3, 5, 0),
new Thickness(14, 0, 5, 0),
new Thickness(14, 0, 5, 0),
new Thickness(14, 0, 5, 0)
}
: new[]
{
new Thickness(1, 3, 1, 0),
new Thickness(1, 0, 1, 0),
new Thickness(1, 0, 1, 0),
new Thickness(1, 0, 1, 0)
};
var items = SettingsNavigationView.MenuItems.OfType<NavigationViewItem>().ToArray();
for (var i = 0; i < items.Length && i < itemMargins.Length; i++)
items[i].Margin = itemMargins[i];
var footerItems = SettingsNavigationView.FooterMenuItems.OfType<NavigationViewItem>().ToArray();
foreach (var item in footerItems)
item.Margin = isPaneOpen ? new Thickness(1, 0, 5, 7) : new Thickness(1, 0, 1, 7);
}
private void SetSectionVisibility(string tag)
{
if (ModeSection is null) return;
var sections = new (string Tag, FrameworkElement Element)[]
{
("Mode", ModeSection),
("Bluetooth", BluetoothPanel),
("Usb", UsbPanel),
("Idle", IdlePanel),
("General", GeneralSection)
};
foreach (var section in sections)
{
section.Element.Visibility = section.Tag == tag ? Visibility.Visible : Visibility.Collapsed;
if (section.Tag != tag)
{
section.Element.Opacity = 1;
section.Element.RenderTransform = null;
}
}
// Re-apply the enabled/disabled look before the transition runs, so the page settles
// at the right opacity. Previously the page animation forced opacity back to 1, which
// silently undid the dimming and left a page that looked active but ignored input.
var mode = GetSelectedMode();
RefreshSectionEnabledStates(mode);
var selected = sections.FirstOrDefault(section => section.Tag == tag).Element;
if (selected is not null)
BeginPageTransition(selected, IsSectionEnabled(tag, mode) ? 1 : DisabledSectionOpacity);
SettingsScrollViewer.ChangeView(null, 0, null);
}
/// <summary>
/// Applies the enabled look to every page. The inactive policy pages stay visible so the
/// user can see what else exists, but they are disabled and ignore both pointer and
/// keyboard input. This is the single source of truth for that state, so navigation
/// cannot leave a page looking active while it silently ignores input.
/// </summary>
private void RefreshSectionEnabledStates(LockMode mode)
{
ApplySectionEnabledState(BluetoothPanel, IsSectionEnabled("Bluetooth", mode));
ApplySectionEnabledState(UsbPanel, IsSectionEnabled("Usb", mode));
ApplySectionEnabledState(IdlePanel, IsSectionEnabled("Idle", mode));
}
/// <summary>
/// Dims a page and stops it accepting input.
/// </summary>
/// <remarks>
/// The state is applied to a ContentControl wrapper because <c>IsHitTestVisible=false</c>
/// only blocks the pointer: Tab focus still enters the controls of a page that is
/// supposed to be off, which let the keyboard reach an inactive policy. IsEnabled on the
/// wrapper disables the whole subtree for both input paths, and a descendant cannot
/// re-enable itself against a disabled ancestor, so a control's own busy state (the scan
/// button) is preserved rather than overwritten.
/// </remarks>
private static void ApplySectionEnabledState(ContentControl element, bool enabled)
{
element.IsEnabled = enabled;
element.Opacity = enabled ? 1 : DisabledSectionOpacity;
}
/// <summary>
/// Whether a page's controls are usable under the current mode. Only the page matching
/// the selected policy is interactive; the rest are shown dimmed.
/// </summary>
private static bool IsSectionEnabled(string tag, LockMode mode) => tag switch
{
"Bluetooth" => mode == LockMode.Bluetooth,
"Usb" => mode == LockMode.Usb,
"Idle" => mode == LockMode.Idle,
// The mode selector and the general settings apply regardless of the chosen policy.
_ => true
};
/// <summary>
/// True when the user has asked Windows to minimise animation. Movement is then
/// replaced by a short opacity change so the state change is still legible.
/// </summary>
private static bool AnimationsDisabled
{
get
{
try { return !new Windows.UI.ViewManagement.UISettings().AnimationsEnabled; }
catch { return false; }
}
}
/// <summary>
/// Fades and slides a page in. <paramref name="settledOpacity"/> is the opacity the page
/// must end at, which is not always 1: an inactive policy page is dimmed to show it is
/// disabled, and forcing 1 here silently un-dimmed it on every navigation.
/// </summary>
private static void BeginPageTransition(FrameworkElement element, double settledOpacity)
{
// Reduced motion keeps the cross-fade (which aids comprehension) but drops the
// slide, so the page change is not a sudden teleport either way.
var travel = AnimationsDisabled ? 0 : 10;
var translate = new TranslateTransform { X = 0, Y = travel };
element.RenderTransform = translate;
element.Opacity = 0;
var storyboard = new Storyboard();
var fade = new DoubleAnimation
{
From = 0,
To = settledOpacity,
Duration = TimeSpan.FromMilliseconds(180),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(fade, element);
Storyboard.SetTargetProperty(fade, "Opacity");
// An 18px / 320ms slide read as "flying in" rather than settling; a short
// 200ms rise inside the 300ms UI budget feels like the content arriving.
if (travel > 0)
{
var slide = new DoubleAnimation
{
From = travel,
To = 0,
Duration = TimeSpan.FromMilliseconds(200),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(slide, translate);
Storyboard.SetTargetProperty(slide, "Y");
storyboard.Children.Add(slide);
}
storyboard.Children.Add(fade);
storyboard.Completed += (_, _) =>
{
element.Opacity = settledOpacity;
element.RenderTransform = null;
};
storyboard.Begin();
}
private void NavigationItem_PointerEntered(object sender, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e)
{
if (sender is FrameworkElement element)
AnimateNavigationItem(element, 2);
}
private void NavigationItem_PointerExited(object sender, Microsoft.UI.Xaml.Input.PointerRoutedEventArgs e)
{
if (sender is FrameworkElement element)
AnimateNavigationItem(element, 0);
}
private static void AnimateNavigationItem(FrameworkElement element, double target)
{
// Navigation is a tens-of-times-a-day interaction, so the hover nudge stays
// barely perceptible (2px) and is skipped entirely when motion is reduced.
if (AnimationsDisabled)
{
if (element.RenderTransform is TranslateTransform existing)
existing.X = 0;
return;
}
var translate = element.RenderTransform as TranslateTransform;
if (translate is null)
{
translate = new TranslateTransform();
element.RenderTransform = translate;
}
var storyboard = new Storyboard();
var animation = new DoubleAnimation
{
To = target,
Duration = TimeSpan.FromMilliseconds(140),
EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut }
};
Storyboard.SetTarget(animation, translate);
Storyboard.SetTargetProperty(animation, "X");
storyboard.Children.Add(animation);
storyboard.Begin();
}
private void Mode_Checked(object sender, RoutedEventArgs e)
{
if (!_initialized || _suppressAutoSave) return;
var mode = sender switch
{
RadioButton { Tag: "Bluetooth" } => LockMode.Bluetooth,
RadioButton { Tag: "Usb" } => LockMode.Usb,
RadioButton { Tag: "Idle" } => LockMode.Idle,
_ => LockMode.None
};
// The radio changes before the policy is validated, so remember what is actually in
// effect. If the edit is rejected (an invalid field for the newly chosen policy), the
// selection has to go back: leaving it on a mode the coordinator never adopted makes
// the UI claim a lock condition that is not running.
var committedMode = _services.Settings?.LockMode ?? LockMode.None;
UpdateModeUi(mode);
if (mode == LockMode.Bluetooth) _ = RefreshBluetoothAsync();
if (ApplyCurrentSettings()) return;
using (new SuppressScope(this))
SetModeRadio(committedMode);
UpdateModeUi(committedMode);
}
private void SetModeRadio(LockMode mode)
{
NoneRadio.IsChecked = mode == LockMode.None;
BluetoothRadio.IsChecked = mode == LockMode.Bluetooth;
UsbRadio.IsChecked = mode == LockMode.Usb;
IdleRadio.IsChecked = mode == LockMode.Idle;
}
private void UpdateModeUi(LockMode mode)
{
// Enabled/disabled appearance lives in one place so navigation animations and mode
// changes cannot drift apart.
RefreshSectionEnabledStates(mode);
// A selected policy with no device is a no-op at runtime, which looks identical
// to a working one. Surface the missing prerequisite instead of implying it works.
var source = _services.Settings;
var missingDevice = mode switch
{
LockMode.Bluetooth => string.IsNullOrWhiteSpace(_selectedBluetooth?.Address ?? source?.Bluetooth?.DeviceAddress),
LockMode.Usb => string.IsNullOrWhiteSpace(_selectedUsb?.InstanceId ?? source?.Usb?.DeviceInstanceId),
_ => false
};
BluetoothSelectionSummary.Visibility = mode == LockMode.Bluetooth ? Visibility.Visible : Visibility.Collapsed;
if (mode == LockMode.Bluetooth)
{
// Keep the summary accurate even before a scan runs, so a configured device is
// stated on startup rather than leaving the note blank. It only reports what is
// currently bound, which is empty until the first scan.
var configured = _selectedBluetooth?.Address ?? _services.Settings?.Bluetooth?.DeviceAddress;
UpdateBluetoothSelectionSummary(configured);
}
// Switching modes changes whether the radio should be feeding the list.
UpdateBluetoothRefreshState();
if (mode != LockMode.None && missingDevice)
{
ModeHintBar.Severity = InfoBarSeverity.Warning;
ModeHintBar.Title = "还需要选择设备";
ModeHintBar.Message = mode == LockMode.Bluetooth
? "选择一个蓝牙设备后该策略才会生效。"
: "选择一个 U 盘后该策略才会生效。";
return;
}
var hint = mode == LockMode.None ? "未启用自动锁定" : mode switch
{
LockMode.Bluetooth => "检测不到设备或 RSSI 低于阈值时锁定",
LockMode.Usb => "指定 U 盘拔出时锁定",
LockMode.Idle => "空闲达到阈值时锁定",
_ => string.Empty
};
ModeHintBar.Severity = InfoBarSeverity.Informational;
ModeHintBar.Title = mode == LockMode.None ? "未启用自动锁定" : "当前策略已选择";
ModeHintBar.Message = hint;
}
private async void RefreshBluetooth_Click(object sender, RoutedEventArgs e) => await RefreshBluetoothAsync();
private async Task RefreshBluetoothAsync()
{
// A scan runs for ten seconds; ignore repeat clicks instead of starting
// overlapping timers and watcher stop/start cycles.
if (_bluetoothScanning) return;
_bluetoothScanning = true;
RefreshBluetoothButton.IsEnabled = false;
// Ten seconds of a dead button reads as a hang; show that scanning is underway.
BluetoothScanRing.IsActive = true;
BluetoothScanRing.Visibility = Visibility.Visible;
BluetoothScanIcon.Visibility = Visibility.Collapsed;
try
{
_services.LockCoordinator.Bluetooth.Start();
// Drive the live list through the shared helper so the timer is started only
// when the page is actually visible.
UpdateBluetoothRefreshState();
RefreshBluetoothList();
await Task.Delay(TimeSpan.FromSeconds(10));
}
catch
{
// A scan is best-effort; the list simply stays as it was.
}
finally
{
_bluetoothScanning = false;
RefreshBluetoothButton.IsEnabled = true;
BluetoothScanRing.IsActive = false;
BluetoothScanRing.Visibility = Visibility.Collapsed;
BluetoothScanIcon.Visibility = Visibility.Visible;
// Release the radio unless the active policy keeps using it.
if (_services.Settings?.LockMode != LockMode.Bluetooth)
_services.LockCoordinator.Bluetooth.Stop();
// Keep the list live only while something is still feeding it data.
UpdateBluetoothRefreshState();
}
}
private void RefreshBluetoothList()
{
var observations = _services.LockCoordinator.Bluetooth.Snapshot();
using var suppress = new SuppressScope(this);
// Rows are reconciled against the existing bound objects rather than replacing
// the whole ItemsSource, so selection and scroll position survive each refresh.
// The monitor returns plain observations; the bound objects are updated here on
// the UI thread, which is where property-change notifications must originate.
if (BluetoothList.ItemsSource is not ObservableCollection<BluetoothDeviceInfo> bound)
{
bound = new ObservableCollection<BluetoothDeviceInfo>();
BluetoothList.ItemsSource = bound;
}
var byAddress = bound.ToDictionary(d => d.Address, StringComparer.OrdinalIgnoreCase);
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var observation in observations)
{
seen.Add(observation.Address);
if (byAddress.TryGetValue(observation.Address, out var existing))
{
if (observation.Name is not null) existing.Name = observation.Name;
existing.Rssi = observation.Rssi;
existing.IsPaired = observation.IsPaired;
existing.Connected = observation.IsConnected;
existing.IsRandomAddress = observation.IsRandomAddress;
}
else
{
var device = new BluetoothDeviceInfo
{
Address = observation.Address,
Rssi = observation.Rssi,
IsPaired = observation.IsPaired,
Connected = observation.IsConnected,
IsRandomAddress = observation.IsRandomAddress
};
if (observation.Name is not null) device.Name = observation.Name;
byAddress[observation.Address] = device;
bound.Add(device);
}
}
// Drop rows that have aged out of the monitor's listing window.
for (var i = bound.Count - 1; i >= 0; i--)
if (!seen.Contains(bound[i].Address))
bound.RemoveAt(i);
BluetoothEmptyState.Visibility = bound.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
var selected = _selectedBluetooth?.Address ?? _services.Settings?.Bluetooth?.DeviceAddress;
if (!string.IsNullOrWhiteSpace(selected)
&& byAddress.TryGetValue(selected, out var matching)
&& !ReferenceEquals(BluetoothList.SelectedItem, matching))
{
BluetoothList.SelectedItem = matching;
_selectedBluetooth = matching;
}
UpdateBluetoothSelectionSummary(selected);
}
/// <summary>
/// Explains the current selection relative to the unlock condition. The list holds
/// devices seen recently, which is a wider window than the presence test the policy
/// uses, so this asks the monitor for the authoritative answer rather than inferring
/// from the list.
/// </summary>
private void UpdateBluetoothSelectionSummary(string? configuredAddress)
{
if (string.IsNullOrWhiteSpace(configuredAddress))
{
BluetoothSelectionSummary.Text = "当前未选择设备,该策略不会生效。";
BluetoothThresholdHintBar.IsOpen = false;
return;
}
var monitor = _services.LockCoordinator.Bluetooth;
// A rotating privacy address cannot be tracked, so selecting one produces a lock
// that repeatedly engages and releases. Say so plainly instead of letting the user
// chase an unexplainable flicker.
if (monitor.IsUnstableIdentity(configuredAddress))
{
BluetoothSelectionSummary.Text = "该设备使用随机蓝牙地址,无法持续识别,会导致反复锁定与解锁。请改选已配对的设备,或已打开蓝牙的耳机 / 手机等固定地址设备。";
BluetoothThresholdHintBar.IsOpen = false;
return;
}
var label = _selectedBluetooth is not null
&& string.Equals(_selectedBluetooth.Address, configuredAddress, StringComparison.OrdinalIgnoreCase)
? $"{_selectedBluetooth.Name}({configuredAddress})"
: configuredAddress;
var threshold = _services.Settings?.Bluetooth?.Threshold;
// A threshold on hardware that never reports RSSI cannot be measured. Warn rather
// than let the user believe a proximity rule is being enforced.
BluetoothThresholdHintBar.IsOpen = threshold is not null && !monitor.SupportsRssi(configuredAddress);
if (BluetoothThresholdHintBar.IsOpen)
{
BluetoothThresholdHintBar.Message = monitor.IsPaired(configuredAddress)
? "该设备是经典蓝牙设备,Windows 不提供其信号强度,因此阈值不会生效;此时以连接状态判断是否在范围内。"
: "尚未读到该设备的信号强度,阈值暂时无法生效;请确认设备正在广播。";
}
var thresholdActive = threshold is int;
var status = _services.LockCoordinator.BluetoothStatus;
var manualOverride = _services.LockCoordinator.ManualUnlockOverride == LockReason.Bluetooth;
// A manual unlock is held until the device is next seen healthy. Reporting the
// ordinary verdict in that state would claim "will lock" while the policy is
// deliberately not re-engaging.
if (manualOverride && status.Presence != BluetoothPresence.Present)
{
BluetoothSelectionSummary.Text = $"已选择:{label},已手动解锁,设备重新被检测到之前不会重复锁定。";
return;
}
switch (status.Presence)
{
case BluetoothPresence.Present:
BluetoothSelectionSummary.Text = status.Reason switch
{
BluetoothReason.SignalAboveThreshold => $"已选择:{label},信号高于或等于阈值 {threshold} dBm,保持解锁。",
BluetoothReason.Connected => $"已选择:{label},设备已连接,保持解锁。",
_ => thresholdActive && monitor.SupportsRssi(configuredAddress)
? $"已选择:{label},信号在阈值附近,按上次判定保持解锁。"
: $"已选择:{label},当前在范围内,保持解锁。"
};
break;
case BluetoothPresence.Absent:
// The monitor reports why it decided this. "Connected but too weak" and
// "not connected" both read as Absent, but they describe opposite situations
// and the user would act on them differently.
BluetoothSelectionSummary.Text = status.Reason switch
{
BluetoothReason.SignalBelowThreshold =>
$"已选择:{label},信号低于阈值 {threshold} dBm,将保持锁定。",
BluetoothReason.NoRecentSignal =>
$"已选择:{label},已有一段时间没有读到信号,将保持锁定。",
BluetoothReason.NeverObserved =>
$"已选择:{label},附近没有检测到该设备,将保持锁定。",
BluetoothReason.NotConnected when monitor.IsPaired(configuredAddress) =>
$"已选择:{label},设备未连接(可能已关机或休眠),将保持锁定。",
_ => thresholdActive
? $"已选择:{label},信号低于阈值 {threshold} dBm,将保持锁定。"
: $"已选择:{label},当前不在范围内,将保持锁定。"
};
break;
default:
BluetoothSelectionSummary.Text = status.Reason == BluetoothReason.ScanIncomplete || !monitor.HasScanned
// Not the same as "away": the radio may simply not have produced data yet,
// and saying "out of range" here would be wrong and alarming.
? $"已选择:{label},等待扫描以确认状态。"
: $"已选择:{label},暂时没有读到信号,锁定状态保持不变。";
break;
}
}
private void BluetoothList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_suppressAutoSave) return;
if (BluetoothList.SelectedItem is not BluetoothDeviceInfo selected) return;
// Rotating privacy addresses cannot be used as a stable credential. Reject the
// selection immediately and restore the last value that was actually persisted.
if (!selected.IsStable || _services.LockCoordinator.Bluetooth.IsUnstableIdentity(selected.Address))
{
ShowError("无法选择随机蓝牙地址。请改选已配对的设备或固定地址设备。");
RestoreBluetoothSelection();
return;
}
_selectedBluetooth = selected;
if (!ApplyCurrentSettings())
RestoreBluetoothSelection();
}
private void RefreshUsb_Click(object sender, RoutedEventArgs e) => RefreshUsbList();
private async void RefreshUsbList()
{
// Enumerating removable disks touches DriveInfo and WMI; keep it off the UI
// thread so the settings page never stalls behind a slow provider.
if (_usbRefreshRunning) return;
_usbRefreshRunning = true;
try
{
var devices = await Task.Run(() => _services.LockCoordinator.Usb.Scan());
ApplyUsbDevices(devices);
}
catch
{
// A failed scan leaves the previous list in place.
}
finally
{
_usbRefreshRunning = false;
}
}
private void ApplyUsbDevices(IReadOnlyList<UsbDeviceInfo> devices)
{
if (_resourcesShutdown) return;
var signature = string.Join('\u001f', devices.Select(d => $"{d.DriveLetter}|{d.Name}|{d.InstanceId}"));
var selected = !string.IsNullOrWhiteSpace(_selectedUsb?.InstanceId)
? _selectedUsb.InstanceId
: _services.Settings?.Usb?.DeviceInstanceId;
using var suppress = new SuppressScope(this);
if (signature != _usbSignature)
{
_usbSignature = signature;
UsbList.ItemsSource = devices;
}
UsbEmptyState.Visibility = devices.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
if (!string.IsNullOrWhiteSpace(selected))
{
// Restore the selection from the list that is actually bound. A scan returns
// brand-new instances, so searching the fresh collection can pick an object that
// is not in the ItemsSource and the selection would silently fail to appear.
var bound = UsbList.ItemsSource as IEnumerable<UsbDeviceInfo> ?? devices;
var matching = bound.FirstOrDefault(d =>
string.Equals(d.InstanceId, selected, StringComparison.OrdinalIgnoreCase)
|| d.Identifiers.Contains(selected, StringComparer.OrdinalIgnoreCase));
if (matching is not null && !ReferenceEquals(UsbList.SelectedItem, matching))
{
UsbList.SelectedItem = matching;
_selectedUsb = matching;
UsbIdText.Text = $"实例 ID:{matching.InstanceId}";
}
}
}
private void UsbList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (_suppressAutoSave) return;
if (UsbList.SelectedItem is not UsbDeviceInfo selected) return;
if (string.IsNullOrWhiteSpace(selected.InstanceId))
{
ShowError("该设备没有可验证的硬件标识,不能用作锁定凭证。请重新插入设备或选择其他设备。");
RestoreUsbSelection();
return;
}
_selectedUsb = selected;
UsbIdText.Text = $"实例 ID:{selected.InstanceId}";
if (!ApplyCurrentSettings())
RestoreUsbSelection();
}
private void RestoreBluetoothSelection()
{
var address = _committedBluetoothAddress;
using var suppress = new SuppressScope(this);
_selectedBluetooth = null;
BluetoothList.SelectedItem = null;
if (!string.IsNullOrWhiteSpace(address)
&& BluetoothList.ItemsSource is IEnumerable<BluetoothDeviceInfo> devices)
{
var matching = devices.FirstOrDefault(d =>
string.Equals(d.Address, address, StringComparison.OrdinalIgnoreCase));
if (matching is not null)
{
_selectedBluetooth = matching;
BluetoothList.SelectedItem = matching;
}
}
UpdateBluetoothSelectionSummary(address);
}
private void RestoreUsbSelection()
{
var instanceId = _committedUsbInstanceId;
using var suppress = new SuppressScope(this);
_selectedUsb = null;
UsbList.SelectedItem = null;
if (!string.IsNullOrWhiteSpace(instanceId)
&& UsbList.ItemsSource is IEnumerable<UsbDeviceInfo> devices)
{
var matching = devices.FirstOrDefault(d =>
string.Equals(d.InstanceId, instanceId, StringComparison.OrdinalIgnoreCase)
|| d.Identifiers.Contains(instanceId, StringComparer.OrdinalIgnoreCase));
if (matching is not null)
{
_selectedUsb = matching;
UsbList.SelectedItem = matching;
UsbIdText.Text = $"实例 ID:{matching.InstanceId}";
}
}
if (_selectedUsb is null)
UsbIdText.Text = string.Empty;
}
private void BluetoothThresholdBox_TextChanged(object sender, TextChangedEventArgs e) => ScheduleApply();
private void IdleMinutesBox_TextChanged(object sender, TextChangedEventArgs e) => ScheduleApply();
private void AutoStartCheckBox_Changed(object sender, RoutedEventArgs e)
{
if (!_initialized || _suppressAutoSave) return;
if (ApplyCurrentSettings()) return;
using var suppress = new SuppressScope(this);
AutoStartCheckBox.IsChecked = _services.Settings.AutoStart;
}
private void RetrySettings_Click(object sender, RoutedEventArgs e) => ApplyCurrentSettings();
/// <summary>
/// Coalesces keystroke-driven edits into a single apply. Typing "-70" would
/// otherwise persist the config and restart the Bluetooth watcher three times.
/// </summary>
private void ScheduleApply()
{
if (!_initialized || _suppressAutoSave) return;
_applyTimer.Stop();
_applyTimer.Start();
}
/// <summary>
/// Validates, persists and applies the current editor state.
/// </summary>
/// <returns>
/// True when the settings were accepted and applied. False means the edit was rejected
/// (invalid field for the active policy) and the caller must not present it as applied.
/// </returns>
private bool ApplyCurrentSettings()
{
if (!_initialized || _suppressAutoSave) return false;
// A pending keystroke apply is now redundant.
_applyTimer.Stop();
var source = _services.Settings ?? new AppSettings();
var mode = GetSelectedMode();
// Keep a valid persisted value when an inactive text field is being edited.
// The active policy still requires its field to be valid before applying.
var threshold = source.Bluetooth.Threshold;
if (TryParseThreshold(out var parsedThreshold))
threshold = parsedThreshold;
else if (mode == LockMode.Bluetooth)
return false;
var bluetoothAddress = _selectedBluetooth?.Address ?? source.Bluetooth.DeviceAddress;
if (mode == LockMode.Bluetooth
&& !string.IsNullOrWhiteSpace(bluetoothAddress)
&& _services.LockCoordinator.Bluetooth.IsUnstableIdentity(bluetoothAddress))
{