Repository navigation
Expand file tree
/
Copy pathMainWindow.cs
More file actions
1788 lines (1655 loc) · 62.5 KB
/
Copy pathMainWindow.cs
File metadata and controls
1788 lines (1655 loc) · 62.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
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.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;
using Microsoft.Win32;
using Forms = System.Windows.Forms;
namespace DesktopNest
{
/// <summary>
/// Coordinates the small desktop-level organizer windows. It deliberately
/// owns no large dashboard window and performs no filesystem polling or AI
/// work while the desktop icon set is idle.
/// </summary>
internal sealed class DesktopHostController : IDisposable
{
private sealed class LayoutGeometrySnapshot
{
public BoxLayoutSetting Layout;
public double Left;
public double Top;
public double Width;
public double Height;
public double ExpandedHeight;
public void Restore()
{
Layout.Left = Left;
Layout.Top = Top;
Layout.Width = Width;
Layout.Height = Height;
Layout.ExpandedHeight = ExpandedHeight;
}
}
private static readonly string[] BoxOrder =
OrganizerCategories.GetIds();
private const double LayoutGap = 14.0;
private const double SnapThreshold = 12.0;
private readonly string _desktopPath;
private readonly bool _noStartupWrite;
private readonly bool _qaMode;
private readonly AppSettings _settings;
private readonly DesktopIndexService _desktopIndex;
private readonly DesktopIndexService _publicDesktopIndex;
private readonly ClassificationCatalog _catalog;
private readonly AiClassificationService _aiService;
private readonly Dictionary<string, OrganizerBoxWindow> _boxes =
new Dictionary<string, OrganizerBoxWindow>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DesktopItem> _snapshot =
new Dictionary<string, DesktopItem>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, DesktopItem> _pendingAi =
new Dictionary<string, DesktopItem>(StringComparer.OrdinalIgnoreCase);
private readonly object _aiSync = new object();
private readonly DispatcherTimer _layoutSaveTimer;
private readonly DispatcherTimer _displayChangeTimer;
private readonly DispatcherTimer _desktopWindowRecoveryTimer;
private readonly HashSet<string> _pendingOrganizerRecovery =
new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private UtilityBoxWindow _utilityBox;
private Forms.NotifyIcon _trayIcon;
private Forms.ToolStripMenuItem _takeoverMenuItem;
private Forms.ToolStripMenuItem _startupMenuItem;
private Forms.ToolStripMenuItem _visibilityMenuItem;
private Icon _trayDrawingIcon;
private DesktopLayerCoordinator _desktopLayerCoordinator;
private bool _started;
private bool _disposed;
private bool _exiting;
private bool _boxesVisible = true;
private bool _aiWorkerRunning;
private bool _initialSnapshotPending = true;
private bool _desktopIconsWereVisible;
private bool _desktopIconsVisibilityKnown;
private bool _desktopIconsHiddenByUs;
private bool _utilityWindowPendingRecovery;
private bool _desktopActivationGuard;
private bool _systemEventsSubscribed;
private bool _layoutBatchInProgress;
private bool _displayRepairPending;
private bool _displayRepairChanged;
private bool _saveSettingsAfterDisplayRepair;
private int _displayChangeRepairPass;
private int _desktopWindowRecoveryAttempts;
private DateTime _lastAiFailureNoticeUtc = DateTime.MinValue;
private string _lastDisplaySignature = String.Empty;
public DesktopHostController(string desktopPath, bool noStartupWrite, bool qaMode)
{
_desktopPath = desktopPath;
_noStartupWrite = noStartupWrite;
_qaMode = qaMode;
_settings = qaMode ? AppSettings.CreateQaSettings() : AppSettings.Load();
_desktopIndex = new DesktopIndexService(desktopPath);
_publicDesktopIndex = CreatePublicDesktopIndex(desktopPath);
_catalog = qaMode ? ClassificationCatalog.CreateEmpty() : ClassificationCatalog.Load();
_aiService = new AiClassificationService();
_layoutSaveTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMilliseconds(450)
};
_layoutSaveTimer.Tick += delegate
{
_layoutSaveTimer.Stop();
SaveSettings();
};
_displayChangeTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(650)
};
_displayChangeTimer.Tick += OnDisplayChangeSettled;
_desktopWindowRecoveryTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(250)
};
_desktopWindowRecoveryTimer.Tick += RecoverDestroyedDesktopWindows;
}
public void Start()
{
if (_started)
{
return;
}
_started = true;
_lastDisplaySignature = CaptureDisplaySignature();
if (!_qaMode)
{
try
{
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
_systemEventsSubscribed = true;
}
catch
{
_systemEventsSubscribed = false;
}
}
if (!_qaMode)
{
RecoverStaleTakeoverLease();
}
ApplyDefaultLayout();
if (!_qaMode)
{
_desktopLayerCoordinator = new DesktopLayerCoordinator(
Application.Current.Dispatcher,
SendAllWindowsToDesktop,
IsDesktopLayerSettled,
DesktopWindowBehavior.MoveForegroundToDesktopIfOrganizer,
SetDesktopActivationGuard);
}
CreateOrganizerWindows();
CreateTrayIcon();
ImportProjectApiKeys();
RefreshDesktop(false);
_desktopIndex.ItemsChanged += OnDesktopItemsChanged;
_desktopIndex.StartWatching();
if (_publicDesktopIndex != null)
{
_publicDesktopIndex.ItemsChanged += OnDesktopItemsChanged;
_publicDesktopIndex.StartWatching();
}
if (!_noStartupWrite && _settings.StartWithWindows)
{
StartupService.TryEnable();
}
if (!_qaMode && _settings.TakeOverDesktopIcons)
{
SetDesktopIconTakeover(true);
}
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle,
new Action(delegate
{
ReflowOrganizerWindows(false, false, true);
SendAllWindowsToDesktop();
ShowFirstRunTakeoverChoice();
if (_desktopLayerCoordinator != null)
{
_desktopLayerCoordinator.RequestRepair();
}
}));
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
if (_desktopLayerCoordinator != null)
{
_desktopLayerCoordinator.Dispose();
_desktopLayerCoordinator = null;
}
DesktopWindowBehavior.ReleaseZOrderMarker();
_layoutSaveTimer.Stop();
_displayChangeTimer.Stop();
_desktopWindowRecoveryTimer.Stop();
if (_systemEventsSubscribed)
{
try
{
SystemEvents.DisplaySettingsChanged -= OnDisplaySettingsChanged;
}
catch
{
}
_systemEventsSubscribed = false;
}
_pendingOrganizerRecovery.Clear();
_utilityWindowPendingRecovery = false;
RestoreDesktopIconsIfNeeded();
SaveCatalog();
SaveSettings();
_desktopIndex.ItemsChanged -= OnDesktopItemsChanged;
_desktopIndex.Dispose();
if (_publicDesktopIndex != null)
{
_publicDesktopIndex.ItemsChanged -= OnDesktopItemsChanged;
_publicDesktopIndex.Dispose();
}
foreach (OrganizerBoxWindow window in _boxes.Values)
{
window.SetControllerClosing();
window.Close();
}
_boxes.Clear();
if (_utilityBox != null)
{
_utilityBox.SetControllerClosing();
_utilityBox.Close();
_utilityBox = null;
}
if (_trayIcon != null)
{
_trayIcon.Visible = false;
_trayIcon.Dispose();
_trayIcon = null;
}
if (_trayDrawingIcon != null)
{
_trayDrawingIcon.Dispose();
_trayDrawingIcon = null;
}
}
private void CreateOrganizerWindows()
{
CreateUtilityWindow();
}
private void CreateUtilityWindow()
{
if (_utilityBox != null)
{
return;
}
UtilityBoxWindow window = new UtilityBoxWindow(
_settings.UtilityBox,
_settings.BoxOpacity);
window.DesktopPinEnabled = !_qaMode;
window.Loaded += OnDesktopWindowLoaded;
window.LayoutChanged += OnLayoutChanged;
window.MoveCompleted += OnWindowMoveCompleted;
window.SettingsRequested += delegate { ShowSettings(); };
window.Closed += delegate
{
if (_qaMode && !_disposed && !_exiting)
{
ExitApplication();
return;
}
if (!_disposed && !_exiting && ReferenceEquals(_utilityBox, window))
{
_utilityBox = null;
_utilityWindowPendingRecovery = true;
RequestDesktopWindowRecovery();
}
};
_utilityBox = window;
if (_boxesVisible && _settings.UtilityBox.Visible)
{
window.Show();
}
}
private void ImportProjectApiKeys()
{
if (_qaMode)
{
return;
}
ApiKeyImportResult result = SecretStore.ImportProjectKeys();
if (!String.IsNullOrWhiteSpace(result.Warning))
{
ShowTrayMessage("API 密钥导入提示", result.Warning, Forms.ToolTipIcon.Warning);
}
else if (result.ImportedCount > 0 && result.PlaintextCleared)
{
ShowTrayMessage(
"API 密钥导入完成",
"密钥已保存到 Windows 凭据管理器,导入文件中对应等号后的内容已清空。",
Forms.ToolTipIcon.Info);
}
}
private OrganizerBoxWindow EnsureOrganizerWindow(string boxId)
{
OrganizerBoxWindow existing;
if (_boxes.TryGetValue(boxId, out existing))
{
return existing;
}
BoxLayoutSetting layout = _settings.FindBox(boxId);
bool assignedDefaultPosition = false;
if (Double.IsNaN(layout.Left) || Double.IsNaN(layout.Top))
{
System.Windows.Point position = FindAvailableBoxPosition(layout);
layout.Left = position.X;
layout.Top = position.Y;
assignedDefaultPosition = true;
}
OrganizerBoxWindow window = new OrganizerBoxWindow(layout, _settings.BoxOpacity);
window.DesktopPinEnabled = !_qaMode;
window.Loaded += OnDesktopWindowLoaded;
window.LayoutChanged += OnLayoutChanged;
window.RenameRequested += OnLayoutChanged;
window.OrganizeRequested += delegate { RefreshDesktop(true); };
window.RearrangeRequested += delegate
{
ReflowOrganizerWindows(true, true, true);
};
window.SettingsRequested += delegate { ShowSettings(); };
window.ExitRequested += delegate { ExitApplication(); };
window.ItemMoveRequested += OnItemMoveRequested;
window.MoveCompleted += OnWindowMoveCompleted;
string windowBoxId = layout.Id;
window.Closed += delegate
{
if (_qaMode && !_disposed && !_exiting)
{
ExitApplication();
return;
}
OrganizerBoxWindow current;
if (!_disposed &&
!_exiting &&
_boxes.TryGetValue(windowBoxId, out current) &&
ReferenceEquals(current, window))
{
_boxes.Remove(windowBoxId);
_pendingOrganizerRecovery.Add(windowBoxId);
RequestDesktopWindowRecovery();
}
};
_boxes[layout.Id] = window;
if (_boxesVisible && layout.Visible)
{
window.Show();
if (_desktopLayerCoordinator != null)
{
_desktopLayerCoordinator.RequestRepair();
}
}
if (assignedDefaultPosition)
{
OnLayoutChanged(window, EventArgs.Empty);
}
return window;
}
private void CreateTrayIcon()
{
_trayIcon = new Forms.NotifyIcon();
try
{
_trayDrawingIcon = Icon.ExtractAssociatedIcon(StartupService.GetExecutablePath());
_trayIcon.Icon = _trayDrawingIcon;
}
catch
{
_trayIcon.Icon = SystemIcons.Application;
}
_trayIcon.Text = "拾光桌面 · 桌面收纳盒";
Forms.ContextMenuStrip menu = new Forms.ContextMenuStrip();
Forms.ToolStripMenuItem organize = new Forms.ToolStripMenuItem("立即整理桌面");
organize.Click += delegate { RefreshDesktop(true); };
menu.Items.Add(organize);
Forms.ToolStripMenuItem rearrange = new Forms.ToolStripMenuItem("自动排列收纳盒");
rearrange.Click += delegate
{
ReflowOrganizerWindows(true, true, true);
};
menu.Items.Add(rearrange);
_visibilityMenuItem = new Forms.ToolStripMenuItem("隐藏收纳盒");
_visibilityMenuItem.Click += delegate { ToggleOrganizerVisibility(); };
menu.Items.Add(_visibilityMenuItem);
menu.Items.Add(new Forms.ToolStripSeparator());
_takeoverMenuItem = new Forms.ToolStripMenuItem("接管系统桌面图标");
_takeoverMenuItem.Checked = _settings.TakeOverDesktopIcons;
_takeoverMenuItem.CheckOnClick = true;
_takeoverMenuItem.Click += delegate
{
SetDesktopIconTakeover(_takeoverMenuItem.Checked);
};
menu.Items.Add(_takeoverMenuItem);
_startupMenuItem = new Forms.ToolStripMenuItem("开机自动启动");
_startupMenuItem.Checked = _settings.StartWithWindows;
_startupMenuItem.CheckOnClick = true;
_startupMenuItem.Click += delegate
{
_settings.StartWithWindows = _startupMenuItem.Checked;
if (!_noStartupWrite)
{
StartupService.SetEnabled(_settings.StartWithWindows);
}
SaveSettings();
};
menu.Items.Add(_startupMenuItem);
Forms.ToolStripMenuItem settings = new Forms.ToolStripMenuItem("设置…");
settings.Click += delegate { ShowSettings(); };
menu.Items.Add(settings);
Forms.ToolStripMenuItem restore = new Forms.ToolStripMenuItem("恢复系统桌面图标");
restore.Click += delegate
{
if (DesktopIconVisibilityService.TrySetVisible(true))
{
DeleteTakeoverLease();
_desktopIconsHiddenByUs = false;
_desktopIconsVisibilityKnown = false;
_settings.TakeOverDesktopIcons = false;
_takeoverMenuItem.Checked = false;
SaveSettings();
RefreshDesktop(false);
}
else
{
ShowTrayMessage("恢复失败", "Explorer 当前没有响应;恢复记录已保留,请稍后重试。", Forms.ToolTipIcon.Warning);
}
};
menu.Items.Add(restore);
menu.Items.Add(new Forms.ToolStripSeparator());
Forms.ToolStripMenuItem exit = new Forms.ToolStripMenuItem("退出拾光桌面");
exit.Click += delegate { ExitApplication(); };
menu.Items.Add(exit);
_trayIcon.ContextMenuStrip = menu;
_trayIcon.DoubleClick += delegate { ToggleOrganizerVisibility(); };
_trayIcon.Visible = !_qaMode;
}
private void RefreshDesktop(bool allowAiForAllUncertain)
{
if (_disposed)
{
return;
}
bool isInitialSnapshot = _initialSnapshotPending;
_initialSnapshotPending = false;
IList<DesktopItem> items = ScanAllDesktopItems();
List<DesktopItem> added = new List<DesktopItem>();
int index;
for (index = 0; index < items.Count; index++)
{
DesktopItem item = items[index];
if (!_snapshot.ContainsKey(item.FullPath))
{
added.Add(item);
}
}
_snapshot.Clear();
for (index = 0; index < items.Count; index++)
{
_snapshot[items[index].FullPath] = items[index];
}
_catalog.RemoveMissing(items);
RenderBoxes(items);
// On the first snapshot, queue only uncached uncertain items. The
// catalog check inside QueueAiClassification makes this a one-time
// upgrade/startup analysis rather than a cost on every boot.
IList<DesktopItem> aiCandidates =
isInitialSnapshot || allowAiForAllUncertain ? items : added;
QueueAiClassification(aiCandidates);
UpdateTrayStatus(items.Count);
}
private IList<DesktopItem> ScanAllDesktopItems()
{
List<DesktopItem> items = new List<DesktopItem>();
HashSet<string> seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
IList<DesktopItem> privateItems = _desktopIndex.Scan(String.Empty);
int index;
for (index = 0; index < privateItems.Count; index++)
{
if (seen.Add(privateItems[index].FullPath))
{
items.Add(privateItems[index]);
}
}
if (_publicDesktopIndex != null)
{
IList<DesktopItem> publicItems = _publicDesktopIndex.Scan(String.Empty);
for (index = 0; index < publicItems.Count; index++)
{
if (seen.Add(publicItems[index].FullPath))
{
items.Add(publicItems[index]);
}
}
}
if (_settings.TakeOverDesktopIcons && UsesPhysicalDesktop())
{
items.Add(new DesktopItem(
"此电脑",
"shell:MyComputerFolder",
String.Empty,
true,
DesktopCategory.Folders,
DateTime.MinValue,
true));
items.Add(new DesktopItem(
"回收站",
"shell:RecycleBinFolder",
String.Empty,
true,
DesktopCategory.Folders,
DateTime.MinValue,
true));
}
return items;
}
private void RenderBoxes(IList<DesktopItem> items)
{
Dictionary<string, List<DesktopItem>> grouped = new Dictionary<string, List<DesktopItem>>(StringComparer.OrdinalIgnoreCase);
int index;
for (index = 0; index < BoxOrder.Length; index++)
{
grouped[BoxOrder[index]] = new List<DesktopItem>();
}
for (index = 0; index < items.Count; index++)
{
DesktopItem item = items[index];
string boxId;
if (!_catalog.TryGet(item, out boxId))
{
boxId = ClassificationCatalog.GetRuleBox(item);
}
List<DesktopItem> target;
if (!grouped.TryGetValue(boxId, out target))
{
target = grouped["other"];
}
target.Add(item);
}
for (index = 0; index < BoxOrder.Length; index++)
{
string boxId = BoxOrder[index];
grouped[boxId].Sort(delegate(DesktopItem first, DesktopItem second)
{
return StringComparer.CurrentCultureIgnoreCase.Compare(first.Name, second.Name);
});
OrganizerBoxWindow window;
if (grouped[boxId].Count > 0)
{
window = EnsureOrganizerWindow(boxId);
window.SetItems(grouped[boxId]);
if (_boxesVisible && window.LayoutSetting.Visible && !window.IsVisible)
{
window.Show();
}
}
else if (_boxes.TryGetValue(boxId, out window))
{
window.SetItems(grouped[boxId]);
window.Hide();
}
}
}
private void QueueAiClassification(IList<DesktopItem> candidates)
{
if (!_settings.AiEnabled || !_aiService.HasKey(_settings.AiProvider))
{
return;
}
lock (_aiSync)
{
int index;
for (index = 0; index < candidates.Count; index++)
{
DesktopItem item = candidates[index];
string cached;
if (ClassificationCatalog.NeedsAi(item) && !_catalog.TryGet(item, out cached))
{
_pendingAi[item.FullPath] = item;
}
}
if (_pendingAi.Count == 0 || _aiWorkerRunning)
{
return;
}
_aiWorkerRunning = true;
}
ThreadPool.QueueUserWorkItem(delegate
{
List<DesktopItem> batch;
lock (_aiSync)
{
batch = new List<DesktopItem>(_pendingAi.Values.Take(30));
int index;
for (index = 0; index < batch.Count; index++)
{
_pendingAi.Remove(batch[index].FullPath);
}
}
Dictionary<string, string> result = null;
try
{
result = _aiService.Classify(_settings.AiProvider, _settings.AiModel, batch);
}
catch
{
result = null;
}
Application.Current.Dispatcher.BeginInvoke(new Action(delegate
{
if (result == null)
{
NotifyAiFailure();
}
ApplyAiResult(batch, result);
bool hasMore;
lock (_aiSync)
{
_aiWorkerRunning = false;
hasMore = _pendingAi.Count > 0;
}
if (hasMore)
{
QueueAiClassification(new List<DesktopItem>());
}
}));
});
}
private void NotifyAiFailure()
{
DateTime now = DateTime.UtcNow;
if (now - _lastAiFailureNoticeUtc < TimeSpan.FromMinutes(5))
{
return;
}
_lastAiFailureNoticeUtc = now;
ShowTrayMessage(
"AI 分类暂时不可用",
"请检查网络、API 密钥和模型设置;本地规则仍会继续工作。",
Forms.ToolTipIcon.Warning);
}
private void ApplyAiResult(IList<DesktopItem> batch, Dictionary<string, string> result)
{
if (_disposed || result == null || result.Count == 0)
{
return;
}
int changed = 0;
int index;
for (index = 0; index < batch.Count; index++)
{
DesktopItem item = batch[index];
DesktopItem current;
string boxId;
string existingBoxId;
if (_snapshot.TryGetValue(item.FullPath, out current) &&
IsSameClassificationTarget(item, current) &&
!_catalog.TryGet(current, out existingBoxId) &&
result.TryGetValue(item.FullPath, out boxId))
{
_catalog.Set(current, boxId, "ai");
changed++;
}
}
if (changed > 0)
{
SaveCatalog();
RenderBoxes(new List<DesktopItem>(_snapshot.Values));
ShowTrayMessage("AI 整理完成", "已为新增的低置信度图标完成归类。", Forms.ToolTipIcon.Info);
}
}
private static bool IsSameClassificationTarget(DesktopItem requested, DesktopItem current)
{
return requested != null && current != null &&
String.Equals(requested.FullPath, current.FullPath, StringComparison.OrdinalIgnoreCase) &&
String.Equals(requested.Name, current.Name, StringComparison.Ordinal) &&
String.Equals(requested.Extension, current.Extension, StringComparison.OrdinalIgnoreCase) &&
requested.IsDirectory == current.IsDirectory &&
requested.IsShellItem == current.IsShellItem;
}
private void OnDesktopItemsChanged(object sender, EventArgs e)
{
// DesktopIndexService already batches Create/Delete/Rename. Comparing
// snapshots here ensures deletions only update layout and never call AI.
RefreshDesktop(false);
}
private void OnItemMoveRequested(object sender, DesktopItemMoveRequestedEventArgs e)
{
DesktopItem item;
if (e != null && _snapshot.TryGetValue(e.Path, out item))
{
_catalog.Set(item, e.TargetBoxId, "manual");
SaveCatalog();
RenderBoxes(new List<DesktopItem>(_snapshot.Values));
}
}
private void OnLayoutChanged(object sender, EventArgs e)
{
if (_qaMode)
{
return;
}
if (_layoutBatchInProgress || _displayRepairPending)
{
return;
}
_layoutSaveTimer.Stop();
_layoutSaveTimer.Start();
}
private void OnDisplaySettingsChanged(object sender, EventArgs e)
{
if (_disposed || _exiting || Application.Current == null)
{
return;
}
Dispatcher dispatcher = Application.Current.Dispatcher;
try
{
if (dispatcher.CheckAccess())
{
QueueDisplayChangeRepair();
}
else
{
dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(QueueDisplayChangeRepair));
}
}
catch (InvalidOperationException)
{
}
}
private void QueueDisplayChangeRepair()
{
if (_disposed || _exiting)
{
return;
}
// WPF can publish transient LocationChanged/SizeChanged events
// before the new monitor DPI has settled. Do not let the shorter
// layout-save debounce persist those intermediate coordinates.
_layoutSaveTimer.Stop();
if (!_displayRepairPending)
{
_displayRepairChanged = false;
}
_displayRepairPending = true;
_displayChangeRepairPass = 0;
_displayChangeTimer.Stop();
_displayChangeTimer.Interval = TimeSpan.FromMilliseconds(650);
_displayChangeTimer.Start();
}
private void OnDisplayChangeSettled(object sender, EventArgs e)
{
_displayChangeTimer.Stop();
if (_disposed || _exiting)
{
return;
}
// A display event can represent a primary-monitor or DPI switch
// even when the logical WPF WorkArea has identical numbers. Both
// finite passes are unconditional: the second pass must repair
// late DPI size changes even when they remain on-screen and do
// not overlap but no longer share aligned row/column edges.
string displaySignature = CaptureDisplaySignature();
_lastDisplaySignature = displaySignature;
_displayRepairChanged =
ReflowOrganizerWindows(true, false, false) ||
_displayRepairChanged;
// Per-monitor DPI changes can arrive just after the display topology
// notification. One finite verification pass catches that last move
// without adding an idle polling loop.
if (_displayChangeRepairPass == 0)
{
_displayChangeRepairPass = 1;
_displayChangeTimer.Interval = TimeSpan.FromMilliseconds(450);
_displayChangeTimer.Start();
}
else
{
_displayChangeRepairPass = 0;
_displayChangeTimer.Interval = TimeSpan.FromMilliseconds(650);
_lastDisplaySignature = CaptureDisplaySignature();
_displayRepairPending = false;
if (_displayRepairChanged || _saveSettingsAfterDisplayRepair)
{
SaveSettings();
}
_displayRepairChanged = false;
_saveSettingsAfterDisplayRepair = false;
}
}
private bool ReflowOrganizerWindows(
bool force,
bool showConfirmation,
bool saveImmediately)
{
if (_disposed || _exiting)
{
return false;
}
List<DesktopLayoutSlot> slots = new List<DesktopLayoutSlot>();
List<Window> placementWindows = new List<Window>();
bool includeUtility = _utilityBox != null &&
_settings.UtilityBox.Visible;
if (includeUtility)
{
slots.Add(new DesktopLayoutSlot(
_settings.UtilityBox,
240.0,
150.0,
42.0));
placementWindows.Add(_utilityBox);
}
List<OrganizerBoxWindow> activeBoxes = new List<OrganizerBoxWindow>();
int index;
for (index = 0; index < BoxOrder.Length; index++)
{
OrganizerBoxWindow window;
if (!_boxes.TryGetValue(BoxOrder[index], out window) ||
!window.LayoutSetting.Visible ||
window.Items.Count == 0)
{
continue;
}
activeBoxes.Add(window);
slots.Add(new DesktopLayoutSlot(
window.LayoutSetting,
190.0,
112.0,
36.0));
placementWindows.Add(window);
}
Rect workArea = SystemParameters.WorkArea;
_layoutBatchInProgress = true;
try
{
if (slots.Count == 0)
{
return false;
}
bool physicalNeedsReflow =
DesktopWindowPlacementService.NeedsReflow(placementWindows);
if (!force && !physicalNeedsReflow)
{
return false;
}
List<LayoutGeometrySnapshot> snapshots =
CaptureLayoutGeometry(slots);
List<Rect> verifiedLayoutRectangles;
bool physicallyArranged =
DesktopWindowPlacementService.Arrange(
placementWindows,
out verifiedLayoutRectangles);
if (!physicallyArranged)
{
if (!DesktopLayoutService.Arrange(slots, workArea))
{
RestoreLayoutGeometry(snapshots);
ApplyPlannedWindowGeometry(
includeUtility,
activeBoxes);
return false;
}
ApplyPlannedWindowGeometry(includeUtility, activeBoxes);
physicallyArranged =
DesktopWindowPlacementService.Arrange(
placementWindows,
out verifiedLayoutRectangles);
if (!physicallyArranged)
{
RestoreLayoutGeometry(snapshots);
ApplyPlannedWindowGeometry(includeUtility, activeBoxes);
return false;
}
}
CaptureVerifiedWindowGeometry(
slots,
verifiedLayoutRectangles);
}
finally
{
_layoutBatchInProgress = false;
}
_layoutSaveTimer.Stop();
if (saveImmediately)
{
SaveSettings();
}
if (!_qaMode && _boxesVisible)
{
SendAllWindowsToDesktop();
if (_desktopLayerCoordinator != null)
{
_desktopLayerCoordinator.RequestRepair();
}
}
if (showConfirmation)
{
ShowTrayMessage(
"收纳盒已排列",
"已按当前屏幕的可用空间重新排列。",
Forms.ToolTipIcon.Info);
}
return true;
}
private static List<LayoutGeometrySnapshot> CaptureLayoutGeometry(
IList<DesktopLayoutSlot> slots)
{
List<LayoutGeometrySnapshot> snapshots =
new List<LayoutGeometrySnapshot>();
int index;
for (index = 0; index < slots.Count; index++)
{
BoxLayoutSetting layout = slots[index].Layout;