/
CodeExplorerViewModel.cs
613 lines (523 loc) · 23 KB
/
CodeExplorerViewModel.cs
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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using NLog;
using Rubberduck.Parsing.Symbols;
using Rubberduck.Parsing.VBA;
using Rubberduck.Settings;
using Rubberduck.SettingsProvider;
using Rubberduck.UI;
using Rubberduck.UI.CodeExplorer.Commands;
using Rubberduck.UI.Command;
using Rubberduck.VBEditor.SafeComWrappers;
using System.Windows;
using System.Windows.Input;
using Rubberduck.Parsing.Annotations;
using Rubberduck.Parsing.UIContext;
using Rubberduck.Templates;
using Rubberduck.UI.CodeExplorer.Commands.DragAndDrop;
using Rubberduck.UI.Command.ComCommands;
using Rubberduck.UI.Controls;
using Rubberduck.UI.UnitTesting.ComCommands;
using Rubberduck.VBEditor.SafeComWrappers.Abstract;
namespace Rubberduck.Navigation.CodeExplorer
{
[Flags]
public enum CodeExplorerSortOrder
{
Undefined = 0,
Name = 1,
CodeLine = 1 << 1,
DeclarationType = 1 << 2,
DeclarationTypeThenName = DeclarationType | Name,
DeclarationTypeThenCodeLine = DeclarationType | CodeLine
}
public interface IPeekDefinitionPopupProvider
{
void PeekDefinition(Declaration target);
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
public sealed class CodeExplorerViewModel : ViewModelBase, IPeekDefinitionPopupProvider
{
// ReSharper disable NotAccessedField.Local - The settings providers aren't used, but several enhancement requests will need them.
#pragma warning disable IDE0052 // Remove unread private members
private readonly RubberduckParserState _state;
private readonly RemoveCommand _externalRemoveCommand;
private readonly IConfigurationService<GeneralSettings> _generalSettingsProvider;
private readonly IConfigurationService<WindowSettings> _windowSettingsProvider;
private readonly IUiDispatcher _uiDispatcher;
private readonly IVBE _vbe;
private readonly ITemplateProvider _templateProvider;
#pragma warning restore IDE0052 // Remove unread private members
// ReSharper restore NotAccessedField.Local
public CodeExplorerViewModel(
RubberduckParserState state,
RemoveCommand removeCommand,
PeekDefinitionNavigateCommand peekNavigateCommand,
IConfigurationService<GeneralSettings> generalSettingsProvider,
IConfigurationService<WindowSettings> windowSettingsProvider,
IUiDispatcher uiDispatcher,
IVBE vbe,
ITemplateProvider templateProvider,
ICodeExplorerSyncProvider syncProvider,
IEnumerable<IAnnotation> annotations)
{
_state = state;
_state.StateChanged += HandleStateChanged;
_state.ModuleStateChanged += ParserState_ModuleStateChanged;
_generalSettingsProvider = generalSettingsProvider;
_generalSettingsProvider.SettingsChanged += GeneralSettingsChanged;
RefreshDragAndDropSetting();
_windowSettingsProvider = windowSettingsProvider;
_uiDispatcher = uiDispatcher;
_vbe = vbe;
_templateProvider = templateProvider;
_externalRemoveCommand = removeCommand;
Annotations = annotations.ToList();
CollapseAllSubnodesCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCollapseNodes, EvaluateCanSwitchNodeState);
ExpandAllSubnodesCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteExpandNodes, EvaluateCanSwitchNodeState);
ClearSearchCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteClearSearchCommand);
CollapseAllCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteCollapseAllCommand);
ExpandAllCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteExpandAllCommand);
if (_externalRemoveCommand != null)
{
RemoveCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteRemoveCommand, _externalRemoveCommand.CanExecute);
}
PeekDefinitionCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecutePeekDefinitionCommand, CanExecutePeekDefinitionCommand);
ClosePeekDefinitionCommand = new DelegateCommand(LogManager.GetCurrentClassLogger(), ExecuteClosePeekDefinitionCommand);
OnPropertyChanged(nameof(Projects));
SyncCodePaneCommand = syncProvider.GetSyncCommand(this);
// Force a call to EvaluateCanExecute
OnPropertyChanged(nameof(SyncCodePaneCommand));
}
public ObservableCollection<ICodeExplorerNode> Projects { get; } = new ObservableCollection<ICodeExplorerNode>();
#pragma warning disable IDE1006 // Naming Styles
private ObservableCollection<Template> templates => _templateProvider.GetTemplates();
#pragma warning restore IDE1006 // Naming Styles
public ObservableCollection<Template> BuiltInTemplates =>
new ObservableCollection<Template>(templates.Where(t => !t.IsUserDefined)
.OrderBy(t => t.Name));
public ObservableCollection<Template> UserDefinedTemplates =>
new ObservableCollection<Template>(templates.Where(t => t.IsUserDefined)
.OrderBy(t => t.Name));
public IEnumerable<IAnnotation> Annotations { get; }
private ICodeExplorerNode _selectedItem;
public ICodeExplorerNode SelectedItem
{
get => _selectedItem;
set
{
if (_selectedItem == value)
{
return;
}
ExpandToNode(value);
_selectedItem = value;
OnPropertyChanged();
OnPropertyChanged(nameof(ExportVisibility));
OnPropertyChanged(nameof(ExportAllVisibility));
OnPropertyChanged(nameof(CanBeAnnotated));
OnPropertyChanged(nameof(AnyTemplatesCanExecute));
}
}
public bool AnyTemplatesCanExecute =>
AddTemplateCommand.CanExecuteForNode(SelectedItem)
&& BuiltInTemplates.Concat(UserDefinedTemplates)
.Any(template => AddTemplateCommand.CanExecute((template.Name, SelectedItem)));
public bool CanBeAnnotated =>
AnnotateDeclarationCommand.CanExecuteForNode(SelectedItem)
&& Annotations.Any(annotation => AnnotateDeclarationCommand.CanExecute((annotation, SelectedItem)));
private CodeExplorerSortOrder _sortOrder = CodeExplorerSortOrder.Name;
public CodeExplorerSortOrder SortOrder
{
get => _sortOrder;
set
{
if (_sortOrder == value)
{
return;
}
_sortOrder = value;
foreach (var project in Projects.OfType<CodeExplorerProjectViewModel>())
{
project.SortOrder = _sortOrder;
}
OnPropertyChanged();
}
}
private bool _canSearch;
public bool CanSearch
{
get => _canSearch;
set
{
_canSearch = value;
OnPropertyChanged();
}
}
private bool _isBusy;
public bool IsBusy
{
get => _isBusy;
set
{
_isBusy = value;
OnPropertyChanged();
}
}
private bool _unparsed = true;
public bool Unparsed
{
get => _unparsed;
set
{
if (_unparsed == value)
{
return;
}
_unparsed = value;
OnPropertyChanged();
}
}
private string _filterText = string.Empty;
public string Search
{
get => _filterText;
set
{
var input = value ?? string.Empty;
if (_filterText.Equals(input))
{
return;
}
_filterText = value;
foreach (var project in Projects)
{
project.Filter = _filterText;
}
OnPropertyChanged();
}
}
private double? _fontSize = 12;
public double? FontSize
{
get => _fontSize ?? 12;
set
{
if (!value.HasValue || value.Equals(_fontSize))
{
return;
}
_fontSize = value;
OnPropertyChanged();
}
}
// This is just a binding hack to force the icon binding to re-evaluate. It has no other functionality and should
// not be used for anything else.
public bool ParserReady
{
get => true;
// ReSharper disable once ValueParameterNotUsed
set => OnPropertyChanged();
}
private void HandleStateChanged(object sender, ParserStateEventArgs e)
{
Unparsed = false;
if (e.State == ParserState.Ready && e.OldState != ParserState.Busy)
{
// Finished up resolving references, so we can now update the reference nodes.
//We have to wait for the task to guarantee that no new parse starts invalidating all cached components.
//CAUTION: This must not be executed from the UI thread!!!
_uiDispatcher.StartTask(() =>
{
var referenceFolders = Projects.SelectMany(node =>
node.Children.OfType<CodeExplorerReferenceFolderViewModel>());
foreach (var library in referenceFolders)
{
library.UpdateChildren();
}
Unparsed = !Projects.Any();
IsBusy = false;
ParserReady = true;
}).Wait();
return;
}
IsBusy = _state.Status != ParserState.Pending && _state.Status <= ParserState.ResolvedDeclarations;
if (e.State == ParserState.ResolvedDeclarations)
{
Synchronize(_state.DeclarationFinder.AllUserDeclarations);
}
}
/// <summary>
/// Updates the ViewModel tree to reflect changes in user declarations after a reparse.
/// </summary>
/// <param name="declarations">
/// The new declarations. This should always be the complete declaration set, and materializing
/// the IEnumerable should be deferred to UI thread.
/// </param>
private void Synchronize(IEnumerable<Declaration> declarations)
{
//We have to wait for the task to guarantee that no new parse starts invalidating all cached components.
_uiDispatcher.StartTask(() =>
{
var updates = declarations.ToList();
var existing = Projects.OfType<CodeExplorerProjectViewModel>().ToList();
foreach (var project in existing)
{
project.Synchronize(ref updates);
if (project.Declaration is null)
{
Projects.Remove(project);
}
}
var adding = updates.OfType<ProjectDeclaration>().ToList();
foreach (var project in adding)
{
var model = new CodeExplorerProjectViewModel(project, ref updates, _state, _vbe, _state.ProjectsProvider) { Filter = Search };
Projects.Add(model);
}
CanSearch = Projects.Any();
}).Wait();
}
private void ParserState_ModuleStateChanged(object sender, ParseProgressEventArgs e)
{
// if we are resolving references, we already have the declarations and don't need to display error
if (!(e.State == ParserState.Error ||
e.State == ParserState.ResolverError &&
e.OldState == ParserState.ResolvingDeclarations))
{
return;
}
var componentProjectId = e.Module.ProjectId;
var module = Projects.OfType<CodeExplorerProjectViewModel>()
.FirstOrDefault(p => p.Declaration?.ProjectId.Equals(componentProjectId) ?? false)?.Children
.OfType<CodeExplorerComponentViewModel>()
.FirstOrDefault(component => component.QualifiedSelection?.QualifiedName.Equals(e.Module) ?? false);
if (module == null)
{
return;
}
module.IsErrorState = true;
}
private void ExecuteClearSearchCommand(object parameter)
{
if (!string.IsNullOrEmpty(Search))
{
Search = string.Empty;
}
}
private void ExecuteCollapseAllCommand(object parameter)
{
foreach (var project in Projects)
{
ExecuteCollapseNodes(project);
}
}
private void ExecuteExpandAllCommand(object parameter)
{
foreach (var project in Projects)
{
ExecuteExpandNodes(project);
}
}
private bool EvaluateCanSwitchNodeState(object parameter)
{
return SelectedItem?.Children?.Any() ?? false;
}
private void ExecuteCollapseNodes(object parameter)
{
if (!(parameter is ICodeExplorerNode node))
{
return;
}
SwitchNodeState(node, false);
}
private void ExecuteExpandNodes(object parameter)
{
if (!(parameter is ICodeExplorerNode node))
{
return;
}
SwitchNodeState(node, true);
}
// this is a special case--we have to reset SelectedItem to prevent a crash
private void ExecuteRemoveCommand(object param)
{
var node = (CodeExplorerComponentViewModel)SelectedItem;
SelectedItem = Projects.FirstOrDefault(p => p.QualifiedSelection.HasValue
&& p.QualifiedSelection.Value.QualifiedName.ProjectId == node.Declaration.ProjectId);
_externalRemoveCommand.Execute(param);
}
public ReparseCommand RefreshCommand { get; set; }
public OpenCommand OpenCommand { get; set; }
public AddVBFormCommand AddVBFormCommand { get; set; }
public AddMDIFormCommand AddMDIFormCommand { get; set; }
public AddUserFormCommand AddUserFormCommand { get; set; }
public AddStdModuleCommand AddStdModuleCommand { get; set; }
public AddClassModuleCommand AddClassModuleCommand { get; set; }
public AddUserControlCommand AddUserControlCommand { get; set; }
public AddPropertyPageCommand AddPropertyPageCommand { get; set; }
public AddUserDocumentCommand AddUserDocumentCommand { get; set; }
public AddTestComponentCommand AddTestModuleCommand { get; set; }
public AddTestModuleWithStubsCommand AddTestModuleWithStubsCommand { get; set; }
public AddTemplateCommand AddTemplateCommand { get; set; }
public AnnotateDeclarationCommand AnnotateDeclarationCommand { get; set; }
public OpenDesignerCommand OpenDesignerCommand { get; set; }
public OpenProjectPropertiesCommand OpenProjectPropertiesCommand { get; set; }
public SetAsStartupProjectCommand SetAsStartupProjectCommand { get; set; }
public RenameCommand RenameCommand { get; set; }
public CodeExplorerMoveToFolderCommand MoveToFolderCommand { get; set; }
public IndentCommand IndenterCommand { get; set; }
public CodeExplorerFindAllReferencesCommand FindAllReferencesCommand { get; set; }
public CodeExplorerFindAllImplementationsCommand FindAllImplementationsCommand { get; set; }
public CommandBase CollapseAllSubnodesCommand { get; }
public CopyResultsCommand CopyResultsCommand { get; set; }
public CommandBase ExpandAllSubnodesCommand { get; }
public ImportCommand ImportCommand { get; set; }
public UpdateFromFilesCommand UpdateFromFilesCommand { get; set; }
public ReplaceProjectContentsFromFilesCommand ReplaceProjectContentsFromFilesCommand { get; set; }
public ExportCommand ExportCommand { get; set; }
public ExportAllCommand ExportAllCommand { get; set; }
public DeleteCommand DeleteCommand { get; set; }
public CommandBase RemoveCommand { get; }
public PrintCommand PrintCommand { get; set; }
public AddRemoveReferencesCommand AddRemoveReferencesCommand { get; set; }
public ICommand ClearSearchCommand { get; }
public CommandBase SyncCodePaneCommand { get; }
public CodeExplorerExtractInterfaceCommand CodeExplorerExtractInterfaceCommand { get; set; }
public CodeExplorerMoveToFolderDragAndDropCommand MoveToFolderDragAndDropCommand { get; set; }
public CommandBase CollapseAllCommand { get; }
public CommandBase ExpandAllCommand { get; }
public CommandBase PeekDefinitionCommand { get; }
public CommandBase ClosePeekDefinitionCommand { get; }
public PeekDefinitionFindAllReferencesCommand PeekFindReferencesCommand { get; set; }
public PeekDefinitionNavigateCommand PeekNavigateCommand { get; set; }
private bool _showPeekDefinitionPopup;
public bool ShowPeekDefinitionPopup
{
get => _showPeekDefinitionPopup;
set
{
if (value != _showPeekDefinitionPopup)
{
_showPeekDefinitionPopup = value;
OnPropertyChanged();
}
}
}
private PeekDefinitionViewModel _peekDefinitionViewModel;
public PeekDefinitionViewModel PeekDefinitionViewModel
{
get => _peekDefinitionViewModel;
private set
{
if (_peekDefinitionViewModel != value)
{
_peekDefinitionViewModel = value;
OnPropertyChanged();
}
}
}
private void ExecutePeekDefinitionCommand(object param)
{
if (param is ICodeExplorerNode node)
{
PeekDefinitionViewModel = new PeekDefinitionViewModel(node, PeekFindReferencesCommand, PeekNavigateCommand, ClosePeekDefinitionCommand, _state);
}
else if (param is Declaration declaration)
{
PeekDefinitionViewModel = new PeekDefinitionViewModel(declaration, PeekFindReferencesCommand, PeekNavigateCommand, ClosePeekDefinitionCommand, _state);
}
else
{
PeekDefinitionViewModel = null;
}
ShowPeekDefinitionPopup = PeekDefinitionViewModel != null;
}
private void ExecuteClosePeekDefinitionCommand(object param) => ShowPeekDefinitionPopup = false;
private bool CanExecutePeekDefinitionCommand(object param) => param is Declaration || SelectedItem is CodeExplorerMemberViewModel || SelectedItem is CodeExplorerComponentViewModel;
public ICodeExplorerNode FindVisibleNodeForDeclaration(Declaration declaration)
{
if (declaration == null)
{
return null;
}
var project = Projects.OfType<CodeExplorerProjectViewModel>().FirstOrDefault(proj =>
(proj.Declaration?.ProjectId ?? string.Empty).Equals(declaration.ProjectId));
if (declaration.DeclarationType == DeclarationType.Project)
{
return project;
}
var child = FindChildNodeForDeclaration(project, declaration);
return child;
}
private ICodeExplorerNode FindChildNodeForDeclaration(ICodeExplorerNode node, Declaration declaration)
{
if (node is null || declaration is null)
{
return null;
}
if (node.Declaration.DeclarationType == declaration.DeclarationType &&
node.Declaration.QualifiedName.Equals(declaration.QualifiedName))
{
return node;
}
return node.Children.OfType<CodeExplorerItemViewModel>()
.Select(child => FindChildNodeForDeclaration(child, declaration))
.FirstOrDefault(child => child != null);
}
private void SwitchNodeState(ICodeExplorerNode node, bool expandedState)
{
node.IsExpanded = expandedState;
foreach (var item in node.Children)
{
item.IsExpanded = expandedState;
SwitchNodeState(item, expandedState);
}
}
/// <summary>
/// Works backward from the passed node and expands all parents to make it visible.
/// </summary>
/// <param name="node"></param>
private void ExpandToNode(ICodeExplorerNode node)
{
while (true)
{
node = node.Parent;
if (node == null)
{
return;
}
node.IsExpanded = true;
}
}
private bool CanExecuteExportAllCommand => ExportAllCommand?.CanExecute(SelectedItem) ?? false;
public Visibility ExportVisibility => _vbe.Kind == VBEKind.Standalone || CanExecuteExportAllCommand ? Visibility.Collapsed : Visibility.Visible;
public Visibility ExportAllVisibility => CanExecuteExportAllCommand ? Visibility.Visible : Visibility.Collapsed;
public Visibility VB6Visibility => _vbe.Kind == VBEKind.Standalone ? Visibility.Visible : Visibility.Collapsed;
public Visibility VBAVisibility => _vbe.Kind == VBEKind.Hosted ? Visibility.Visible : Visibility.Collapsed;
public bool AllowDragAndDrop { get; internal set; }
private void GeneralSettingsChanged(object sender, ConfigurationChangedEventArgs e)
{
RefreshDragAndDropSetting();
}
private void RefreshDragAndDropSetting()
{
AllowDragAndDrop = _generalSettingsProvider.Read().EnableFolderDragAndDrop;
}
public void Dispose()
{
if (_state != null)
{
_state.StateChanged -= HandleStateChanged;
_state.ModuleStateChanged -= ParserState_ModuleStateChanged;
_generalSettingsProvider.SettingsChanged -= GeneralSettingsChanged;
}
}
// IPeekDefinitionPopupProvider.PeekDefinition
public void PeekDefinition(Declaration target) => ExecutePeekDefinitionCommand(target);
}
}