-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
TerminalPage.cpp
5313 lines (4722 loc) · 216 KB
/
TerminalPage.cpp
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "TerminalPage.h"
#include <LibraryResources.h>
#include <TerminalCore/ControlKeyStates.hpp>
#include <til/latch.h>
#include <Utils.h>
#include "../../types/inc/utils.hpp"
#include "App.h"
#include "ColorHelper.h"
#include "DebugTapConnection.h"
#include "SettingsPaneContent.h"
#include "ScratchpadContent.h"
#include "SnippetsPaneContent.h"
#include "TabRowControl.h"
#include "TerminalPage.g.cpp"
#include "RenameWindowRequestedArgs.g.cpp"
#include "RequestMoveContentArgs.g.cpp"
#include "RequestReceiveContentArgs.g.cpp"
#include "LaunchPositionRequest.g.cpp"
using namespace winrt;
using namespace winrt::Microsoft::Terminal::Control;
using namespace winrt::Microsoft::Terminal::Settings::Model;
using namespace winrt::Microsoft::Terminal::TerminalConnection;
using namespace winrt::Microsoft::Terminal;
using namespace winrt::Windows::ApplicationModel::DataTransfer;
using namespace winrt::Windows::Foundation::Collections;
using namespace winrt::Windows::System;
using namespace winrt::Windows::System;
using namespace winrt::Windows::UI;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::UI::Text;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Media;
using namespace ::TerminalApp;
using namespace ::Microsoft::Console;
using namespace ::Microsoft::Terminal::Core;
using namespace std::chrono_literals;
#define HOOKUP_ACTION(action) _actionDispatch->action({ this, &TerminalPage::_Handle##action });
namespace winrt
{
namespace MUX = Microsoft::UI::Xaml;
namespace WUX = Windows::UI::Xaml;
using IInspectable = Windows::Foundation::IInspectable;
using VirtualKeyModifiers = Windows::System::VirtualKeyModifiers;
}
namespace winrt::TerminalApp::implementation
{
TerminalPage::TerminalPage(TerminalApp::WindowProperties properties, const TerminalApp::ContentManager& manager) :
_tabs{ winrt::single_threaded_observable_vector<TerminalApp::TabBase>() },
_mruTabs{ winrt::single_threaded_observable_vector<TerminalApp::TabBase>() },
_startupActions{ winrt::single_threaded_vector<ActionAndArgs>() },
_manager{ manager },
_hostingHwnd{},
_WindowProperties{ std::move(properties) }
{
InitializeComponent();
_WindowProperties.PropertyChanged({ get_weak(), &TerminalPage::_windowPropertyChanged });
}
// Method Description:
// - implements the IInitializeWithWindow interface from shobjidl_core.
// - We're going to use this HWND as the owner for the ConPTY windows, via
// ConptyConnection::ReparentWindow. We need this for applications that
// call GetConsoleWindow, and attempt to open a MessageBox for the
// console. By marking the conpty windows as owned by the Terminal HWND,
// the message box will be owned by the Terminal window as well.
// - see GH#2988
HRESULT TerminalPage::Initialize(HWND hwnd)
{
if (!_hostingHwnd.has_value())
{
// GH#13211 - if we haven't yet set the owning hwnd, reparent all the controls now.
for (const auto& tab : _tabs)
{
if (auto terminalTab{ _GetTerminalTabImpl(tab) })
{
terminalTab->GetRootPane()->WalkTree([&](auto&& pane) {
if (const auto& term{ pane->GetTerminalControl() })
{
term.OwningHwnd(reinterpret_cast<uint64_t>(hwnd));
}
});
}
// We don't need to worry about resetting the owning hwnd for the
// SUI here. GH#13211 only repros for a defterm connection, where
// the tab is spawned before the window is created. It's not
// possible to make a SUI tab like that, before the window is
// created. The SUI could be spawned as a part of a window restore,
// but that would still work fine. The window would be created
// before restoring previous tabs in that scenario.
}
}
_hostingHwnd = hwnd;
return S_OK;
}
// INVARIANT: This needs to be called on OUR UI thread!
void TerminalPage::SetSettings(CascadiaSettings settings, bool needRefreshUI)
{
assert(Dispatcher().HasThreadAccess());
if (_settings == nullptr)
{
// Create this only on the first time we load the settings.
_terminalSettingsCache = TerminalApp::TerminalSettingsCache{ settings, *_bindings };
}
_settings = settings;
// Make sure to call SetCommands before _RefreshUIForSettingsReload.
// SetCommands will make sure the KeyChordText of Commands is updated, which needs
// to happen before the Settings UI is reloaded and tries to re-read those values.
if (const auto p = CommandPaletteElement())
{
p.SetActionMap(_settings.ActionMap());
}
if (needRefreshUI)
{
_RefreshUIForSettingsReload();
}
// Upon settings update we reload the system settings for scrolling as well.
// TODO: consider reloading this value periodically.
_systemRowsToScroll = _ReadSystemRowsToScroll();
}
bool TerminalPage::IsRunningElevated() const noexcept
{
// GH#2455 - Make sure to try/catch calls to Application::Current,
// because that _won't_ be an instance of TerminalApp::App in the
// LocalTests
try
{
return Application::Current().as<TerminalApp::App>().Logic().IsRunningElevated();
}
CATCH_LOG();
return false;
}
bool TerminalPage::CanDragDrop() const noexcept
{
try
{
return Application::Current().as<TerminalApp::App>().Logic().CanDragDrop();
}
CATCH_LOG();
return true;
}
void TerminalPage::Create()
{
// Hookup the key bindings
_HookupKeyBindings(_settings.ActionMap());
_tabContent = this->TabContent();
_tabRow = this->TabRow();
_tabView = _tabRow.TabView();
_rearranging = false;
const auto canDragDrop = CanDragDrop();
_tabRow.PointerMoved({ get_weak(), &TerminalPage::_RestorePointerCursorHandler });
_tabView.CanReorderTabs(canDragDrop);
_tabView.CanDragTabs(canDragDrop);
_tabView.TabDragStarting({ get_weak(), &TerminalPage::_TabDragStarted });
_tabView.TabDragCompleted({ get_weak(), &TerminalPage::_TabDragCompleted });
auto tabRowImpl = winrt::get_self<implementation::TabRowControl>(_tabRow);
_newTabButton = tabRowImpl->NewTabButton();
if (_settings.GlobalSettings().ShowTabsInTitlebar())
{
// Remove the TabView from the page. We'll hang on to it, we need to
// put it in the titlebar.
uint32_t index = 0;
if (this->Root().Children().IndexOf(_tabRow, index))
{
this->Root().Children().RemoveAt(index);
}
// Inform the host that our titlebar content has changed.
SetTitleBarContent.raise(*this, _tabRow);
// GH#13143 Manually set the tab row's background to transparent here.
//
// We're doing it this way because ThemeResources are tricky. We
// default in XAML to using the appropriate ThemeResource background
// color for our TabRow. When tabs in the titlebar are _disabled_,
// this will ensure that the tab row has the correct theme-dependent
// value. When tabs in the titlebar are _enabled_ (the default),
// we'll switch the BG to Transparent, to let the Titlebar Control's
// background be used as the BG for the tab row.
//
// We can't do it the other way around (default to Transparent, only
// switch to a color when disabling tabs in the titlebar), because
// looking up the correct ThemeResource from and App dictionary is a
// capital-H Hard problem.
const auto transparent = Media::SolidColorBrush();
transparent.Color(Windows::UI::Colors::Transparent());
_tabRow.Background(transparent);
}
_updateThemeColors();
// Initialize the state of the CloseButtonOverlayMode property of
// our TabView, to match the tab.showCloseButton property in the theme.
if (const auto theme = _settings.GlobalSettings().CurrentTheme())
{
const auto visibility = theme.Tab() ? theme.Tab().ShowCloseButton() : Settings::Model::TabCloseButtonVisibility::Always;
switch (visibility)
{
case Settings::Model::TabCloseButtonVisibility::Never:
_tabView.CloseButtonOverlayMode(MUX::Controls::TabViewCloseButtonOverlayMode::Auto);
break;
case Settings::Model::TabCloseButtonVisibility::Hover:
_tabView.CloseButtonOverlayMode(MUX::Controls::TabViewCloseButtonOverlayMode::OnPointerOver);
break;
default:
_tabView.CloseButtonOverlayMode(MUX::Controls::TabViewCloseButtonOverlayMode::Always);
break;
}
}
// Hookup our event handlers to the ShortcutActionDispatch
_RegisterActionCallbacks();
//Event Bindings (Early)
_newTabButton.Click([weakThis{ get_weak() }](auto&&, auto&&) {
if (auto page{ weakThis.get() })
{
page->_OpenNewTerminalViaDropdown(NewTerminalArgs());
}
});
_newTabButton.Drop({ get_weak(), &TerminalPage::_NewTerminalByDrop });
_tabView.SelectionChanged({ this, &TerminalPage::_OnTabSelectionChanged });
_tabView.TabCloseRequested({ this, &TerminalPage::_OnTabCloseRequested });
_tabView.TabItemsChanged({ this, &TerminalPage::_OnTabItemsChanged });
_tabView.TabDragStarting({ this, &TerminalPage::_onTabDragStarting });
_tabView.TabStripDragOver({ this, &TerminalPage::_onTabStripDragOver });
_tabView.TabStripDrop({ this, &TerminalPage::_onTabStripDrop });
_tabView.TabDroppedOutside({ this, &TerminalPage::_onTabDroppedOutside });
_CreateNewTabFlyout();
_UpdateTabWidthMode();
// Settings AllowDependentAnimations will affect whether animations are
// enabled application-wide, so we don't need to check it each time we
// want to create an animation.
WUX::Media::Animation::Timeline::AllowDependentAnimations(!_settings.GlobalSettings().DisableAnimations());
// Once the page is actually laid out on the screen, trigger all our
// startup actions. Things like Panes need to know at least how big the
// window will be, so they can subdivide that space.
//
// _OnFirstLayout will remove this handler so it doesn't get called more than once.
_layoutUpdatedRevoker = _tabContent.LayoutUpdated(winrt::auto_revoke, { this, &TerminalPage::_OnFirstLayout });
_isAlwaysOnTop = _settings.GlobalSettings().AlwaysOnTop();
// DON'T set up Toasts/TeachingTips here. They should be loaded and
// initialized the first time they're opened, in whatever method opens
// them.
// Setup mouse vanish attributes
SystemParametersInfoW(SPI_GETMOUSEVANISH, 0, &_shouldMouseVanish, false);
_tabRow.ShowElevationShield(IsRunningElevated() && _settings.GlobalSettings().ShowAdminShield());
// Store cursor, so we can restore it, e.g., after mouse vanishing
// (we'll need to adapt this logic once we make cursor context aware)
try
{
_defaultPointerCursor = CoreWindow::GetForCurrentThread().PointerCursor();
}
CATCH_LOG();
}
Windows::UI::Xaml::Automation::Peers::AutomationPeer TerminalPage::OnCreateAutomationPeer()
{
return Automation::Peers::FrameworkElementAutomationPeer(*this);
}
// Method Description:
// - This is a bit of trickiness: If we're running unelevated, and the user
// passed in only --elevate actions, the we don't _actually_ want to
// restore the layouts here. We're not _actually_ about to create the
// window. We're simply going to toss the commandlines
// Arguments:
// - <none>
// Return Value:
// - true if we're not elevated but all relevant pane-spawning actions are elevated
bool TerminalPage::ShouldImmediatelyHandoffToElevated(const CascadiaSettings& settings) const
{
// GH#12267: Don't forget about defterm handoff here. If we're being
// created for embedding, then _yea_, we don't need to handoff to an
// elevated window.
if (!_startupActions || IsRunningElevated() || _shouldStartInboundListener || _startupActions.Size() == 0)
{
// there aren't startup actions, or we're elevated. In that case, go for it.
return false;
}
// Check that there's at least one action that's not just an elevated newTab action.
for (const auto& action : _startupActions)
{
// Only new terminal panes will be requesting elevation.
NewTerminalArgs newTerminalArgs{ nullptr };
if (action.Action() == ShortcutAction::NewTab)
{
const auto& args{ action.Args().try_as<NewTabArgs>() };
if (args)
{
newTerminalArgs = args.ContentArgs().try_as<NewTerminalArgs>();
}
else
{
// This was a nt action that didn't have any args. The default
// profile may want to be elevated, so don't just early return.
}
}
else if (action.Action() == ShortcutAction::SplitPane)
{
const auto& args{ action.Args().try_as<SplitPaneArgs>() };
if (args)
{
newTerminalArgs = args.ContentArgs().try_as<NewTerminalArgs>();
}
else
{
// This was a nt action that didn't have any args. The default
// profile may want to be elevated, so don't just early return.
}
}
else
{
// This was not a new tab or split pane action.
// This doesn't affect the outcome
continue;
}
// It's possible that newTerminalArgs is null here.
// GetProfileForArgs should be resilient to that.
const auto profile{ settings.GetProfileForArgs(newTerminalArgs) };
if (profile.Elevate())
{
continue;
}
// The profile didn't want to be elevated, and we aren't elevated.
// We're going to open at least one tab, so return false.
return false;
}
return true;
}
// Method Description:
// - Escape hatch for immediately dispatching requests to elevated windows
// when first launched. At this point in startup, the window doesn't exist
// yet, XAML hasn't been started, but we need to dispatch these actions.
// We can't just go through ProcessStartupActions, because that processes
// the actions async using the XAML dispatcher (which doesn't exist yet)
// - DON'T CALL THIS if you haven't already checked
// ShouldImmediatelyHandoffToElevated. If you're thinking about calling
// this outside of the one place it's used, that's probably the wrong
// solution.
// Arguments:
// - settings: the settings we should use for dispatching these actions. At
// this point in startup, we hadn't otherwise been initialized with these,
// so use them now.
// Return Value:
// - <none>
void TerminalPage::HandoffToElevated(const CascadiaSettings& settings)
{
if (!_startupActions)
{
return;
}
// Hookup our event handlers to the ShortcutActionDispatch
_settings = settings;
_HookupKeyBindings(_settings.ActionMap());
_RegisterActionCallbacks();
for (const auto& action : _startupActions)
{
// only process new tabs and split panes. They're all going to the elevated window anyways.
if (action.Action() == ShortcutAction::NewTab || action.Action() == ShortcutAction::SplitPane)
{
_actionDispatch->DoAction(action);
}
}
}
winrt::fire_and_forget TerminalPage::_NewTerminalByDrop(const Windows::Foundation::IInspectable&, winrt::Windows::UI::Xaml::DragEventArgs e)
try
{
const auto data = e.DataView();
if (!data.Contains(StandardDataFormats::StorageItems()))
{
co_return;
}
const auto weakThis = get_weak();
const auto items = co_await data.GetStorageItemsAsync();
const auto strongThis = weakThis.get();
if (!strongThis)
{
co_return;
}
TraceLoggingWrite(
g_hTerminalAppProvider,
"NewTabByDragDrop",
TraceLoggingDescription("Event emitted when the user drag&drops onto the new tab button"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage));
for (const auto& item : items)
{
auto directory = item.Path();
std::filesystem::path path(std::wstring_view{ directory });
if (!std::filesystem::is_directory(path))
{
directory = winrt::hstring{ path.parent_path().native() };
}
NewTerminalArgs args;
args.StartingDirectory(directory);
_OpenNewTerminalViaDropdown(args);
}
}
CATCH_LOG()
// Method Description:
// - This method is called once command palette action was chosen for dispatching
// We'll use this event to dispatch this command.
// Arguments:
// - command - command to dispatch
// Return Value:
// - <none>
void TerminalPage::_OnDispatchCommandRequested(const IInspectable& sender, const Microsoft::Terminal::Settings::Model::Command& command)
{
const auto& actionAndArgs = command.ActionAndArgs();
_actionDispatch->DoAction(sender, actionAndArgs);
}
// Method Description:
// - This method is called once command palette command line was chosen for execution
// We'll use this event to create a command line execution command and dispatch it.
// Arguments:
// - command - command to dispatch
// Return Value:
// - <none>
void TerminalPage::_OnCommandLineExecutionRequested(const IInspectable& /*sender*/, const winrt::hstring& commandLine)
{
ExecuteCommandlineArgs args{ commandLine };
ActionAndArgs actionAndArgs{ ShortcutAction::ExecuteCommandline, args };
_actionDispatch->DoAction(actionAndArgs);
}
// Method Description:
// - This method is called once on startup, on the first LayoutUpdated event.
// We'll use this event to know that we have an ActualWidth and
// ActualHeight, so we can now attempt to process our list of startup
// actions.
// - We'll remove this event handler when the event is first handled.
// - If there are no startup actions, we'll open a single tab with the
// default profile.
// Arguments:
// - <unused>
// Return Value:
// - <none>
void TerminalPage::_OnFirstLayout(const IInspectable& /*sender*/, const IInspectable& /*eventArgs*/)
{
// Only let this succeed once.
_layoutUpdatedRevoker.revoke();
// This event fires every time the layout changes, but it is always the
// last one to fire in any layout change chain. That gives us great
// flexibility in finding the right point at which to initialize our
// renderer (and our terminal). Any earlier than the last layout update
// and we may not know the terminal's starting size.
if (_startupState == StartupState::NotInitialized)
{
_startupState = StartupState::InStartup;
ProcessStartupActions(_startupActions, true);
// If we were told that the COM server needs to be started to listen for incoming
// default application connections, start it now.
// This MUST be done after we've registered the event listener for the new connections
// or the COM server might start receiving requests on another thread and dispatch
// them to nowhere.
_StartInboundListener();
}
}
// Routine Description:
// - Will start the listener for inbound console handoffs if we have already determined
// that we should do so.
// NOTE: Must be after TerminalPage::_OnNewConnection has been connected up.
// Arguments:
// - <unused> - Looks at _shouldStartInboundListener
// Return Value:
// - <none> - May fail fast if setup fails as that would leave us in a weird state.
void TerminalPage::_StartInboundListener()
{
if (_shouldStartInboundListener)
{
_shouldStartInboundListener = false;
// Hook up inbound connection event handler
_newConnectionRevoker = ConptyConnection::NewConnection(winrt::auto_revoke, { this, &TerminalPage::_OnNewConnection });
try
{
winrt::Microsoft::Terminal::TerminalConnection::ConptyConnection::StartInboundListener();
}
// If we failed to start the listener, it will throw.
// We don't want to fail fast here because if a peasant has some trouble with
// starting the listener, we don't want it to crash and take all its tabs down
// with it.
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
}
}
// Method Description:
// - Process all the startup actions in the provided list of startup
// actions. We'll do this all at once here.
// Arguments:
// - actions: a winrt vector of actions to process. Note that this must NOT
// be an IVector&, because we need the collection to be accessible on the
// other side of the co_await.
// - initial: if true, we're parsing these args during startup, and we
// should fire an Initialized event.
// - cwd: If not empty, we should try switching to this provided directory
// while processing these actions. This will allow something like `wt -w 0
// nt -d .` from inside another directory to work as expected.
// Return Value:
// - <none>
winrt::fire_and_forget TerminalPage::ProcessStartupActions(Windows::Foundation::Collections::IVector<ActionAndArgs> actions,
const bool initial,
const winrt::hstring cwd,
const winrt::hstring env)
{
auto weakThis{ get_weak() };
// Handle it on a subsequent pass of the UI thread.
co_await wil::resume_foreground(Dispatcher(), CoreDispatcherPriority::Normal);
// If the caller provided a CWD, "switch" to that directory, then switch
// back once we're done. This looks weird though, because we have to set
// up the scope_exit _first_. We'll release the scope_exit if we don't
// actually need it.
auto originalVirtualCwd{ _WindowProperties.VirtualWorkingDirectory() };
auto restoreCwd = wil::scope_exit([&originalVirtualCwd, this]() {
// ignore errors, we'll just power on through. We'd rather do
// something rather than fail silently if the directory doesn't
// actually exist.
_WindowProperties.VirtualWorkingDirectory(originalVirtualCwd);
});
// Literally the same thing with env vars too
auto originalVirtualEnv{ _WindowProperties.VirtualEnvVars() };
auto restoreEnv = wil::scope_exit([&originalVirtualEnv, this]() {
_WindowProperties.VirtualEnvVars(originalVirtualEnv);
});
if (cwd.empty())
{
// We didn't actually need to change the virtual CWD, so we don't
// need to restore it
restoreCwd.release();
}
else
{
_WindowProperties.VirtualWorkingDirectory(cwd);
}
if (env.empty())
{
restoreEnv.release();
}
else
{
_WindowProperties.VirtualEnvVars(env);
}
if (auto page{ weakThis.get() })
{
for (const auto& action : actions)
{
if (auto page{ weakThis.get() })
{
_actionDispatch->DoAction(action);
}
else
{
co_return;
}
}
// GH#6586: now that we're done processing all startup commands,
// focus the active control. This will work as expected for both
// commandline invocations and for `wt` action invocations.
if (const auto& terminalTab{ _GetFocusedTabImpl() })
{
if (const auto& content{ terminalTab->GetActiveContent() })
{
content.Focus(FocusState::Programmatic);
}
}
}
if (initial)
{
_CompleteInitialization();
}
}
// Method Description:
// - Perform and steps that need to be done once our initial state is all
// set up. This includes entering fullscreen mode and firing our
// Initialized event.
// Arguments:
// - <none>
// Return Value:
// - <none>
winrt::fire_and_forget TerminalPage::_CompleteInitialization()
{
_startupState = StartupState::Initialized;
// GH#632 - It's possible that the user tried to create the terminal
// with only one tab, with only an elevated profile. If that happens,
// we'll create _another_ process to host the elevated version of that
// profile. This can happen from the jumplist, or if the default profile
// is `elevate:true`, or from the commandline.
//
// However, we need to make sure to close this window in that scenario.
// Since there aren't any _tabs_ in this window, we won't ever get a
// closed event. So do it manually.
//
// GH#12267: Make sure that we don't instantly close ourselves when
// we're readying to accept a defterm connection. In that case, we don't
// have a tab yet, but will once we're initialized.
if (_tabs.Size() == 0 && !_shouldStartInboundListener && !_isEmbeddingInboundListener)
{
CloseWindowRequested.raise(*this, nullptr);
co_return;
}
else
{
// GH#11561: When we start up, our window is initially just a frame
// with a transparent content area. We're gonna do all this startup
// init on the UI thread, so the UI won't actually paint till it's
// all done. This results in a few frames where the frame is
// visible, before the page paints for the first time, before any
// tabs appears, etc.
//
// To mitigate this, we're gonna wait for the UI thread to finish
// everything it's gotta do for the initial init, and _then_ fire
// our Initialized event. By waiting for everything else to finish
// (CoreDispatcherPriority::Low), we let all the tabs and panes
// actually get created. In the window layer, we're gonna cloak the
// window till this event is fired, so we don't actually see this
// frame until we're actually all ready to go.
//
// This will result in the window seemingly not loading as fast, but
// it will actually take exactly the same amount of time before it's
// usable.
//
// We also experimented with drawing a solid BG color before the
// initialization is finished. However, there are still a few frames
// after the frame is displayed before the XAML content first draws,
// so that didn't actually resolve any issues.
Dispatcher().RunAsync(CoreDispatcherPriority::Low, [weak = get_weak()]() {
if (auto self{ weak.get() })
{
self->Initialized.raise(*self, nullptr);
}
});
}
}
// Method Description:
// - Show a dialog with "About" information. Displays the app's Display
// Name, version, getting started link, source code link, documentation link, release
// Notes link, send feedback link and privacy policy link.
void TerminalPage::_ShowAboutDialog()
{
_ShowDialogHelper(L"AboutDialog");
}
winrt::hstring TerminalPage::ApplicationDisplayName()
{
return CascadiaSettings::ApplicationDisplayName();
}
winrt::hstring TerminalPage::ApplicationVersion()
{
return CascadiaSettings::ApplicationVersion();
}
// Method Description:
// - Helper to show a content dialog
// - We only open a content dialog if there isn't one open already
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowDialogHelper(const std::wstring_view& name)
{
if (auto presenter{ _dialogPresenter.get() })
{
co_return co_await presenter.ShowDialog(FindName(name).try_as<WUX::Controls::ContentDialog>());
}
co_return ContentDialogResult::None;
}
// Method Description:
// - Displays a dialog to warn the user that they are about to close all open windows.
// Once the user clicks the OK button, shut down the application.
// If cancel is clicked, the dialog will close.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See _ShowDialog for details
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowQuitDialog()
{
return _ShowDialogHelper(L"QuitDialog");
}
// Method Description:
// - Displays a dialog for warnings found while closing the terminal app using
// key binding with multiple tabs opened. Display messages to warn user
// that more than 1 tab is opened, and once the user clicks the OK button, remove
// all the tabs and shut down and app. If cancel is clicked, the dialog will close
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See _ShowDialog for details
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowCloseWarningDialog()
{
return _ShowDialogHelper(L"CloseAllDialog");
}
// Method Description:
// - Displays a dialog for warnings found while closing the terminal tab marked as read-only
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowCloseReadOnlyDialog()
{
return _ShowDialogHelper(L"CloseReadOnlyDialog");
}
// Method Description:
// - Displays a dialog to warn the user about the fact that the text that
// they are trying to paste contains the "new line" character which can
// have the effect of starting commands without the user's knowledge if
// it is pasted on a shell where the "new line" character marks the end
// of a command.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See _ShowDialog for details
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowMultiLinePasteWarningDialog()
{
return _ShowDialogHelper(L"MultiLinePasteDialog");
}
// Method Description:
// - Displays a dialog to warn the user about the fact that the text that
// they are trying to paste is very long, in case they did not mean to
// paste it but pressed the paste shortcut by accident.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See _ShowDialog for details
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> TerminalPage::_ShowLargePasteWarningDialog()
{
return _ShowDialogHelper(L"LargePasteDialog");
}
// Method Description:
// - Builds the flyout (dropdown) attached to the new tab button, and
// attaches it to the button. Populates the flyout with one entry per
// Profile, displaying the profile's name. Clicking each flyout item will
// open a new tab with that profile.
// Below the profiles are the static menu items: settings, command palette
void TerminalPage::_CreateNewTabFlyout()
{
auto newTabFlyout = WUX::Controls::MenuFlyout{};
newTabFlyout.Placement(WUX::Controls::Primitives::FlyoutPlacementMode::BottomEdgeAlignedLeft);
// Create profile entries from the NewTabMenu configuration using a
// recursive helper function. This returns a std::vector of FlyoutItemBases,
// that we then add to our Flyout.
auto entries = _settings.GlobalSettings().NewTabMenu();
auto items = _CreateNewTabFlyoutItems(entries);
for (const auto& item : items)
{
newTabFlyout.Items().Append(item);
}
// add menu separator
auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};
newTabFlyout.Items().Append(separatorItem);
// add static items
{
// Create the settings button.
auto settingsItem = WUX::Controls::MenuFlyoutItem{};
settingsItem.Text(RS_(L"SettingsMenuItem"));
const auto settingsToolTip = RS_(L"SettingsToolTip");
WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));
Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);
WUX::Controls::SymbolIcon ico{};
ico.Symbol(WUX::Controls::Symbol::Setting);
settingsItem.Icon(ico);
settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });
newTabFlyout.Items().Append(settingsItem);
auto actionMap = _settings.ActionMap();
const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(L"Terminal.OpenSettingsUI") };
if (settingsKeyChord)
{
_SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);
}
// Create the command palette button.
auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};
commandPaletteFlyout.Text(RS_(L"CommandPaletteMenuItem"));
const auto commandPaletteToolTip = RS_(L"CommandPaletteToolTip");
WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));
Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);
WUX::Controls::FontIcon commandPaletteIcon{};
commandPaletteIcon.Glyph(L"\xE945");
commandPaletteIcon.FontFamily(Media::FontFamily{ L"Segoe Fluent Icons, Segoe MDL2 Assets" });
commandPaletteFlyout.Icon(commandPaletteIcon);
commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });
newTabFlyout.Items().Append(commandPaletteFlyout);
const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(L"Terminal.ToggleCommandPalette") };
if (commandPaletteKeyChord)
{
_SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);
}
// Create the about button.
auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};
aboutFlyout.Text(RS_(L"AboutMenuItem"));
const auto aboutToolTip = RS_(L"AboutToolTip");
WUX::Controls::ToolTipService::SetToolTip(aboutFlyout, box_value(aboutToolTip));
Automation::AutomationProperties::SetHelpText(aboutFlyout, aboutToolTip);
WUX::Controls::SymbolIcon aboutIcon{};
aboutIcon.Symbol(WUX::Controls::Symbol::Help);
aboutFlyout.Icon(aboutIcon);
aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });
newTabFlyout.Items().Append(aboutFlyout);
}
// Before opening the fly-out set focus on the current tab
// so no matter how fly-out is closed later on the focus will return to some tab.
// We cannot do it on closing because if the window loses focus (alt+tab)
// the closing event is not fired.
// It is important to set the focus on the tab
// Since the previous focus location might be discarded in the background,
// e.g., the command palette will be dismissed by the menu,
// and then closing the fly-out will move the focus to wrong location.
newTabFlyout.Opening([this](auto&&, auto&&) {
_FocusCurrentTab(true);
});
// Necessary for fly-out sub items to get focus on a tab before collapsing. Related to #15049
newTabFlyout.Closing([this](auto&&, auto&&) {
if (!_commandPaletteIs(Visibility::Visible))
{
_FocusCurrentTab(true);
}
});
_newTabButton.Flyout(newTabFlyout);
}
// Method Description:
// - For a given list of tab menu entries, this method will create the corresponding
// list of flyout items. This is a recursive method that calls itself when it comes
// across a folder entry.
std::vector<WUX::Controls::MenuFlyoutItemBase> TerminalPage::_CreateNewTabFlyoutItems(IVector<NewTabMenuEntry> entries)
{
std::vector<WUX::Controls::MenuFlyoutItemBase> items;
if (entries == nullptr || entries.Size() == 0)
{
return items;
}
for (const auto& entry : entries)
{
if (entry == nullptr)
{
continue;
}
switch (entry.Type())
{
case NewTabMenuEntryType::Separator:
{
items.push_back(WUX::Controls::MenuFlyoutSeparator{});
break;
}
// A folder has a custom name and icon, and has a number of entries that require
// us to call this method recursively.
case NewTabMenuEntryType::Folder:
{
const auto folderEntry = entry.as<FolderEntry>();
const auto folderEntries = folderEntry.Entries();
// If the folder is empty, we should skip the entry if AllowEmpty is false, or
// when the folder should inline.
// The IsEmpty check includes semantics for nested (empty) folders
if (folderEntries.Size() == 0 && (!folderEntry.AllowEmpty() || folderEntry.Inlining() == FolderEntryInlining::Auto))
{
break;
}
// Recursively generate flyout items
auto folderEntryItems = _CreateNewTabFlyoutItems(folderEntries);
// If the folder should auto-inline and there is only one item, do so.
if (folderEntry.Inlining() == FolderEntryInlining::Auto && folderEntries.Size() == 1)
{
for (auto const& folderEntryItem : folderEntryItems)
{
items.push_back(folderEntryItem);
}
break;
}
// Otherwise, create a flyout
auto folderItem = WUX::Controls::MenuFlyoutSubItem{};
folderItem.Text(folderEntry.Name());
auto icon = _CreateNewTabFlyoutIcon(folderEntry.Icon());
folderItem.Icon(icon);
for (const auto& folderEntryItem : folderEntryItems)
{
folderItem.Items().Append(folderEntryItem);
}
// If the folder is empty, and by now we know we set AllowEmpty to true,
// create a placeholder item here
if (folderEntries.Size() == 0)
{
auto placeholder = WUX::Controls::MenuFlyoutItem{};
placeholder.Text(RS_(L"NewTabMenuFolderEmpty"));
placeholder.IsEnabled(false);
folderItem.Items().Append(placeholder);
}
items.push_back(folderItem);
break;
}
// Any "collection entry" will simply make us add each profile in the collection
// separately. This collection is stored as a map <int, Profile>, so the correct
// profile index is already known.
case NewTabMenuEntryType::RemainingProfiles:
case NewTabMenuEntryType::MatchProfiles:
{
const auto remainingProfilesEntry = entry.as<ProfileCollectionEntry>();
if (remainingProfilesEntry.Profiles() == nullptr)
{
break;
}
for (auto&& [profileIndex, remainingProfile] : remainingProfilesEntry.Profiles())
{
items.push_back(_CreateNewTabFlyoutProfile(remainingProfile, profileIndex));
}
break;
}
// A single profile, the profile index is also given in the entry
case NewTabMenuEntryType::Profile:
{
const auto profileEntry = entry.as<ProfileEntry>();
if (profileEntry.Profile() == nullptr)