-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
TermControl.cpp
4321 lines (3823 loc) · 179 KB
/
TermControl.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 "TermControl.h"
#include <LibraryResources.h>
#include <inputpaneinterop.h>
#include "TermControlAutomationPeer.h"
#include "../../renderer/atlas/AtlasEngine.h"
#include "../../tsf/Handle.h"
#include "TermControl.g.cpp"
using namespace ::Microsoft::Console::Types;
using namespace ::Microsoft::Console::VirtualTerminal;
using namespace ::Microsoft::Terminal::Core;
using namespace winrt::Windows::Graphics::Display;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Input;
using namespace winrt::Windows::UI::Xaml::Automation::Peers;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::UI::ViewManagement;
using namespace winrt::Windows::UI::Input;
using namespace winrt::Windows::System;
using namespace winrt::Windows::ApplicationModel::DataTransfer;
using namespace winrt::Windows::Storage::Streams;
// The minimum delay between updates to the scroll bar's values.
// The updates are throttled to limit power usage.
constexpr const auto ScrollBarUpdateInterval = std::chrono::milliseconds(8);
// The minimum delay between updating the TSF input control.
// This is already throttled primarily in the ControlCore, with a timeout of 100ms. We're adding another smaller one here, as the (potentially x-proc) call will come in off the UI thread
constexpr const auto TsfRedrawInterval = std::chrono::milliseconds(8);
// The minimum delay between updating the locations of regex patterns
constexpr const auto UpdatePatternLocationsInterval = std::chrono::milliseconds(500);
// The minimum delay between emitting warning bells
constexpr const auto TerminalWarningBellInterval = std::chrono::milliseconds(1000);
constexpr std::wstring_view StateNormal{ L"Normal" };
constexpr std::wstring_view StateCollapsed{ L"Collapsed" };
DEFINE_ENUM_FLAG_OPERATORS(winrt::Microsoft::Terminal::Control::CopyFormat);
DEFINE_ENUM_FLAG_OPERATORS(winrt::Microsoft::Terminal::Control::MouseButtonState);
// WinUI 3's UIElement.ProtectedCursor property allows someone to set the cursor on a per-element basis.
// This would allow us to hide the cursor when the TermControl has input focus and someone starts typing.
// Unfortunately, no equivalent exists for WinUI 2 so we fake it with the CoreWindow.
// There are 3 downsides:
// * SetPointerCapture() is global state and may interfere with other components.
// * You can't start dragging the cursor (for text selection) while it's still hidden.
// * The CoreWindow covers the union of all window rectangles, so the cursor is hidden even if it's outside
// the current foreground window, but still on top of another Terminal window in the background.
static void hideCursorUntilMoved()
{
static CoreCursor previousCursor{ nullptr };
static const auto shouldVanish = []() {
BOOL shouldVanish = TRUE;
SystemParametersInfoW(SPI_GETMOUSEVANISH, 0, &shouldVanish, 0);
if (!shouldVanish)
{
return false;
}
const auto window = CoreWindow::GetForCurrentThread();
static constexpr auto releaseCapture = [](CoreWindow window, PointerEventArgs) {
if (previousCursor)
{
window.ReleasePointerCapture();
}
};
static constexpr auto restoreCursor = [](CoreWindow window, PointerEventArgs) {
if (previousCursor)
{
window.PointerCursor(previousCursor);
previousCursor = nullptr;
}
};
winrt::Windows::Foundation::TypedEventHandler<CoreWindow, PointerEventArgs> releaseCaptureHandler{ releaseCapture };
std::ignore = window.PointerMoved(releaseCaptureHandler);
std::ignore = window.PointerPressed(releaseCaptureHandler);
std::ignore = window.PointerReleased(releaseCaptureHandler);
std::ignore = window.PointerWheelChanged(releaseCaptureHandler);
std::ignore = window.PointerCaptureLost(restoreCursor);
return true;
}();
if (shouldVanish && !previousCursor)
{
try
{
const auto window = CoreWindow::GetForCurrentThread();
previousCursor = window.PointerCursor();
if (!previousCursor)
{
return;
}
window.PointerCursor(nullptr);
window.SetPointerCapture();
}
catch (...)
{
// Swallow the 0x80070057 "Failed to get pointer information." exception that randomly occurs.
// Curiously, it doesn't happen during the PointerCursor() but during the SetPointerCapture() call (thanks, WinUI).
}
}
}
// InputPane::GetForCurrentView() does not reliably work for XAML islands,
// as it assumes that there's a 1:1 relationship between windows and threads.
//
// During testing, I found that the input pane shows up when touching into the terminal even if
// TryShow is never called. This surprised me, but I figured it's worth trying it without this.
static void setInputPaneVisibility(HWND hwnd, bool visible)
{
static const auto inputPaneInterop = []() {
return winrt::try_get_activation_factory<InputPane, IInputPaneInterop>();
}();
if (!inputPaneInterop)
{
return;
}
winrt::com_ptr<IInputPane2> inputPane;
if (FAILED(inputPaneInterop->GetForWindow(hwnd, winrt::guid_of<IInputPane2>(), inputPane.put_void())))
{
return;
}
bool result;
if (visible)
{
std::ignore = inputPane->TryShow(&result);
}
else
{
std::ignore = inputPane->TryHide(&result);
}
}
static Microsoft::Console::TSF::Handle& GetTSFHandle()
{
// NOTE: If we ever go back to 1 thread per 1 window,
// you need to swap the `static` with a `thread_local`.
static auto s_tsf = ::Microsoft::Console::TSF::Handle::Create();
return s_tsf;
}
namespace winrt::Microsoft::Terminal::Control::implementation
{
static void _translatePathInPlace(std::wstring& fullPath, PathTranslationStyle translationStyle)
{
static constexpr wil::zwstring_view s_pathPrefixes[] = {
{},
/* WSL */ L"/mnt/",
/* Cygwin */ L"/cygdrive/",
/* MSYS2 */ L"/",
};
static constexpr wil::zwstring_view sSingleQuoteEscape = L"'\\''";
static constexpr auto cchSingleQuoteEscape = sSingleQuoteEscape.size();
if (translationStyle == PathTranslationStyle::None)
{
return;
}
// All of the other path translation modes current result in /-delimited paths
std::replace(fullPath.begin(), fullPath.end(), L'\\', L'/');
// Escape single quotes, assuming translated paths are always quoted by a pair of single quotes.
size_t pos = 0;
while ((pos = fullPath.find(L'\'', pos)) != std::wstring::npos)
{
// ' -> '\'' (for POSIX shell)
fullPath.replace(pos, 1, sSingleQuoteEscape);
// Arithmetic overflow cannot occur here.
pos += cchSingleQuoteEscape;
}
if (fullPath.size() >= 2 && fullPath.at(1) == L':')
{
// C:/foo/bar -> Cc/foo/bar
fullPath.at(1) = til::tolower_ascii(fullPath.at(0));
// Cc/foo/bar -> [PREFIX]c/foo/bar
fullPath.replace(0, 1, s_pathPrefixes[static_cast<int>(translationStyle)]);
}
else if (translationStyle == PathTranslationStyle::WSL)
{
// Stripping the UNC name and distribution prefix only applies to WSL.
static constexpr std::wstring_view wslPathPrefixes[] = { L"//wsl.localhost/", L"//wsl$/" };
for (auto prefix : wslPathPrefixes)
{
if (til::starts_with(fullPath, prefix))
{
if (const auto idx = fullPath.find(L'/', prefix.size()); idx != std::wstring::npos)
{
// //wsl.localhost/Ubuntu-18.04/foo/bar -> /foo/bar
fullPath.erase(0, idx);
}
else
{
// //wsl.localhost/Ubuntu-18.04 -> /
fullPath = L"/";
}
break;
}
}
}
}
TsfDataProvider::TsfDataProvider(TermControl* termControl) noexcept :
_termControl{ termControl }
{
}
STDMETHODIMP TsfDataProvider::QueryInterface(REFIID, void**) noexcept
{
return E_NOTIMPL;
}
ULONG STDMETHODCALLTYPE TsfDataProvider::AddRef() noexcept
{
return 1;
}
ULONG STDMETHODCALLTYPE TsfDataProvider::Release() noexcept
{
return 1;
}
HWND TsfDataProvider::GetHwnd()
{
if (!_hwnd)
{
// WinUI's WinRT based TSF runs in its own window "Windows.UI.Input.InputSite.WindowClass" (..."great")
// and in order for us to snatch the focus away from that one we need to find its HWND.
// The way we do it here is by finding the existing, active TSF context and getting the HWND from it.
_hwnd = GetTSFHandle().FindWindowOfActiveTSF();
if (!_hwnd)
{
_hwnd = reinterpret_cast<HWND>(_termControl->OwningHwnd());
}
}
return _hwnd;
}
RECT TsfDataProvider::GetViewport()
{
const auto hwnd = reinterpret_cast<HWND>(_termControl->OwningHwnd());
RECT clientRect;
GetWindowRect(hwnd, &clientRect);
return clientRect;
}
RECT TsfDataProvider::GetCursorPosition()
{
const auto core = _getCore();
if (!core)
{
return {};
}
const auto hwnd = reinterpret_cast<HWND>(_termControl->OwningHwnd());
RECT clientRect;
GetWindowRect(hwnd, &clientRect);
const auto scaleFactor = static_cast<float>(DisplayInformation::GetForCurrentView().RawPixelsPerViewPixel());
const auto localOrigin = _termControl->TransformToVisual(nullptr).TransformPoint({});
const auto padding = _termControl->GetPadding();
const auto cursorPosition = core->CursorPosition();
const auto fontSize = core->FontSize();
// fontSize is not in DIPs, so we need to first multiply by scaleFactor and then do the rest.
const auto left = clientRect.left + (localOrigin.X + static_cast<float>(padding.Left)) * scaleFactor + cursorPosition.X * fontSize.Width;
const auto top = clientRect.top + (localOrigin.Y + static_cast<float>(padding.Top)) * scaleFactor + cursorPosition.Y * fontSize.Height;
const auto right = left + fontSize.Width;
const auto bottom = top + fontSize.Height;
return {
lroundf(left),
lroundf(top),
lroundf(right),
lroundf(bottom),
};
}
void TsfDataProvider::HandleOutput(std::wstring_view text)
{
const auto core = _getCore();
if (!core)
{
return;
}
core->SendInput(text);
}
::Microsoft::Console::Render::Renderer* TsfDataProvider::GetRenderer()
{
const auto core = _getCore();
if (!core)
{
return nullptr;
}
return core->GetRenderer();
}
ControlCore* TsfDataProvider::_getCore() const noexcept
{
return get_self<ControlCore>(_termControl->_core);
}
TermControl::TermControl(IControlSettings settings,
Control::IControlAppearance unfocusedAppearance,
TerminalConnection::ITerminalConnection connection) :
TermControl{ winrt::make<implementation::ControlInteractivity>(settings, unfocusedAppearance, connection) }
{
}
TermControl::TermControl(Control::ControlInteractivity content) :
_interactivity{ content },
_isInternalScrollBarUpdate{ false },
_autoScrollVelocity{ 0 },
_autoScrollingPointerPoint{ std::nullopt },
_lastAutoScrollUpdateTime{ std::nullopt },
_searchBox{ nullptr }
{
InitializeComponent();
_core = _interactivity.Core();
// This event is specifically triggered by the renderer thread, a BG thread. Use a weak ref here.
_revokers.RendererEnteredErrorState = _core.RendererEnteredErrorState(winrt::auto_revoke, { get_weak(), &TermControl::_RendererEnteredErrorState });
// IMPORTANT! Set this callback up sooner rather than later. If we do it
// after Enable, then it'll be possible to paint the frame once
// _before_ the warning handler is set up, and then warnings from
// the first paint will be ignored!
_revokers.RendererWarning = _core.RendererWarning(winrt::auto_revoke, { get_weak(), &TermControl::_RendererWarning });
// ALSO IMPORTANT: Make sure to set this callback up in the ctor, so
// that we won't miss any swap chain changes.
_revokers.SwapChainChanged = _core.SwapChainChanged(winrt::auto_revoke, { get_weak(), &TermControl::RenderEngineSwapChainChanged });
// These callbacks can only really be triggered by UI interactions. So
// they don't need weak refs - they can't be triggered unless we're
// alive.
_revokers.BackgroundColorChanged = _core.BackgroundColorChanged(winrt::auto_revoke, { get_weak(), &TermControl::_coreBackgroundColorChanged });
_revokers.FontSizeChanged = _core.FontSizeChanged(winrt::auto_revoke, { get_weak(), &TermControl::_coreFontSizeChanged });
_revokers.TransparencyChanged = _core.TransparencyChanged(winrt::auto_revoke, { get_weak(), &TermControl::_coreTransparencyChanged });
_revokers.RaiseNotice = _core.RaiseNotice(winrt::auto_revoke, { get_weak(), &TermControl::_coreRaisedNotice });
_revokers.HoveredHyperlinkChanged = _core.HoveredHyperlinkChanged(winrt::auto_revoke, { get_weak(), &TermControl::_hoveredHyperlinkChanged });
_revokers.OutputIdle = _core.OutputIdle(winrt::auto_revoke, { get_weak(), &TermControl::_coreOutputIdle });
_revokers.UpdateSelectionMarkers = _core.UpdateSelectionMarkers(winrt::auto_revoke, { get_weak(), &TermControl::_updateSelectionMarkers });
_revokers.coreOpenHyperlink = _core.OpenHyperlink(winrt::auto_revoke, { get_weak(), &TermControl::_HyperlinkHandler });
_revokers.interactivityOpenHyperlink = _interactivity.OpenHyperlink(winrt::auto_revoke, { get_weak(), &TermControl::_HyperlinkHandler });
_revokers.interactivityScrollPositionChanged = _interactivity.ScrollPositionChanged(winrt::auto_revoke, { get_weak(), &TermControl::_ScrollPositionChanged });
_revokers.ContextMenuRequested = _interactivity.ContextMenuRequested(winrt::auto_revoke, { get_weak(), &TermControl::_contextMenuHandler });
// "Bubbled" events - ones we want to handle, by raising our own event.
_revokers.TitleChanged = _core.TitleChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleTitleChanged });
_revokers.TabColorChanged = _core.TabColorChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleTabColorChanged });
_revokers.TaskbarProgressChanged = _core.TaskbarProgressChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleSetTaskbarProgress });
_revokers.ConnectionStateChanged = _core.ConnectionStateChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleConnectionStateChanged });
_revokers.ShowWindowChanged = _core.ShowWindowChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleShowWindowChanged });
_revokers.CloseTerminalRequested = _core.CloseTerminalRequested(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleCloseTerminalRequested });
_revokers.CompletionsChanged = _core.CompletionsChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleCompletionsChanged });
_revokers.RestartTerminalRequested = _core.RestartTerminalRequested(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleRestartTerminalRequested });
_revokers.SearchMissingCommand = _core.SearchMissingCommand(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleSearchMissingCommand });
_revokers.WindowSizeChanged = _core.WindowSizeChanged(winrt::auto_revoke, { get_weak(), &TermControl::_bubbleWindowSizeChanged });
_revokers.PasteFromClipboard = _interactivity.PasteFromClipboard(winrt::auto_revoke, { get_weak(), &TermControl::_bubblePasteFromClipboard });
_revokers.RefreshQuickFixUI = _core.RefreshQuickFixUI(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {
RefreshQuickFixMenu();
});
// Initialize the terminal only once the swapchainpanel is loaded - that
// way, we'll be able to query the real pixel size it got on layout
_layoutUpdatedRevoker = SwapChainPanel().LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {
// 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 (_InitializeTerminal(InitializeReason::Create))
{
// Only let this succeed once.
_layoutUpdatedRevoker.revoke();
}
});
// Get our dispatcher. This will get us the same dispatcher as
// TermControl::Dispatcher().
auto dispatcher = winrt::Windows::System::DispatcherQueue::GetForCurrentThread();
// These three throttled functions are triggered by terminal output and interact with the UI.
// Since Close() is the point after which we are removed from the UI, but before the
// destructor has run, we MUST check control->_IsClosing() before actually doing anything.
_playWarningBell = std::make_shared<ThrottledFuncLeading>(
dispatcher,
TerminalWarningBellInterval,
[weakThis = get_weak()]() {
if (auto control{ weakThis.get() }; control && !control->_IsClosing())
{
control->WarningBell.raise(*control, nullptr);
}
});
_updateScrollBar = std::make_shared<ThrottledFuncTrailing<ScrollBarUpdate>>(
dispatcher,
ScrollBarUpdateInterval,
[weakThis = get_weak()](const auto& update) {
if (auto control{ weakThis.get() }; control && !control->_IsClosing())
{
control->_throttledUpdateScrollbar(update);
}
});
// These events might all be triggered by the connection, but that
// should be drained and closed before we complete destruction. So these
// are safe.
//
// NOTE: _ScrollPositionChanged has to be registered after we set up the
// _updateScrollBar func. Otherwise, we could get a callback from an
// attached content before we set up the throttled func, and that'll A/V
_revokers.coreScrollPositionChanged = _core.ScrollPositionChanged(winrt::auto_revoke, { get_weak(), &TermControl::_ScrollPositionChanged });
_revokers.WarningBell = _core.WarningBell(winrt::auto_revoke, { get_weak(), &TermControl::_coreWarningBell });
static constexpr auto AutoScrollUpdateInterval = std::chrono::microseconds(static_cast<int>(1.0 / 30.0 * 1000000));
_autoScrollTimer.Interval(AutoScrollUpdateInterval);
_autoScrollTimer.Tick({ get_weak(), &TermControl::_UpdateAutoScroll });
_ApplyUISettings();
_originalPrimaryElements = winrt::single_threaded_observable_vector<Controls::ICommandBarElement>();
_originalSecondaryElements = winrt::single_threaded_observable_vector<Controls::ICommandBarElement>();
_originalSelectedPrimaryElements = winrt::single_threaded_observable_vector<Controls::ICommandBarElement>();
_originalSelectedSecondaryElements = winrt::single_threaded_observable_vector<Controls::ICommandBarElement>();
for (const auto& e : ContextMenu().PrimaryCommands())
{
_originalPrimaryElements.Append(e);
}
for (const auto& e : ContextMenu().SecondaryCommands())
{
_originalSecondaryElements.Append(e);
}
for (const auto& e : SelectionContextMenu().PrimaryCommands())
{
_originalSelectedPrimaryElements.Append(e);
}
for (const auto& e : SelectionContextMenu().SecondaryCommands())
{
_originalSelectedSecondaryElements.Append(e);
}
ContextMenu().Closed([weakThis = get_weak()](auto&&, auto&&) {
if (auto control{ weakThis.get() }; control && !control->_IsClosing())
{
const auto& menu{ control->ContextMenu() };
menu.PrimaryCommands().Clear();
menu.SecondaryCommands().Clear();
for (const auto& e : control->_originalPrimaryElements)
{
menu.PrimaryCommands().Append(e);
}
for (const auto& e : control->_originalSecondaryElements)
{
menu.SecondaryCommands().Append(e);
}
}
});
SelectionContextMenu().Closed([weakThis = get_weak()](auto&&, auto&&) {
if (auto control{ weakThis.get() }; control && !control->_IsClosing())
{
const auto& menu{ control->SelectionContextMenu() };
menu.PrimaryCommands().Clear();
menu.SecondaryCommands().Clear();
for (const auto& e : control->_originalSelectedPrimaryElements)
{
menu.PrimaryCommands().Append(e);
}
for (const auto& e : control->_originalSelectedSecondaryElements)
{
menu.SecondaryCommands().Append(e);
}
}
});
if constexpr (Feature_QuickFix::IsEnabled())
{
QuickFixMenu().Closed([weakThis = get_weak()](auto&&, auto&&) {
if (auto control{ weakThis.get() }; control && !control->_IsClosing())
{
// Expand the quick fix button if it's collapsed (looks nicer)
if (control->_quickFixButtonCollapsible)
{
VisualStateManager::GoToState(*control, StateCollapsed, false);
}
}
});
}
}
void TermControl::_QuickFixButton_PointerEntered(const IInspectable& /*sender*/, const PointerRoutedEventArgs& /*e*/)
{
if (!_IsClosing() && _quickFixButtonCollapsible)
{
VisualStateManager::GoToState(*this, StateNormal, false);
}
}
void TermControl::_QuickFixButton_PointerExited(const IInspectable& /*sender*/, const PointerRoutedEventArgs& /*e*/)
{
if (!_IsClosing() && _quickFixButtonCollapsible)
{
VisualStateManager::GoToState(*this, StateCollapsed, false);
}
}
// Function Description:
// - Static helper for building a new TermControl from an already existing
// content. We'll attach the existing swapchain to this new control's
// SwapChainPanel. The IKeyBindings might belong to a non-agile object on
// a new thread, so we'll hook up the core to these new bindings.
// Arguments:
// - content: The preexisting ControlInteractivity to connect to.
// - keybindings: The new IKeyBindings instance to use for this control.
// Return Value:
// - The newly constructed TermControl.
Control::TermControl TermControl::NewControlByAttachingContent(Control::ControlInteractivity content,
const Microsoft::Terminal::Control::IKeyBindings& keyBindings)
{
const auto term{ winrt::make_self<TermControl>(content) };
term->_initializeForAttach(keyBindings);
return *term;
}
void TermControl::_initializeForAttach(const Microsoft::Terminal::Control::IKeyBindings& keyBindings)
{
_AttachDxgiSwapChainToXaml(reinterpret_cast<HANDLE>(_core.SwapChainHandle()));
_interactivity.AttachToNewControl(keyBindings);
// Initialize the terminal only once the swapchainpanel is loaded - that
// way, we'll be able to query the real pixel size it got on layout
auto r = SwapChainPanel().LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {
// Replace the normal initialize routine with one that will allow up
// to complete initialization even though the Core was already
// initialized.
if (_InitializeTerminal(InitializeReason::Reattach))
{
// Only let this succeed once.
_layoutUpdatedRevoker.revoke();
}
});
_layoutUpdatedRevoker.swap(r);
}
uint64_t TermControl::ContentId() const
{
return _interactivity.Id();
}
TerminalConnection::ITerminalConnection TermControl::Connection()
{
return _core.Connection();
}
void TermControl::Connection(const TerminalConnection::ITerminalConnection& newConnection)
{
_core.Connection(newConnection);
}
void TermControl::_throttledUpdateScrollbar(const ScrollBarUpdate& update)
{
if (!_initializedTerminal)
{
return;
}
// Assumptions:
// * we're already not closing
// * caller already checked weak ptr to make sure we're still alive
_isInternalScrollBarUpdate = true;
auto scrollBar = ScrollBar();
if (update.newValue)
{
scrollBar.Value(*update.newValue);
}
scrollBar.Maximum(update.newMaximum);
scrollBar.Minimum(update.newMinimum);
scrollBar.ViewportSize(update.newViewportSize);
// scroll one full screen worth at a time when the scroll bar is clicked
scrollBar.LargeChange(std::max(update.newViewportSize - 1, 0.));
_isInternalScrollBarUpdate = false;
if (_showMarksInScrollbar)
{
const auto scaleFactor = DisplayInformation::GetForCurrentView().RawPixelsPerViewPixel();
const auto scrollBarWidthInDIP = scrollBar.ActualWidth();
const auto scrollBarHeightInDIP = scrollBar.ActualHeight();
const auto scrollBarWidthInPx = gsl::narrow_cast<int32_t>(lrint(scrollBarWidthInDIP * scaleFactor));
const auto scrollBarHeightInPx = gsl::narrow_cast<int32_t>(lrint(scrollBarHeightInDIP * scaleFactor));
const auto canvas = FindName(L"ScrollBarCanvas").as<Controls::Image>();
auto source = canvas.Source().try_as<Media::Imaging::WriteableBitmap>();
if (!source || scrollBarWidthInPx != source.PixelWidth() || scrollBarHeightInPx != source.PixelHeight())
{
source = Media::Imaging::WriteableBitmap{ scrollBarWidthInPx, scrollBarHeightInPx };
canvas.Source(source);
canvas.Width(scrollBarWidthInDIP);
canvas.Height(scrollBarHeightInDIP);
}
const auto buffer = source.PixelBuffer();
const auto data = buffer.data();
const auto stride = scrollBarWidthInPx * sizeof(til::color);
// The bitmap has the size of the entire scrollbar, but we want the marks to only show in the range the "thumb"
// (the scroll indicator) can move. That's why we need to add an offset to the start of the drawable bitmap area
// (to offset the decrease button) and subtract twice that (to offset the increase button as well).
//
// The WinUI standard scrollbar defines a Margin="2,0,2,0" for the "VerticalPanningThumb" and a Padding="0,4,0,0"
// for the "VerticalDecrementTemplate" (and similar for the increment), but it seems neither of those is correct,
// because a padding for 3 DIPs seem to be the exact right amount to add.
const auto increaseDecreaseButtonHeight = scrollBarWidthInPx + lround(3 * scaleFactor);
const auto drawableDataStart = data + stride * increaseDecreaseButtonHeight;
const auto drawableRange = scrollBarHeightInPx - 2 * increaseDecreaseButtonHeight;
// Protect the remaining code against negative offsets. This normally can't happen
// and this code just exists so it doesn't crash if I'm ever wrong about this.
// (The window has a min. size that ensures that there's always a scrollbar thumb.)
if (drawableRange < 0)
{
return;
}
// The scrollbar bitmap is divided into 3 evenly sized stripes:
// Left: Regular marks
// Center: nothing
// Right: Search marks
const auto pipWidth = (scrollBarWidthInPx + 1) / 3;
const auto pipHeight = lround(1 * scaleFactor);
const auto maxOffsetY = drawableRange - pipHeight;
const auto offsetScale = maxOffsetY / gsl::narrow_cast<float>(update.newMaximum + update.newViewportSize);
// A helper to turn a TextBuffer row offset into a bitmap offset.
const auto dataAt = [&](til::CoordType row) [[msvc::forceinline]] {
const auto y = std::clamp<long>(lrintf(row * offsetScale), 0, maxOffsetY);
return drawableDataStart + stride * y;
};
// A helper to draw a single pip (mark) at the given location.
const auto drawPip = [&](uint8_t* beg, til::color color) [[msvc::forceinline]] {
const auto end = beg + pipHeight * stride;
for (; beg < end; beg += stride)
{
// a til::color does NOT have the same RGBA format as the bitmap.
#pragma warning(suppress : 26490) // Don't use reinterpret_cast (type.1).
const DWORD c = 0xff << 24 | color.r << 16 | color.g << 8 | color.b;
std::fill_n(reinterpret_cast<DWORD*>(beg), pipWidth, c);
}
};
memset(data, 0, buffer.Length());
if (const auto marks = _core.ScrollMarks())
{
for (const auto& m : marks)
{
const auto row = m.Row;
const til::color color{ m.Color.Color };
const auto base = dataAt(row);
drawPip(base, color);
}
}
if (_searchBox && _searchBox->IsOpen())
{
const auto core = winrt::get_self<ControlCore>(_core);
const auto& searchMatches = core->SearchResultRows();
const auto color = core->ForegroundColor();
const auto rightAlignedOffset = (scrollBarWidthInPx - pipWidth) * sizeof(til::color);
til::CoordType lastRow = til::CoordTypeMin;
for (const auto& span : searchMatches)
{
if (lastRow != span.start.y)
{
lastRow = span.start.y;
const auto base = dataAt(lastRow) + rightAlignedOffset;
drawPip(base, color);
}
}
}
source.Invalidate();
canvas.Visibility(Visibility::Visible);
}
}
// Method Description:
// - Loads the search box from the xaml UI and focuses it.
void TermControl::CreateSearchBoxControl()
{
// Lazy load the search box control.
if (auto loadedSearchBox{ FindName(L"SearchBox") })
{
if (auto searchBox{ loadedSearchBox.try_as<::winrt::Microsoft::Terminal::Control::SearchBoxControl>() })
{
// get at its private implementation
_searchBox.copy_from(winrt::get_self<implementation::SearchBoxControl>(searchBox));
// If a text is selected inside terminal, use it to populate the search box.
// If the search box already contains a value, it will be overridden.
if (_core.HasSelection())
{
// Currently we populate the search box only if a single line is selected.
// Empirically, multi-line selection works as well on sample scenarios,
// but since code paths differ, extra work is required to ensure correctness.
if (!_core.HasMultiLineSelection())
{
const auto selectedLine{ _core.SelectedText(true) };
_searchBox->PopulateTextbox(selectedLine);
}
}
_searchBox->Open([weakThis = get_weak()]() {
if (const auto self = weakThis.get(); self && !self->_IsClosing())
{
self->_searchScrollOffset = self->_calculateSearchScrollOffset();
self->_searchBox->SetFocusOnTextbox();
self->_refreshSearch();
}
});
}
}
}
// This is called when a Find Next/Previous Match action is triggered.
void TermControl::SearchMatch(const bool goForward)
{
if (_IsClosing())
{
return;
}
if (!_searchBox || !_searchBox->IsOpen())
{
CreateSearchBoxControl();
}
else
{
const auto request = SearchRequest{ _searchBox->Text(), goForward, _searchBox->CaseSensitive(), _searchBox->RegularExpression(), false, _searchScrollOffset };
_handleSearchResults(_core.Search(request));
}
}
// Method Description:
// Find if search box text edit currently is in focus
// Return Value:
// - true, if search box text edit is in focus
bool TermControl::SearchBoxEditInFocus() const
{
if (!_searchBox)
{
return false;
}
return _searchBox->TextBox().FocusState() == FocusState::Keyboard;
}
// Method Description:
// - Search text in text buffer. This is triggered if the user clicks the
// search button, presses enter, or changes the search criteria.
// Arguments:
// - text: the text to search
// - goForward: boolean that represents if the current search direction is forward
// - caseSensitive: boolean that represents if the current search is case-sensitive
// Return Value:
// - <none>
void TermControl::_Search(const winrt::hstring& text,
const bool goForward,
const bool caseSensitive,
const bool regularExpression)
{
if (_searchBox && _searchBox->IsOpen())
{
const auto request = SearchRequest{ text, goForward, caseSensitive, regularExpression, false, _searchScrollOffset };
_handleSearchResults(_core.Search(request));
}
}
// Method Description:
// - The handler for the "search criteria changed" event. Initiates a new search.
// Arguments:
// - text: the text to search
// - goForward: indicates whether the search should be performed forward (if set to true) or backward
// - caseSensitive: boolean that represents if the current search is case-sensitive
// Return Value:
// - <none>
void TermControl::_SearchChanged(const winrt::hstring& text,
const bool goForward,
const bool caseSensitive,
const bool regularExpression)
{
if (_searchBox && _searchBox->IsOpen())
{
// We only want to update the search results based on the new text. Set
// `resetOnly` to true so we don't accidentally update the current match index.
const auto request = SearchRequest{ text, goForward, caseSensitive, regularExpression, true, _searchScrollOffset };
const auto result = _core.Search(request);
_handleSearchResults(result);
}
}
// Method Description:
// - The handler for the close button or pressing "Esc" when focusing on the
// search dialog.
// Arguments:
// - IInspectable: not used
// - RoutedEventArgs: not used
// Return Value:
// - <none>
void TermControl::_CloseSearchBoxControl(const winrt::Windows::Foundation::IInspectable& /*sender*/,
const RoutedEventArgs& /*args*/)
{
_searchBox->Close();
_core.ClearSearch();
// Clear search highlights scroll marks (by triggering an update after closing the search box)
if (_showMarksInScrollbar)
{
const auto scrollBar = ScrollBar();
ScrollBarUpdate update{
.newValue = scrollBar.Value(),
.newMaximum = scrollBar.Maximum(),
.newMinimum = scrollBar.Minimum(),
.newViewportSize = scrollBar.ViewportSize(),
};
_updateScrollBar->Run(update);
}
// Set focus back to terminal control
this->Focus(FocusState::Programmatic);
}
void TermControl::UpdateControlSettings(IControlSettings settings)
{
UpdateControlSettings(settings, _core.UnfocusedAppearance());
}
// Method Description:
// - Given Settings having been updated, applies the settings to the current terminal.
// Return Value:
// - <none>
void TermControl::UpdateControlSettings(IControlSettings settings, IControlAppearance unfocusedAppearance)
{
_core.UpdateSettings(settings, unfocusedAppearance);
_UpdateSettingsFromUIThread();
_UpdateAppearanceFromUIThread(_focused ? _core.FocusedAppearance() : _core.UnfocusedAppearance());
}
// Method Description:
// - Dispatches a call to the UI thread and updates the appearance
// Arguments:
// - newAppearance: the new appearance to set
void TermControl::UpdateAppearance(IControlAppearance newAppearance)
{
_UpdateAppearanceFromUIThread(newAppearance);
}
// Method Description:
// - Updates the settings of the current terminal.
// - This method is separate from UpdateSettings because there is an apparent optimizer
// issue that causes one of our hstring -> wstring_view conversions to result in garbage,
// but only from a coroutine context. See GH#8723.
// - INVARIANT: This method must be called from the UI thread.
// Arguments:
// - newSettings: the new settings to set
void TermControl::_UpdateSettingsFromUIThread()
{
if (_IsClosing())
{
return;
}
// Update our control settings
_ApplyUISettings();
}
// Method Description:
// - Updates the appearance
// - INVARIANT: This method must be called from the UI thread.
// Arguments:
// - newAppearance: the new appearance to set
void TermControl::_UpdateAppearanceFromUIThread(Control::IControlAppearance newAppearance)
{
if (_IsClosing())
{
return;
}
_SetBackgroundImage(newAppearance);
// Update our control settings
const auto bg = newAppearance.DefaultBackground();
// In the future, this might need to be changed to a
// _InitializeBackgroundBrush call instead, because we may need to
// switch from a solid color brush to an acrylic one.
_changeBackgroundColor(bg);
// Update selection markers
Windows::UI::Xaml::Media::SolidColorBrush cursorColorBrush{ til::color{ newAppearance.CursorColor() } };
SelectionStartMarker().Fill(cursorColorBrush);
SelectionEndMarker().Fill(cursorColorBrush);
_core.ApplyAppearance(_focused);
}
// Method Description:
// - Writes the given sequence as input to the active terminal connection,
// Arguments:
// - wstr: the string of characters to write to the terminal connection.
// Return Value:
// - <none>
void TermControl::SendInput(const winrt::hstring& wstr)
{
// Dismiss any previewed input.
PreviewInput(hstring{});
// only broadcast if there's an actual listener. Saves the overhead of some object creation.
if (StringSent)
{
StringSent.raise(*this, winrt::make<StringSentEventArgs>(wstr));
}
RawWriteString(wstr);
}
void TermControl::ClearBuffer(Control::ClearBufferType clearType)
{
_core.ClearBuffer(clearType);
}
void TermControl::ToggleShaderEffects()
{
_core.ToggleShaderEffects();
}
// Method Description:
// - Style our UI elements based on the values in our settings, and set up
// other control-specific settings. This method will be called whenever
// the settings are reloaded.
// * Calls _InitializeBackgroundBrush to set up the Xaml brush responsible
// for the control's background
// * Calls _BackgroundColorChanged to style the background of the control
// - Core settings will be passed to the terminal in _InitializeTerminal
// Arguments:
// - <none>
// Return Value:
// - <none>
void TermControl::_ApplyUISettings()
{
_InitializeBackgroundBrush();
// settings might be out-of-proc in the future
auto settings{ _core.Settings() };
// Apply padding as swapChainPanel's margin
const auto newMargin = ParseThicknessFromPadding(settings.Padding());
SwapChainPanel().Margin(newMargin);
// Apply settings for scrollbar
if (settings.ScrollState() == ScrollbarState::Hidden)
{
// In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the
// Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to
// achieve the intended effect.
ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);
ScrollBar().Visibility(Visibility::Collapsed);
}
else // (default or Visible)
{
// Default behavior
ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);
ScrollBar().Visibility(Visibility::Visible);
}
_interactivity.UpdateSettings();
{
const auto inputScope = settings.DefaultInputScope();
const auto alpha = inputScope == DefaultInputScope::AlphanumericHalfWidth;
::Microsoft::Console::TSF::Handle::SetDefaultScopeAlphanumericHalfWidth(alpha);
}