-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathTerminalPage.cpp
More file actions
10352 lines (9368 loc) · 437 KB
/
Copy pathTerminalPage.cpp
File metadata and controls
10352 lines (9368 loc) · 437 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "TerminalPage.h"
#include <iomanip>
#include <json/json.h>
#include <TerminalCore/ControlKeyStates.hpp>
#include <TerminalThemeHelpers.h>
#include <til/hash.h>
#include <til/unicode.h>
#include <Utils.h>
#include "../../types/inc/ColorFix.hpp"
#include "../../types/inc/utils.hpp"
#include "../WinRTUtils/inc/WtExeUtils.h"
#include "../inc/AgentRegistry.h"
#include "../inc/AgentPolicy.h"
#include "../inc/AgentPaneBackend.h"
#include "../TerminalSettingsAppAdapterLib/TerminalSettings.h"
#include "AgentPaneContent.h"
#include "AgentPaneDragStash.h"
#include "AgentPaneLog.h"
#include "App.h"
#include "DebugTapConnection.h"
#include "FreOverlay.h"
#include "MarkdownPaneContent.h"
#include "Remoting.h"
#include "ScratchpadContent.h"
#include "SettingsPaneContent.h"
#include "SharedWta.h"
#include "SnippetsPaneContent.h"
#include "TabRowControl.h"
#include "TerminalSettingsCache.h"
#include "LaunchPositionRequest.g.cpp"
#include "WindowListEntry.g.cpp"
#include "WindowListRequest.g.cpp"
#include "RenameWindowRequestedArgs.g.cpp"
#include "OpenWindowRequestedArgs.g.cpp"
#include "RequestMoveContentArgs.g.cpp"
#include "TerminalPage.g.cpp"
using namespace winrt;
using namespace winrt::Microsoft::Management::Deployment;
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::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;
namespace AgentPolicy = ::Microsoft::Terminal::Settings::Model::AgentPolicy;
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 clipboard
{
static SRWLOCK lock = SRWLOCK_INIT;
struct ClipboardHandle
{
explicit ClipboardHandle(bool open) :
_open{ open }
{
}
~ClipboardHandle()
{
if (_open)
{
ReleaseSRWLockExclusive(&lock);
CloseClipboard();
}
}
explicit operator bool() const noexcept
{
return _open;
}
private:
bool _open = false;
};
ClipboardHandle open(HWND hwnd)
{
// Turns out, OpenClipboard/CloseClipboard are not thread-safe whatsoever,
// and on CloseClipboard, the GetClipboardData handle may get freed.
// The problem is that WinUI also uses OpenClipboard (through WinRT which uses OLE),
// and so even with this mutex we can still crash randomly if you copy something via WinUI.
// Makes you wonder how many Windows apps are subtly broken, huh.
AcquireSRWLockExclusive(&lock);
bool success = false;
// OpenClipboard may fail to acquire the internal lock --> retry.
for (DWORD sleep = 10;; sleep *= 2)
{
if (OpenClipboard(hwnd))
{
success = true;
break;
}
// 10 iterations
if (sleep > 10000)
{
break;
}
Sleep(sleep);
}
if (!success)
{
ReleaseSRWLockExclusive(&lock);
}
return ClipboardHandle{ success };
}
void write(wil::zwstring_view text, std::string_view html, std::string_view rtf)
{
static const auto regular = [](const UINT format, const void* src, const size_t bytes) {
wil::unique_hglobal handle{ THROW_LAST_ERROR_IF_NULL(GlobalAlloc(GMEM_MOVEABLE, bytes)) };
const auto locked = GlobalLock(handle.get());
memcpy(locked, src, bytes);
GlobalUnlock(handle.get());
THROW_LAST_ERROR_IF_NULL(SetClipboardData(format, handle.get()));
handle.release();
};
static const auto registered = [](const wchar_t* format, const void* src, size_t bytes) {
const auto id = RegisterClipboardFormatW(format);
if (!id)
{
LOG_LAST_ERROR();
return;
}
regular(id, src, bytes);
};
EmptyClipboard();
if (!text.empty())
{
// As per: https://learn.microsoft.com/en-us/windows/win32/dataxchg/standard-clipboard-formats
// CF_UNICODETEXT: [...] A null character signals the end of the data.
// --> We add +1 to the length. This works because .c_str() is null-terminated.
regular(CF_UNICODETEXT, text.c_str(), (text.size() + 1) * sizeof(wchar_t));
}
if (!html.empty())
{
registered(L"HTML Format", html.data(), html.size());
}
if (!rtf.empty())
{
registered(L"Rich Text Format", rtf.data(), rtf.size());
}
}
winrt::hstring read()
{
// This handles most cases of pasting text as the OS converts most formats to CF_UNICODETEXT automatically.
if (const auto handle = GetClipboardData(CF_UNICODETEXT))
{
const wil::unique_hglobal_locked lock{ handle };
const auto str = static_cast<const wchar_t*>(lock.get());
if (!str)
{
return {};
}
const auto maxLen = GlobalSize(handle) / sizeof(wchar_t);
const auto len = wcsnlen(str, maxLen);
return winrt::hstring{ str, gsl::narrow_cast<uint32_t>(len) };
}
// We get CF_HDROP when a user copied a file with Ctrl+C in Explorer and pastes that into the terminal (among others).
if (const auto handle = GetClipboardData(CF_HDROP))
{
const wil::unique_hglobal_locked lock{ handle };
const auto drop = static_cast<HDROP>(lock.get());
if (!drop)
{
return {};
}
const auto cap = DragQueryFileW(drop, 0, nullptr, 0);
if (cap == 0)
{
return {};
}
auto buffer = winrt::impl::hstring_builder{ cap };
const auto len = DragQueryFileW(drop, 0, buffer.data(), cap + 1);
if (len == 0)
{
return {};
}
return buffer.to_hstring();
}
return {};
}
} // namespace clipboard
namespace winrt::TerminalApp::implementation
{
TerminalPage::TerminalPage(TerminalApp::WindowProperties properties, const TerminalApp::ContentManager& manager) :
_tabs{ winrt::single_threaded_observable_vector<TerminalApp::Tab>() },
_mruTabs{ winrt::single_threaded_observable_vector<TerminalApp::Tab>() },
_manager{ manager },
_hostingHwnd{},
_WindowProperties{ std::move(properties) }
{
InitializeComponent();
_WindowProperties.PropertyChanged({ get_weak(), &TerminalPage::_windowPropertyChanged });
}
TerminalPage::~TerminalPage()
{
// wta-helper processes are conpty children of TermControl and so
// are torn down by the standard pane teardown path. No per-page
// wta-process watch state to disarm here (removed in Phase 5).
}
// 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 tabImpl{ _GetTabImpl(tab) })
{
tabImpl->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());
const bool firstLoad = (_settings == nullptr);
if (firstLoad)
{
// Create this only on the first time we load the settings.
_terminalSettingsCache = std::make_shared<TerminalSettingsCache>(settings);
}
_settings = settings;
// Seed the agent-settings baseline on first load so that later
// in-memory mutations (e.g. the bottom-bar agent selector click,
// which mutates AcpAgent *before* calling _RebuildAgentStack) are
// correctly diffed against the startup state. Without this, the
// very first _RebuildAgentStack invocation would take the lazy
// "seed-and-skip" branch with the *already-mutated* value and the
// real rebuild would never run.
if (firstLoad)
{
_lastAgentSettings = _CaptureAgentSettingsSnapshot();
_agentSettingsSnapshotInitialized = true;
}
// Shell-integration reconcile (silent, background).
//
// Fires on first-load AND whenever EffectiveAutoErrorDetectionEnabled
// changes between settings reloads. This handles two cases that
// the explicit FRE/Settings-Save install paths miss:
//
// 1. Toggle-OFF: previously a no-op, leaving our $PROFILE block
// in place. We now call UninstallForTarget to strip it.
// 2. Roaming/sync: a synced settings.json arriving on a fresh
// machine never triggered an install because no user action
// ran. First-load reconcile installs based on an explicit
// setting value (sync delivers one). When no explicit value
// exists (truly fresh user), first-load is a no-op and the
// FRE / Settings Save flow remains the consent path.
//
// Install/Uninstall are both idempotent — when the on-disk state
// already matches the desired state they return alreadyInstalled
// and do no I/O beyond a read. Safe to call every reload.
{
const bool currentDetection = _settings.GlobalSettings().EffectiveAutoErrorDetectionEnabled();
const bool hasExplicit = _settings.GlobalSettings().HasAutoErrorDetectionEnabled();
const bool isFirstLoad = !_autoErrorDetectionSnapshotInitialized;
// First load gating:
// - explicit value present (true or false, e.g. roaming-synced settings.json,
// or local user has already saved) -> reconcile, which installs or removes
// to match the user's expressed intent.
// - no explicit value (fresh user, default true) -> do NOT install just because
// the default is true. The FRE / Settings Save flow is the explicit consent
// path for first-time PowerShell profile mutation.
// Subsequent reloads: fire on any change (so explicit toggle in Settings works
// even when transitioning back to the default value) AND on the false->true
// transition of explicit-ness (covers a user/sync adding the explicit key while
// the effective value happens to match the previously-defaulted value).
const bool effectiveChanged = (_lastAutoErrorDetectionEnabled != currentDetection);
const bool explicitTurnedOn = (!_lastAutoErrorDetectionHasExplicit && hasExplicit);
const bool shouldReconcile = isFirstLoad
? hasExplicit
: (effectiveChanged || explicitTurnedOn);
_lastAutoErrorDetectionEnabled = currentDetection;
_lastAutoErrorDetectionHasExplicit = hasExplicit;
_autoErrorDetectionSnapshotInitialized = true;
if (shouldReconcile)
{
// Publish latest desired state BEFORE spawning the
// coroutine so the eventual locked re-read picks it up.
_shellIntegrationDesiredEnabled.store(currentDetection, std::memory_order_release);
_ReconcileShellIntegration();
}
}
// Hot-reload of runtime agent config (autofix gate, acp-model,
// delegate agent/model). When any of these change between settings
// reloads we push a single consolidated `agent_config_changed`
// event to the running wta-helper(s) so they update in place,
// WITHOUT tearing down and restarting the agent pane. This is the
// unified dispatch for every hot-updatable agent setting — adding a
// new one means adding a field to AgentRuntimeConfigSnapshot, not a
// bespoke diff/emit block here. (Agent *identity* changes still go
// through _RebuildAgentStack in _RefreshUIForSettingsReload.)
_EmitAgentRuntimeConfigIfChanged();
// 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();
_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();
_workspaceFlyout = tabRowImpl->WorkspaceFlyout();
_workspaceDropdown = tabRowImpl->WorkspaceDropdown();
// Set the initial workspace name from the window name.
// Use raw WindowName() so unnamed windows show no text.
_tabRow.WorkspaceName(_WindowProperties.WindowName());
// Rebuild the workspace flyout each time it opens so it always
// reflects the latest set of persisted workspaces.
_workspaceFlyout.Opening([weakThis{ get_weak() }](auto&&, auto&&) {
if (auto page{ weakThis.get() })
{
page->_PopulateWorkspaceFlyout();
}
});
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
// 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;
_tabItemMiddleClickHookEnabled = visibility == Settings::Model::TabCloseButtonVisibility::Never;
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() })
{
TraceLoggingWrite(
g_hTerminalAppProvider,
"NewTabMenuDefaultButtonClicked",
TraceLoggingDescription("Event emitted when the default button from the new tab split button is invoked"),
TraceLoggingValue(page->NumberOfTabs(), "TabCount", "The count of tabs currently opened in this window"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServiceUsage));
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();
_showTabsFullscreen = _settings.GlobalSettings().ShowTabsFullscreen();
// DON'T set up Toasts/TeachingTips here. They should be loaded and
// initialized the first time they're opened, in whatever method opens
// them.
_tabRow.ShowElevationShield(IsRunningElevated() && _settings.GlobalSettings().ShowAdminShield());
// Apply the ShowWorkspacesButton theme setting.
if (const auto theme = _settings.GlobalSettings().CurrentTheme())
{
_tabRow.ShowWorkspacesButton(theme.Window() ? theme.Window().ShowWorkspacesButton() : true);
}
_adjustProcessPriorityThrottled = std::make_shared<ThrottledFunc<>>(
DispatcherQueue::GetForCurrentThread(),
til::throttled_func_options{
.delay = std::chrono::milliseconds{ 100 },
.debounce = true,
.trailing = true,
},
[=]() {
_adjustProcessPriority();
});
}
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
{
if (_startupActions.empty() || _startupConnection || IsRunningElevated())
{
// No point in handing off if we got no startup actions, or we're already elevated.
// Also, we shouldn't need to elevate handoff ConPTY connections.
assert(!_startupConnection);
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.empty())
{
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);
}
}
}
safe_void_coroutine 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 when the user submits a foreground agent prompt
// from the command palette (? prefix). Opens or reuses an agent pane
// and sends the prompt to it.
// Arguments:
// - prompt - the user's agent prompt text
// Return Value:
// - <none>
void TerminalPage::_OnAgentForegroundPromptRequested(const IInspectable& /*sender*/, const winrt::hstring& prompt)
{
_agentPaneLog("_OnAgentForegroundPromptRequested: prompt='" + winrt::to_string(prompt) + "' empty=" + (prompt.empty() ? "true" : "false"));
if (!prompt.empty())
{
_DelegatePromptToAgent(prompt);
}
// Empty ? is a no-op. Use >Toggle AI assistant (openAgentPane action) to open the agent pane.
}
// Method Description:
// - This method is called when the user submits a background agent task
// from the command palette (& prefix). Currently a stub that will be
// connected to the Background Task Manager (C9) in a future change.
// Arguments:
// - prompt - the user's background task prompt text
// Return Value:
// - <none>
void TerminalPage::_OnAgentBackgroundTaskRequested(const IInspectable& /*sender*/, const winrt::hstring& /*prompt*/)
{
// TODO: Route to Background Task Manager (C9) when available.
// For now, this is a no-op stub. Future implementation will:
// 1. Submit the prompt to the Background Task Manager
// 2. Show a status indicator in the tab bar
// 3. Deliver results via toast notification on completion
}
// Method Description:
// - Auto-detects an installed agent CLI by iterating the GPO-filtered
// built-in agent list and searching the system PATH for each.
// Arguments:
// - <none>
// Return Value:
// - The bare agent id (e.g. "copilot", "claude") of the first found
// CLI, or empty string if none found. Callers must pass the result
// through _BuildAgentCommandLine to get a launchable command.
winrt::hstring TerminalPage::_DetectAgentCli() const
{
wchar_t buffer[MAX_PATH];
// Walk the policy-filtered agent list so we never auto-detect an
// agent that is blocked by GPO. FilteredAcpAgents() returns only
// agents whose id passes AgentPolicy::IsAgentAllowed(); when no
// AllowedAgents policy is configured it returns all built-in agents.
namespace Reg = ::Microsoft::Terminal::Settings::Model::AgentRegistry;
for (const auto& agent : Reg::FilteredAcpAgents())
{
if (SearchPathW(nullptr, agent.id.data(), L".exe", MAX_PATH, buffer, nullptr) > 0 ||
SearchPathW(nullptr, agent.id.data(), L".cmd", MAX_PATH, buffer, nullptr) > 0)
{
return winrt::hstring{ agent.id };
}
}
return winrt::hstring{};
}
// Method Description:
// - Auto-detects the WTA (Windows Terminal Agent) executable by searching
// the system PATH. WTA is the preferred way to launch agents because it
// handles protocol config injection, giving agents access to Windows Terminal
// tools (pane management, capture-pane, etc.) via the Terminal Protocol (wtcli).
// Arguments:
// - <none>
// Return Value:
// - The full path to wta.exe, or empty string if not found.
winrt::hstring TerminalPage::_DetectWtaPath() const
{
const auto modulePath = std::filesystem::path{ wil::GetModuleFileNameW<std::wstring>(nullptr) };
const auto moduleDir = modulePath.parent_path();
// 1. Check for wta.exe next to the running module (packaged / installed
// scenario). A co-located wta.exe inherits the package identity of
// the Terminal process, which is required for COM activation.
{
const auto sibling = moduleDir / L"wta.exe";
std::error_code ec;
if (std::filesystem::exists(sibling, ec))
{
return winrt::hstring{ sibling.lexically_normal().wstring() };
}
}
// 2. Walk up from the running module to find a local dev build.
// This is the fallback for development when wta.exe is not
// co-located with the Terminal binary.
auto cursor = moduleDir;
while (!cursor.empty())
{
for (const auto& relative : {
std::filesystem::path{ L"tools\\wta\\target\\debug\\wta.exe" },
std::filesystem::path{ L"tools\\wta\\target\\release\\wta.exe" },
})
{
const auto candidate = cursor / relative;
std::error_code ec;
if (std::filesystem::exists(candidate, ec))
{
return winrt::hstring{ candidate.lexically_normal().wstring() };
}
}
const auto parent = cursor.parent_path();
if (parent == cursor)
{
break;
}
cursor = parent;
}
// 3. Fall back to system PATH.
wchar_t buffer[MAX_PATH];
if (SearchPathW(nullptr, L"wta", L".exe", MAX_PATH, buffer, nullptr) > 0)
{
return winrt::hstring{ buffer };
}
return winrt::hstring{};
}
// Look up a tab by its StableId. Linear scan over `_tabs`. Returns
// nullptr if no tab has that id.
winrt::com_ptr<Tab> TerminalPage::_FindTabByStableId(const winrt::hstring& stableId) const
{
if (stableId.empty())
{
return {};
}
for (const auto& tab : _tabs)
{
if (auto tabImpl = _GetTabImpl(tab))
{
if (tabImpl->StableId() == stableId)
{
return tabImpl;
}
}
}
return {};
}
SplitDirection TerminalPage::_AgentPanePositionToSplitDirection(const winrt::hstring& position)
{
if (position == L"bottom")
return SplitDirection::Down;
if (position == L"top" || position == L"up")
return SplitDirection::Up;
if (position == L"left")
return SplitDirection::Left;
return SplitDirection::Right;
}
// ── First-run experience ──────────────────────────────────────────────
bool TerminalPage::_IsFreRequired() const
{
return !ApplicationState::SharedInstance().AgentFreCompleted();
}
void TerminalPage::_ShowFreOverlay()
{
if (auto overlay = FindName(L"FreOverlayElement").try_as<winrt::TerminalApp::FreOverlay>())
{
overlay.Initialize(_settings);
overlay.Completed({ get_weak(), &TerminalPage::_OnFreCompleted });
overlay.Visibility(Visibility::Visible);
// Focus the Next button so Enter triggers it immediately.
// Also announce the page title to screen readers via
// RaiseNotificationEvent so Narrator reads it on entry.
// Dispatched at Low priority so it runs after all pending layout.
Dispatcher().RunAsync(winrt::Windows::UI::Core::CoreDispatcherPriority::Low,
[weak = get_weak()]() {
auto self = weak.get();
if (!self) return;
if (auto overlay = self->FreOverlayElement())
{
if (auto nextBtn = overlay.FindName(L"NextButton").try_as<Controls::Button>())
{
nextBtn.Focus(FocusState::Programmatic);
// Announce page title to screen readers
if (auto peer = winrt::Windows::UI::Xaml::Automation::Peers::FrameworkElementAutomationPeer::FromElement(nextBtn))
{
peer.RaiseNotificationEvent(
winrt::Windows::UI::Xaml::Automation::Peers::AutomationNotificationKind::Other,
winrt::Windows::UI::Xaml::Automation::Peers::AutomationNotificationProcessing::ImportantMostRecent,
RS_(L"FreOverlay_WelcomeTitle/Text"),
L"FreWelcomeAnnouncement");
}
}
}
});
// Hide the tab bar during FRE — the full-screen wizard replaces
// the entire window content. Restored in _OnFreCompleted.
TabRow().Visibility(Visibility::Collapsed);
}
}
void TerminalPage::_OnFreCompleted(const winrt::TerminalApp::FreOverlay& /*sender*/,
const winrt::Windows::Foundation::IInspectable& args)
{
// Hide the FRE overlay
if (auto overlay = FreOverlayElement())
{
overlay.Visibility(Visibility::Collapsed);
}
// Restore the tab bar
TabRow().Visibility(Visibility::Visible);
// Persist: never show FRE again
ApplicationState::SharedInstance().AgentFreCompleted(true);
// Flush settings to disk (FreOverlay already wrote to GlobalSettings
// via _OnSaveButtonClick; if the user closed without saving, defaults
// are used).
_lastAgentSettings = _CaptureAgentSettingsSnapshot();
try
{
_settings.WriteSettingsToDisk();
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
// Execute deferred startup actions — tab creation was postponed
// until FRE completed so that the ConptyConnection picks up any
// PATH changes from winget installs (see _OnFirstLayout deferral).
if (_deferredStartupConnection)
{