-
Notifications
You must be signed in to change notification settings - Fork 675
Expand file tree
/
Copy pathDynamoView.xaml.cs
More file actions
3396 lines (2906 loc) · 136 KB
/
Copy pathDynamoView.xaml.cs
File metadata and controls
3396 lines (2906 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Dynamo.Configuration;
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Presets;
using Dynamo.Graph.Workspaces;
using Dynamo.Logging;
using Dynamo.Models;
using Dynamo.Nodes;
using Dynamo.PackageManager;
using Dynamo.PackageManager.UI;
using Dynamo.PythonServices;
using Dynamo.Search.SearchElements;
using Dynamo.Selection;
using Dynamo.Services;
using Dynamo.UI.Commands;
using Dynamo.UI.Controls;
using Dynamo.UI.Prompts;
using Dynamo.Utilities;
using Dynamo.ViewModels;
using Dynamo.Views;
using Dynamo.Wpf;
using Dynamo.Wpf.Authentication;
using Dynamo.Wpf.Extensions;
using Dynamo.Wpf.UI;
using Dynamo.Wpf.UI.GuidedTour;
using Dynamo.Wpf.Utilities;
using Dynamo.Wpf.Views;
using Dynamo.Wpf.Views.Debug;
using Dynamo.Wpf.Views.FileTrust;
using Dynamo.Wpf.Views.GuidedTour;
using Dynamo.Wpf.Windows;
using HelixToolkit.Wpf.SharpDX;
using ICSharpCode.AvalonEdit;
using PythonNodeModels;
using Brush = System.Windows.Media.Brush;
using Exception = System.Exception;
using Image = System.Windows.Controls.Image;
using Point = System.Windows.Point;
using Res = Dynamo.Wpf.Properties.Resources;
using ResourceNames = Dynamo.Wpf.Interfaces.ResourceNames;
using Size = System.Windows.Size;
using String = System.String;
namespace Dynamo.Controls
{
/// <summary>
/// Interaction logic for DynamoView.xaml
/// </summary>
public partial class DynamoView : Window, IDisposable
{
public const string BackgroundPreviewName = "BackgroundPreview";
private const int SideBarCollapseThreshold = 20;
private const int RightSideBarCollapseThreshold = 100;
private const int navigationInterval = 100;
private const string GraphMetadataExtensionId = "28992e1d-abb9-417f-8b1b-05e053bee670";
// This is used to determine whether ESC key is being held down
private bool IsEscKeyPressed = false;
// internal for testing.
internal readonly NodeViewCustomizationLibrary nodeViewCustomizationLibrary;
private double restoreWidth = 0;
private DynamoViewModel dynamoViewModel;
private readonly Stopwatch _timer;
private StartPageViewModel startPage;
private int tabSlidingWindowStart, tabSlidingWindowEnd;
private readonly LoginService loginService;
private ShortcutToolbar shortcutBar;
private PreferencesView preferencesWindow;
private PackageManagerView packageManagerWindow;
private bool loaded = false;
private bool graphMetadataHooked;
private MenuItem graphPropsGeneralMenuItem;
private MenuItem graphPropsExtensionMenuItem;
// This is to identify whether the PerformShutdownSequenceOnViewModel() method has been
// called on the view model and the process is not cancelled
private bool isPSSCalledOnViewModelNoCancel = false;
private readonly DispatcherTimer _workspaceResizeTimer = new DispatcherTimer { Interval = new TimeSpan(0, 0, 0, 0, 500), IsEnabled = false };
private ViewLoadedParams sharedViewExtensionLoadedParams;
/// <summary>
/// keeps the width right menu of the ShourtcutBar
/// </summary>
private double toolBarRightMenuWidth = 0;
/// <summary>
/// Keeps the additional Width based on the paddings and margins from the shorcutBar controls to calculate the whole Width
/// </summary>
private double additionalWidth = 50;
/// <summary>
/// Extensions currently displayed as windows.
/// Made internal for testing purposes only.
/// </summary>
internal Dictionary<string, ExtensionWindow> ExtensionWindows { get; set; } = new Dictionary<string, ExtensionWindow>();
internal ViewExtensionManager viewExtensionManager;
internal Watch3DView BackgroundPreview { get; private set; }
private FileTrustWarning fileTrustWarningPopup = null;
internal ShortcutToolbar ShortcutBar { get { return shortcutBar; } }
internal PreferencesView PreferencesWindow
{
get { return preferencesWindow; }
}
internal Dynamo.UI.Views.HomePage homePage;
/// <summary>
/// Keeps the default value of the Window's MinWidth to calculate it again later
/// </summary>
internal double DefaultMinWidth = 0;
/// <summary>
/// Command to toggle the library (left) sidebar visibility.
/// </summary>
public ICommand ToggleLibrarySidebarCommand { get; private set; }
/// <summary>
/// Command to toggle the extensions (right) sidebar visibility.
/// </summary>
public ICommand ToggleExtensionsSidebarCommand { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="dynamoViewModel">Dynamo view model</param>
public DynamoView(DynamoViewModel dynamoViewModel)
{
// The user's choice to enable hardware acceleration is now saved in
// the Dynamo preferences. It is set to true by default.
// When the view is constructed, we enable or disable hardware acceleration based on that preference.
// This preference is not exposed in the UI and can be used to debug hardware issues only
// by modifying the preferences xml.
RenderOptions.ProcessRenderMode = dynamoViewModel.Model.PreferenceSettings.UseHardwareAcceleration ?
RenderMode.Default : RenderMode.SoftwareOnly;
this.dynamoViewModel = dynamoViewModel;
this.dynamoViewModel.UIDispatcher = Dispatcher;
nodeViewCustomizationLibrary = new NodeViewCustomizationLibrary(this.dynamoViewModel.Model.Logger);
DataContext = dynamoViewModel;
Title = dynamoViewModel.BrandingResourceProvider.GetString(ResourceNames.MainWindow.Title);
tabSlidingWindowStart = tabSlidingWindowEnd = 0;
//Initialize the ViewExtensionManager with the CommonDataDirectory so that view extensions found here are checked first for dll's with signed certificates
viewExtensionManager = new ViewExtensionManager(dynamoViewModel.Model.ExtensionManager);
_timer = new Stopwatch();
_timer.Start();
ToggleLibrarySidebarCommand = new DelegateCommand(_ => ToggleLibrarySidebarCollapseStatus());
ToggleExtensionsSidebarCommand = new DelegateCommand(_ => ToggleExtensionBarCollapseStatus());
InitializeComponent();
Loaded += DynamoView_Loaded;
Unloaded += DynamoView_Unloaded;
SizeChanged += DynamoView_SizeChanged;
LocationChanged += DynamoView_LocationChanged;
MouseLeftButtonDown += DynamoView_MouseLeftButtonDown;
// Apply appropriate expand/collapse library button state depending on initial width
UpdateLibraryCollapseIcon();
// Check that preference bounds are actually within one
// of the available monitors.
if (CheckVirtualScreenSize())
{
System.Windows.Forms.Screen[] screens = System.Windows.Forms.Screen.AllScreens;
int leftLimit = 0;
int topLimit = 0;
foreach (var screen in screens)
{
leftLimit += screen.Bounds.Width;
topLimit += screen.Bounds.Height;
}
Left = dynamoViewModel.Model.PreferenceSettings.WindowX;
Top = dynamoViewModel.Model.PreferenceSettings.WindowY;
Width = dynamoViewModel.Model.PreferenceSettings.WindowW;
Height = dynamoViewModel.Model.PreferenceSettings.WindowH;
//When the previous location was in a secondary screen then the next time Dynamo is launched will try to use the same location, then we need to added this validations to show Dynamo in the right place
if (Left > leftLimit)
Left = 0;
if (Top > topLimit)
Top = 0;
}
else
{
Left = 0;
Top = 0;
Width = 1024;
Height = 768;
}
_workspaceResizeTimer.Tick += _resizeTimer_Tick;
if (dynamoViewModel.Model.AuthenticationManager.HasAuthProvider)
{
loginService = new LoginService(this, new System.Windows.Forms.WindowsFormsSynchronizationContext());
dynamoViewModel.Model.AuthenticationManager.AuthProvider.RequestLogin += loginService.ShowLogin;
}
DynamoModel.OnRequestUpdateLoadBarStatus(new SplashScreenLoadEventArgs(Res.SplashScreenViewExtensions, 100));
var viewExtensions = new List<IViewExtension>();
foreach (var dir in dynamoViewModel.Model.PathManager.ViewExtensionsDirectories)
{
viewExtensions.AddRange(viewExtensionManager.ExtensionLoader.LoadDirectory(dir));
}
viewExtensionManager.MessageLogged += Log;
var startupParams = new ViewStartupParams(dynamoViewModel);
foreach (var ext in viewExtensions)
{
try
{
if (ext is ILogSource logSource)
{
logSource.MessageLogged += Log;
}
if (ext is INotificationSource notificationSource)
{
notificationSource.NotificationLogged += LogNotification;
}
ext.Startup(startupParams);
// if we are starting ViewExtension (A) which is a source of other extensions (like packageManager)
// then we can start the ViewExtension(s) (B) that it requested be loaded.
if (ext is IViewExtensionSource)
{
foreach (var loadedExtension in ((ext as IViewExtensionSource).RequestedExtensions))
{
(loadedExtension).Startup(startupParams);
}
}
viewExtensionManager.Add(ext);
}
catch (Exception exc)
{
Log(ext.Name + ": " + exc.Message);
}
}
// when an extension is added if dynamoView is loaded, call loaded on
// that extension (this alerts late loaded extensions).
this.viewExtensionManager.ExtensionAdded += (extension) =>
{
if (this.loaded)
{
DynamoLoadedViewExtensionHandler(new ViewLoadedParams(this, this.dynamoViewModel),
new List<IViewExtension>() { extension });
}
};
// Add an event handler to check if the collection is modified.
dynamoViewModel.SideBarTabItems.CollectionChanged += this.OnCollectionChanged;
this.HideOrShowRightSideBar();
this.dynamoViewModel.RequestPaste += OnRequestPaste;
this.dynamoViewModel.RequestCloseHomeWorkSpace += OnRequestCloseHomeWorkSpace;
this.dynamoViewModel.RequestReturnFocusToView += OnRequestReturnFocusToView;
this.dynamoViewModel.Model.WorkspaceSaving += OnWorkspaceSaving;
this.dynamoViewModel.Model.WorkspaceOpened += OnWorkspaceOpened;
this.dynamoViewModel.Model.WorkspaceAdded += OnWorkspaceAdded;
this.dynamoViewModel.Model.WorkspaceHidden += OnWorkspaceHidden;
this.dynamoViewModel.RequestEnableShortcutBarItems += DynamoViewModel_RequestEnableShortcutBarItems;
this.dynamoViewModel.RequestExportWorkSpaceAsImage += OnRequestExportWorkSpaceAsImage;
this.dynamoViewModel.ShowGraphPropertiesRequested += DynamoViewModel_ShowGraphPropertiesRequested;
//add option to update python engine for all python nodes in the workspace.
AddPythonEngineToMainMenu();
PythonEngineManager.Instance.AvailableEngines.CollectionChanged += OnPythonEngineListUpdated;
dynamoViewModel.Owner = this;
FocusableGrid.InputBindings.Clear();
if (fileTrustWarningPopup == null)
{
fileTrustWarningPopup = new FileTrustWarning(this);
}
if (!DynamoModel.IsTestMode && string.IsNullOrEmpty(DynamoModel.HostAnalyticsInfo.HostName) && Application.Current != null)
{
Application.Current.MainWindow = this;
}
DefaultMinWidth = MinWidth;
PinHomeButton();
}
private void DynamoViewModel_ShowGraphPropertiesRequested(object sender, EventArgs e)
{
EnsureGraphPropertiesBinding();
var provider = viewExtensionManager.ViewExtensions
.OfType<IExtensionMenuProvider>()
.FirstOrDefault(ext => (ext as IViewExtension)?.UniqueId == GraphMetadataExtensionId);
var extItem = provider?.GetFileMenuItem();
if (extItem == null) return;
extItem.IsChecked = !extItem.IsChecked;
}
private void EnsureGraphPropertiesBinding()
{
if (graphMetadataHooked) return;
graphPropsGeneralMenuItem = this.FindName("general") as MenuItem;
if (graphPropsGeneralMenuItem == null) return;
var provider = viewExtensionManager.ViewExtensions
.OfType<IExtensionMenuProvider>()
.FirstOrDefault(ext => (ext as IViewExtension)?.UniqueId == GraphMetadataExtensionId);
graphPropsExtensionMenuItem = provider?.GetFileMenuItem();
if (graphPropsExtensionMenuItem == null) return;
graphPropsGeneralMenuItem.IsCheckable = true;
graphPropsGeneralMenuItem.IsChecked = graphPropsExtensionMenuItem.IsChecked;
graphPropsExtensionMenuItem.Checked += OnGraphMetadataChecked;
graphPropsExtensionMenuItem.Unchecked += OnGraphMetadataUnchecked;
graphMetadataHooked = true;
}
private void OnGraphMetadataChecked(object sender, RoutedEventArgs e)
{
if (graphPropsGeneralMenuItem != null)
{
graphPropsGeneralMenuItem.IsChecked = true;
}
}
private void OnGraphMetadataUnchecked(object sender, RoutedEventArgs e)
{
if (graphPropsGeneralMenuItem != null)
{
graphPropsGeneralMenuItem.IsChecked = false;
}
}
private void OnRequestCloseHomeWorkSpace()
{
CalculateWindowMinWidth();
}
private void OnPythonEngineListUpdated(object sender, NotifyCollectionChangedEventArgs e)
{
//Update the main menu Python Engine list whenever a python engine is added or removed.
AddPythonEngineToMainMenu();
}
/// <summary>
/// Populates the PythonEngineMenu in the main menu bar with currently available python engines.
/// </summary>
private void AddPythonEngineToMainMenu()
{
PythonEngineMenu.Items.Clear();
var availablePythonEngines = PythonEngineManager.Instance.AvailableEngines.Select(x => x.Name).ToList();
availablePythonEngines.Select(pythonEngine => new MenuItem
{
Header = pythonEngine,
Command = dynamoViewModel.UpdateAllPythonEngineCommand,
CommandParameter = pythonEngine
}).ToList().ForEach(x => PythonEngineMenu.Items.Add(x));
}
private void OnWorkspaceHidden(WorkspaceModel workspace)
{
CalculateWindowMinWidth();
}
private void OnWorkspaceAdded(WorkspaceModel workspace)
{
CalculateWindowMinWidth();
}
private void OnRequestExportWorkSpaceAsImage(object parameter)
{
var workspace = this.ChildOfType<WorkspaceView>();
WorkspaceView.ExportImageResult isCurrentWorkSpaceValidForImage = workspace.IsWorkSpaceRenderValidAsImage(true);
if (isCurrentWorkSpaceValidForImage == WorkspaceView.ExportImageResult.IsValidAsImage)
{
dynamoViewModel.ShowSaveImageDialogAndSave(parameter);
}
else if (isCurrentWorkSpaceValidForImage == WorkspaceView.ExportImageResult.EmptyDrawing)
{
dynamoViewModel.ToastManager?.CreateRealTimeInfoWindow(Res.CantExportWorkspaceAsImageEmptyMessage, true);
}
else if (isCurrentWorkSpaceValidForImage == WorkspaceView.ExportImageResult.NotValidAsImage)
{
dynamoViewModel.ToastManager?.CreateRealTimeInfoWindow(Res.CantExportWorkspaceAsImageNotValidMessage, true);
}
}
void DynamoView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (PreferencesWindow != null && PreferencesWindow.IsLoaded)
{
dynamoViewModel.ToastManager?.CreateRealTimeInfoWindow(Res.PreferencesMustBeClosedMessage, true);
}
}
private void DynamoViewModel_RequestEnableShortcutBarItems(bool enable)
{
if (!(saveThisButton is null))
{
saveThisButton.IsEnabled = enable;
saveButton.IsEnabled = enable;
}
if (!(exportMenu is null))
{
exportMenu.IsEnabled = enable;
}
if (!(shortcutBar is null))
{
shortcutBar.IsNewButtonEnabled = enable;
shortcutBar.IsOpenButtonEnabled = enable;
shortcutBar.IsSaveButtonEnabled = enable;
shortcutBar.IsLoginMenuEnabled = enable;
shortcutBar.IsExportMenuEnabled = enable;
shortcutBar.IsNotificationCenterEnabled = enable;
if (dynamoViewModel.ShowStartPage)
{
shortcutBar.IsNewButtonEnabled = true;
shortcutBar.IsOpenButtonEnabled = true;
shortcutBar.IsLoginMenuEnabled = true;
shortcutBar.IsNotificationCenterEnabled = true;
}
if (dynamoViewModel.Model.NoNetworkMode)
{
shortcutBar.IsLoginMenuEnabled = false;
}
}
}
private void OnWorkspaceOpened(WorkspaceModel workspace)
{
if (!(saveThisButton is null))
{
saveThisButton.IsEnabled = true;
saveButton.IsEnabled = true;
}
if (!(exportMenu is null))
{
exportMenu.IsEnabled = true;
}
if (!(shortcutBar is null))
{
ShortcutBar.IsSaveButtonEnabled = true;
shortcutBar.IsExportMenuEnabled = true;
}
if (!(workspace is HomeWorkspaceModel hws))
return;
foreach (var extension in viewExtensionManager.StorageAccessViewExtensions)
{
DynamoModel.RaiseIExtensionStorageAccessWorkspaceOpened(hws, extension, dynamoViewModel.Model.Logger);
}
}
private void OnWorkspaceSaving(WorkspaceModel workspace, Graph.SaveContext saveContext)
{
if (!(workspace is HomeWorkspaceModel hws))
return;
foreach (var extension in viewExtensionManager.StorageAccessViewExtensions)
{
DynamoModel.RaiseIExtensionStorageAccessWorkspaceSaving(hws, extension, saveContext, dynamoViewModel.Model.Logger);
}
dynamoViewModel?.CheckOnlineAccess();
}
private void OnPythonEngineUpgradeToastRequested(string msg, bool stayOpen, string filePath)
{
Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.ContextIdle,
new Action(() =>
{
Uri fileUri = null;
var hasFile = !string.IsNullOrWhiteSpace(filePath) && Uri.TryCreate(filePath, UriKind.Absolute, out fileUri);
dynamoViewModel.ToastManager?.CreateRealTimeInfoWindow(
msg,
stayOpen,
headerText: Res.CPython3EngineNotificationMessageBoxHeader,
hyperlinkText: Res.LearnMore,
hyperlinkUri: new Uri(Res.CPython3EngineUpgradeLearnMoreUri),
fileLinkUri: hasFile ? fileUri : null);
}));
}
/// <summary>
/// Adds an extension control or if it already exists it makes sure it is focused.
/// The control may be added as a window or a tab in the extension bar depending on settings.
/// </summary>
/// <param name="viewExtension">View extension adding the content</param>
/// <param name="content">Control being added</param>
/// <returns>True if the control was added, false if it already existed</returns>
internal bool AddOrFocusExtensionControl(IViewExtension viewExtension, UIElement content)
{
var window = ExtensionWindows.ContainsKey(viewExtension.Name) ? ExtensionWindows[viewExtension.Name] : null;
var tab = FindExtensionTab(viewExtension);
var addExtensionControl = window == null && tab == null;
if (addExtensionControl)
{
var settings = this.dynamoViewModel.PreferenceSettings.ViewExtensionSettings.Find(s => s.UniqueId == viewExtension.UniqueId);
// Create default settings if they do not currently exist
if (settings == null)
{
settings = new ViewExtensionSettings()
{
Name = viewExtension.Name,
UniqueId = viewExtension.UniqueId,
DisplayMode = ViewExtensionDisplayMode.DockRight
};
this.dynamoViewModel.PreferenceSettings.ViewExtensionSettings.Add(settings);
}
if (this.dynamoViewModel.PreferenceSettings.EnablePersistExtensions)
{
settings.IsOpen = true;
}
if (settings.DisplayMode == ViewExtensionDisplayMode.FloatingWindow)
{
window = AddExtensionWindow(viewExtension, content, settings.WindowSettings);
}
else
{
tab = AddExtensionTab(viewExtension, content);
}
}
else
{
// Set focus on the existing control
if (window != null)
{
window.Focus();
}
else if (tab != null)
{
// Make sure the extension bar is visible
if (ExtensionsCollapsed)
{
ToggleExtensionBarCollapseStatus();
}
tabDynamic.SelectedItem = tab;
}
}
return addExtensionControl;
}
private ExtensionWindow AddExtensionWindow(IViewExtension viewExtension, UIElement content, WindowSettings windowSettings)
{
ExtensionWindow window;
if (windowSettings == null)
{
window = new ExtensionWindow();
window.Owner = this;
}
else
{
var windowRect = new ModelessChildWindow.WindowRect()
{
Left = windowSettings.Left,
Top = windowSettings.Top,
Width = windowSettings.Width,
Height = windowSettings.Height
};
window = new ExtensionWindow(this, ref windowRect);
if (windowSettings.Status == WindowStatus.Maximized)
{
// Rather than setting the WindowState here, this is delayed to the Loaded event.
// This helps overcome a bug which makes the window appear always on the primary screen.
window.ShouldMaximize = true;
}
}
// Setting the content of the undocked window
// Icon is passed from DynamoView (respecting Host integrator icon)
SetApplicationIcon();
window.Icon = this.Icon;
if (content is Window container)
{
content = container.Content as UIElement;
container.Owner = this;
}
window.ExtensionContent.Content = content;
window.Title = viewExtension.Name;
window.Tag = viewExtension;
window.Uid = viewExtension.UniqueId;
window.Closing += ExtensionWindow_Closing;
window.Closed += ExtensionWindow_Closed;
window.Show();
ExtensionWindows.Add(viewExtension.Name, window);
return window;
}
private void ExtensionWindow_Closing(object sender, CancelEventArgs e)
{
var window = sender as ExtensionWindow;
SaveExtensionWindowSettings(window);
}
private void SaveExtensionWindowSettings(ExtensionWindow window)
{
var extension = window.Tag as IViewExtension;
var settings = this.dynamoViewModel.Model.PreferenceSettings.ViewExtensionSettings.Find(ext => ext.UniqueId == extension.UniqueId);
if (settings != null)
{
if (settings.WindowSettings == null)
{
settings.WindowSettings = new WindowSettings();
}
settings.WindowSettings.Status = window.WindowState == WindowState.Maximized ? WindowStatus.Maximized : WindowStatus.Normal;
settings.WindowSettings.Left = (int)window.SavedWindowRect.Left;
settings.WindowSettings.Top = (int)window.SavedWindowRect.Top;
settings.WindowSettings.Width = (int)window.SavedWindowRect.Width;
settings.WindowSettings.Height = (int)window.SavedWindowRect.Height;
}
}
private TabItem AddExtensionTab(IViewExtension viewExtension, UIElement content)
{
// creates a new tab item
var tab = new TabItem();
tab.Header = viewExtension.Name;
tab.Tag = viewExtension;
tab.Uid = viewExtension.UniqueId;
tab.HeaderTemplate = tabDynamic.FindResource("TabHeader") as DataTemplate;
// setting the extension UI to the current tab content
// based on whether it is a UserControl element or window element.
if (content is Window container)
{
content = container.Content as UIElement;
// Make sure the extension window closes with Dynamo
container.Owner = this;
}
tab.Content = content;
//Insert the tab at the end
dynamoViewModel.SideBarTabItems.Insert(dynamoViewModel.SideBarTabItems.Count, tab);
tabDynamic.SelectedItem = tab;
return tab;
}
private void UpdateNodeIcons_Click(object sender, RoutedEventArgs e)
{
var updateNodeIconsWindow = new UpdateNodeIconsWindow(dynamoViewModel.Model.SearchModel.Entries);
updateNodeIconsWindow.Owner = this;
updateNodeIconsWindow.WindowStartupLocation = WindowStartupLocation.CenterOwner;
updateNodeIconsWindow.ShowDialog();
}
/// <summary>
/// Dock the window to right side bar panel.
/// </summary>
/// <param name="window">The window that needs to be docked</param>
/// <param name="nodeModel">NodeModel, if it is a node window</param>
/// <param name="hideUIElement">Any UI element to hide after docking it in the right sidebar(like the toolbar).</param>
/// <returns></returns>
internal TabItem DockWindowInSideBar(Window window, NodeModel nodeModel = null, UIElement hideUIElement = null)
{
var tabItem = dynamoViewModel.SideBarTabItems.OfType<TabItem>().SingleOrDefault(tabtem => tabtem.Uid.ToString() == window.Uid);
if (tabItem != null)
{
tabDynamic.SelectedItem = tabItem;
if (ExtensionsCollapsed) ToggleExtensionBarCollapseStatus();
return tabItem;
}
if (hideUIElement != null)
{
hideUIElement.Visibility = Visibility.Collapsed;
}
var content = window.Content;
// creates a new tab item
var tab = new TabItem();
tab.Header = window.Title;
tab.Tag = window;
tab.Uid = window.Uid;
tab.HeaderTemplate = tabDynamic.FindResource("TabHeader") as DataTemplate;
// setting the window UI to the current tab content
// based on whether it is a UserControl element or window element.
if (content is Window container)
{
content = container.Content as UIElement;
// Make sure the window closes with Dynamo
container.Owner = this;
}
tab.Content = content;
//Insert the tab at the end
dynamoViewModel.SideBarTabItems.Insert(dynamoViewModel.SideBarTabItems.Count, tab);
tabDynamic.SelectedItem = tab;
if (nodeModel != null)
{
dynamoViewModel.DockedNodeWindows.Add(window.Uid);
dynamoViewModel.NodeWindowsState[window.Uid] = ViewExtensionDisplayMode.DockRight;
}
return tab;
}
/// <summary>
/// This method will close an extension control, whether it's on the side bar or undocked as a window.
/// </summary>
/// <param name="viewExtension">Extension to be closed</param>
/// <returns></returns>
internal void CloseExtensionControl(IViewExtension viewExtension)
{
string tabName = viewExtension.Name;
TabItem tabitem = dynamoViewModel.SideBarTabItems.OfType<TabItem>().SingleOrDefault(n => n.Header.ToString() == tabName);
if (viewExtension is ViewExtensionBase viewExtensionBase)
{
viewExtensionBase.Closed();
}
CloseRightSideBarTab(tabitem);
CloseExtensionWindow(tabName);
}
/// <summary>
/// Event handler for the CloseButton.
/// This method triggers the close operation on the selected tab.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void OnCloseRightSideBarTab(object sender, RoutedEventArgs e)
{
try
{
string tabId = (sender as Button).Uid.ToString();
TabItem tabitem = dynamoViewModel.SideBarTabItems.OfType<TabItem>().SingleOrDefault(n => n.Uid.ToString() == tabId);
if (tabitem.Tag is ViewExtensionBase viewExtensionBase)
{
viewExtensionBase.Closed();
}
NodeModel nodeModel = dynamoViewModel.GetDockedWindowNodeModel(tabitem.Uid);
if (nodeModel is PythonNode pythonNode)
{
var editor = (tabitem.Content as Grid).ChildOfType<TextEditor>();
if (editor != null && editor.IsModified)
{
pythonNode.OnWarnUserScript();
return;
}
}
CloseRightSideBarTab(tabitem);
if (dynamoViewModel.DockedNodeWindows.Contains(tabitem.Uid))
{
dynamoViewModel.DockedNodeWindows.Remove(tabitem.Uid);
}
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log("Failed to close the tab from right side-bar panel.");
dynamoViewModel.Model.Logger.Log(ex.Message);
dynamoViewModel.Model.Logger.Log(ex.StackTrace);
}
}
/// <summary>
/// Close right side-bar panel tab by extension tab item
/// </summary>
/// <param name="tabitem">target tab item</param>
internal void CloseRightSideBarTab(TabItem tabitem)
{
TabItem tabToBeRemoved = tabitem;
// get the selected tab
TabItem selectedTab = tabDynamic.SelectedItem as TabItem;
if (tabToBeRemoved != null && dynamoViewModel.SideBarTabItems.Count > 0)
{
// Remove the tab from the binding collection SideBarTabItems
dynamoViewModel.SideBarTabItems.Remove(tabToBeRemoved);
// Disconnect content from tab to allow it to be moved.
tabToBeRemoved.Content = null;
// Highlight previously selected tab. if that is removed then Highlight the first tab
if (selectedTab.Equals(tabToBeRemoved))
{
if (dynamoViewModel.SideBarTabItems.Count > 0)
{
selectedTab = dynamoViewModel.SideBarTabItems[0];
}
}
tabDynamic.SelectedItem = selectedTab;
}
}
private void CloseExtensionWindow(string name)
{
if (ExtensionWindows.ContainsKey(name))
{
var extension = ExtensionWindows[name];
extension.Close();
// Disconnect content to allow it to be moved.
extension.ExtensionContent.Content = null;
ExtensionWindows.Remove(name);
}
}
internal void OnUndockRightSideBarTab(object sender, RoutedEventArgs e)
{
try
{
var tabId = (sender as Button).Uid.ToString();
var tabItem = dynamoViewModel.SideBarTabItems.OfType<TabItem>().SingleOrDefault(tab => tab.Uid.ToString() == tabId);
var tabName = tabItem.Header.ToString();
// If docked window is a node window, undock the window and call the action on the node.
if (dynamoViewModel.DockedNodeWindows.Contains(tabItem.Uid))
{
UndockWindow(tabItem);
}
else// if it an extension, undock the extension and update settings.
{
UndockExtension(tabItem);
Analytics.TrackEvent(
Actions.Undock,
Categories.ViewExtensionOperations, tabName);
}
}
catch (Exception ex)
{
dynamoViewModel.Model.Logger.Log("Failed to undock the tab from right side-bar panel.");
dynamoViewModel.Model.Logger.Log(ex.Message);
dynamoViewModel.Model.Logger.Log(ex.StackTrace);
}
}
/// <summary>
/// Undocks the extension with the given name.
/// Made internal for testing purposes only.
/// </summary>
/// <param name="name">Name of the extension</param>
internal void UndockExtension(string name)
{
var tabItem = dynamoViewModel.SideBarTabItems.OfType<TabItem>().SingleOrDefault(tab => tab.Header.ToString() == name);
var content = tabItem.Content as UIElement;
CloseRightSideBarTab(tabItem);
var extension = tabItem.Tag as IViewExtension;
var settings = this.dynamoViewModel.PreferenceSettings.ViewExtensionSettings.Find(s => s.UniqueId == extension.UniqueId);
AddExtensionWindow(extension, content, settings?.WindowSettings);
if (settings != null)
{
settings.DisplayMode = ViewExtensionDisplayMode.FloatingWindow;
}
}
/// <summary>
/// Undocks the extension from the right side bar.
/// </summary>
/// <param name="tabItem">Tab item to be undocked</param>
internal void UndockExtension(TabItem tabItem)
{
var content = tabItem.Content as UIElement;
CloseRightSideBarTab(tabItem);
var extension = tabItem.Tag as IViewExtension;
var settings = this.dynamoViewModel.PreferenceSettings.ViewExtensionSettings.Find(s => s.UniqueId == extension.UniqueId);
AddExtensionWindow(extension, content, settings?.WindowSettings);
if (settings != null)
{
settings.DisplayMode = ViewExtensionDisplayMode.FloatingWindow;
}
}
/// <summary>
/// Undocks to an internal Dynamo window by checking the window type.
/// </summary>
/// <param name="tabItem">Tab item to be undocked</param>
internal void UndockWindow(TabItem tabItem)
{
NodeModel nodeModel = dynamoViewModel.GetDockedWindowNodeModel(tabItem.Uid);
dynamoViewModel.NodeWindowsState[tabItem.Uid] = ViewExtensionDisplayMode.FloatingWindow;
//if the undocked window is a python node, open the script edit window.
if (nodeModel is PythonNode)
{
var pythonNode = nodeModel as PythonNode;
Window window = tabItem.Tag as Window;
var textEditor = window.FindName("editText") as TextEditor;
if (textEditor.IsModified)
{
pythonNode.OnNodeEdited(textEditor.Text);
}
else
{
pythonNode.OnNodeEdited(null);
}
Analytics.TrackEvent(
Actions.Undock,
Categories.PythonOperations, tabItem.Header.ToString());
}
CloseRightSideBarTab(tabItem);
dynamoViewModel.DockedNodeWindows.Remove(tabItem.Uid);
}
/// <summary>
/// Sets DynamoView icon to that of the currently running application. This is set for reuse
/// in custom child windows rather than for the main window itself, which is not customized.
/// </summary>
private void SetApplicationIcon()
{
if (this.Icon == null && !DynamoModel.IsTestMode)
{
var applicationPath = Process.GetCurrentProcess().MainModule.FileName;
try
{
var icon = System.Drawing.Icon.ExtractAssociatedIcon(applicationPath);
var bmp = icon.ToBitmap();
MemoryStream stream = new MemoryStream();
bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
stream.Seek(0, SeekOrigin.Begin);
PngBitmapDecoder pngDecoder = new PngBitmapDecoder(stream, BitmapCreateOptions.None, BitmapCacheOption.Default);
this.Icon = pngDecoder.Frames[0];
}
catch (Exception ex)
{
Log(string.Format(Dynamo.Wpf.Properties.Resources.ErrorLoadingIcon, ex.Message));
}
}
}
private void ExtensionWindow_Closed(object sender, EventArgs e)
{
var window = sender as ExtensionWindow;
var extName = window.Title;
var content = window.ExtensionContent.Content as UIElement;
// Release content from window
window.ExtensionContent.Content = null;
ExtensionWindows.Remove(extName);
var extension = window.Tag as IViewExtension;
if (window.DockRequested)
{
AddExtensionTab(extension, content);
var settings = this.dynamoViewModel.PreferenceSettings.ViewExtensionSettings.Find(s => s.UniqueId == extension.UniqueId);
if (settings != null)
{
settings.DisplayMode = ViewExtensionDisplayMode.DockRight;
}
Analytics.TrackEvent(Actions.Dock, Categories.ViewExtensionOperations, extName);