-
Notifications
You must be signed in to change notification settings - Fork 809
Expand file tree
/
Copy pathPowerShellHostViewModel.cs
More file actions
700 lines (538 loc) · 18.9 KB
/
PowerShellHostViewModel.cs
File metadata and controls
700 lines (538 loc) · 18.9 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
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;
using Dragablz;
using MahApps.Metro.Controls.Dialogs;
using NETworkManager.Controls;
using NETworkManager.Localization.Resources;
using NETworkManager.Models;
using NETworkManager.Models.EventSystem;
using NETworkManager.Models.PowerShell;
using NETworkManager.Profiles;
using NETworkManager.Settings;
using NETworkManager.Utilities;
using NETworkManager.Views;
using PowerShell = NETworkManager.Profiles.Application.PowerShell;
namespace NETworkManager.ViewModels;
public class PowerShellHostViewModel : ViewModelBase, IProfileManager
{
#region Variables
private readonly IDialogCoordinator _dialogCoordinator;
private readonly DispatcherTimer _searchDispatcherTimer = new();
public IInterTabClient InterTabClient { get; }
private string _interTabPartition;
public string InterTabPartition
{
get => _interTabPartition;
set
{
if (value == _interTabPartition)
return;
_interTabPartition = value;
OnPropertyChanged();
}
}
public ObservableCollection<DragablzTabItem> TabItems { get; }
private readonly bool _isLoading;
private bool _isViewActive = true;
private bool _disableFocusEmbeddedWindow;
private bool _isConfigured;
public bool IsConfigured
{
get => _isConfigured;
set
{
if (value == _isConfigured)
return;
_isConfigured = value;
OnPropertyChanged();
}
}
private int _selectedTabIndex;
public int SelectedTabIndex
{
get => _selectedTabIndex;
set
{
if (value == _selectedTabIndex)
return;
_selectedTabIndex = value;
OnPropertyChanged();
}
}
/*
private DragablzTabItem _selectedTabItem;
public DragablzTabItem SelectedTabItem
{
get => _selectedTabItem;
set
{
if (value == _selectedTabItem)
return;
_selectedTabItem = value;
// Focus embedded window on switching tab
if (!_disableFocusEmbeddedWindow)
FocusEmbeddedWindow();
OnPropertyChanged();
}
}
*/
private bool _headerContextMenuIsOpen;
public bool HeaderContextMenuIsOpen
{
get => _headerContextMenuIsOpen;
set
{
if (value == _headerContextMenuIsOpen)
return;
_headerContextMenuIsOpen = value;
OnPropertyChanged();
}
}
#region Profiles
private ICollectionView _profiles;
public ICollectionView Profiles
{
get => _profiles;
private set
{
if (value == _profiles)
return;
_profiles = value;
OnPropertyChanged();
}
}
private ProfileInfo _selectedProfile = new();
public ProfileInfo SelectedProfile
{
get => _selectedProfile;
set
{
if (value == _selectedProfile)
return;
_selectedProfile = value;
OnPropertyChanged();
}
}
private string _search;
public string Search
{
get => _search;
set
{
if (value == _search)
return;
_search = value;
// Start searching...
IsSearching = true;
_searchDispatcherTimer.Start();
OnPropertyChanged();
}
}
private bool _textBoxSearchIsFocused;
private bool _isSearching;
public bool IsSearching
{
get => _isSearching;
set
{
if (value == _isSearching)
return;
_isSearching = value;
OnPropertyChanged();
}
}
private bool _canProfileWidthChange = true;
private double _tempProfileWidth;
private bool _expandProfileView;
public bool ExpandProfileView
{
get => _expandProfileView;
set
{
if (value == _expandProfileView)
return;
if (!_isLoading)
SettingsManager.Current.PowerShell_ExpandProfileView = value;
_expandProfileView = value;
if (_canProfileWidthChange)
ResizeProfile(false);
OnPropertyChanged();
}
}
private GridLength _profileWidth;
public GridLength ProfileWidth
{
get => _profileWidth;
set
{
if (value == _profileWidth)
return;
if (!_isLoading && Math.Abs(value.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) >
GlobalStaticConfiguration.Profile_FloatPointFix) // Do not save the size when collapsed
SettingsManager.Current.PowerShell_ProfileWidth = value.Value;
_profileWidth = value;
if (_canProfileWidthChange)
ResizeProfile(true);
OnPropertyChanged();
}
}
private bool _profileContextMenuIsOpen;
public bool ProfileContextMenuIsOpen
{
get => _profileContextMenuIsOpen;
set
{
if (value == _profileContextMenuIsOpen)
return;
_profileContextMenuIsOpen = value;
OnPropertyChanged();
}
}
#endregion
#endregion
#region Constructor, load settings
public PowerShellHostViewModel(IDialogCoordinator instance)
{
_isLoading = true;
_dialogCoordinator = instance;
CheckSettings();
InterTabClient = new DragablzInterTabClient(ApplicationName.PowerShell);
InterTabPartition = ApplicationName.PowerShell.ToString();
TabItems = [];
// Profiles
SetProfilesView();
ProfileManager.OnProfilesUpdated += ProfileManager_OnProfilesUpdated;
_searchDispatcherTimer.Interval = GlobalStaticConfiguration.SearchDispatcherTimerTimeSpan;
_searchDispatcherTimer.Tick += SearchDispatcherTimer_Tick;
LoadSettings();
SettingsManager.Current.PropertyChanged += SettingsManager_PropertyChanged;
_isLoading = false;
}
private void LoadSettings()
{
ExpandProfileView = SettingsManager.Current.PowerShell_ExpandProfileView;
ProfileWidth = ExpandProfileView
? new GridLength(SettingsManager.Current.PowerShell_ProfileWidth)
: new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed);
_tempProfileWidth = SettingsManager.Current.PowerShell_ProfileWidth;
}
#endregion
#region ICommand & Actions
public ItemActionCallback CloseItemCommand => CloseItemAction;
private void CloseItemAction(ItemActionCallbackArgs<TabablzControl> args)
{
((args.DragablzItem.Content as DragablzTabItem)?.View as PowerShellControl)?.CloseTab();
}
private bool Connect_CanExecute(object obj)
{
return IsConfigured;
}
public ICommand ConnectCommand => new RelayCommand(_ => ConnectAction(), Connect_CanExecute);
private void ConnectAction()
{
Connect().ConfigureAwait(false);
}
private bool IsConnected_CanExecute(object view)
{
if (view is PowerShellControl control)
return control.IsConnected;
return false;
}
public ICommand ReconnectCommand => new RelayCommand(ReconnectAction);
private void ReconnectAction(object view)
{
if (view is not PowerShellControl control)
return;
if (control.ReconnectCommand.CanExecute(null))
control.ReconnectCommand.Execute(null);
}
public ICommand ResizeWindowCommand => new RelayCommand(ResizeWindowAction, IsConnected_CanExecute);
private void ResizeWindowAction(object view)
{
if (view is PowerShellControl control)
control.ResizeEmbeddedWindow();
}
public ICommand ConnectProfileCommand => new RelayCommand(_ => ConnectProfileAction(), ConnectProfile_CanExecute);
private bool ConnectProfile_CanExecute(object obj)
{
return !IsSearching && SelectedProfile != null;
}
private void ConnectProfileAction()
{
ConnectProfile();
}
public ICommand ConnectProfileExternalCommand => new RelayCommand(_ => ConnectProfileExternalAction());
private void ConnectProfileExternalAction()
{
ConnectProfileExternal();
}
public ICommand AddProfileCommand => new RelayCommand(_ => AddProfileAction());
private void AddProfileAction()
{
ProfileDialogManager
.ShowAddProfileDialog(this, this, _dialogCoordinator, null, null, ApplicationName.PowerShell)
.ConfigureAwait(false);
}
private bool ModifyProfile_CanExecute(object obj)
{
return SelectedProfile is { IsDynamic: false };
}
public ICommand EditProfileCommand => new RelayCommand(_ => EditProfileAction(), ModifyProfile_CanExecute);
private void EditProfileAction()
{
ProfileDialogManager.ShowEditProfileDialog(this, _dialogCoordinator, SelectedProfile).ConfigureAwait(false);
}
public ICommand CopyAsProfileCommand => new RelayCommand(_ => CopyAsProfileAction(), ModifyProfile_CanExecute);
private void CopyAsProfileAction()
{
ProfileDialogManager.ShowCopyAsProfileDialog(this, _dialogCoordinator, SelectedProfile).ConfigureAwait(false);
}
public ICommand DeleteProfileCommand => new RelayCommand(_ => DeleteProfileAction(), ModifyProfile_CanExecute);
private void DeleteProfileAction()
{
ProfileDialogManager
.ShowDeleteProfileDialog(this, _dialogCoordinator, new List<ProfileInfo> { SelectedProfile })
.ConfigureAwait(false);
}
public ICommand EditGroupCommand => new RelayCommand(EditGroupAction);
private void EditGroupAction(object group)
{
ProfileDialogManager.ShowEditGroupDialog(this, _dialogCoordinator, ProfileManager.GetGroup(group.ToString()))
.ConfigureAwait(false);
}
public ICommand TextBoxSearchGotFocusCommand
{
get { return new RelayCommand(_ => _textBoxSearchIsFocused = true); }
}
public ICommand TextBoxSearchLostFocusCommand
{
get { return new RelayCommand(_ => _textBoxSearchIsFocused = false); }
}
public ICommand ClearSearchCommand => new RelayCommand(_ => ClearSearchAction());
private void ClearSearchAction()
{
Search = string.Empty;
}
public ICommand OpenSettingsCommand => new RelayCommand(_ => OpenSettingsAction());
private static void OpenSettingsAction()
{
EventSystem.RedirectToSettings();
}
#endregion
#region Methods
private void CheckSettings()
{
IsConfigured = !string.IsNullOrEmpty(SettingsManager.Current.PowerShell_ApplicationFilePath) &&
File.Exists(SettingsManager.Current.PowerShell_ApplicationFilePath);
}
private async Task Connect(string host = null)
{
var customDialog = new CustomDialog
{
Title = Strings.Connect
};
var connectViewModel = new PowerShellConnectViewModel(async instance =>
{
await _dialogCoordinator.HideMetroDialogAsync(this, customDialog);
ConfigurationManager.OnDialogClose();
// Create profile info
var sessionInfo = new PowerShellSessionInfo
{
EnableRemoteConsole = instance.EnableRemoteConsole,
Host = instance.Host,
Command = instance.Command,
AdditionalCommandLine = instance.AdditionalCommandLine,
ExecutionPolicy = instance.ExecutionPolicy
};
// Add to history
// Note: The history can only be updated after the values have been read.
// Otherwise, in some cases, incorrect values are taken over.
AddHostToHistory(instance.Host);
// Connect
Connect(sessionInfo);
}, async _ =>
{
await _dialogCoordinator.HideMetroDialogAsync(this, customDialog);
ConfigurationManager.OnDialogClose();
}, host);
customDialog.Content = new PowerShellConnectDialog
{
DataContext = connectViewModel
};
ConfigurationManager.OnDialogOpen();
await _dialogCoordinator.ShowMetroDialogAsync(this, customDialog);
}
private void ConnectProfile()
{
Connect(PowerShell.CreateSessionInfo(SelectedProfile),
SelectedProfile.Name);
}
private void ConnectProfileExternal()
{
var sessionInfo =
PowerShell.CreateSessionInfo(SelectedProfile);
Process.Start(new ProcessStartInfo
{
FileName = SettingsManager.Current.PowerShell_ApplicationFilePath,
Arguments = Models.PowerShell.PowerShell.BuildCommandLine(sessionInfo)
});
}
private void Connect(PowerShellSessionInfo sessionInfo, string header = null)
{
sessionInfo.ApplicationFilePath = SettingsManager.Current.PowerShell_ApplicationFilePath;
var tabId = Guid.NewGuid();
TabItems.Add(new DragablzTabItem(
header ?? (sessionInfo.EnableRemoteConsole ? sessionInfo.Host : Strings.PowerShell),
new PowerShellControl(tabId, sessionInfo), tabId));
// Select the added tab
_disableFocusEmbeddedWindow = true;
SelectedTabIndex = TabItems.Count - 1;
_disableFocusEmbeddedWindow = false;
}
public void AddTab(string host)
{
Connect(host).ConfigureAwait(false);
}
// Modify history list
private static void AddHostToHistory(string host)
{
if (string.IsNullOrEmpty(host))
return;
SettingsManager.Current.PowerShell_HostHistory = new ObservableCollection<string>(
ListHelper.Modify(SettingsManager.Current.PowerShell_HostHistory.ToList(), host,
SettingsManager.Current.General_HistoryListEntries));
}
private void ResizeProfile(bool dueToChangedSize)
{
_canProfileWidthChange = false;
if (dueToChangedSize)
{
ExpandProfileView = Math.Abs(ProfileWidth.Value - GlobalStaticConfiguration.Profile_WidthCollapsed) >
GlobalStaticConfiguration.Profile_FloatPointFix;
}
else
{
if (ExpandProfileView)
{
ProfileWidth =
Math.Abs(_tempProfileWidth - GlobalStaticConfiguration.Profile_WidthCollapsed) <
GlobalStaticConfiguration.Profile_FloatPointFix
? new GridLength(GlobalStaticConfiguration.Profile_DefaultWidthExpanded)
: new GridLength(_tempProfileWidth);
}
else
{
_tempProfileWidth = ProfileWidth.Value;
ProfileWidth = new GridLength(GlobalStaticConfiguration.Profile_WidthCollapsed);
}
}
_canProfileWidthChange = true;
}
public void FocusEmbeddedWindow()
{
/* Don't continue if
- Search TextBox is focused
- Header ContextMenu is opened
- Profile ContextMenu is opened
*/
if (_textBoxSearchIsFocused || HeaderContextMenuIsOpen || ProfileContextMenuIsOpen)
return;
var window = Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);
if (window == null)
return;
// Find all TabablzControl in the active window
foreach (var tabablzControl in VisualTreeHelper.FindVisualChildren<TabablzControl>(window))
{
// Skip if no items
if (tabablzControl.Items.Count == 0)
continue;
// Focus embedded window in the selected tab
(((DragablzTabItem)tabablzControl.SelectedItem)?.View as IEmbeddedWindow)?.FocusEmbeddedWindow();
break;
}
}
public void OnViewVisible()
{
_isViewActive = true;
RefreshProfiles();
FocusEmbeddedWindow();
}
public void OnViewHide()
{
_isViewActive = false;
}
private void SetProfilesView(ProfileInfo profile = null)
{
Profiles = new CollectionViewSource
{
Source = ProfileManager.Groups.SelectMany(x => x.Profiles).Where(x => x.PowerShell_Enabled)
.OrderBy(x => x.Group).ThenBy(x => x.Name)
}.View;
Profiles.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ProfileInfo.Group)));
Profiles.Filter = o =>
{
if (o is not ProfileInfo info)
return false;
if (string.IsNullOrEmpty(Search))
return true;
var search = Search.Trim();
// Search by: Tag=xxx (exact match, ignore case)
/*
if (search.StartsWith(ProfileManager.TagIdentifier, StringComparison.OrdinalIgnoreCase))
return !string.IsNullOrEmpty(info.Tags) && info.PingMonitor_Enabled && info.Tags.Replace(" ", "").Split(';').Any(str => search.Substring(ProfileManager.TagIdentifier.Length, search.Length - ProfileManager.TagIdentifier.Length).Equals(str, StringComparison.OrdinalIgnoreCase));
*/
// Search by: Name, PowerShell_Host
return info.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1 ||
info.PowerShell_Host.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1;
};
// Set specific profile or first if null
SelectedProfile = null;
if (profile != null)
SelectedProfile = Profiles.Cast<ProfileInfo>().FirstOrDefault(x => x.Equals(profile)) ??
Profiles.Cast<ProfileInfo>().FirstOrDefault();
else
SelectedProfile = Profiles.Cast<ProfileInfo>().FirstOrDefault();
}
private void RefreshProfiles()
{
if (!_isViewActive)
return;
SetProfilesView(SelectedProfile);
}
public void OnProfileManagerDialogOpen()
{
ConfigurationManager.OnDialogOpen();
}
public void OnProfileManagerDialogClose()
{
ConfigurationManager.OnDialogClose();
}
#endregion
#region Event
private void ProfileManager_OnProfilesUpdated(object sender, EventArgs e)
{
RefreshProfiles();
}
private void SearchDispatcherTimer_Tick(object sender, EventArgs e)
{
_searchDispatcherTimer.Stop();
RefreshProfiles();
IsSearching = false;
}
private void SettingsManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(SettingsInfo.PowerShell_ApplicationFilePath))
CheckSettings();
}
#endregion
}