-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathMain.axaml.cs
More file actions
1609 lines (1349 loc) · 72.2 KB
/
Main.axaml.cs
File metadata and controls
1609 lines (1349 loc) · 72.2 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 Avalonia;
using Avalonia.Controls.Templates;
using Avalonia.Data;
using Avalonia.Media;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media.Imaging;
using Avalonia.Threading;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using TabSchematics;
namespace CRT
{
public partial class Main : Window
{
// Window placement: tracks the last known normal-state size and position
private double _restoreWidth;
private double _restoreHeight;
private PixelPoint _restorePosition;
private DispatcherTimer? _windowPlacementSaveTimer;
private bool _windowPlacementReady = false;
// Category filter: suppresses saves during programmatic selection changes
private bool _suppressCategoryFilterSave;
private BoardData? _currentBoardData;
private bool _suppressComponentHighlightUpdate;
private ComponentInfoWindow? _singleComponentInfoWindow;
private readonly Dictionary<string, ComponentInfoWindow> _componentInfoWindowsByKey = new(StringComparer.OrdinalIgnoreCase);
internal bool isHoveringComponent = false;
// Blink selected highlights
private DispatcherTimer? _blinkSelectedTimer;
private bool _blinkSelectedPhaseVisible = true;
private bool _blinkSelectedEnabled;
// Region toggle: local override, does not affect the global setting
private string _localRegion = UserSettings.Region;
public string LocalRegion => this._localRegion;
private bool _suppressRegionToggle;
// Cascading offset for multiple popups
private int _popupCascadeOffset = 0;
// Fullscreen
private SchematicsFullscreenWindow? _schematicsFullscreenWindow;
public Main()
{
InitializeComponent();
this.TabSchematicsControl.Initialize(this);
this.TabOverview.Initialize(this);
this.TabContribute.Initialize(this);
// Restore left panel width from settings
this.RootGrid.ColumnDefinitions[0].Width = new GridLength(UserSettings.LeftPanelWidth);
this.RootGrid.ColumnDefinitions[2].Width = new GridLength(1, GridUnitType.Star);
// Subscribe to splitter pointer-release to persist positions when a drag ends.
// handledEventsToo: true is required because GridSplitter marks the event as handled.
this.MainSplitter.AddHandler(
InputElement.PointerReleasedEvent,
this.OnMainSplitterPointerReleased,
RoutingStrategies.Bubble,
handledEventsToo: true);
// Initialize restore values from settings, then apply window placement before Show()
// so Normal windows appear at the right place/size with zero flicker.
// Maximized windows are positioned on the saved screen before being maximized so the
// OS maximizes them on the correct monitor.
this._restoreWidth = Math.Max(this.MinWidth, UserSettings.WindowWidth);
this._restoreHeight = Math.Max(this.MinHeight, UserSettings.WindowHeight);
this._restorePosition = new PixelPoint(UserSettings.WindowX, UserSettings.WindowY);
// Wireup "blink" button
this.BlinkSelectedCheckBox.IsChecked = UserSettings.BlinkSelected;
if (UserSettings.HasWindowPlacement)
{
this.WindowStartupLocation = WindowStartupLocation.Manual;
this.Width = this._restoreWidth;
this.Height = this._restoreHeight;
if (UserSettings.WindowState == nameof(Avalonia.Controls.WindowState.Maximized))
{
// Place anywhere on the saved screen so the OS maximizes it there
this.Position = new PixelPoint(UserSettings.WindowScreenX + 100, UserSettings.WindowScreenY + 100);
this.WindowState = Avalonia.Controls.WindowState.Maximized;
}
else
{
this.Position = this._restorePosition;
}
}
this.Opened += this.OnWindowFirstOpened;
this.Closing += this.OnWindowClosing;
this.Closed += this.OnWindowClosed;
this.UpdateRegionButtonsState();
this.HardwareComboBox.SelectionChanged += this.OnHardwareSelectionChanged;
this.BoardComboBox.SelectionChanged += this.OnBoardSelectionChanged;
this.CategoryFilterListBox.SelectionChanged += this.OnCategoryFilterSelectionChanged;
this.ComponentFilterListBox.SelectionChanged += this.OnComponentFilterSelectionChanged;
this.PopulateHardwareDropDown();
var versionString = AppConfig.AppVersionString;
var assembly = Assembly.GetExecutingAssembly();
this.PopulateAboutTab(assembly, versionString);
this.Title = versionString != "0.0.0"
? $"Classic Repair Toolbox {versionString}"
: "Classic Repair Toolbox";
this.AddHandler(
InputElement.PointerPressedEvent,
this.OnMainPointerPressedCloseSinglePopup,
RoutingStrategies.Bubble,
handledEventsToo: true
);
this.AddHandler(
InputElement.KeyDownEvent,
this.OnMainKeyDownCloseSinglePopup,
RoutingStrategies.Tunnel,
handledEventsToo: true
);
this.AddHandler(
InputElement.PointerReleasedEvent,
(s, e) =>
{
Dispatcher.UIThread.Post(() =>
{
// Abort stealing focus if another window (like the component popup) is currently active
if (!this.IsActive)
{
return;
}
// Do not steal focus if we are on tabs that utilize text inputs
var selectedTab = this.MainTabControl?.SelectedItem as TabItem;
string? tabHeader = selectedTab?.Header?.ToString();
if (tabHeader == "Feedback" || tabHeader == "Configuration")
{
return;
}
// Avoid stealing focus if another TextBox currently holds it naturally
var focusedElement = TopLevel.GetTopLevel(this)?.FocusManager?.GetFocusedElement();
if (focusedElement is global::Avalonia.Controls.TextBox && focusedElement != this.ComponentSearchTextBox)
{
return;
}
if (this.ComponentSearchTextBox != null && !this.ComponentSearchTextBox.IsFocused)
{
this.ComponentSearchTextBox.Focus();
}
}, DispatcherPriority.Background);
},
RoutingStrategies.Bubble,
handledEventsToo: true
);
if (UserSettings.CheckVersionOnLaunch)
{
this.CheckForAppUpdate();
}
else if (DataManager.DataUpdateRequiresAppUpdate)
{
// Notify if they aren't checking for app updates but missing critical data updates
this.UpdateBannerText.Text = "Newer main Excel data file is available, but requires a newer application version. No more data updates will be given for this version";
this.UpdateBannerInstallButton.IsVisible = false;
this.UpdateBannerViewNotesButton.IsVisible = false;
this.UpdateBanner.IsVisible = true;
}
this.StartBackgroundSyncAsync();
}
// ###########################################################################################
// Checks for an available update on startup and shows the banner if one is found.
// ###########################################################################################
private async void CheckForAppUpdate()
{
bool? available = await UpdateService.CheckForUpdateAsync();
if (available == true)
{
this.UpdateBannerText.Text = $"Version {UpdateService.PendingVersion} is available";
this.UpdateBanner.IsVisible = true;
}
else if (DataManager.DataUpdateRequiresAppUpdate)
{
// App Velopack doesn't see an update, but manifest demands one.
this.UpdateBannerText.Text = "Newer main Excel data file is available, but requires a newer application version. No more data updates will be given for this version";
this.UpdateBannerInstallButton.IsVisible = false;
this.UpdateBannerViewNotesButton.IsVisible = false;
this.UpdateBanner.IsVisible = true;
}
}
// ###########################################################################################
// Shows the sync banner during background sync, then hides it automatically if nothing
// changed, or keeps it visible with an update summary and a refresh button.
// ###########################################################################################
private async void StartBackgroundSyncAsync()
{
if (!DataManager.HasPendingSync)
return;
this.SyncBannerText.Text = "Checking data from online source - please wait...";
this.SyncBannerRefreshButton.IsVisible = false;
this.SyncBanner.IsVisible = true;
int changed = await DataManager.SyncRemainingAsync(status =>
Dispatcher.UIThread.Post(() => this.SyncBannerText.Text = status));
if (changed > 0)
{
this.SyncBannerText.Text = changed == 1
? "1 file updated in the background - please refresh board"
: $"{changed} files updated in the background - please refresh board";
this.SyncBannerRefreshButton.IsVisible = true;
}
else
{
this.SyncBanner.IsVisible = false;
}
}
// ###########################################################################################
// Manually reloads the current board configuration.
// ###########################################################################################
private void OnRefreshBoardClick(object? sender, RoutedEventArgs e)
{
this.SyncBanner.IsVisible = false;
this.OnBoardSelectionChanged(null, null!);
}
// ###########################################################################################
// Dismisses the sync banner.
// ###########################################################################################
private void OnSyncBannerDismiss(object? sender, RoutedEventArgs e)
{
this.SyncBanner.IsVisible = false;
}
// ###########################################################################################
// Dismisses the sync banner when clicking anywhere on it.
// ###########################################################################################
private void OnSyncBannerPointerPressed(object? sender, PointerPressedEventArgs e)
{
this.SyncBanner.IsVisible = false;
}
// ###########################################################################################
// Dismisses the update banner without cancelling the update.
// ###########################################################################################
private void OnUpdateBannerDismiss(object? sender, RoutedEventArgs e)
{
this.UpdateBanner.IsVisible = false;
}
// ###########################################################################################
// Opens the GitHub release notes page for the pending update version.
// ###########################################################################################
private void OnViewReleaseNotesClick(object? sender, RoutedEventArgs e)
{
string version = UpdateService.PendingVersion ?? string.Empty;
string url = string.IsNullOrWhiteSpace(version)
? $"https://github.com/{AppConfig.GitHubOwner}/{AppConfig.GitHubRepo}/releases"
: $"https://github.com/{AppConfig.GitHubOwner}/{AppConfig.GitHubRepo}/releases/tag/{version}";
this.OpenUrl(url);
}
// ###########################################################################################
// Downloads and installs the pending update, showing progress in the banner text.
// ###########################################################################################
private async void OnInstallUpdateClick(object? sender, RoutedEventArgs e)
{
this.UpdateBannerInstallButton.IsEnabled = false;
this.UpdateBannerViewNotesButton.IsEnabled = false;
this.UpdateBannerDismissButton.IsEnabled = false;
this.UpdateBannerText.Text = "Downloading update...";
await UpdateService.DownloadAndInstallAsync(progress =>
{
Dispatcher.UIThread.Post(() => this.UpdateBannerText.Text = $"Downloading update: {progress}%");
});
}
// ###########################################################################################
// Populates the hardware drop-down with distinct hardware names from loaded data.
// ###########################################################################################
private void PopulateHardwareDropDown()
{
var hardwareNames = DataManager.HardwareBoards
.Select(e => e.HardwareName)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
this.HardwareComboBox.ItemsSource = hardwareNames;
if (hardwareNames.Count == 0)
{
this.HardwareComboBox.SelectedIndex = -1;
return;
}
var lastHardware = UserSettings.GetLastHardware();
var savedIndex = hardwareNames.FindIndex(h =>
string.Equals(h, lastHardware, StringComparison.OrdinalIgnoreCase));
this.HardwareComboBox.SelectedIndex = savedIndex >= 0 ? savedIndex : 0;
}
// ###########################################################################################
// Filters the board drop-down to only show boards belonging to the selected hardware.
// ###########################################################################################
private void OnHardwareSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
var selectedHardware = this.HardwareComboBox.SelectedItem as string;
var boards = DataManager.HardwareBoards
.Where(entry => string.Equals(entry.HardwareName, selectedHardware, StringComparison.OrdinalIgnoreCase))
.Select(entry => entry.BoardName)
.Where(b => !string.IsNullOrWhiteSpace(b))
.ToList();
this.BoardComboBox.ItemsSource = boards;
if (string.IsNullOrWhiteSpace(selectedHardware) || boards.Count == 0)
{
this.BoardComboBox.SelectedIndex = -1;
return;
}
UserSettings.SetLastHardware(selectedHardware);
var lastBoard = UserSettings.GetLastBoardForHardware(selectedHardware);
var savedIndex = boards.FindIndex(b =>
string.Equals(b, lastBoard, StringComparison.OrdinalIgnoreCase));
this.BoardComboBox.SelectedIndex = savedIndex >= 0 ? savedIndex : 0;
}
// ###########################################################################################
// Handles board selection changes - loads board data and builds the thumbnail gallery.
// ###########################################################################################
private async void OnBoardSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
this._suppressCategoryFilterSave = true;
foreach (var thumb in this.TabSchematicsControl.currentThumbnails)
{
if (!ReferenceEquals(thumb.ImageSource, thumb.BaseThumbnail))
(thumb.ImageSource as IDisposable)?.Dispose();
(thumb.BaseThumbnail as IDisposable)?.Dispose();
}
this.TabSchematicsControl.currentThumbnails.Clear();
this.TabSchematicsControl.FindControl<ListBox>("SchematicsThumbnailList")!.ItemsSource = null;
this.CategoryFilterListBox.ItemsSource = null;
this.ComponentFilterListBox.ItemsSource = null;
this.TabSchematicsControl.highlightIndexBySchematic = new(StringComparer.OrdinalIgnoreCase);
this.TabSchematicsControl.schematicByName = new(StringComparer.OrdinalIgnoreCase);
this.TabSchematicsControl.highlightRectsBySchematicAndLabel = new(StringComparer.OrdinalIgnoreCase);
this._currentBoardData = null;
this.UpdateRegionButtonsState();
this.PopulateBoardInfoSection(null, null);
this.TabSchematicsControl.ResetSchematicsViewer();
var selectedHardware = this.HardwareComboBox.SelectedItem as string;
var selectedBoard = this.BoardComboBox.SelectedItem as string;
if (string.IsNullOrEmpty(selectedHardware) || string.IsNullOrEmpty(selectedBoard))
return;
UserSettings.SetLastHardware(selectedHardware);
UserSettings.SetLastBoardForHardware(selectedHardware, selectedBoard);
var entry = DataManager.HardwareBoards.FirstOrDefault(ent =>
string.Equals(ent.HardwareName, selectedHardware, StringComparison.OrdinalIgnoreCase) &&
string.Equals(ent.BoardName, selectedBoard, StringComparison.OrdinalIgnoreCase));
if (entry == null || string.IsNullOrWhiteSpace(entry.ExcelDataFile))
return;
var boardData = await DataManager.LoadBoardDataAsync(entry);
if (boardData == null)
return;
this._currentBoardData = boardData;
this.UpdateRegionButtonsState();
this.PopulateBoardInfoSection(boardData.RevisionDate, boardData.Credits);
// Populate category filter in insertion order
var categories = BuildDistinctCategories(boardData);
var boardKey = this.GetCurrentBoardKey();
this.CategoryFilterListBox.ItemsSource = categories;
var savedCategories = UserSettings.GetSelectedCategories(boardKey);
if (savedCategories == null)
{
try
{
this.CategoryFilterListBox.SelectAll();
}
catch (OutOfMemoryException ex)
{
Logger.Debug(ex, "Failed to apply default category selection - group was too large to select");
}
}
else
{
for (int i = 0; i < categories.Count; i++)
{
if (savedCategories.Contains(categories[i], StringComparer.OrdinalIgnoreCase))
this.CategoryFilterListBox.Selection.Select(i);
}
}
this._suppressCategoryFilterSave = false;
// Populate component filter for this board
var activeCategories = new HashSet<string>(
this.CategoryFilterListBox.SelectedItems?.Cast<string>() ?? Enumerable.Empty<string>(),
StringComparer.OrdinalIgnoreCase);
var searchTerm = this.ComponentSearchTextBox?.Text ?? string.Empty;
var componentItems = BuildComponentItems(boardData, UserSettings.Region, activeCategories, searchTerm);
this._suppressComponentHighlightUpdate = true;
this.ComponentFilterListBox.ItemsSource = componentItems;
if (!string.IsNullOrWhiteSpace(searchTerm))
{
try { this.ComponentFilterListBox.SelectAll(); } catch { }
}
this._suppressComponentHighlightUpdate = false;
this.TabSchematicsControl.highlightRectsBySchematicAndLabel = await Task.Run(() => TabSchematics.BuildHighlightRects(boardData, UserSettings.Region));
this.TabSchematicsControl.schematicByName = boardData.Schematics
.Where(s => !string.IsNullOrWhiteSpace(s.SchematicName))
.ToDictionary(s => s.SchematicName, s => s, StringComparer.OrdinalIgnoreCase);
this.TabSchematicsControl.highlightIndexBySchematic = new(StringComparer.OrdinalIgnoreCase);
var loaded = await Task.Run(() =>
{
var result = new List<(string Name, string FullPath, Bitmap? FullBitmap)>();
foreach (var schematic in boardData.Schematics)
{
if (string.IsNullOrWhiteSpace(schematic.SchematicImageFile))
continue;
var fullPath = Path.Combine(DataManager.DataRoot,
schematic.SchematicImageFile.Replace('/', Path.DirectorySeparatorChar));
Bitmap? bitmap = null;
if (File.Exists(fullPath))
{
try { bitmap = new Bitmap(fullPath); }
catch (Exception ex) { Logger.Warning($"Could not load schematic image [{fullPath}] - [{ex.Message}]"); }
}
result.Add((schematic.SchematicName, fullPath, bitmap));
}
return result;
});
var thumbnails = new List<SchematicThumbnail>();
foreach (var (name, fullPath, fullBitmap) in loaded)
{
RenderTargetBitmap? baseThumbnail = null;
PixelSize originalPixelSize = default;
if (fullBitmap != null)
{
baseThumbnail = TabSchematics.CreateScaledThumbnail(fullBitmap, AppConfig.ThumbnailMaxWidth);
originalPixelSize = fullBitmap.PixelSize;
fullBitmap.Dispose();
}
thumbnails.Add(new SchematicThumbnail
{
Name = name,
ImageFilePath = fullPath,
BaseThumbnail = baseThumbnail,
OriginalPixelSize = originalPixelSize,
ImageSource = baseThumbnail,
VisualOpacity = 1.0,
IsMatchForSelection = false
});
}
this.TabSchematicsControl.LoadSortedThumbnails(boardKey, thumbnails);
if (this.TabSchematicsControl.currentThumbnails.Count > 0)
{
var savedSchematic = UserSettings.GetLastSchematicForBoard(boardKey);
var orderedThumbnails = this.TabSchematicsControl.currentThumbnails.ToList();
var savedIndex = string.IsNullOrEmpty(savedSchematic) ? -1 : orderedThumbnails.FindIndex(t =>
string.Equals(t.Name, savedSchematic, StringComparison.OrdinalIgnoreCase));
this.TabSchematicsControl.FindControl<ListBox>("SchematicsThumbnailList")!.SelectedIndex = savedIndex >= 0 ? savedIndex : 0;
}
var ratio = UserSettings.GetSchematicsSplitterRatio(boardKey);
var innerGrid = this.TabSchematicsControl.FindControl<Grid>("SchematicsInnerGrid");
if (innerGrid != null)
{
innerGrid.ColumnDefinitions[0].Width = new GridLength(ratio * 100.0, GridUnitType.Star);
innerGrid.ColumnDefinitions[2].Width = new GridLength((1.0 - ratio) * 100.0, GridUnitType.Star);
}
// Populate the Resources tab
var localFiles = boardData.BoardLocalFiles.Select(f => new ResourceItem(
f.Category,
f.Name,
string.IsNullOrWhiteSpace(f.File) ? string.Empty : Path.Combine(DataManager.DataRoot, f.File.Replace('/', Path.DirectorySeparatorChar))
));
var webLinks = boardData.BoardLinks.Select(l => new ResourceItem(
l.Category,
l.Name,
l.Url
));
this.TabResources.LoadData(localFiles, webLinks);
this.TabOverview.LoadData(boardData);
this.TabContribute.LoadData(boardData, this._localRegion);
// Sync any existing search filter right away if applied
this.TabOverview.ApplyFilter(this.ComponentSearchTextBox?.Text ?? string.Empty);
}
// ###########################################################################################
// Handles component selection changes and drives highlight updates in both the main viewer
// and all thumbnails.
// ###########################################################################################
private void OnComponentFilterSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (this._suppressComponentHighlightUpdate)
return;
var boardLabels = this.ComponentFilterListBox.SelectedItems?
.Cast<ComponentListItem>()
.Select(item => item.BoardLabel)
.Where(l => !string.IsNullOrEmpty(l))
.ToList() ?? new List<string>();
if (!string.IsNullOrWhiteSpace(this.ComponentSearchTextBox?.Text))
{
var allItems = this.ComponentFilterListBox.ItemsSource?.Cast<ComponentListItem>();
if (allItems != null)
{
boardLabels = allItems
.Select(item => item.BoardLabel)
.Where(l => !string.IsNullOrEmpty(l))
.ToList();
}
}
this.TabSchematicsControl.UpdateHighlightsForComponents(boardLabels);
}
// ###########################################################################################
// Saves the selected category list for the current board whenever the user changes it.
// ###########################################################################################
private void OnCategoryFilterSelectionChanged(object? sender, SelectionChangedEventArgs e)
{
if (this._suppressCategoryFilterSave)
return;
var boardKey = this.GetCurrentBoardKey();
if (string.IsNullOrEmpty(boardKey))
return;
var selected = this.CategoryFilterListBox.SelectedItems?
.Cast<string>()
.ToList() ?? new List<string>();
UserSettings.SetSelectedCategories(boardKey, selected);
if (this._currentBoardData != null)
{
var previouslySelectedKeys = new HashSet<string>(
this.ComponentFilterListBox.SelectedItems?.Cast<ComponentListItem>()
.Select(i => i.SelectionKey) ?? Enumerable.Empty<string>(),
StringComparer.OrdinalIgnoreCase);
var categoryFilter = new HashSet<string>(selected, StringComparer.OrdinalIgnoreCase);
var searchTerm = this.ComponentSearchTextBox?.Text ?? string.Empty;
var componentItems = BuildComponentItems(this._currentBoardData, this._localRegion, categoryFilter, searchTerm);
this._suppressComponentHighlightUpdate = true;
this.ComponentFilterListBox.ItemsSource = componentItems;
if (!string.IsNullOrWhiteSpace(searchTerm))
{
try { this.ComponentFilterListBox.SelectAll(); } catch { }
}
else
{
for (int i = 0; i < componentItems.Count; i++)
{
if (previouslySelectedKeys.Contains(componentItems[i].SelectionKey))
this.ComponentFilterListBox.Selection.Select(i);
}
}
this._suppressComponentHighlightUpdate = false;
var survivingLabels = componentItems
.Where(item => previouslySelectedKeys.Contains(item.SelectionKey))
.Select(item => item.BoardLabel)
.Where(l => !string.IsNullOrEmpty(l))
.ToList();
if (!string.IsNullOrWhiteSpace(searchTerm))
{
survivingLabels = componentItems
.Select(item => item.BoardLabel)
.Where(l => !string.IsNullOrEmpty(l))
.ToList();
}
this.TabSchematicsControl.UpdateHighlightsForComponents(survivingLabels);
}
}
// ###########################################################################################
// Returns a composite key uniquely identifying the current hardware and board selection.
// ###########################################################################################
internal string GetCurrentBoardKey()
{
var hw = this.HardwareComboBox.SelectedItem as string;
var board = this.BoardComboBox.SelectedItem as string;
if (string.IsNullOrEmpty(hw) || string.IsNullOrEmpty(board))
{
return string.Empty;
}
return $"{hw}|{board}";
}
// ###########################################################################################
// Saves the left panel width after the main splitter drag ends.
// ###########################################################################################
private void OnMainSplitterPointerReleased(object? sender, PointerReleasedEventArgs e)
{
Dispatcher.UIThread.Post(() => UserSettings.LeftPanelWidth = this.LeftPanel.Bounds.Width);
}
// ###########################################################################################
// On first open: validates the saved position is on a live screen and focuses the search.
// ###########################################################################################
private void OnWindowFirstOpened(object? sender, EventArgs e)
{
this.Opened -= this.OnWindowFirstOpened;
if (UserSettings.HasWindowPlacement && this.WindowState == Avalonia.Controls.WindowState.Normal)
{
double scaling = this.RenderScaling > 0 ? this.RenderScaling : 1.0;
int centerX = this._restorePosition.X + (int)((this._restoreWidth * scaling) / 2);
int centerY = this._restorePosition.Y + (int)((this._restoreHeight * scaling) / 2);
bool isOnScreen = this.Screens.All.Any(s =>
centerX >= s.Bounds.X &&
centerY >= s.Bounds.Y &&
centerX < s.Bounds.X + s.Bounds.Width &&
centerY < s.Bounds.Y + s.Bounds.Height);
if (!isOnScreen)
{
var primary = this.Screens.Primary;
if (primary != null)
{
this.Position = new PixelPoint(
primary.Bounds.X + Math.Max(0, (primary.Bounds.Width - (int)(this.Width * scaling)) / 2),
primary.Bounds.Y + Math.Max(0, (primary.Bounds.Height - (int)(this.Height * scaling)) / 2));
}
}
}
this.PropertyChanged += (s, args) =>
{
if (!this._windowPlacementReady)
return;
if (args.Property == Window.WindowStateProperty)
this.ScheduleWindowPlacementSave();
};
this.PositionChanged += this.OnWindowPositionChanged;
this.SizeChanged += this.OnWindowSizeChanged;
if (UserSettings.ValidateDataOnLaunch)
{
_ = Task.Run(DataValidator.ValidateAllDataAsync);
}
Dispatcher.UIThread.Post(() => this._windowPlacementReady = true, DispatcherPriority.Background);
Dispatcher.UIThread.Post(() =>
{
this.ComponentSearchTextBox?.Focus();
}, DispatcherPriority.Background);
}
// ###########################################################################################
// Tracks the window's position in Normal state and schedules a debounced save.
// ###########################################################################################
private void OnWindowPositionChanged(object? sender, PixelPointEventArgs e)
{
if (!this._windowPlacementReady)
return;
if (this.WindowState == Avalonia.Controls.WindowState.Normal)
{
this._restorePosition = e.Point;
this.ScheduleWindowPlacementSave();
}
}
// ###########################################################################################
// Tracks the window's size in Normal state and schedules a debounced save.
// ###########################################################################################
private void OnWindowSizeChanged(object? sender, SizeChangedEventArgs e)
{
if (!this._windowPlacementReady)
return;
if (this.WindowState == Avalonia.Controls.WindowState.Normal)
{
this._restoreWidth = e.NewSize.Width;
this._restoreHeight = e.NewSize.Height;
this.ScheduleWindowPlacementSave();
}
}
// ###########################################################################################
// Resets and starts a 500 ms debounce timer;
// ###########################################################################################
private void ScheduleWindowPlacementSave()
{
if (this._windowPlacementSaveTimer == null)
{
this._windowPlacementSaveTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
this._windowPlacementSaveTimer.Tick += (s, e) =>
{
this._windowPlacementSaveTimer.Stop();
this.CommitWindowPlacement();
};
}
this._windowPlacementSaveTimer.Stop();
this._windowPlacementSaveTimer.Start();
}
// ###########################################################################################
// Captures the current window state and screen, then persists to settings.
// ###########################################################################################
private void CommitWindowPlacement()
{
var state = this.WindowState == Avalonia.Controls.WindowState.Minimized
? Avalonia.Controls.WindowState.Normal
: this.WindowState;
double scaling = this.RenderScaling > 0 ? this.RenderScaling : 1.0;
double w = this.Bounds.Width > 0 ? this.Bounds.Width : this._restoreWidth;
double h = this.Bounds.Height > 0 ? this.Bounds.Height : this._restoreHeight;
int centerX = this.Position.X + (int)((w * scaling) / 2);
int centerY = this.Position.Y + (int)((h * scaling) / 2);
var screen = this.Screens.All.FirstOrDefault(s =>
centerX >= s.Bounds.X &&
centerY >= s.Bounds.Y &&
centerX < s.Bounds.X + s.Bounds.Width &&
centerY < s.Bounds.Y + s.Bounds.Height)
?? this.Screens.Primary;
UserSettings.SaveWindowPlacement(
state.ToString(),
this._restoreWidth,
this._restoreHeight,
this._restorePosition.X,
this._restorePosition.Y,
screen?.Bounds.X ?? 0,
screen?.Bounds.Y ?? 0,
screen?.Bounds.Width ?? 1920,
screen?.Bounds.Height ?? 1080,
screen?.Scaling ?? 1.0);
}
// ###########################################################################################
// Stops any pending debounce timer and does a final synchronous save on close.
// ###########################################################################################
private void OnWindowClosing(object? sender, WindowClosingEventArgs e)
{
if (this._schematicsFullscreenWindow != null)
{
this._schematicsFullscreenWindow.Close();
}
this._blinkSelectedTimer?.Stop();
this._windowPlacementSaveTimer?.Stop();
this.CommitWindowPlacement();
}
// ###########################################################################################
// Forces the entire application (and all its sub-windows) to shut down once the main window
// has successfully completed its closing sequence.
// ###########################################################################################
private void OnWindowClosed(object? sender, EventArgs e)
{
if (Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop)
{
Dispatcher.UIThread.Post(() =>
{
desktop.Shutdown();
});
}
}
// ###########################################################################################
// Builds a distinct list of component categories in the order they first appear.
// ###########################################################################################
private static List<string> BuildDistinctCategories(BoardData boardData)
{
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var categories = new List<string>();
foreach (var component in boardData.Components)
{
if (!string.IsNullOrWhiteSpace(component.Category) && seen.Add(component.Category))
categories.Add(component.Category);
}
return categories;
}
// ###########################################################################################
// Lightweight view model for a component list item.
// ###########################################################################################
internal sealed class ComponentListItem
{
public string DisplayText { get; init; } = string.Empty;
public string BoardLabel { get; init; } = string.Empty;
public string SelectionKey { get; init; } = string.Empty;
public override string ToString() => this.DisplayText;
}
// ###########################################################################################
// Builds component list items filtered by the given region and search string.
// ###########################################################################################
private static List<ComponentListItem> BuildComponentItems(BoardData boardData, string region, HashSet<string>? categoryFilter = null, string searchTerm = "")
{
var items = new List<ComponentListItem>();
var searchTerms = string.IsNullOrWhiteSpace(searchTerm)
? Array.Empty<string>()
: searchTerm.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var component in boardData.Components)
{
var componentRegion = component.Region?.Trim() ?? string.Empty;
if (!string.IsNullOrEmpty(componentRegion) &&
!string.Equals(componentRegion, region, StringComparison.OrdinalIgnoreCase))
continue;
if (categoryFilter != null && !categoryFilter.Contains(component.Category ?? string.Empty))
continue;
var parts = new List<string>(3);
if (!string.IsNullOrWhiteSpace(component.BoardLabel))
parts.Add(component.BoardLabel.Trim());
if (!string.IsNullOrWhiteSpace(component.FriendlyName))
parts.Add(component.FriendlyName.Trim());
if (!string.IsNullOrWhiteSpace(component.TechnicalNameOrValue))
parts.Add(component.TechnicalNameOrValue.Trim());
if (parts.Count == 0)
continue;
string displayString = string.Join(" | ", parts);
if (searchTerms.Length > 0)
{
bool matches = true;
foreach (var term in searchTerms)
{
if (displayString.IndexOf(term, StringComparison.OrdinalIgnoreCase) < 0)
{
matches = false;
break;
}
}
if (!matches)
continue;
}
items.Add(new ComponentListItem
{
BoardLabel = component.BoardLabel?.Trim() ?? string.Empty,
DisplayText = displayString,
SelectionKey = string.Join("\u001F",
component.BoardLabel?.Trim() ?? string.Empty,
component.FriendlyName?.Trim() ?? string.Empty,
component.TechnicalNameOrValue?.Trim() ?? string.Empty,
component.Region?.Trim() ?? string.Empty)
});
}
return items;
}
// ###########################################################################################
// Opens the persistent AppData folder that contains the log and settings files.
// ###########################################################################################
private void OnOpenAppDataFolderClick(object? sender, RoutedEventArgs e)
{
var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var directory = Path.Combine(appData, AppConfig.AppFolderName);
try
{
Directory.CreateDirectory(directory);
if (OperatingSystem.IsWindows())
{
Process.Start(new ProcessStartInfo("explorer.exe", $"\"{directory}\"")
{
UseShellExecute = true
});
}
else if (OperatingSystem.IsMacOS())
{
Process.Start("open", directory);
}
else
{
Process.Start("xdg-open", directory);
}
}
catch (Exception ex)
{
Logger.Warning($"Failed to open app data folder - [{directory}] - [{ex.Message}]");
}
}
// ###########################################################################################
// Populates About tab fields and loads changelog content from embedded assets.
// ###########################################################################################
private void PopulateAboutTab(Assembly assembly, string? versionString)
{
this.TabAbout.InitializeAbout(assembly, versionString);
}
// ###########################################################################################
// Opens the configured URL in the system default browser.
// ###########################################################################################
private void OpenUrl(string url)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = url,
UseShellExecute = true
});
}
catch (Exception ex)
{
Logger.Warning($"Failed to open URL - [{url}] - [{ex.Message}]");
}
}