-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecoded_addchecked.cs
More file actions
1247 lines (1099 loc) · 50.7 KB
/
Copy pathdecoded_addchecked.cs
File metadata and controls
1247 lines (1099 loc) · 50.7 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 CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FilterPlus.Models;
using FilterPlus.Services;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
namespace FilterPlus.ViewModels;
public partial class SelectionFilterViewModel : ObservableObject
{
private readonly RevitSelectionService _selectionService;
private Autodesk.Revit.UI.ExternalEvent _pickElementsEvent;
public System.Action HideWindowRequested { get; set; }
public System.Action ShowWindowRequested { get; set; }
// Pre-fetched data for each scope (loaded once at startup in API context)
private List<ElementModel> _currentSelectionElements = new();
private List<ElementModel> _elementsVisibleInViewElements = new();
private List<ElementModel> _elementsBelongingToViewElements = new();
private List<ElementModel> _allModelElements = new();
// Active list displayed in the tree
private List<ElementModel> _activeElements = new();
public ObservableCollection<TreeItemViewModel> RootNodes { get; } = new();
public ObservableCollection<string> Categories { get; } = new();
public ObservableCollection<string> Families { get; } = new();
public ObservableCollection<string> Types { get; } = new();
public ObservableCollection<string> Levels { get; } = new();
public ObservableCollection<string> Worksets { get; } = new();
[ObservableProperty] private string _selectedCategory;
[ObservableProperty] private string _selectedFamily;
[ObservableProperty] private string _selectedType;
[ObservableProperty] private string _selectedLevel;
[ObservableProperty] private string _selectedWorkset;
[ObservableProperty] private string _statusMessage;
[ObservableProperty] private int _checkedElementsCount;
[ObservableProperty] private string _filterText = string.Empty;
[ObservableProperty] private bool _isBusy;
[ObservableProperty] private bool _isOnly3DModels;
[ObservableProperty] private bool _isOnlyAnnotation;
[ObservableProperty] private bool _hasBoundingBox;
[ObservableProperty] private bool _isLiveSelection;
[ObservableProperty] private bool _sortByPhase;
[ObservableProperty] private bool _sortByLevel;
[ObservableProperty] private bool _sortByWorkset;
[ObservableProperty] private bool _isUseOr;
[ObservableProperty] private bool _isOnlyByName;
[ObservableProperty] private bool _isUseRegex;
// Increase Checked Options
[ObservableProperty] private bool _increaseWhatSameCategory;
[ObservableProperty] private bool _increaseWhatSameFamily;
[ObservableProperty] private bool _increaseWhatSameType;
[ObservableProperty] private bool _increaseWhatSameWorkset;
[ObservableProperty] private bool _increaseWhatHostOfElement;
[ObservableProperty] private bool _increaseWhatHostedElements;
[ObservableProperty] private bool _increaseWhatNestedElements;
[ObservableProperty] private bool _increaseWhatJoinedElements;
[ObservableProperty] private bool _increaseWhatSupercomponent;
[ObservableProperty] private bool _increaseWhatGroupOfAssembly;
[ObservableProperty] private bool _increaseWhatDependent;
[ObservableProperty] private bool _increaseWhatIntersects;
[ObservableProperty] private bool _increaseWhatSameMEPSystem;
[ObservableProperty] private bool _increaseWhereAllModel = true;
[ObservableProperty] private bool _increaseWhereCurrentView;
[ObservableProperty] private bool _increaseWhereVisibleInView;
[ObservableProperty] private bool _increaseHowAddToCurrent = true;
[ObservableProperty] private bool _increaseHowCreateNew;
[ObservableProperty] private bool _increaseUnselectBelongsToGroup;
[ObservableProperty] private bool _increaseUnselectBelongsToAssembly;
private List<string> _activeGroupings = new List<string>();
[ObservableProperty] private SelectionScope _currentScope = SelectionScope.CurrentSelection;
private HashSet<Autodesk.Revit.DB.ElementId> _persistentCheckedIds = new();
[RelayCommand]
private void ExpandAll()
{
if (RootNodes == null || !RootNodes.Any()) return;
int targetLevel = FindLowestUnexpandedLevel(RootNodes);
if (targetLevel != int.MaxValue)
{
if (targetLevel == 0)
{
ForceCollapseAll(RootNodes.SelectMany(r => r.Children));
}
SetExpandedStateAtLevel(RootNodes, targetLevel, true);
}
}
[RelayCommand]
private void CollapseAll()
{
if (RootNodes == null || !RootNodes.Any()) return;
int targetLevel = FindHighestExpandedLevel(RootNodes);
if (targetLevel > 0) // Never collapse Level 0 (Root "All")
{
SetExpandedStateAtLevel(RootNodes, targetLevel, false);
}
}
private int FindLowestUnexpandedLevel(IEnumerable<TreeItemViewModel> nodes)
{
int lowest = int.MaxValue;
foreach (var node in nodes)
{
if (node.Children.Count > 0)
{
if (!node.IsExpanded)
{
if (node.Level < lowest) lowest = node.Level;
}
else
{
int childLowest = FindLowestUnexpandedLevel(node.Children);
if (childLowest < lowest) lowest = childLowest;
}
}
}
return lowest;
}
private int FindHighestExpandedLevel(IEnumerable<TreeItemViewModel> nodes)
{
int highest = -1;
foreach (var node in nodes)
{
if (node.IsExpanded && node.Children.Count > 0)
{
if (node.Level > highest) highest = node.Level;
int childHighest = FindHighestExpandedLevel(node.Children);
if (childHighest > highest) highest = childHighest;
}
}
return highest;
}
private void SetExpandedStateAtLevel(IEnumerable<TreeItemViewModel> nodes, int targetLevel, bool state)
{
foreach (var node in nodes)
{
if (node.Level == targetLevel)
{
if (node.Children.Count > 0) node.IsExpanded = state;
}
else if (node.Level < targetLevel)
{
SetExpandedStateAtLevel(node.Children, targetLevel, state);
}
}
}
private void ForceCollapseAll(IEnumerable<TreeItemViewModel> nodes)
{
foreach (var node in nodes)
{
node.IsExpanded = false;
ForceCollapseAll(node.Children);
}
}
private int FindMaxTreeDepth(IEnumerable<TreeItemViewModel> nodes)
{
int max = 0;
foreach (var node in nodes)
{
if (node.Level > max) max = node.Level;
if (node.Children.Count > 0)
{
int childMax = FindMaxTreeDepth(node.Children);
if (childMax > max) max = childMax;
}
}
return max;
}
[RelayCommand]
private void OpenConfiguration()
{
var configView = new Views.ConfigurationView();
configView.ShowDialog();
}
private bool _isRestoringState = false;
private bool _isInitializing = false;
private int _lastExpandedDepth = 0;
private void OnTreeSelectionChanged()
{
if (TreeItemViewModel.IsBulkUpdating) return;
UpdatePersistentCheckedIdsFromTree();
if (IsLiveSelection)
{
ApplyFilter();
}
}
/// <summary>
/// Constructor: called in Revit API context. Pre-fetches all scope data safely here.
/// </summary>
public SelectionFilterViewModel(RevitSelectionService selectionService)
{
LoggerService.LogInfo("SelectionFilterViewModel initializing...");
_selectionService = selectionService;
try
{
// 1. Get initial selection IDs from Revit (safe: API context)
_persistentCheckedIds = _selectionService.GetInitialSelectionIds();
LoggerService.LogInfo($"Initial selection IDs count: {_persistentCheckedIds.Count}");
// 2. Pre-fetch all scopes NOW (we are in Revit API thread)
LoggerService.LogInfo("Pre-fetching CurrentSelection elements...");
_currentSelectionElements = _selectionService.GetAvailableElements(SelectionScope.CurrentSelection);
LoggerService.LogInfo($"CurrentSelection: {_currentSelectionElements.Count} elements.");
LoggerService.LogInfo("Pre-fetching ElementsVisibleInView elements...");
_elementsVisibleInViewElements = _selectionService.GetAvailableElements(SelectionScope.ElementsVisibleInView);
LoggerService.LogInfo($"ElementsVisibleInView: {_elementsVisibleInViewElements.Count} elements.");
LoggerService.LogInfo("Pre-fetching ElementsBelongingToView elements...");
_elementsBelongingToViewElements = _selectionService.GetAvailableElements(SelectionScope.ElementsBelongingToView);
LoggerService.LogInfo($"ElementsBelongingToView: {_elementsBelongingToViewElements.Count} elements.");
LoggerService.LogInfo("Pre-fetching AllModelElements elements...");
var allRaw = _selectionService.GetAvailableElements(SelectionScope.AllModelElements);
_allModelElements = allRaw.Count > 10000 ? allRaw.Take(10000).ToList() : allRaw;
LoggerService.LogInfo($"AllModelElements: {_allModelElements.Count} elements (raw: {allRaw.Count}).");
// 3. Build tree for the default scope (CurrentSelection)
_activeElements = _currentSelectionElements;
BuildTree();
}
catch (Exception ex)
{
LoggerService.LogError("ViewModel Constructor", ex);
}
}
/// <summary>
/// Called when scope radio button changes. NO Revit API calls here ÔÇô uses pre-fetched data.
/// </summary>
partial void OnCurrentScopeChanged(SelectionScope value)
{
if (TreeItemViewModel.IsBulkUpdating) return;
try
{
LoggerService.LogInfo($"Scope switched to: {value}. Rebuilding tree from pre-fetched data...");
_activeElements = value switch
{
SelectionScope.CurrentSelection => _currentSelectionElements,
SelectionScope.ElementsVisibleInView => _elementsVisibleInViewElements,
SelectionScope.ElementsBelongingToView => _elementsBelongingToViewElements,
SelectionScope.AllModelElements => _allModelElements,
_ => _currentSelectionElements
};
LoggerService.LogInfo($"Active elements for scope {value}: {_activeElements.Count}");
BuildTree();
}
catch (Exception ex)
{
LoggerService.LogError("OnCurrentScopeChanged", ex);
}
}
partial void OnIsOnly3DModelsChanged(bool value)
{
if (value)
{
IsOnlyAnnotation = false;
HasBoundingBox = false;
UncheckHiddenElements(e => !e.IsModelElement);
}
BuildTree();
}
partial void OnIsOnlyAnnotationChanged(bool value)
{
if (value)
{
IsOnly3DModels = false;
HasBoundingBox = false;
UncheckHiddenElements(e => !e.IsAnnotation);
}
BuildTree();
}
partial void OnHasBoundingBoxChanged(bool value)
{
if (value)
{
IsOnly3DModels = false;
IsOnlyAnnotation = false;
UncheckHiddenElements(e => !e.HasBoundingBox);
}
BuildTree();
}
private void UncheckHiddenElements(Func<ElementModel, bool> isHiddenPredicate)
{
if (_activeElements == null) return;
var hiddenIds = _activeElements.Where(isHiddenPredicate).Select(e => e.Id).ToList();
bool changed = false;
foreach (var id in hiddenIds)
{
if (_persistentCheckedIds.Contains(id))
{
_persistentCheckedIds.Remove(id);
changed = true;
}
}
if (changed) CheckedElementsCount = _persistentCheckedIds.Count;
}
partial void OnIsLiveSelectionChanged(bool value)
{
if (value)
{
ApplyFilter();
}
}
partial void OnSortByPhaseChanged(bool value)
{
if (value) { if (!_activeGroupings.Contains("Phase")) _activeGroupings.Add("Phase"); }
else _activeGroupings.Remove("Phase");
BuildTree();
}
partial void OnSortByLevelChanged(bool value)
{
if (value) { if (!_activeGroupings.Contains("Level")) _activeGroupings.Add("Level"); }
else _activeGroupings.Remove("Level");
BuildTree();
}
partial void OnSortByWorksetChanged(bool value)
{
if (value) { if (!_activeGroupings.Contains("Workset")) _activeGroupings.Add("Workset"); }
else _activeGroupings.Remove("Workset");
BuildTree();
}
private IEnumerable<ElementModel> GetFilteredElements()
{
if (_activeElements == null) return Enumerable.Empty<ElementModel>();
var filtered = _activeElements.AsEnumerable();
if (IsOnly3DModels) filtered = filtered.Where(e => e.IsModelElement);
if (IsOnlyAnnotation) filtered = filtered.Where(e => e.IsAnnotation);
if (HasBoundingBox) filtered = filtered.Where(e => e.HasBoundingBox);
return filtered;
}
/// <summary>Rebuilds dropdowns and the tree from _activeElements. Safe to call from UI thread.</summary>
private void BuildTree()
{
IsBusy = true;
TreeItemViewModel.IsBulkUpdating = true;
LoggerService.LogInfo($"BuildTree: {_activeElements.Count} elements for scope {CurrentScope}.");
try
{
int semanticExpansionLevel = 0; // Default semantic depth
bool hasPreviousState = false;
if (RootNodes != null && RootNodes.Any())
{
hasPreviousState = true;
int oldMaxDepth = FindMaxTreeDepth(RootNodes);
int oldG = oldMaxDepth - 4; // Base elements start at Level 4 with 0 groupings
if (oldG < 0) oldG = 0;
int lowestUnexpanded = FindLowestUnexpandedLevel(RootNodes);
int oldExpandedLevel = (lowestUnexpanded != int.MaxValue) ? lowestUnexpanded - 1 : FindHighestExpandedLevel(RootNodes);
semanticExpansionLevel = oldExpandedLevel - oldG;
}
var filtered = GetFilteredElements().ToList();
StatusMessage = $"Elementos encontrados: {filtered.Count}";
UpdateDropdowns(filtered);
InitializeTree(filtered, !hasPreviousState);
// Restore the semantic expansion depth
if (hasPreviousState && RootNodes != null)
{
int newG = _activeGroupings.Count;
int newExpandedLevel = newG + semanticExpansionLevel;
for (int i = 0; i <= newExpandedLevel; i++)
{
SetExpandedStateAtLevel(RootNodes, i, true);
}
}
}
catch (Exception ex)
{
LoggerService.LogError("BuildTree", ex);
}
finally
{
foreach (var node in RootNodes) node.RefreshState();
TreeItemViewModel.IsBulkUpdating = false;
OnTreeSelectionChanged();
IsBusy = false;
LoggerService.LogInfo("BuildTree completed.");
}
}
private void UpdateDropdowns(IEnumerable<ElementModel> filteredElements)
{
LoggerService.LogInfo("Updating filter dropdowns...");
var elements = filteredElements.ToList();
// Guardar selecciones actuales
var prevCat = SelectedCategory;
var prevFam = SelectedFamily;
var prevType = SelectedType;
Categories.Clear();
Families.Clear();
Types.Clear();
Levels.Clear();
Worksets.Clear();
Categories.Add("Todos");
Families.Add("Todos");
Types.Add("Todos");
Levels.Add("Todos");
Worksets.Add("Todos");
foreach (var cat in elements.Select(e => e.CategoryName).Distinct().OrderBy(x => x))
Categories.Add(cat);
foreach (var fam in elements.Select(e => e.FamilyName).Distinct().OrderBy(x => x))
Families.Add(fam);
foreach (var type in elements.Select(e => e.TypeName).Distinct().OrderBy(x => x))
Types.Add(type);
foreach (var lev in elements.Select(e => e.LevelName).Distinct().OrderBy(x => x))
Levels.Add(lev);
foreach (var ws in elements.Select(e => e.WorksetName).Distinct().OrderBy(x => x))
Worksets.Add(ws);
// Restore previous selection if still valid
SelectedCategory = Categories.Contains(prevCat) ? prevCat : "Todos";
SelectedFamily = Families.Contains(prevFam) ? prevFam : "Todos";
SelectedType = Types.Contains(prevType) ? prevType : "Todos";
}
private void BuildCategorySubTree(IEnumerable<ElementModel> elementsInCategory, TreeItemViewModel catNode)
{
int catCount = 0;
var families = elementsInCategory.GroupBy(e => e.FamilyName).OrderBy(g => g.Key);
foreach (var famGroup in families)
{
var famNode = new TreeItemViewModel(famGroup.Key, catNode, catNode.Level + 1, OnTreeSelectionChanged);
catNode.Children.Add(famNode);
int famCount = 0;
var types = famGroup.GroupBy(e => e.TypeName).OrderBy(g => g.Key);
foreach (var typeGroup in types)
{
var typeNode = new TreeItemViewModel(typeGroup.Key, famNode, famNode.Level + 1, OnTreeSelectionChanged);
famNode.Children.Add(typeNode);
int strCount = 0;
foreach (var element in typeGroup.OrderBy(e => e.Id.ToString()))
{
var elNode = new TreeItemViewModel(element.Id.ToString(), typeNode, typeNode.Level + 1, OnTreeSelectionChanged)
{
ElementId = element.Id,
SearchableMetadata = element.SearchableMetadata
};
typeNode.Children.Add(elNode);
strCount++;
}
typeNode.Count = strCount;
famCount += strCount;
}
famNode.Count = famCount;
catCount += famCount;
}
catNode.Count = catCount;
}
private void BuildGroupedTree(IEnumerable<ElementModel> elements, TreeItemViewModel parentNode, int groupingIndex)
{
if (groupingIndex >= _activeGroupings.Count)
{
var categories = elements.GroupBy(e => e.CategoryName).OrderBy(g => g.Key);
foreach (var catGroup in categories)
{
var catNode = new TreeItemViewModel(catGroup.Key, parentNode, parentNode.Level + 1, OnTreeSelectionChanged);
parentNode.Children.Add(catNode);
BuildCategorySubTree(catGroup, catNode);
}
parentNode.Count = parentNode.Children.Sum(c => c.Count);
return;
}
string groupingType = _activeGroupings[groupingIndex];
if (groupingType == "Phase")
{
var phases = elements.GroupBy(e => new { e.PhaseName, e.PhaseOrder }).OrderBy(g => g.Key.PhaseOrder);
foreach (var phaseGroup in phases)
{
var phaseNode = new TreeItemViewModel(phaseGroup.Key.PhaseName, parentNode, parentNode.Level + 1, OnTreeSelectionChanged);
parentNode.Children.Add(phaseNode);
BuildGroupedTree(phaseGroup, phaseNode, groupingIndex + 1);
}
parentNode.Count = parentNode.Children.Sum(c => c.Count);
}
else if (groupingType == "Level")
{
var levels = elements.GroupBy(e => string.IsNullOrEmpty(e.LevelName) ? "None" : e.LevelName).OrderBy(g => g.Key);
foreach (var levelGroup in levels)
{
var levelNode = new TreeItemViewModel(levelGroup.Key, parentNode, parentNode.Level + 1, OnTreeSelectionChanged);
parentNode.Children.Add(levelNode);
BuildGroupedTree(levelGroup, levelNode, groupingIndex + 1);
}
parentNode.Count = parentNode.Children.Sum(c => c.Count);
}
else if (groupingType == "Workset")
{
var worksets = elements.GroupBy(e => string.IsNullOrEmpty(e.WorksetName) ? "None" : e.WorksetName).OrderBy(g => g.Key);
foreach (var wsGroup in worksets)
{
var wsNode = new TreeItemViewModel(wsGroup.Key, parentNode, parentNode.Level + 1, OnTreeSelectionChanged);
parentNode.Children.Add(wsNode);
BuildGroupedTree(wsGroup, wsNode, groupingIndex + 1);
}
parentNode.Count = parentNode.Children.Sum(c => c.Count);
}
}
private void InitializeTree(IEnumerable<ElementModel> filteredElements, bool forceExpand)
{
try
{
var elements = filteredElements.ToList();
LoggerService.LogInfo($"Building tree structure offline for {elements.Count} elements...");
var rootAll = new TreeItemViewModel("All", null, 0, OnTreeSelectionChanged);
BuildGroupedTree(elements, rootAll, 0);
rootAll.Count = rootAll.Children.Sum(c => c.Count);
if (_persistentCheckedIds.Count > 0)
{
LoggerService.LogInfo($"Applying selection state for {_persistentCheckedIds.Count} checked elements...");
ApplyInitialSelection(rootAll, _persistentCheckedIds, forceExpand);
}
rootAll.IsExpanded = true;
// Swap RootNodes on UI thread
var uiDispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
if (uiDispatcher.CheckAccess())
{
LoggerService.LogInfo($"Swapping tree root directly. New total: {rootAll.Count}");
RootNodes.Clear();
RootNodes.Add(rootAll);
}
else
{
uiDispatcher.Invoke(() => {
RootNodes.Clear();
RootNodes.Add(rootAll);
});
}
LoggerService.LogInfo($"Tree built and swapped. {rootAll.Count} visible elements.");
}
catch (Exception ex)
{
LoggerService.LogError("InitializeTree", ex);
}
}
private bool ApplyInitialSelection(TreeItemViewModel node, HashSet<Autodesk.Revit.DB.ElementId> selectedIds, bool forceExpand)
{
if (node.Children.Count == 0)
{
if (node.ElementId != null && selectedIds.Contains(node.ElementId))
{
node.IsChecked = true;
return true;
}
return false;
}
bool hasCheckedChildren = false;
foreach (var child in node.Children)
{
if (ApplyInitialSelection(child, selectedIds, forceExpand))
hasCheckedChildren = true;
}
if (hasCheckedChildren && forceExpand) node.IsExpanded = true;
return hasCheckedChildren;
}
public void SetExternalEvent(Autodesk.Revit.UI.ExternalEvent externalEvent)
{
_pickElementsEvent = externalEvent;
}
[RelayCommand]
private void PickElements()
{
// 1. Apply current selection so it's visible in Revit
ApplyFilter();
// 2. Hide the addin window
HideWindowRequested?.Invoke();
// 3. Trigger the external event for PickObjects
_pickElementsEvent?.Raise();
}
public void OnPickElementsFinished(List<Autodesk.Revit.DB.ElementId> newIds)
{
var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
dispatcher.InvokeAsync(() =>
{
if (newIds != null && newIds.Count > 0)
{
// Add new IDs to the persistent selection
foreach (var id in newIds)
{
_persistentCheckedIds.Add(id);
}
// Ensure newly picked elements are injected into the active elements so they show up in the tree!
var allKnownById = _allModelElements.ToDictionary(e => e.Id);
foreach (var id in newIds)
{
if (allKnownById.TryGetValue(id, out var model))
{
if (_activeElements != null && !_activeElements.Any(e => e.Id == id))
{
_activeElements.Add(model);
}
}
}
// Force a tree refresh so the newly selected items are checked
BuildTree();
}
// Restore the window
ShowWindowRequested?.Invoke();
});
}
private void UpdatePersistentCheckedIdsFromTree()
{
var selectedIdsInTree = new List<Autodesk.Revit.DB.ElementId>();
foreach (var node in RootNodes) node.GetAllSelectedIds(selectedIdsInTree);
var activeElementIds = _activeElements?.Select(e => e.Id).ToHashSet() ?? new HashSet<Autodesk.Revit.DB.ElementId>();
// Mantener los IDs que estaban checkeados pero que no pertenecen al scope/filtro actual
var idsFromOtherScopes = _persistentCheckedIds.Where(id => !activeElementIds.Contains(id));
_persistentCheckedIds = selectedIdsInTree.Concat(idsFromOtherScopes).ToHashSet();
CheckedElementsCount = _persistentCheckedIds.Count;
}
[RelayCommand]
private void ApplyFilter()
{
try
{
// ÔöÇÔöÇ 1. Actualizar el estado persistente de IDs marcados ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
UpdatePersistentCheckedIdsFromTree();
var finalIds = _persistentCheckedIds.ToList();
StatusMessage = $"Seleccionados: {finalIds.Count}";
// ÔöÇÔöÇ 2. Aplicar la selecci├│n en Revit ÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇÔöÇ
_selectionService.SetSelection(finalIds);
// ÔöÇÔöÇ 4. Reconstruir _currentSelectionElements desde TODOS los scopes ÔöÇÔöÇÔöÇÔöÇ
// Buscamos el ElementModel de cada ID seleccionado en el pool completo,
// así no se pierden elementos que no estuvieran en el scope activo actual.
var allKnownById = _currentSelectionElements
.Concat(_elementsVisibleInViewElements)
.Concat(_elementsBelongingToViewElements)
.Concat(_allModelElements)
.GroupBy(e => e.Id)
.Select(g => g.First())
.ToDictionary(e => e.Id);
_currentSelectionElements = _persistentCheckedIds
.Where(id => allKnownById.ContainsKey(id))
.Select(id => allKnownById[id])
.ToList();
LoggerService.LogInfo(
$"Apply Selection: {_persistentCheckedIds.Count} IDs applied. " +
$"CurrentSelection updated to {_currentSelectionElements.Count} elements.");
// Clear search text if it exists, without reverting the selection in the UI
if (!string.IsNullOrEmpty(FilterText))
{
var dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;
dispatcher.InvokeAsync(() =>
{
FilterText = string.Empty;
});
}
}
catch (Exception ex)
{
LoggerService.LogError("Applying Filter", ex);
}
}
[RelayCommand]
private void ClearFilters()
{
SelectedCategory = "Todos";
SelectedFamily = "Todos";
SelectedType = "Todos";
SelectedLevel = "Todos";
SelectedWorkset = "Todos";
foreach(var node in RootNodes) node.IsChecked = false;
ApplyFilter();
}
[RelayCommand]
private void ApplySearch()
{
string searchText = FilterText;
if (string.IsNullOrWhiteSpace(searchText)) return;
System.Text.RegularExpressions.Regex searchRegex = null;
if (IsUseRegex)
{
try
{
// Compile regex with a 2-second timeout to prevent ReDoS (Regular Expression Denial of Service) attacks
searchRegex = new System.Text.RegularExpressions.Regex(
searchText,
System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled,
TimeSpan.FromSeconds(2));
}
catch (Exception ex)
{
// Invalid regex syntax or other parsing error
LoggerService.LogInfo("Invalid regex pattern: " + ex.Message);
StatusMessage = "Invalid Regex Pattern";
return; // Stop the search safely
}
}
else
{
// Only sanitize input if we are NOT using Regex, otherwise we strip valid regex tokens
searchText = SecurityUtils.SanitizeInput(searchText).ToLowerInvariant();
}
TreeItemViewModel.IsBulkUpdating = true;
// If Use OR is OFF, the new search replaces the current selection.
if (!IsUseOr)
{
foreach (var node in RootNodes) node.SetCheckedState(false);
}
// Apply the current search matches
foreach (var node in RootNodes)
FilterNode(node, searchText, searchRegex, false);
// Ensure parent nodes reflect child states properly
foreach (var node in RootNodes) node.RefreshState();
TreeItemViewModel.IsBulkUpdating = false;
OnTreeSelectionChanged();
// Clear the text box after applying
FilterText = string.Empty;
}
[RelayCommand]
private void ApplyIncreaseChecked()
{
try
{
TreeItemViewModel.IsBulkUpdating = true;
LoggerService.LogInfo($"[ApplyIncreaseChecked] START. Current Scope in Select: {CurrentScope}. _activeElements count: {(_activeElements?.Count ?? 0)}.");
// 1. Get currently checked ElementIds from the tree
var currentCheckedIds = new List<Autodesk.Revit.DB.ElementId>();
foreach (var node in RootNodes)
node.GetAllSelectedIds(currentCheckedIds);
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked elements in explorer tree: {currentCheckedIds.Count}. IDs: {string.Join(", ", currentCheckedIds)}");
if (currentCheckedIds.Count == 0)
{
TreeItemViewModel.IsBulkUpdating = false;
StatusMessage = "No elements selected in the tree to expand.";
return;
}
var doc = _selectionService.Document;
var sourceElements = currentCheckedIds.Select(id => doc.GetElement(id)).Where(e => e != null).ToList();
// 2. Define search domain based on WHERE
// Query Revit database directly to avoid any 10,000 pre-fetch limit during selection expansion
List<Autodesk.Revit.DB.Element> domainElements;
if (IncreaseWhereVisibleInView)
{
// Match "Elements Visible" (SelectionScope.ElementsVisibleInView)
var visibleCollector = new Autodesk.Revit.DB.FilteredElementCollector(doc, doc.ActiveView.Id);
domainElements = visibleCollector.WhereElementIsNotElementType().ToElements().ToList();
LoggerService.LogInfo($"[ApplyIncreaseChecked] Domain: Visible in current view. Collector count: {domainElements.Count}.");
}
else if (IncreaseWhereCurrentView)
{
// Match "Elements in View" (SelectionScope.ElementsBelongingToView)
var viewCollector = new Autodesk.Revit.DB.FilteredElementCollector(doc);
domainElements = viewCollector.WhereElementIsNotElementType().ToElements()
.Where(el => el.OwnerViewId == doc.ActiveView.Id || el.get_BoundingBox(doc.ActiveView) != null)
.ToList();
LoggerService.LogInfo($"[ApplyIncreaseChecked] Domain: Current View. Collector count: {domainElements.Count}.");
}
else
{
var modelCollector = new Autodesk.Revit.DB.FilteredElementCollector(doc);
domainElements = modelCollector.WhereElementIsNotElementType().ToElements().ToList();
LoggerService.LogInfo($"[ApplyIncreaseChecked] Domain: All Model. Collector count: {domainElements.Count}.");
}
var targetIds = new HashSet<Autodesk.Revit.DB.ElementId>();
// 3. Apply WHAT rules
if (IncreaseWhatSameCategory)
{
var targetCatIds = sourceElements.Select(e => e.Category?.Id).Where(id => id != null).ToHashSet();
foreach (var el in domainElements)
{
if (el.Category != null && targetCatIds.Contains(el.Category.Id))
targetIds.Add(el.Id);
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Same Category'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatSameFamily || IncreaseWhatSameType)
{
var targetFamilyNames = new HashSet<string>();
var targetTypeIds = new HashSet<Autodesk.Revit.DB.ElementId>();
foreach (var el in sourceElements)
{
var typeId = el.GetTypeId();
if (typeId != null && typeId != Autodesk.Revit.DB.ElementId.InvalidElementId)
{
targetTypeIds.Add(typeId);
var type = doc.GetElement(typeId) as Autodesk.Revit.DB.ElementType;
if (type != null && !string.IsNullOrEmpty(type.FamilyName))
{
targetFamilyNames.Add(type.FamilyName);
}
}
}
foreach (var el in domainElements)
{
var typeId = el.GetTypeId();
if (typeId == null || typeId == Autodesk.Revit.DB.ElementId.InvalidElementId) continue;
if (IncreaseWhatSameType)
{
if (targetTypeIds.Contains(typeId))
targetIds.Add(el.Id);
}
else if (IncreaseWhatSameFamily)
{
var type = doc.GetElement(typeId) as Autodesk.Revit.DB.ElementType;
if (type != null && !string.IsNullOrEmpty(type.FamilyName) && targetFamilyNames.Contains(type.FamilyName))
{
targetIds.Add(el.Id);
}
}
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Same Family/Type'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatSameWorkset && doc.IsWorkshared)
{
var targetWorksetIds = sourceElements.Select(e => e.WorksetId).Where(id => id != Autodesk.Revit.DB.WorksetId.InvalidWorksetId).ToHashSet();
foreach (var el in domainElements)
{
if (targetWorksetIds.Contains(el.WorksetId))
targetIds.Add(el.Id);
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Same Workset'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatHostOfElement)
{
foreach (var el in sourceElements)
{
if (el is Autodesk.Revit.DB.FamilyInstance fi && fi.Host != null)
targetIds.Add(fi.Host.Id);
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Host of Element'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatHostedElements)
{
var sourceIdsHash = sourceElements.Select(e => e.Id).ToHashSet();
foreach (var el in domainElements)
{
if (el is Autodesk.Revit.DB.FamilyInstance fi && fi.Host != null && sourceIdsHash.Contains(fi.Host.Id))
targetIds.Add(el.Id);
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Hosted Elements'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatNestedElements)
{
foreach (var el in sourceElements)
{
if (el is Autodesk.Revit.DB.FamilyInstance fi)
{
var subComponents = fi.GetSubComponentIds();
foreach (var subId in subComponents) targetIds.Add(subId);
}
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Nested Elements'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatJoinedElements)
{
foreach (var el in sourceElements)
{
try {
var joined = Autodesk.Revit.DB.JoinGeometryUtils.GetJoinedElements(doc, el);
foreach (var jId in joined) targetIds.Add(jId);
} catch {} // Fails for elements that cannot be joined
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Joined Elements'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatSupercomponent)
{
foreach (var el in sourceElements)
{
if (el is Autodesk.Revit.DB.FamilyInstance fi && fi.SuperComponent != null)
{
targetIds.Add(fi.SuperComponent.Id);
}
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Supercomponent'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatGroupOfAssembly)
{
foreach (var el in sourceElements)
{
if (el.GroupId != Autodesk.Revit.DB.ElementId.InvalidElementId)
{
var group = doc.GetElement(el.GroupId) as Autodesk.Revit.DB.Group;
if (group != null)
{
foreach (var memberId in group.GetMemberIds()) targetIds.Add(memberId);
}
}
if (el.AssemblyInstanceId != Autodesk.Revit.DB.ElementId.InvalidElementId)
{
var assembly = doc.GetElement(el.AssemblyInstanceId) as Autodesk.Revit.DB.AssemblyInstance;
if (assembly != null)
{
foreach (var memberId in assembly.GetMemberIds()) targetIds.Add(memberId);
}
}
}
LoggerService.LogInfo($"[ApplyIncreaseChecked] Checked 'Group or Assembly'. Accumulative targets: {targetIds.Count}.");
}
if (IncreaseWhatDependent)
{
foreach (var el in sourceElements)