Rewrite HwndTerminal to build on ControlInteractivity and -Core #20812
GROQ_API_KEY / GROQ_API_KEY_backup in .env
@@ -403,10 +433,10 @@ private IntPtr TerminalContainer_MessageHook(IntPtr hwnd, int msg, IntPtr wParam
this.Connection?.Resize((uint)dimensions.Y, (uint)dimensions.X);
break;
- case NativeMethods.WindowMessage.WM_MOUSEWHEEL:
- var delta = (short)(((long)wParam) >> 16);
- this.UserScrolled?.Invoke(this, delta);
- break;
+ //case NativeMethods.WindowMessage.WM_MOUSEWHEEL:
TODO look at this
@@ -5,6 +5,7 @@
<RootNamespace>Microsoft.Terminal.Wpf</RootNamespace>
<AssemblyName>Microsoft.Terminal.Wpf</AssemblyName>
<UseWpf>true</UseWpf>
+ <LangVersion>9.0</LangVersion>
yeah I used some fancy operators
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#pragma once
+
+// Keep in sync with TerminalTheme.cs
+typedef struct _TerminalTheme
+{
+ COLORREF DefaultBackground;
+ COLORREF DefaultForeground;
+ COLORREF DefaultSelectionBackground;
+ uint32_t CursorStyle; // This will be converted to DispatchTypes::CursorStyle (size_t), but C# cannot marshal an enum type and have it fit in a size_t.
+ COLORREF ColorTable[16];
+} TerminalTheme;
+
+typedef void* PTERM;
+typedef void(__stdcall* PSCROLLCB)(int, int, int);
+typedef void(__stdcall* PWRITECB)(const wchar_t*);
+
+typedef struct _TerminalDispatcherCallouts
+{
+ bool(__stdcall* pDispatcherTryEnqueueWork)(void*, int, void*);
+ bool(__stdcall* pDispatcherHasThreadAccess)(void*);
+ // Context which will be passed back to the above function pointers.
+ void* context;
+} TerminalDispatcherCallouts;
+
+#define TERMINAL_API_TABLE(XX) \
+ XX(SendOutput, LPCWSTR, data) \
+ XX(RegisterScrollCallback, PSCROLLCB, callback) \
+ XX(TriggerResize, _In_ til::CoordType, width, _In_ til::CoordType, height, _Out_ til::size*, dimensions) \
+ XX(TriggerResizeWithDimension, _In_ til::size, dimensions, _Out_ til::size*, dimensionsInPixels) \
+ XX(CalculateResize, _In_ til::CoordType, width, _In_ til::CoordType, height, _Out_ til::size*, dimensions) \
+ XX(DpiChanged, int, newDpi) \
+ XX(UserScroll, int, viewTop) \
+ XX(GetSelection, const wchar_t**, out) \
+ XX(IsSelectionActive, bool*, out) \
+ XX(SetTheme, TerminalTheme, theme, LPCWSTR, fontFamily, til::CoordType, fontSize, int, newDpi) \
+ XX(RegisterWriteCallback, PWRITECB, callback) \
+ XX(SendKeyEvent, WORD, vkey, WORD, scanCode, WORD, flags, bool, keyDown) \
+ XX(SendCharEvent, wchar_t, ch, WORD, flags, WORD, scanCode)
+
+extern "C" {
+#define API_NAME(name) Terminal##name
+#define GENERATOR_0(name) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM);
+#define GENERATOR_1(name, t1, a1) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM, t1);
+#define GENERATOR_2(name, t1, a1, t2, a2) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM, t1, t2);
+#define GENERATOR_3(name, t1, a1, t2, a2, t3, a3) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM, t1, t2, t3);
+#define GENERATOR_4(name, t1, a1, t2, a2, t3, a3, t4, a4) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM, t1, t2, t3, t4);
+#define GENERATOR_N(name, t1, a1, t2, a2, t3, a3, t4, a4, MACRO, ...) MACRO
+#define GENERATOR(...) \
+ GENERATOR_N(__VA_ARGS__, GENERATOR_4, GENERATOR_4, GENERATOR_3, GENERATOR_3, GENERATOR_2, GENERATOR_2, GENERATOR_1, GENERATOR_1, GENERATOR_0) \
+ (__VA_ARGS__)
+TERMINAL_API_TABLE(GENERATOR)
+#undef GENERATOR
+#undef GENERATOR_0
+#undef GENERATOR_1
+#undef GENERATOR_2
+#undef GENERATOR_3
+#undef GENERATOR_4
+#undef GENERATOR_N
+#undef API_NAME
+
+__declspec(dllexport) HRESULT __stdcall CreateTerminal(HWND parentHwnd, TerminalDispatcherCallouts dispatcherCallouts, _Out_ void** hwnd, _Out_ PTERM* terminal);
THIS FILE IS NOT INTENDED FOR PUBLICATION AND IS AN IMPLEMENTATION DETAIL FOR NOW
The idea is that if we DO add a flat C API, we could generate it using these macros. This just makes my life easier.
check-spelling found more than 20 potential problems in the proposed changes. Check the [Files changed](/microsoft/terminal/pull/20812/files) tab for more details.
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view wsv{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(wsv.data()), static_cast<uint32_t>(wsv.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Setup the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these rodered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
+ EventRegistrationToken*)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP remove_ShutdownStarting(
+ EventRegistrationToken)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP add_ShutdownCompleted(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_IInspectable*,
+ EventRegistrationToken*)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP remove_ShutdownCompleted(
+ EventRegistrationToken)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP get_HasThreadAccess(boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result);
+ *result = _callouts.pDispatcherHasThreadAccess(_callouts.context);
+ return S_OK;
+ }
+
+private:
+ TerminalDispatcherCallouts _callouts;
+};
+
+__declspec(dllexport) HRESULT __stdcall InteropQueueHandlerInvoke(void* ptr)
+{
+ auto handler = static_cast<::ABI::Windows::System::IDispatcherQueueHandler*>(ptr);
+ const auto hr = handler->Invoke();
+ handler->Release();
+ return hr;
+}
+#pragma endregion
+
+extern "C" void __stdcall AvoidBuggyTSFConsoleFlags()
+{
+ Microsoft::Console::TSF::Handle::AvoidBuggyTSFConsoleFlags();
+}
+
+__declspec(dllexport) HRESULT __stdcall CreateTerminal(HWND parentHwnd, _In_ TerminalDispatcherCallouts dispatcherCallouts, _Out_ void** hwnd, _Out_ PTERM* terminal)
+{
+ winrt::Windows::System::DispatcherQueue localDispatcherQueue{ nullptr };
+ if (dispatcherCallouts.pDispatcherTryEnqueueWork != nullptr)
+ {
+ auto dispatcher = winrt::make<CalloutBasedDispatcherQueue>(std::move(dispatcherCallouts));
+ winrt::copy_from_abi(localDispatcherQueue, winrt::get_abi(dispatcher));
+ }
+ auto inner = new HwndTerminal{ parentHwnd, localDispatcherQueue };
+ *terminal = inner;
+ *hwnd = inner->_hwnd.get();
+ inner->Initialize();
+ return S_OK;
+}
+
+__declspec(dllexport) void __stdcall DestroyTerminal(PTERM terminal)
+{
+ delete (HwndTerminal*)terminal;
+}
+
+// Generate all of the C->C++ bridge functions.
+#define API_NAME(name) Terminal##name
+#define GENERATOR_0(name) \
+ __declspec(dllexport) HRESULT __stdcall API_NAME(name)(PTERM terminal) \
+ try \
+ { \
+ return ((HwndTerminal*)(terminal))->name(); \
this literally takes all the API definitions and creates dllexported functions that (1) cast to HwndTerminal* and (2) forward all arguments to the member function of the same name
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view wsv{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(wsv.data()), static_cast<uint32_t>(wsv.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Setup the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these rodered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
these functions are lamost entirely yanked from the old code
@check-spelling-bot Report
🔴 Please review
See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.
<details><summary>Unrecognized words (11)</summary>
CDispatcher
CKS
CSystem
INCONTACT
PSCROLLCB
PTERM
PWRITECB
PWSTR
rodered
workitems
wsv
</details>
<details><summary>These words are not needed and should be removed
</summary>ADDREF CLAUDE DDESHARE PCWCH PSTR pwstr yizz
</details><p></p>
<details><summary>To accept these unrecognized words as correct and remove the previously acknowledged and now absent words,
you could run the following commands</summary>
... in a clone of the git@github.com:microsoft/terminal.git repository
on the dev/duhowett/win7-wpf-termcontrol-squash branch ([ℹ️ how do I use this?](
https://docs.check-spelling.dev/Accepting-Suggestions)):
`` sh
curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/cfb6f7e75bbfc89c71eaa30366d0c166f1bd9c8c/apply.pl' |
perl - 'https://github.com/microsoft/terminal/actions/runs/38959242163/attempts/1' &&
git commit -m 'Update check-spelling metadata'
json</details>
<details><summary>Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary</summary>
This includes both **expected items** (2030) from .github/actions/spelling/expect/alphabet.txt .github/actions/spelling/expect/expect.txt .github/actions/spelling/expect/web.txt and **unrecognized words** (11)
Dictionary | Entries | Covers | Uniquely
-|-|-|-
[cspell:cpp/src/lang-keywords.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/lang-keywords.txt)|44|3|3|
[cspell:csharp/csharp.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/csharp/csharp.txt)|32|2|2|
[cspell:cpp/src/compiler-clang-attributes.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/compiler-clang-attributes.txt)|46|2|2|
[cspell:aws/aws.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/aws/aws.txt)|218|2|2|
[cspell:python/src/python/python.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/python/src/python/python.txt)|392|2|2|
Consider adding to the `extra_dictionaries` array (in the `.github/actions/spelling/config.json` file):
"cspell:cpp/src/lang-keywords.txt",
"cspell:csharp/csharp.txt",
"cspell:cpp/src/compiler-clang-attributes.txt",
"cspell:aws/aws.txt",
"cspell:python/src/python/python.txt",
To stop checking additional dictionaries, put (in the `.github/actions/spelling/config.json` file):
json"check_extra_dictionaries": []
</details>
#### Forbidden patterns 🙅 (1)
In order to address this, you could change the content to not match the forbidden patterns (comments before forbidden patterns may help explain why they're forbidden), add patterns for acceptable instances, or adjust the forbidden patterns themselves.
These forbidden patterns matched content:
##### Should be `set up` (`setup` is a noun / `set up` is a verb)
\b[Ss]etup(?= (?:an?|the|to)\b)
`
<details><summary>Errors ❌ (1)</summary>
See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.
❌ Errors | Count
-|-
❌ forbidden-pattern | 1
See ❌ Event descriptions for more information.
</details>
<!-- See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples%3A-advice --> <!-- markdownlint-disable MD033 MD041 -->
<details>
<summary>
:pencil2: Contributor please read this
</summary>
By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.
If the listed items are:
... misspelled, then please correct them instead of using the command.
... names, please add them to
.github/actions/spelling/allow/names.txt.
... APIs, you can add them to a file in .github/actions/spelling/allow/.
... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in .github/actions/spelling/patterns/.See the
README.md in each directory for more information.:microscope: You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. :wink:
<details><summary>If the flagged items are :exploding_head: false positives</summary>
If items relate to a ...
binary file (or some other file you wouldn't want to check at all).
Please add a file path to the
excludes.txt file matching the containing file. File paths are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your files.
^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude [README.md](
../tree/HEAD/README.md) (on whichever branch you're using).well-formed pattern. If you can write a [pattern](
https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
) that would match it,
try adding it to the
patterns.txt` file. Patterns are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your lines.
Note that patterns can't match multiline strings.
</details>
</details>
I recommend a...
git diff --color-moved=dimmed-zebra --color-moved-ws=ignore-all-space (git merge-base origin/dev/duhowett/win7-wpf-termcontrol-squash origin/main) origin/dev/duhowett/win7-wpf-termcontrol-squash
it'll show you what is copied (gray) and what has been rewritten (red, green)
I wonder if I should rename FlatC to HwndTerminal and _really_ make a mess of the diff.
@check-spelling-bot Report
🔴 Please review
See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.
Unrecognized words (1)
PWSTR
<details><summary>These words are not needed and should be removed
</summary>ADDREF CLAUDE DDESHARE PCWCH PSTR pwstr yizz
</details><p></p>
<details><summary>To accept these unrecognized words as correct and remove the previously acknowledged and now absent words,
you could run the following commands</summary>
... in a clone of the git@github.com:microsoft/terminal.git repository
on the dev/duhowett/win7-wpf-termcontrol-squash branch ([ℹ️ how do I use this?](
https://docs.check-spelling.dev/Accepting-Suggestions)):
`` sh
curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/cfb6f7e75bbfc89c71eaa30366d0c166f1bd9c8c/apply.pl' |
perl - 'https://github.com/microsoft/terminal/actions/runs/38962576123/attempts/1' &&
git commit -m 'Update check-spelling metadata'
json</details>
<details><summary>Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary</summary>
This includes both **expected items** (2030) from .github/actions/spelling/expect/alphabet.txt .github/actions/spelling/expect/expect.txt .github/actions/spelling/expect/web.txt and **unrecognized words** (1)
Dictionary | Entries | Covers | Uniquely
-|-|-|-
[cspell:cpp/src/lang-keywords.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/lang-keywords.txt)|44|3|3|
[cspell:csharp/csharp.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/csharp/csharp.txt)|32|2|2|
[cspell:cpp/src/compiler-clang-attributes.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/compiler-clang-attributes.txt)|46|2|2|
[cspell:aws/aws.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/aws/aws.txt)|218|2|2|
[cspell:python/src/python/python.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/python/src/python/python.txt)|392|2|2|
Consider adding to the `extra_dictionaries` array (in the `.github/actions/spelling/config.json` file):
"cspell:cpp/src/lang-keywords.txt",
"cspell:csharp/csharp.txt",
"cspell:cpp/src/compiler-clang-attributes.txt",
"cspell:aws/aws.txt",
"cspell:python/src/python/python.txt",
To stop checking additional dictionaries, put (in the `.github/actions/spelling/config.json` file):
json"check_extra_dictionaries": []
`
</details>
<!-- See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples%3A-advice --> <!-- markdownlint-disable MD033 MD041 -->
<details>
<summary>
:pencil2: Contributor please read this
</summary>
By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.
If the listed items are:
... misspelled, then please correct them instead of using the command.
... names, please add them to
.github/actions/spelling/allow/names.txt.
... APIs, you can add them to a file in .github/actions/spelling/allow/.
... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in .github/actions/spelling/patterns/.See the
README.md in each directory for more information.:microscope: You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. :wink:
<details><summary>If the flagged items are :exploding_head: false positives</summary>
If items relate to a ...
binary file (or some other file you wouldn't want to check at all).
Please add a file path to the
excludes.txt file matching the containing file. File paths are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your files.
^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude [README.md](
../tree/HEAD/README.md) (on whichever branch you're using).well-formed pattern. If you can write a [pattern](
https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
) that would match it,
try adding it to the
patterns.txt` file. Patterns are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your lines.
Note that patterns can't match multiline strings.
</details>
</details>
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
check-spelling / Unrecognized Spelling
[CKS](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
check-spelling / Unrecognized Spelling
[CKS](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
check-spelling / Unrecognized Spelling
[CKS](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
check-spelling / Unrecognized Spelling
[CKS](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
check-spelling / Unrecognized Spelling
[CKS](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
check-spelling / Unrecognized Spelling
[CSystem](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
check-spelling / Unrecognized Spelling
[CDispatcher](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
check-spelling / Unrecognized Spelling
[CSystem](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
check-spelling / Unrecognized Spelling
[CDispatcher](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
+ EventRegistrationToken*)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP remove_ShutdownStarting(
+ EventRegistrationToken)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP add_ShutdownCompleted(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_IInspectable*,
check-spelling / Unrecognized Spelling
[CSystem](#security-tab) is not a recognized word
@@ -0,0 +1,859 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#include "pch.h"
+
+#include "FlatC.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
+
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
+
+#include "HwndTerminalAutomationPeer.hpp"
+
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
+
+#pragma warning(disable : 4100)
+
+using namespace winrt::Microsoft::Terminal::Control;
+using namespace winrt::Microsoft::Terminal::Core;
+using CKS = ::Microsoft::Terminal::Core::ControlKeyStates;
+
+static CKS getControlKeyState() noexcept
+{
+ struct KeyModifier
+ {
+ int vkey;
+ CKS flags;
+ };
+
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, CKS::RightAltPressed },
+ { VK_LMENU, CKS::LeftAltPressed },
+ { VK_RCONTROL, CKS::RightCtrlPressed },
+ { VK_LCONTROL, CKS::LeftCtrlPressed },
+ { VK_SHIFT, CKS::ShiftPressed },
+ } };
+
+ CKS flags;
+
+ for (const auto& mod : modifiers)
+ {
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
+
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
+
+ return flags;
+}
+
+static MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
+{
+ MouseButtonState state{};
+ WI_UpdateFlag(state, MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
+}
+
+static Point PointFromLParam(LPARAM lParam)
+{
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
+}
+
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
+{
+ void WriteInput(winrt::array_view<const char16_t> d)
+ {
+ if (_pfnWriteCallback)
+ {
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
+ }
+ }
+
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
+
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
+
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
+
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
+ {
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
+ }
+};
+
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, IControlSettings, ICoreSettings, IControlAppearance, ICoreAppearance, ICoreScheme>
+{
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
+
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
+
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
+
+ til::color DynamicDefaultForeground() const
+ {
+ return _theme.DefaultForeground;
+ }
+ til::color DynamicDefaultBackground() const
+ {
+ return _theme.DefaultBackground;
+ }
+ til::color DynamicSelectionBackground() const
+ {
+ return til::color{ _theme.DefaultSelectionBackground };
+ }
+ winrt::hstring DynamicFontFace() const
+ {
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
+ }
+
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
+
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
+
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
+ }
+
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
+
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
+{
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
+ {
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
+ {
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
+ }
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
+ {
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
+ }
+ catch (...)
+ {
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
+ }
+
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
+
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
+
+ return RegisterClassW(&wc) != 0;
+ }
+
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
+
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
+
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
+
+ wil::unique_hwnd _hwnd;
+
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
+
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
+
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
+
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ }
+
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
+ {
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
+ }
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
+ {
+ _scrollCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
+
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
+
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
+
+ return S_OK;
+ }
+
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
+ {
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
+ }
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
+ return S_OK;
+ }
+
+ HRESULT DpiChanged(int newDpi)
+ {
+ _core->ScaleChanged((float)newDpi / 96.0f);
+ return S_OK;
+ }
+
+ HRESULT UserScroll(int viewTop)
+ {
+ _interactivity->UpdateScrollbar(static_cast<float>(viewTop) /* TODO(DH) */);
+ return S_OK;
+ }
+
+ HRESULT GetSelection(const wchar_t** out)
+ {
+ auto strings = _core->SelectedText(true);
+ auto concatenated = std::accumulate(std::begin(strings), std::end(strings), std::wstring{}, [](auto&& l, auto&& r) {
+ return l + r;
+ });
+ auto returnText = wil::make_cotaskmem_string_nothrow(concatenated.c_str());
+ *out = returnText.release();
+ return S_OK;
+ }
+
+ HRESULT IsSelectionActive(bool* out)
+ {
+ *out = _core->HasSelection();
+ return S_OK;
+ }
+
+ HRESULT SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
+ {
+ _settingsBridge->SetTheme(theme, fontFamily, fontSize, newDpi);
+ _core->UpdateSettings(*_settingsBridge, nullptr);
+ _interactivity->UpdateSettings();
+ _core->ScaleChanged((static_cast<float>(newDpi) / USER_DEFAULT_SCREEN_DPI));
+ _core->ApplyAppearance(_focused);
+ return S_OK;
+ }
+
+ HRESULT RegisterWriteCallback(PWRITECB callback)
+ {
+ _connection->_pfnWriteCallback = callback;
+ return S_OK;
+ }
+
+ HRESULT SendKeyEvent(WORD vkey, WORD scanCode, WORD flags, bool keyDown)
+ {
+ if (_tsfHandle)
+ {
+ // If a composition just ended, its text is still queued up inside TSF. Hand it to
+ // the connection now, so that a key the IME passed on to us can't reach the
+ // connection before the text it finalized - neither by being forwarded to the PTY,
+ // nor by triggering an action bound to it. GH#20244
+ _tsfHandle.FlushPendingComposition();
+
+ if (_tsfHandle.HasActiveComposition())
+ {
+ // While TSF has an active composition, key events must not be forwarded
+ // to the PTY directly. The IME re-injects navigation/confirmation keys
+ // after composition ends, at which point HasActiveComposition() == false
+ // and they are forwarded normally. This mirrors conhost v1 behavior in
+ // src/interactivity/win32/windowio.cpp.
+ return S_OK;
+ }
+ }
+
+ _core->TrySendKeyEvent(vkey, scanCode, getControlKeyState(), keyDown);
+
+ if (vkey && keyDown && _uiaProvider)
+ {
+ _uiaProvider->RecordKeyEvent(vkey);
+ }
+
+ return S_OK;
+ }
+
+ HRESULT SendCharEvent(wchar_t ch, WORD flags, WORD scanCode)
+ {
+ _core->SendCharEvent(ch, scanCode, getControlKeyState());
+ return S_OK;
+ }
+
+ void Initialize()
+ {
+ RECT windowRect;
+ GetWindowRect(_hwnd.get(), &windowRect);
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ // BODGY: the +/-1 is because ControlCore will ignore an Initialize with zero size (oops)
+ // because in the old days, TermControl would accidentally try to resize the Swap Chain to 0x0 (oops)
+ // and therefore resize the connection to 0x0 (oops)
+ _core->InitializeWithHwnd(
+ gsl::narrow_cast<float>(windowRect.right - windowRect.left + 1),
+ gsl::narrow_cast<float>(windowRect.bottom - windowRect.top + 1),
+ (static_cast<float>(dpi) / USER_DEFAULT_SCREEN_DPI),
+ reinterpret_cast<uint64_t>(_hwnd.get()));
+ _interactivity->Initialize();
+ _core->ApplyAppearance(_focused);
+
+ _core->EnablePainting();
+
+ _initialized = true;
+ }
+
+#pragma region HwndTerminal Accessibility
+ til::size GetFontSize() const noexcept
+ {
+ if (_core)
+ {
+ return { til::math::rounding, _core->FontSize() };
+ }
+ return {};
+ }
+
+ til::rect GetBounds() const noexcept
+ {
+ til::rect windowRect;
+ GetWindowRect(_hwnd.get(), windowRect.as_win32_rect());
+ return windowRect;
+ }
+
+ til::rect GetPadding() const noexcept
+ {
+ return {};
+ }
+
+ void ChangeViewport(const til::inclusive_rect& NewWindow)
+ {
+ if (!_interactivity)
+ {
+ return;
+ }
+ _interactivity->UpdateScrollbar(static_cast<float>(NewWindow.top));
+ }
+
+ HRESULT GetHostUiaProvider(IRawElementProviderSimple** provider) noexcept
+ {
+ return UiaHostProviderFromHwnd(_hwnd.get(), provider);
+ }
+#pragma endregion
+
+private:
+ struct TsfDataProvider : public Microsoft::Console::TSF::IDataProvider
+ {
+ TsfDataProvider(HwndTerminal* t) :
+ _terminal(t) {}
+ virtual ~TsfDataProvider() = default;
+ STDMETHODIMP QueryInterface(REFIID, void**) noexcept override;
+ ULONG STDMETHODCALLTYPE AddRef() noexcept override;
+ ULONG STDMETHODCALLTYPE Release() noexcept override;
+ HWND GetHwnd() override;
+ RECT GetViewport() override;
+ RECT GetCursorPosition() override;
+ void HandleOutput(std::wstring_view text) override;
+ Microsoft::Console::Render::Renderer* GetRenderer() override;
+ HwndTerminal* _terminal;
+ };
+ winrt::com_ptr<CallbackBasedConnection> _connection;
+ winrt::com_ptr<BasicTerminalSettings> _settingsBridge;
+ winrt::com_ptr<implementation::ControlInteractivity> _interactivity{ nullptr };
+ winrt::com_ptr<implementation::ControlCore> _core{ nullptr };
+ bool _initialized{ false };
+ bool _focused{ false };
+ winrt::com_ptr<HwndTerminalAutomationPeer> _uiaProvider;
+ PSCROLLCB _scrollCallback{};
+
+ // Keep these ordered as-is for proper destruction.
+ TsfDataProvider _tsfDataProvider{ this };
+ Microsoft::Console::TSF::Handle _tsfHandle;
+
+ void _scrollPositionChanged(const winrt::Windows::Foundation::IInspectable& i, const ScrollPositionChangedArgs& update)
+ {
+ if (_scrollCallback)
+ {
+ _scrollCallback(update.ViewTop(), update.ViewHeight(), update.BufferSize());
+ }
+ }
+
+ IRawElementProviderSimple* _getUiaProvider() noexcept
+ {
+ // If TermControlUiaProvider throws during construction,
+ // we don't want to try constructing an instance again and again.
+ if (!_uiaProvider)
+ {
+ try
+ {
+ if (!_core)
+ {
+ return nullptr;
+ }
+ LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(_uiaProvider.put(), _core->GetRenderData(), this));
+ _interactivity->SetUiaEventDispatcher(_uiaProvider.get());
+ }
+ catch (...)
+ {
+ LOG_HR(wil::ResultFromCaughtException());
+ _uiaProvider = nullptr;
+ }
+ }
+
+ return _uiaProvider.get();
+ }
+};
+
+STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
+{
+ return E_NOTIMPL;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
+{
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+{
+ return 1;
+}
+
+HWND HwndTerminal::TsfDataProvider::GetHwnd()
+{
+ return _terminal->_hwnd.get();
+}
+
+RECT HwndTerminal::TsfDataProvider::GetViewport()
+{
+ const auto hwnd = GetHwnd();
+
+ RECT rc;
+ GetClientRect(hwnd, &rc);
+
+ // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
+ // > The left and top members are zero. The right and bottom members contain the width and height of the window.
+ // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
+ ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
+ rc.right += rc.left;
+ rc.bottom += rc.top;
+
+ return rc;
+}
+
+RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
+{
+ // Convert from columns/rows to pixels.
+ til::point cursorPos;
+ til::size fontSize;
+ {
+ auto rawCursorPos = _terminal->_core->CursorPosition();
+ cursorPos = til::point{
+ static_cast<til::CoordType>(rawCursorPos.X),
+ static_cast<til::CoordType>(rawCursorPos.Y),
+ };
+ fontSize = { til::math::rounding, _terminal->_core->FontSize() }; // measured in pixels, not DIP
+ }
+ POINT ptSuggestion = {
+ .x = cursorPos.x * fontSize.width,
+ .y = cursorPos.y * fontSize.height,
+ };
+
+ ClientToScreen(GetHwnd(), &ptSuggestion);
+
+ // Final measurement should be in pixels
+ return {
+ .left = ptSuggestion.x,
+ .top = ptSuggestion.y,
+ .right = ptSuggestion.x + fontSize.width,
+ .bottom = ptSuggestion.y + fontSize.height,
+ };
+}
+
+void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
+{
+ _terminal->_core->SendInput(text);
+}
+
+Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+{
+ return _terminal->_core->GetRenderer();
+}
+
+#pragma region Implementation of IDispatcherQueue
+struct CalloutBasedDispatcherQueue : public winrt::implements<CalloutBasedDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue, ::ABI::Windows::System::IDispatcherQueue2>
+{
+ CalloutBasedDispatcherQueue(TerminalDispatcherCallouts callouts) : _callouts{ std::move(callouts) } {}
+
+ IFACEMETHODIMP CreateTimer(::ABI::Windows::System::IDispatcherQueueTimer** result)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP TryEnqueue(::ABI::Windows::System::IDispatcherQueueHandler* callback, boolean* result)
+ {
+ return TryEnqueueWithPriority(::ABI::Windows::System::DispatcherQueuePriority::DispatcherQueuePriority_Normal, callback, result);
+ }
+
+ IFACEMETHODIMP TryEnqueueWithPriority(
+ ::ABI::Windows::System::DispatcherQueuePriority priority,
+ ::ABI::Windows::System::IDispatcherQueueHandler* callback,
+ boolean* result)
+ {
+ RETURN_HR_IF(E_INVALIDARG, !result || !callback);
+ callback->AddRef(); // Retain on transition to managed
+ *result = _callouts.pDispatcherTryEnqueueWork(_callouts.context, static_cast<int>(priority), callback);
+ return S_OK;
+ }
+
+ IFACEMETHODIMP add_ShutdownStarting(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_Windows__CSystem__CDispatcherQueueShutdownStartingEventArgs*,
+ EventRegistrationToken*)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP remove_ShutdownStarting(
+ EventRegistrationToken)
+ {
+ return E_FAIL;
+ }
+
+ IFACEMETHODIMP add_ShutdownCompleted(
+ __FITypedEventHandler_2_Windows__CSystem__CDispatcherQueue_IInspectable*,
check-spelling / Unrecognized Spelling
[CDispatcher](#security-tab) is not a recognized word
@check-spelling-bot Report
🔴 Please review
See the 📂 files view, the 📜action log, 👼 SARIF report, or 📝 job summary for details.
Unrecognized words (3)
CDispatcher
CKS
CSystem
<details><summary>These words are not needed and should be removed
</summary>ADDREF CLAUDE DDESHARE PCWCH PSTR yizz
</details><p></p>
<details><summary>To accept these unrecognized words as correct and remove the previously acknowledged and now absent words,
you could run the following commands</summary>
... in a clone of the git@github.com:microsoft/terminal.git repository
on the dev/duhowett/win7-wpf-termcontrol-squash branch ([ℹ️ how do I use this?](
https://docs.check-spelling.dev/Accepting-Suggestions)):
`` sh
curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/cfb6f7e75bbfc89c71eaa30366d0c166f1bd9c8c/apply.pl' |
perl - 'https://github.com/microsoft/terminal/actions/runs/39290155277/attempts/1' &&
git commit -m 'Update check-spelling metadata'
json</details>
<details><summary>Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary</summary>
This includes both **expected items** (2030) from .github/actions/spelling/expect/alphabet.txt .github/actions/spelling/expect/expect.txt .github/actions/spelling/expect/web.txt and **unrecognized words** (3)
Dictionary | Entries | Covers | Uniquely
-|-|-|-
[cspell:cpp/src/lang-keywords.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/lang-keywords.txt)|44|3|3|
[cspell:csharp/csharp.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/csharp/csharp.txt)|32|2|2|
[cspell:cpp/src/compiler-clang-attributes.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/cpp/src/compiler-clang-attributes.txt)|46|2|2|
[cspell:aws/aws.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/aws/aws.txt)|218|2|2|
[cspell:python/src/python/python.txt](https://raw.githubusercontent.com/check-spelling/cspell-dicts/v20230509/dictionaries/python/src/python/python.txt)|392|2|2|
Consider adding to the `extra_dictionaries` array (in the `.github/actions/spelling/config.json` file):
"cspell:cpp/src/lang-keywords.txt",
"cspell:csharp/csharp.txt",
"cspell:cpp/src/compiler-clang-attributes.txt",
"cspell:aws/aws.txt",
"cspell:python/src/python/python.txt",
To stop checking additional dictionaries, put (in the `.github/actions/spelling/config.json` file):
json"check_extra_dictionaries": []
`
</details>
<!-- See https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples%3A-advice --> <!-- markdownlint-disable MD033 MD041 -->
<details>
<summary>
:pencil2: Contributor please read this
</summary>
By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.
If the listed items are:
... misspelled, then please correct them instead of using the command.
... names, please add them to
.github/actions/spelling/allow/names.txt.
... APIs, you can add them to a file in .github/actions/spelling/allow/.
... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in .github/actions/spelling/patterns/.See the
README.md in each directory for more information.:microscope: You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. :wink:
<details><summary>If the flagged items are :exploding_head: false positives</summary>
If items relate to a ...
binary file (or some other file you wouldn't want to check at all).
Please add a file path to the
excludes.txt file matching the containing file. File paths are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your files.
^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude [README.md](
../tree/HEAD/README.md) (on whichever branch you're using).well-formed pattern. If you can write a [pattern](
https://github.com/check-spelling/check-spelling/wiki/Configuration-Examples:-patterns
) that would match it,
try adding it to the
patterns.txt` file. Patterns are Perl 5 Regular Expressions - you can [test](
https://www.regexplanet.com/advanced/perl/) yours before committing to verify it will match your lines.
Note that patterns can't match multiline strings.
</details>
</details>
/cc @javierdlg it is finally here
@@ -2712,7 +2712,8 @@ namespace winrt::Microsoft::Terminal::Control::implementation
// UWP XAML scrollbars aren't guaranteed to be the same size as the
// ComCtl scrollbars, but it's certainly close enough.
- const auto scrollbarSize = GetSystemMetricsForDpi(SM_CXVSCROLL, dpi);
+ auto scrollbarSize = GetSystemMetrics(SM_CXVSCROLL);
+ scrollbarSize = gsl::narrow_cast<decltype(scrollbarSize)>(scrollbarSize * (dpi / 96));
Eh?
And also: scrollbarSize * (dpi / 96) = integer scale only.
@@ -7,17 +7,18 @@ EXPORTS
AvoidBuggyTSFConsoleFlags
CreateTerminal
DestroyTerminal
+ TerminalSendOutput
+ TerminalRegisterScrollCallback
+ TerminalTriggerResize
+ TerminalTriggerResizeWithDimension
SCHOCKSCHWERENOT! AN UNSORTED LIST!
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#pragma once
+
+// Keep in sync with TerminalTheme.cs
+typedef struct _TerminalTheme
+{
+ COLORREF DefaultBackground;
+ COLORREF DefaultForeground;
+ COLORREF DefaultSelectionBackground;
+ uint32_t CursorStyle; // This will be converted to DispatchTypes::CursorStyle (size_t), but C# cannot marshal an enum type and have it fit in a size_t.
+ COLORREF ColorTable[16];
+} TerminalTheme;
+
+typedef void* PTERM;
+typedef void(__stdcall* PSCROLLCB)(int, int, int);
+typedef void(__stdcall* PWRITECB)(const wchar_t*);
Weird names with no param names?
BTW C# does not support strings with lengths huh? (For PWRITECB.)
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#pragma once
+
+// Keep in sync with TerminalTheme.cs
+typedef struct _TerminalTheme
+{
+ COLORREF DefaultBackground;
+ COLORREF DefaultForeground;
+ COLORREF DefaultSelectionBackground;
+ uint32_t CursorStyle; // This will be converted to DispatchTypes::CursorStyle (size_t), but C# cannot marshal an enum type and have it fit in a size_t.
+ COLORREF ColorTable[16];
+} TerminalTheme;
+
+typedef void* PTERM;
+typedef void(__stdcall* PSCROLLCB)(int, int, int);
+typedef void(__stdcall* PWRITECB)(const wchar_t*);
+
+typedef struct _TerminalDispatcherCallouts
+{
+ bool(__stdcall* pDispatcherTryEnqueueWork)(void*, int, void*);
+ bool(__stdcall* pDispatcherHasThreadAccess)(void*);
Why p prefix? If anything, it should be fn or pfn, right?
@@ -0,0 +1,71 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+
+#pragma once
+
+// Keep in sync with TerminalTheme.cs
+typedef struct _TerminalTheme
+{
+ COLORREF DefaultBackground;
+ COLORREF DefaultForeground;
+ COLORREF DefaultSelectionBackground;
+ uint32_t CursorStyle; // This will be converted to DispatchTypes::CursorStyle (size_t), but C# cannot marshal an enum type and have it fit in a size_t.
+ COLORREF ColorTable[16];
+} TerminalTheme;
+
+typedef void* PTERM;
+typedef void(__stdcall* PSCROLLCB)(int, int, int);
+typedef void(__stdcall* PWRITECB)(const wchar_t*);
+
+typedef struct _TerminalDispatcherCallouts
+{
+ bool(__stdcall* pDispatcherTryEnqueueWork)(void*, int, void*);
+ bool(__stdcall* pDispatcherHasThreadAccess)(void*);
+ // Context which will be passed back to the above function pointers.
+ void* context;
+} TerminalDispatcherCallouts;
+
+#define TERMINAL_API_TABLE(XX) \
+ XX(SendOutput, LPCWSTR, data) \
I cannot discern an order of these functions, but I think it could be sorted.
@@ -19,6 +19,22 @@ internal static class NativeMethods
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
public delegate void WriteCallback([In, MarshalAs(UnmanagedType.LPWStr)] string data);
+ public struct DispatcherCallouts
+ {
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ public DispatcherTryEnqueue tryEnqueue;
+
+ [MarshalAs(UnmanagedType.FunctionPtr)]
+ public DispatcherHasThreadAccess hasThreadAccess;
+ public IntPtr context;
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ public delegate bool DispatcherTryEnqueue(IntPtr context, int priority, IntPtr obj);
+
+ [UnmanagedFunctionPointer(CallingConvention.StdCall)]
+ public delegate bool DispatcherHasThreadAccess(IntPtr context);
Do these two not get marshalled?
@@ -175,9 +191,12 @@ public enum SetWindowPosFlags : uint
public static extern void AvoidBuggyTSFConsoleFlags();
[DllImport("Microsoft.Terminal.Control.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, PreserveSig = false)]
- public static extern void CreateTerminal(IntPtr parent, out IntPtr hwnd, out IntPtr terminal);
+ public static extern void CreateTerminal(IntPtr parent, [MarshalAs(UnmanagedType.Struct)] DispatcherCallouts dispatcherCallouts, out IntPtr hwnd, out IntPtr terminal);
+
+ [DllImport("Microsoft.Terminal.Control.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
+ public static extern void DestroyTerminal(IntPtr terminal);
- [DllImport("Microsoft.Terminal.Control.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, PreserveSig = true)]
+ [DllImport("Microsoft.Terminal.Control.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall, PreserveSig = false)]
But the functions still return HRESULT aren't they?
@@ -26,6 +27,40 @@ public class TerminalContainer : HwndHost
private NativeMethods.ScrollCallback scrollCallback;
private NativeMethods.WriteCallback writeCallback;
+ private DispatcherWrapper dispatcherWrapper;
+
+ // These callbacks are provided to CreateTerminal so that the terminal
+ // core can schedule work items on the same dispatcher queue as WPF.
+ // They must be pinned with GC handles so that they do not get garbage collected.
+ private NativeMethods.DispatcherCallouts dispatcherCallouts;
+ private GCHandle dispatcherTryEnqueueCalloutGCHandle;
+ private GCHandle dispatcherHasThreadAccessCalloutGCHandle;
+
+ private class DispatcherWrapper
+ {
+ private readonly Dispatcher dispatcher;
+
+ public DispatcherWrapper(Dispatcher dispatcher)
+ {
+ this.dispatcher = dispatcher;
+ }
+
+#pragma warning disable IDE0060
+ public bool TryEnqueue(IntPtr context, int priority, IntPtr obj)
+ {
I guess it would be possible to make them static functions by unwrapping the context into this if C# permits this (still a DispatcherWrapper tho to prevent pinning the bigger this in memory)?
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
AH sort order.
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
-using namespace ::Microsoft::Console::VirtualTerminal;
-using namespace ::Microsoft::Terminal::Core;
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
-static LPCWSTR term_window_class = L"HwndTerminalClass";
+#include "HwndTerminalAutomationPeer.hpp"
-STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
-{
- return E_NOTIMPL;
-}
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
-{
- return 1;
-}
+#pragma warning(disable : 4100)
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+namespace MT
{
- return 1;
+ namespace Control = winrt::Microsoft::Terminal::Control;
+ namespace Core = winrt::Microsoft::Terminal::Core;
}
-HWND HwndTerminal::TsfDataProvider::GetHwnd()
+static auto getControlKeyState() noexcept
{
- return _terminal->GetHwnd();
-}
-
-RECT HwndTerminal::TsfDataProvider::GetViewport()
-{
- const auto hwnd = GetHwnd();
-
- RECT rc;
- GetClientRect(hwnd, &rc);
+ using ControlKeyStates = ::Microsoft::Terminal::Core::ControlKeyStates;
+ struct KeyModifier
+ {
+ int vkey;
+ ControlKeyStates flags;
+ };
- // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
- // > The left and top members are zero. The right and bottom members contain the width and height of the window.
- // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
- ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
- rc.right += rc.left;
- rc.bottom += rc.top;
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, ControlKeyStates::RightAltPressed },
+ { VK_LMENU, ControlKeyStates::LeftAltPressed },
+ { VK_RCONTROL, ControlKeyStates::RightCtrlPressed },
+ { VK_LCONTROL, ControlKeyStates::LeftCtrlPressed },
+ { VK_SHIFT, ControlKeyStates::ShiftPressed },
+ } };
- return rc;
-}
+ ControlKeyStates flags;
-RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
-{
- // Convert from columns/rows to pixels.
- til::point cursorPos;
- til::size fontSize;
+ for (const auto& mod : modifiers)
{
- const auto lock = _terminal->_terminal->LockForReading();
- cursorPos = _terminal->_terminal->GetTextBuffer().GetCursor().GetPosition(); // measured in terminal cells
- fontSize = _terminal->_actualFont.GetSize(); // measured in pixels, not DIP
- }
- POINT ptSuggestion = {
- .x = cursorPos.x * fontSize.width,
- .y = cursorPos.y * fontSize.height,
- };
-
- ClientToScreen(GetHwnd(), &ptSuggestion);
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
- // Final measurement should be in pixels
- return {
- .left = ptSuggestion.x,
- .top = ptSuggestion.y,
- .right = ptSuggestion.x + fontSize.width,
- .bottom = ptSuggestion.y + fontSize.height,
- };
-}
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
-void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
-{
- _terminal->_WriteTextToConnection(text);
+ return flags;
}
-Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+static MT::Control::MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
{
- return _terminal->_renderer.get();
+ MT::Control::MouseButtonState state{};
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
}
-// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
-// "If the high-order bit is 1, the key is down; otherwise, it is up."
-static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
-
-static constexpr bool _IsMouseMessage(UINT uMsg)
+static MT::Core::Point PointFromLParam(LPARAM lParam)
{
- return uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK ||
- uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK ||
- uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK ||
- uMsg == WM_MOUSEMOVE || uMsg == WM_MOUSEWHEEL || uMsg == WM_MOUSEHWHEEL;
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
}
-LRESULT CALLBACK HwndTerminal::HwndTerminalWndProc(
- HWND hwnd,
- UINT uMsg,
- WPARAM wParam,
- LPARAM lParam) noexcept
-try
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
{
- if (WM_NCCREATE == uMsg)
+ void WriteInput(winrt::array_view<const char16_t> d)
{
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
- that->_hwnd = wil::unique_hwnd(hwnd);
-
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- return DefWindowProc(hwnd, WM_NCCREATE, wParam, lParam);
- }
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- const auto publicTerminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
- if (publicTerminal)
- {
- if (_IsMouseMessage(uMsg))
+ if (_pfnWriteCallback)
{
- if (publicTerminal->_CanSendVTMouseInput() && publicTerminal->_SendMouseEvent(uMsg, wParam, lParam))
- {
- // GH#6401: Capturing the mouse ensures that we get drag/release events
- // even if the user moves outside the window.
- // _SendMouseEvent returns false if the terminal's not in VT mode, so we'll
- // fall through to release the capture.
- switch (uMsg)
- {
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- SetCapture(hwnd);
- break;
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- default:
- break;
- }
-
- // Suppress all mouse events that made it into the terminal.
- return 0;
- }
- }
-
- switch (uMsg)
- {
- case WM_GETOBJECT:
- if (lParam == UiaRootObjectId)
- {
- return UiaReturnRawElementProvider(hwnd, wParam, lParam, publicTerminal->_GetUiaProvider());
- }
- break;
- case WM_LBUTTONDOWN:
- LOG_IF_FAILED(publicTerminal->_StartSelection(lParam));
- return 0;
- case WM_LBUTTONUP:
- publicTerminal->_singleClickTouchdownPos = std::nullopt;
- [[fallthrough]];
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- case WM_MOUSEMOVE:
- if (WI_IsFlagSet(wParam, MK_LBUTTON))
- {
- LOG_IF_FAILED(publicTerminal->_MoveSelection(lParam));
- return 0;
- }
- break;
- case WM_RBUTTONDOWN:
- try
- {
- if (publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- if (publicTerminal->_terminal->IsSelectionActive())
- {
- const auto bufferData = publicTerminal->_terminal->RetrieveSelectedTextFromBuffer(false, false, true, true);
- LOG_IF_FAILED(publicTerminal->_CopyTextToSystemClipboard(bufferData.plainText, bufferData.html, bufferData.rtf));
- publicTerminal->_ClearSelection();
- return 0;
- }
- }
- publicTerminal->_PasteTextFromClipboard();
- return 0;
- }
- CATCH_LOG();
- case WM_DESTROY:
- // Release Terminal's hwnd so Teardown doesn't try to destroy it again
- publicTerminal->_hwnd.release();
- publicTerminal->Teardown();
- return 0;
- default:
- break;
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
The input is not necessarily null terminated (it may be a string-view)! That's the reason I changed it to a winrt::array_view. This may work: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshal.ptrtostringuni?view=net-10.0#system-runtime-interopservices-marshal-ptrtostringuni(system-intptr-system-int32)
There's the newer: https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.marshalling.utf16stringmarshaller?view=net-10.0
...but apparently non-null-terminated strings don't exist.
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
-using namespace ::Microsoft::Console::VirtualTerminal;
-using namespace ::Microsoft::Terminal::Core;
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
-static LPCWSTR term_window_class = L"HwndTerminalClass";
+#include "HwndTerminalAutomationPeer.hpp"
-STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
-{
- return E_NOTIMPL;
-}
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
-{
- return 1;
-}
+#pragma warning(disable : 4100)
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+namespace MT
{
- return 1;
+ namespace Control = winrt::Microsoft::Terminal::Control;
+ namespace Core = winrt::Microsoft::Terminal::Core;
}
-HWND HwndTerminal::TsfDataProvider::GetHwnd()
+static auto getControlKeyState() noexcept
{
- return _terminal->GetHwnd();
-}
-
-RECT HwndTerminal::TsfDataProvider::GetViewport()
-{
- const auto hwnd = GetHwnd();
-
- RECT rc;
- GetClientRect(hwnd, &rc);
+ using ControlKeyStates = ::Microsoft::Terminal::Core::ControlKeyStates;
+ struct KeyModifier
+ {
+ int vkey;
+ ControlKeyStates flags;
+ };
- // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
- // > The left and top members are zero. The right and bottom members contain the width and height of the window.
- // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
- ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
- rc.right += rc.left;
- rc.bottom += rc.top;
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, ControlKeyStates::RightAltPressed },
+ { VK_LMENU, ControlKeyStates::LeftAltPressed },
+ { VK_RCONTROL, ControlKeyStates::RightCtrlPressed },
+ { VK_LCONTROL, ControlKeyStates::LeftCtrlPressed },
+ { VK_SHIFT, ControlKeyStates::ShiftPressed },
+ } };
- return rc;
-}
+ ControlKeyStates flags;
-RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
-{
- // Convert from columns/rows to pixels.
- til::point cursorPos;
- til::size fontSize;
+ for (const auto& mod : modifiers)
{
- const auto lock = _terminal->_terminal->LockForReading();
- cursorPos = _terminal->_terminal->GetTextBuffer().GetCursor().GetPosition(); // measured in terminal cells
- fontSize = _terminal->_actualFont.GetSize(); // measured in pixels, not DIP
- }
- POINT ptSuggestion = {
- .x = cursorPos.x * fontSize.width,
- .y = cursorPos.y * fontSize.height,
- };
-
- ClientToScreen(GetHwnd(), &ptSuggestion);
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
- // Final measurement should be in pixels
- return {
- .left = ptSuggestion.x,
- .top = ptSuggestion.y,
- .right = ptSuggestion.x + fontSize.width,
- .bottom = ptSuggestion.y + fontSize.height,
- };
-}
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
-void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
-{
- _terminal->_WriteTextToConnection(text);
+ return flags;
}
-Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+static MT::Control::MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
{
- return _terminal->_renderer.get();
+ MT::Control::MouseButtonState state{};
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
}
-// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
-// "If the high-order bit is 1, the key is down; otherwise, it is up."
-static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
-
-static constexpr bool _IsMouseMessage(UINT uMsg)
+static MT::Core::Point PointFromLParam(LPARAM lParam)
{
- return uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK ||
- uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK ||
- uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK ||
- uMsg == WM_MOUSEMOVE || uMsg == WM_MOUSEWHEEL || uMsg == WM_MOUSEHWHEEL;
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
}
-LRESULT CALLBACK HwndTerminal::HwndTerminalWndProc(
- HWND hwnd,
- UINT uMsg,
- WPARAM wParam,
- LPARAM lParam) noexcept
-try
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
{
- if (WM_NCCREATE == uMsg)
+ void WriteInput(winrt::array_view<const char16_t> d)
{
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
- that->_hwnd = wil::unique_hwnd(hwnd);
-
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- return DefWindowProc(hwnd, WM_NCCREATE, wParam, lParam);
- }
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- const auto publicTerminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
- if (publicTerminal)
- {
- if (_IsMouseMessage(uMsg))
+ if (_pfnWriteCallback)
{
- if (publicTerminal->_CanSendVTMouseInput() && publicTerminal->_SendMouseEvent(uMsg, wParam, lParam))
- {
- // GH#6401: Capturing the mouse ensures that we get drag/release events
- // even if the user moves outside the window.
- // _SendMouseEvent returns false if the terminal's not in VT mode, so we'll
- // fall through to release the capture.
- switch (uMsg)
- {
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- SetCapture(hwnd);
- break;
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- default:
- break;
- }
-
- // Suppress all mouse events that made it into the terminal.
- return 0;
- }
- }
-
- switch (uMsg)
- {
- case WM_GETOBJECT:
- if (lParam == UiaRootObjectId)
- {
- return UiaReturnRawElementProvider(hwnd, wParam, lParam, publicTerminal->_GetUiaProvider());
- }
- break;
- case WM_LBUTTONDOWN:
- LOG_IF_FAILED(publicTerminal->_StartSelection(lParam));
- return 0;
- case WM_LBUTTONUP:
- publicTerminal->_singleClickTouchdownPos = std::nullopt;
- [[fallthrough]];
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- case WM_MOUSEMOVE:
- if (WI_IsFlagSet(wParam, MK_LBUTTON))
- {
- LOG_IF_FAILED(publicTerminal->_MoveSelection(lParam));
- return 0;
- }
- break;
- case WM_RBUTTONDOWN:
- try
- {
- if (publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- if (publicTerminal->_terminal->IsSelectionActive())
- {
- const auto bufferData = publicTerminal->_terminal->RetrieveSelectedTextFromBuffer(false, false, true, true);
- LOG_IF_FAILED(publicTerminal->_CopyTextToSystemClipboard(bufferData.plainText, bufferData.html, bufferData.rtf));
- publicTerminal->_ClearSelection();
- return 0;
- }
- }
- publicTerminal->_PasteTextFromClipboard();
- return 0;
- }
- CATCH_LOG();
- case WM_DESTROY:
- // Release Terminal's hwnd so Teardown doesn't try to destroy it again
- publicTerminal->_hwnd.release();
- publicTerminal->Teardown();
- return 0;
- default:
- break;
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
}
}
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-catch (...)
-{
- LOG_CAUGHT_EXCEPTION();
- return 0;
-}
-static bool RegisterTermClass(HINSTANCE hInstance) noexcept
-{
- WNDCLASSW wc;
- if (GetClassInfoW(hInstance, term_window_class, &wc))
- {
- return true;
- }
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
- wc.style = 0;
- wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = hInstance;
- wc.hIcon = nullptr;
- wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
- wc.hbrBackground = nullptr;
- wc.lpszMenuName = nullptr;
- wc.lpszClassName = term_window_class;
-
- return RegisterClassW(&wc) != 0;
-}
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
-HwndTerminal::HwndTerminal(HWND parentHwnd) noexcept :
- _desiredFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, 14, CP_UTF8 },
- _actualFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, { 0, 14 }, CP_UTF8, false },
- _uiaProvider{ nullptr },
- _currentDpi{ USER_DEFAULT_SCREEN_DPI },
- _pfnWriteCallback{ nullptr },
- _multiClickTime{ 500 } // this will be overwritten by the windows system double-click time
-{
- auto hInstance = wil::GetModuleInstanceHandle();
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
- if (RegisterTermClass(hInstance))
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
{
- // The WS_EX_NOREDIRECTIONBITMAP flag is used to disable the GDI redirection surface
- // for reduced memory usage, because the window is fully rendered in DX.
- CreateWindowExW(
- WS_EX_NOREDIRECTIONBITMAP,
- term_window_class,
- nullptr,
- WS_CHILD |
- WS_CLIPCHILDREN |
- WS_CLIPSIBLINGS |
- WS_VISIBLE,
- 0,
- 0,
- 0,
- 0,
- parentHwnd,
- nullptr,
- hInstance,
- this);
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
}
-}
-
-HwndTerminal::~HwndTerminal()
-{
- Teardown();
-}
+};
-HRESULT HwndTerminal::Initialize()
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, MT::Control::IControlSettings, MT::Core::ICoreSettings, MT::Control::IControlAppearance, MT::Core::ICoreAppearance, MT::Core::ICoreScheme>
{
- _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>();
- const auto lock = _terminal->LockForWriting();
-
- auto& renderSettings = _terminal->GetRenderSettings();
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_BACKGROUND, RGB(12, 12, 12));
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_FOREGROUND, RGB(204, 204, 204));
- _renderer = std::make_unique<::Microsoft::Console::Render::Renderer>(renderSettings, _terminal.get());
-
- auto engine = std::make_unique<::Microsoft::Console::Render::AtlasEngine>();
- RETURN_IF_FAILED(engine->SetHwnd(_hwnd.get()));
- _renderer->AddRenderEngine(engine.get());
-
- _UpdateFont(USER_DEFAULT_SCREEN_DPI);
- RECT windowRect;
- GetWindowRect(_hwnd.get(), &windowRect);
-
- const til::size windowSize{ windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
-
- // Fist set up the dx engine with the window size in pixels.
- // Then, using the font, get the number of characters that can fit.
- const auto viewInPixels = Viewport::FromDimensions({ 0, 0 }, windowSize);
- RETURN_IF_FAILED(engine->SetWindowSize({ viewInPixels.Width(), viewInPixels.Height() }));
-
- _renderEngine = std::move(engine);
-
- _terminal->Create({ 80, 25 }, 9001, *_renderer);
- _terminal->SetWriteInputCallback([=](std::wstring_view input) noexcept { _WriteTextToConnection(input); });
- _terminal->SetCopyToClipboardCallback([=](wil::zwstring_view text) noexcept { _CopyTextToSystemClipboard(text, {}, {}); });
- _renderer->EnablePainting();
-
- _multiClickTime = std::chrono::milliseconds{ GetDoubleClickTime() };
-
- return S_OK;
-}
-
-void HwndTerminal::Teardown() noexcept
-try
-{
- // As a rule, detach resources from the Terminal before shutting them down.
- // This ensures that teardown is reentrant.
- _tsfHandle = {};
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
Could use some vertical spacing here and there.
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
-using namespace ::Microsoft::Console::VirtualTerminal;
-using namespace ::Microsoft::Terminal::Core;
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
-static LPCWSTR term_window_class = L"HwndTerminalClass";
+#include "HwndTerminalAutomationPeer.hpp"
-STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
-{
- return E_NOTIMPL;
-}
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
-{
- return 1;
-}
+#pragma warning(disable : 4100)
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+namespace MT
{
- return 1;
+ namespace Control = winrt::Microsoft::Terminal::Control;
+ namespace Core = winrt::Microsoft::Terminal::Core;
}
-HWND HwndTerminal::TsfDataProvider::GetHwnd()
+static auto getControlKeyState() noexcept
{
- return _terminal->GetHwnd();
-}
-
-RECT HwndTerminal::TsfDataProvider::GetViewport()
-{
- const auto hwnd = GetHwnd();
-
- RECT rc;
- GetClientRect(hwnd, &rc);
+ using ControlKeyStates = ::Microsoft::Terminal::Core::ControlKeyStates;
+ struct KeyModifier
+ {
+ int vkey;
+ ControlKeyStates flags;
+ };
- // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
- // > The left and top members are zero. The right and bottom members contain the width and height of the window.
- // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
- ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
- rc.right += rc.left;
- rc.bottom += rc.top;
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, ControlKeyStates::RightAltPressed },
+ { VK_LMENU, ControlKeyStates::LeftAltPressed },
+ { VK_RCONTROL, ControlKeyStates::RightCtrlPressed },
+ { VK_LCONTROL, ControlKeyStates::LeftCtrlPressed },
+ { VK_SHIFT, ControlKeyStates::ShiftPressed },
+ } };
- return rc;
-}
+ ControlKeyStates flags;
-RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
-{
- // Convert from columns/rows to pixels.
- til::point cursorPos;
- til::size fontSize;
+ for (const auto& mod : modifiers)
{
- const auto lock = _terminal->_terminal->LockForReading();
- cursorPos = _terminal->_terminal->GetTextBuffer().GetCursor().GetPosition(); // measured in terminal cells
- fontSize = _terminal->_actualFont.GetSize(); // measured in pixels, not DIP
- }
- POINT ptSuggestion = {
- .x = cursorPos.x * fontSize.width,
- .y = cursorPos.y * fontSize.height,
- };
-
- ClientToScreen(GetHwnd(), &ptSuggestion);
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
- // Final measurement should be in pixels
- return {
- .left = ptSuggestion.x,
- .top = ptSuggestion.y,
- .right = ptSuggestion.x + fontSize.width,
- .bottom = ptSuggestion.y + fontSize.height,
- };
-}
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
-void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
-{
- _terminal->_WriteTextToConnection(text);
+ return flags;
}
-Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+static MT::Control::MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
{
- return _terminal->_renderer.get();
+ MT::Control::MouseButtonState state{};
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
}
-// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
-// "If the high-order bit is 1, the key is down; otherwise, it is up."
-static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
-
-static constexpr bool _IsMouseMessage(UINT uMsg)
+static MT::Core::Point PointFromLParam(LPARAM lParam)
{
- return uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK ||
- uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK ||
- uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK ||
- uMsg == WM_MOUSEMOVE || uMsg == WM_MOUSEWHEEL || uMsg == WM_MOUSEHWHEEL;
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
}
-LRESULT CALLBACK HwndTerminal::HwndTerminalWndProc(
- HWND hwnd,
- UINT uMsg,
- WPARAM wParam,
- LPARAM lParam) noexcept
-try
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
{
- if (WM_NCCREATE == uMsg)
+ void WriteInput(winrt::array_view<const char16_t> d)
{
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
- that->_hwnd = wil::unique_hwnd(hwnd);
-
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- return DefWindowProc(hwnd, WM_NCCREATE, wParam, lParam);
- }
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- const auto publicTerminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
- if (publicTerminal)
- {
- if (_IsMouseMessage(uMsg))
+ if (_pfnWriteCallback)
{
- if (publicTerminal->_CanSendVTMouseInput() && publicTerminal->_SendMouseEvent(uMsg, wParam, lParam))
- {
- // GH#6401: Capturing the mouse ensures that we get drag/release events
- // even if the user moves outside the window.
- // _SendMouseEvent returns false if the terminal's not in VT mode, so we'll
- // fall through to release the capture.
- switch (uMsg)
- {
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- SetCapture(hwnd);
- break;
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- default:
- break;
- }
-
- // Suppress all mouse events that made it into the terminal.
- return 0;
- }
- }
-
- switch (uMsg)
- {
- case WM_GETOBJECT:
- if (lParam == UiaRootObjectId)
- {
- return UiaReturnRawElementProvider(hwnd, wParam, lParam, publicTerminal->_GetUiaProvider());
- }
- break;
- case WM_LBUTTONDOWN:
- LOG_IF_FAILED(publicTerminal->_StartSelection(lParam));
- return 0;
- case WM_LBUTTONUP:
- publicTerminal->_singleClickTouchdownPos = std::nullopt;
- [[fallthrough]];
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- case WM_MOUSEMOVE:
- if (WI_IsFlagSet(wParam, MK_LBUTTON))
- {
- LOG_IF_FAILED(publicTerminal->_MoveSelection(lParam));
- return 0;
- }
- break;
- case WM_RBUTTONDOWN:
- try
- {
- if (publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- if (publicTerminal->_terminal->IsSelectionActive())
- {
- const auto bufferData = publicTerminal->_terminal->RetrieveSelectedTextFromBuffer(false, false, true, true);
- LOG_IF_FAILED(publicTerminal->_CopyTextToSystemClipboard(bufferData.plainText, bufferData.html, bufferData.rtf));
- publicTerminal->_ClearSelection();
- return 0;
- }
- }
- publicTerminal->_PasteTextFromClipboard();
- return 0;
- }
- CATCH_LOG();
- case WM_DESTROY:
- // Release Terminal's hwnd so Teardown doesn't try to destroy it again
- publicTerminal->_hwnd.release();
- publicTerminal->Teardown();
- return 0;
- default:
- break;
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
}
}
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-catch (...)
-{
- LOG_CAUGHT_EXCEPTION();
- return 0;
-}
-static bool RegisterTermClass(HINSTANCE hInstance) noexcept
-{
- WNDCLASSW wc;
- if (GetClassInfoW(hInstance, term_window_class, &wc))
- {
- return true;
- }
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
- wc.style = 0;
- wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = hInstance;
- wc.hIcon = nullptr;
- wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
- wc.hbrBackground = nullptr;
- wc.lpszMenuName = nullptr;
- wc.lpszClassName = term_window_class;
-
- return RegisterClassW(&wc) != 0;
-}
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
-HwndTerminal::HwndTerminal(HWND parentHwnd) noexcept :
- _desiredFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, 14, CP_UTF8 },
- _actualFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, { 0, 14 }, CP_UTF8, false },
- _uiaProvider{ nullptr },
- _currentDpi{ USER_DEFAULT_SCREEN_DPI },
- _pfnWriteCallback{ nullptr },
- _multiClickTime{ 500 } // this will be overwritten by the windows system double-click time
-{
- auto hInstance = wil::GetModuleInstanceHandle();
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
- if (RegisterTermClass(hInstance))
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
{
- // The WS_EX_NOREDIRECTIONBITMAP flag is used to disable the GDI redirection surface
- // for reduced memory usage, because the window is fully rendered in DX.
- CreateWindowExW(
- WS_EX_NOREDIRECTIONBITMAP,
- term_window_class,
- nullptr,
- WS_CHILD |
- WS_CLIPCHILDREN |
- WS_CLIPSIBLINGS |
- WS_VISIBLE,
- 0,
- 0,
- 0,
- 0,
- parentHwnd,
- nullptr,
- hInstance,
- this);
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
}
-}
-
-HwndTerminal::~HwndTerminal()
-{
- Teardown();
-}
+};
-HRESULT HwndTerminal::Initialize()
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, MT::Control::IControlSettings, MT::Core::ICoreSettings, MT::Control::IControlAppearance, MT::Core::ICoreAppearance, MT::Core::ICoreScheme>
{
- _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>();
- const auto lock = _terminal->LockForWriting();
-
- auto& renderSettings = _terminal->GetRenderSettings();
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_BACKGROUND, RGB(12, 12, 12));
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_FOREGROUND, RGB(204, 204, 204));
- _renderer = std::make_unique<::Microsoft::Console::Render::Renderer>(renderSettings, _terminal.get());
-
- auto engine = std::make_unique<::Microsoft::Console::Render::AtlasEngine>();
- RETURN_IF_FAILED(engine->SetHwnd(_hwnd.get()));
- _renderer->AddRenderEngine(engine.get());
-
- _UpdateFont(USER_DEFAULT_SCREEN_DPI);
- RECT windowRect;
- GetWindowRect(_hwnd.get(), &windowRect);
-
- const til::size windowSize{ windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
-
- // Fist set up the dx engine with the window size in pixels.
- // Then, using the font, get the number of characters that can fit.
- const auto viewInPixels = Viewport::FromDimensions({ 0, 0 }, windowSize);
- RETURN_IF_FAILED(engine->SetWindowSize({ viewInPixels.Width(), viewInPixels.Height() }));
-
- _renderEngine = std::move(engine);
-
- _terminal->Create({ 80, 25 }, 9001, *_renderer);
- _terminal->SetWriteInputCallback([=](std::wstring_view input) noexcept { _WriteTextToConnection(input); });
- _terminal->SetCopyToClipboardCallback([=](wil::zwstring_view text) noexcept { _CopyTextToSystemClipboard(text, {}, {}); });
- _renderer->EnablePainting();
-
- _multiClickTime = std::chrono::milliseconds{ GetDoubleClickTime() };
-
- return S_OK;
-}
-
-void HwndTerminal::Teardown() noexcept
-try
-{
- // As a rule, detach resources from the Terminal before shutting them down.
- // This ensures that teardown is reentrant.
- _tsfHandle = {};
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
- // Shut down the renderer (and therefore the thread) before we implode
- _renderer.reset();
- _renderEngine.reset();
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
- // These two callbacks have a dangling reference to `this`; let's just clear them
- _terminal->SetWriteInputCallback(nullptr);
- _terminal->SetCopyToClipboardCallback(nullptr);
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
- if (auto localHwnd{ _hwnd.release() })
+ til::color DynamicDefaultForeground() const
{
- // If we're being called through WM_DESTROY, we won't get here (hwnd is already released)
- // If we're not, we may end up in Teardown _again_... but by the time we do, all other
- // resources have been released and will not be released again.
- DestroyWindow(localHwnd);
+ return _theme.DefaultForeground;
}
-}
-CATCH_LOG();
-
-void HwndTerminal::RegisterScrollCallback(std::function<void(int, int, int)> callback)
-{
- if (!_terminal)
+ til::color DynamicDefaultBackground() const
{
- return;
+ return _theme.DefaultBackground;
}
- _terminal->SetScrollPositionChangedCallback(callback);
-}
-
-void HwndTerminal::_WriteTextToConnection(const std::wstring_view input) noexcept
-{
- if (input.empty() || !_pfnWriteCallback)
+ til::color DynamicSelectionBackground() const
{
- return;
+ return til::color{ _theme.DefaultSelectionBackground };
}
-
- try
+ winrt::hstring DynamicFontFace() const
{
- auto callingText{ wil::make_cotaskmem_string(input.data(), input.size()) };
- _pfnWriteCallback(callingText.release());
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
}
- CATCH_LOG();
-}
-
-void HwndTerminal::RegisterWriteCallback(const void _stdcall callback(wchar_t*))
-{
- _pfnWriteCallback = callback;
-}
-::Microsoft::Console::Render::IRenderData* HwndTerminal::GetRenderData() const noexcept
-{
- return _terminal.get();
-}
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
-HWND HwndTerminal::GetHwnd() const noexcept
-{
- return _hwnd.get();
-}
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
-void HwndTerminal::_UpdateFont(int newDpi)
-{
- if (!_terminal)
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
{
- return;
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
}
- _currentDpi = newDpi;
- // TODO: MSFT:20895307 If the font doesn't exist, this doesn't
- // actually fail. We need a way to gracefully fallback.
- _renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont);
-}
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
-IRawElementProviderSimple* HwndTerminal::_GetUiaProvider() noexcept
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
{
- // If TermControlUiaProvider throws during construction,
- // we don't want to try constructing an instance again and again.
- if (!_uiaProvider)
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
{
- try
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
{
- if (!_terminal)
- {
- return nullptr;
- }
- LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(&_uiaProvider, this->GetRenderData(), this));
- _uiaEngine = std::make_unique<::Microsoft::Console::Render::UiaEngine>(_uiaProvider.Get());
- LOG_IF_FAILED(_uiaEngine->Enable());
- const auto lock = _terminal->LockForWriting();
- _renderer->AddRenderEngine(_uiaEngine.get());
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
}
- catch (...)
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
{
- LOG_HR(wil::ResultFromCaughtException());
- _uiaProvider = nullptr;
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
}
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
}
-
- return _uiaProvider.Get();
-}
-
-HRESULT HwndTerminal::Refresh(const til::size windowSize, _Out_ til::size* dimensions)
-{
- RETURN_HR_IF_NULL(E_NOT_VALID_STATE, _terminal);
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensions);
-
- const auto lock = _terminal->LockForWriting();
-
- _terminal->ClearSelection();
-
- RETURN_IF_FAILED(_renderEngine->SetWindowSize(windowSize));
-
- // Invalidate everything
- _renderer->TriggerRedrawAll();
-
- // Convert our new dimensions to characters
- const auto viewInPixels = Viewport::FromDimensions({}, windowSize);
- const auto vp = _renderEngine->GetViewportInCharacters(viewInPixels);
-
- // Guard against resizing below the visible minimum (GH#19996).
- auto size = vp.Dimensions();
- size.width = std::max(size.width, MINIMUM_VISIBLE_CELLS);
- size.height = std::max(size.height, MINIMUM_VISIBLE_CELLS);
-
- // If this function succeeds with S_FALSE, then the terminal didn't
- // actually change size. No need to notify the connection of this
- // no-op.
- // TODO: MSFT:20642295 Resizing the buffer will corrupt it
- // I believe we'll need support for CSI 2J, and additionally I think
- // we're resetting the viewport to the top
- RETURN_IF_FAILED(_terminal->UserResize(size));
- dimensions->width = size.width;
- dimensions->height = size.height;
-
- return S_OK;
-}
-
-void HwndTerminal::SendOutput(std::wstring_view data)
-{
- if (!_terminal)
+ catch (...)
{
- return;
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
}
- const auto lock = _terminal->LockForWriting();
- _terminal->Write(data);
-}
-
-void _stdcall AvoidBuggyTSFConsoleFlags()
-{
- Microsoft::Console::TSF::Handle::AvoidBuggyTSFConsoleFlags();
-}
-
-HRESULT _stdcall CreateTerminal(HWND parentHwnd, _Out_ void** hwnd, _Out_ void** terminal)
-{
- auto publicTerminal = std::make_unique<HwndTerminal>(parentHwnd);
-
- RETURN_IF_FAILED(publicTerminal->Initialize());
- *hwnd = publicTerminal->GetHwnd();
- *terminal = publicTerminal.release();
-
- return S_OK;
-}
-
-void _stdcall TerminalRegisterScrollCallback(void* terminal, void __stdcall callback(int, int, int))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterScrollCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalRegisterWriteCallback(void* terminal, const void __stdcall callback(wchar_t*))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterWriteCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalSendOutput(void* terminal, LPCWSTR data)
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->SendOutput(data);
-}
-CATCH_LOG()
-
-/// <summary>
-/// Triggers a terminal resize using the new width and height in pixel.
-/// </summary>
-/// <param name="terminal">Terminal pointer.</param>
-/// <param name="width">New width of the terminal in pixels.</param>
-/// <param name="height">New height of the terminal in pixels</param>
-/// <param name="dimensions">Out parameter containing the columns and rows that fit the new size.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResize(_In_ void* terminal, _In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
-
- LOG_IF_WIN32_BOOL_FALSE(SetWindowPos(
- publicTerminal->GetHwnd(),
- nullptr,
- 0,
- 0,
- static_cast<int>(width),
- static_cast<int>(height),
- 0));
-
- const til::size windowSize{ width, height };
- return publicTerminal->Refresh(windowSize, dimensions);
-}
-
-/// <summary>
-/// Helper method for resizing the terminal using character column and row counts
-/// </summary>
-/// <param name="terminal">Pointer to the terminal object.</param>
-/// <param name="dimensionsInCharacters">New terminal size in row and column count.</param>
-/// <param name="dimensionsInPixels">Out parameter with the new size of the renderer.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResizeWithDimension(_In_ void* terminal, _In_ til::size dimensionsInCharacters, _Out_ til::size* dimensionsInPixels)
-try
-{
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensionsInPixels);
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
- const auto publicTerminal = static_cast<const HwndTerminal*>(terminal);
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
- Viewport viewInPixels;
- {
- const auto viewInCharacters = Viewport::FromDimensions({}, dimensionsInCharacters);
- const auto lock = publicTerminal->_terminal->LockForReading();
- viewInPixels = publicTerminal->_renderEngine->GetViewportInPixels(viewInCharacters);
+ return RegisterClassW(&wc) != 0;
}
- dimensionsInPixels->width = viewInPixels.Width();
- dimensionsInPixels->height = viewInPixels.Height();
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
We use std::chrono::microseconds throughout ControlCore for timings? What the heck, that completely went by me!
And why system_clock? It should be steady_clock I'm pretty sure. And we should pass std::chrono::steady_clock::time_point _or_ we migrate over to double and seconds, which would be good for the next 2000 years.
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
-using namespace ::Microsoft::Console::VirtualTerminal;
-using namespace ::Microsoft::Terminal::Core;
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
-static LPCWSTR term_window_class = L"HwndTerminalClass";
+#include "HwndTerminalAutomationPeer.hpp"
-STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
-{
- return E_NOTIMPL;
-}
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
-{
- return 1;
-}
+#pragma warning(disable : 4100)
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+namespace MT
{
- return 1;
+ namespace Control = winrt::Microsoft::Terminal::Control;
+ namespace Core = winrt::Microsoft::Terminal::Core;
}
-HWND HwndTerminal::TsfDataProvider::GetHwnd()
+static auto getControlKeyState() noexcept
{
- return _terminal->GetHwnd();
-}
-
-RECT HwndTerminal::TsfDataProvider::GetViewport()
-{
- const auto hwnd = GetHwnd();
-
- RECT rc;
- GetClientRect(hwnd, &rc);
+ using ControlKeyStates = ::Microsoft::Terminal::Core::ControlKeyStates;
+ struct KeyModifier
+ {
+ int vkey;
+ ControlKeyStates flags;
+ };
- // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
- // > The left and top members are zero. The right and bottom members contain the width and height of the window.
- // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
- ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
- rc.right += rc.left;
- rc.bottom += rc.top;
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, ControlKeyStates::RightAltPressed },
+ { VK_LMENU, ControlKeyStates::LeftAltPressed },
+ { VK_RCONTROL, ControlKeyStates::RightCtrlPressed },
+ { VK_LCONTROL, ControlKeyStates::LeftCtrlPressed },
+ { VK_SHIFT, ControlKeyStates::ShiftPressed },
+ } };
- return rc;
-}
+ ControlKeyStates flags;
-RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
-{
- // Convert from columns/rows to pixels.
- til::point cursorPos;
- til::size fontSize;
+ for (const auto& mod : modifiers)
{
- const auto lock = _terminal->_terminal->LockForReading();
- cursorPos = _terminal->_terminal->GetTextBuffer().GetCursor().GetPosition(); // measured in terminal cells
- fontSize = _terminal->_actualFont.GetSize(); // measured in pixels, not DIP
- }
- POINT ptSuggestion = {
- .x = cursorPos.x * fontSize.width,
- .y = cursorPos.y * fontSize.height,
- };
-
- ClientToScreen(GetHwnd(), &ptSuggestion);
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
- // Final measurement should be in pixels
- return {
- .left = ptSuggestion.x,
- .top = ptSuggestion.y,
- .right = ptSuggestion.x + fontSize.width,
- .bottom = ptSuggestion.y + fontSize.height,
- };
-}
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
-void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
-{
- _terminal->_WriteTextToConnection(text);
+ return flags;
}
-Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+static MT::Control::MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
{
- return _terminal->_renderer.get();
+ MT::Control::MouseButtonState state{};
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
}
-// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
-// "If the high-order bit is 1, the key is down; otherwise, it is up."
-static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
-
-static constexpr bool _IsMouseMessage(UINT uMsg)
+static MT::Core::Point PointFromLParam(LPARAM lParam)
{
- return uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK ||
- uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK ||
- uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK ||
- uMsg == WM_MOUSEMOVE || uMsg == WM_MOUSEWHEEL || uMsg == WM_MOUSEHWHEEL;
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
}
-LRESULT CALLBACK HwndTerminal::HwndTerminalWndProc(
- HWND hwnd,
- UINT uMsg,
- WPARAM wParam,
- LPARAM lParam) noexcept
-try
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
{
- if (WM_NCCREATE == uMsg)
+ void WriteInput(winrt::array_view<const char16_t> d)
{
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
- that->_hwnd = wil::unique_hwnd(hwnd);
-
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- return DefWindowProc(hwnd, WM_NCCREATE, wParam, lParam);
- }
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- const auto publicTerminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
- if (publicTerminal)
- {
- if (_IsMouseMessage(uMsg))
+ if (_pfnWriteCallback)
{
- if (publicTerminal->_CanSendVTMouseInput() && publicTerminal->_SendMouseEvent(uMsg, wParam, lParam))
- {
- // GH#6401: Capturing the mouse ensures that we get drag/release events
- // even if the user moves outside the window.
- // _SendMouseEvent returns false if the terminal's not in VT mode, so we'll
- // fall through to release the capture.
- switch (uMsg)
- {
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- SetCapture(hwnd);
- break;
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- default:
- break;
- }
-
- // Suppress all mouse events that made it into the terminal.
- return 0;
- }
- }
-
- switch (uMsg)
- {
- case WM_GETOBJECT:
- if (lParam == UiaRootObjectId)
- {
- return UiaReturnRawElementProvider(hwnd, wParam, lParam, publicTerminal->_GetUiaProvider());
- }
- break;
- case WM_LBUTTONDOWN:
- LOG_IF_FAILED(publicTerminal->_StartSelection(lParam));
- return 0;
- case WM_LBUTTONUP:
- publicTerminal->_singleClickTouchdownPos = std::nullopt;
- [[fallthrough]];
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- case WM_MOUSEMOVE:
- if (WI_IsFlagSet(wParam, MK_LBUTTON))
- {
- LOG_IF_FAILED(publicTerminal->_MoveSelection(lParam));
- return 0;
- }
- break;
- case WM_RBUTTONDOWN:
- try
- {
- if (publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- if (publicTerminal->_terminal->IsSelectionActive())
- {
- const auto bufferData = publicTerminal->_terminal->RetrieveSelectedTextFromBuffer(false, false, true, true);
- LOG_IF_FAILED(publicTerminal->_CopyTextToSystemClipboard(bufferData.plainText, bufferData.html, bufferData.rtf));
- publicTerminal->_ClearSelection();
- return 0;
- }
- }
- publicTerminal->_PasteTextFromClipboard();
- return 0;
- }
- CATCH_LOG();
- case WM_DESTROY:
- // Release Terminal's hwnd so Teardown doesn't try to destroy it again
- publicTerminal->_hwnd.release();
- publicTerminal->Teardown();
- return 0;
- default:
- break;
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
}
}
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-catch (...)
-{
- LOG_CAUGHT_EXCEPTION();
- return 0;
-}
-static bool RegisterTermClass(HINSTANCE hInstance) noexcept
-{
- WNDCLASSW wc;
- if (GetClassInfoW(hInstance, term_window_class, &wc))
- {
- return true;
- }
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
- wc.style = 0;
- wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = hInstance;
- wc.hIcon = nullptr;
- wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
- wc.hbrBackground = nullptr;
- wc.lpszMenuName = nullptr;
- wc.lpszClassName = term_window_class;
-
- return RegisterClassW(&wc) != 0;
-}
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
-HwndTerminal::HwndTerminal(HWND parentHwnd) noexcept :
- _desiredFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, 14, CP_UTF8 },
- _actualFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, { 0, 14 }, CP_UTF8, false },
- _uiaProvider{ nullptr },
- _currentDpi{ USER_DEFAULT_SCREEN_DPI },
- _pfnWriteCallback{ nullptr },
- _multiClickTime{ 500 } // this will be overwritten by the windows system double-click time
-{
- auto hInstance = wil::GetModuleInstanceHandle();
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
- if (RegisterTermClass(hInstance))
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
{
- // The WS_EX_NOREDIRECTIONBITMAP flag is used to disable the GDI redirection surface
- // for reduced memory usage, because the window is fully rendered in DX.
- CreateWindowExW(
- WS_EX_NOREDIRECTIONBITMAP,
- term_window_class,
- nullptr,
- WS_CHILD |
- WS_CLIPCHILDREN |
- WS_CLIPSIBLINGS |
- WS_VISIBLE,
- 0,
- 0,
- 0,
- 0,
- parentHwnd,
- nullptr,
- hInstance,
- this);
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
}
-}
-
-HwndTerminal::~HwndTerminal()
-{
- Teardown();
-}
+};
-HRESULT HwndTerminal::Initialize()
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, MT::Control::IControlSettings, MT::Core::ICoreSettings, MT::Control::IControlAppearance, MT::Core::ICoreAppearance, MT::Core::ICoreScheme>
{
- _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>();
- const auto lock = _terminal->LockForWriting();
-
- auto& renderSettings = _terminal->GetRenderSettings();
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_BACKGROUND, RGB(12, 12, 12));
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_FOREGROUND, RGB(204, 204, 204));
- _renderer = std::make_unique<::Microsoft::Console::Render::Renderer>(renderSettings, _terminal.get());
-
- auto engine = std::make_unique<::Microsoft::Console::Render::AtlasEngine>();
- RETURN_IF_FAILED(engine->SetHwnd(_hwnd.get()));
- _renderer->AddRenderEngine(engine.get());
-
- _UpdateFont(USER_DEFAULT_SCREEN_DPI);
- RECT windowRect;
- GetWindowRect(_hwnd.get(), &windowRect);
-
- const til::size windowSize{ windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
-
- // Fist set up the dx engine with the window size in pixels.
- // Then, using the font, get the number of characters that can fit.
- const auto viewInPixels = Viewport::FromDimensions({ 0, 0 }, windowSize);
- RETURN_IF_FAILED(engine->SetWindowSize({ viewInPixels.Width(), viewInPixels.Height() }));
-
- _renderEngine = std::move(engine);
-
- _terminal->Create({ 80, 25 }, 9001, *_renderer);
- _terminal->SetWriteInputCallback([=](std::wstring_view input) noexcept { _WriteTextToConnection(input); });
- _terminal->SetCopyToClipboardCallback([=](wil::zwstring_view text) noexcept { _CopyTextToSystemClipboard(text, {}, {}); });
- _renderer->EnablePainting();
-
- _multiClickTime = std::chrono::milliseconds{ GetDoubleClickTime() };
-
- return S_OK;
-}
-
-void HwndTerminal::Teardown() noexcept
-try
-{
- // As a rule, detach resources from the Terminal before shutting them down.
- // This ensures that teardown is reentrant.
- _tsfHandle = {};
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
- // Shut down the renderer (and therefore the thread) before we implode
- _renderer.reset();
- _renderEngine.reset();
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
- // These two callbacks have a dangling reference to `this`; let's just clear them
- _terminal->SetWriteInputCallback(nullptr);
- _terminal->SetCopyToClipboardCallback(nullptr);
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
- if (auto localHwnd{ _hwnd.release() })
+ til::color DynamicDefaultForeground() const
{
- // If we're being called through WM_DESTROY, we won't get here (hwnd is already released)
- // If we're not, we may end up in Teardown _again_... but by the time we do, all other
- // resources have been released and will not be released again.
- DestroyWindow(localHwnd);
+ return _theme.DefaultForeground;
}
-}
-CATCH_LOG();
-
-void HwndTerminal::RegisterScrollCallback(std::function<void(int, int, int)> callback)
-{
- if (!_terminal)
+ til::color DynamicDefaultBackground() const
{
- return;
+ return _theme.DefaultBackground;
}
- _terminal->SetScrollPositionChangedCallback(callback);
-}
-
-void HwndTerminal::_WriteTextToConnection(const std::wstring_view input) noexcept
-{
- if (input.empty() || !_pfnWriteCallback)
+ til::color DynamicSelectionBackground() const
{
- return;
+ return til::color{ _theme.DefaultSelectionBackground };
}
-
- try
+ winrt::hstring DynamicFontFace() const
{
- auto callingText{ wil::make_cotaskmem_string(input.data(), input.size()) };
- _pfnWriteCallback(callingText.release());
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
}
- CATCH_LOG();
-}
-
-void HwndTerminal::RegisterWriteCallback(const void _stdcall callback(wchar_t*))
-{
- _pfnWriteCallback = callback;
-}
-::Microsoft::Console::Render::IRenderData* HwndTerminal::GetRenderData() const noexcept
-{
- return _terminal.get();
-}
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
-HWND HwndTerminal::GetHwnd() const noexcept
-{
- return _hwnd.get();
-}
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
-void HwndTerminal::_UpdateFont(int newDpi)
-{
- if (!_terminal)
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
{
- return;
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
}
- _currentDpi = newDpi;
- // TODO: MSFT:20895307 If the font doesn't exist, this doesn't
- // actually fail. We need a way to gracefully fallback.
- _renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont);
-}
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
-IRawElementProviderSimple* HwndTerminal::_GetUiaProvider() noexcept
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
{
- // If TermControlUiaProvider throws during construction,
- // we don't want to try constructing an instance again and again.
- if (!_uiaProvider)
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
{
- try
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
{
- if (!_terminal)
- {
- return nullptr;
- }
- LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(&_uiaProvider, this->GetRenderData(), this));
- _uiaEngine = std::make_unique<::Microsoft::Console::Render::UiaEngine>(_uiaProvider.Get());
- LOG_IF_FAILED(_uiaEngine->Enable());
- const auto lock = _terminal->LockForWriting();
- _renderer->AddRenderEngine(_uiaEngine.get());
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
}
- catch (...)
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
{
- LOG_HR(wil::ResultFromCaughtException());
- _uiaProvider = nullptr;
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
}
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
}
-
- return _uiaProvider.Get();
-}
-
-HRESULT HwndTerminal::Refresh(const til::size windowSize, _Out_ til::size* dimensions)
-{
- RETURN_HR_IF_NULL(E_NOT_VALID_STATE, _terminal);
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensions);
-
- const auto lock = _terminal->LockForWriting();
-
- _terminal->ClearSelection();
-
- RETURN_IF_FAILED(_renderEngine->SetWindowSize(windowSize));
-
- // Invalidate everything
- _renderer->TriggerRedrawAll();
-
- // Convert our new dimensions to characters
- const auto viewInPixels = Viewport::FromDimensions({}, windowSize);
- const auto vp = _renderEngine->GetViewportInCharacters(viewInPixels);
-
- // Guard against resizing below the visible minimum (GH#19996).
- auto size = vp.Dimensions();
- size.width = std::max(size.width, MINIMUM_VISIBLE_CELLS);
- size.height = std::max(size.height, MINIMUM_VISIBLE_CELLS);
-
- // If this function succeeds with S_FALSE, then the terminal didn't
- // actually change size. No need to notify the connection of this
- // no-op.
- // TODO: MSFT:20642295 Resizing the buffer will corrupt it
- // I believe we'll need support for CSI 2J, and additionally I think
- // we're resetting the viewport to the top
- RETURN_IF_FAILED(_terminal->UserResize(size));
- dimensions->width = size.width;
- dimensions->height = size.height;
-
- return S_OK;
-}
-
-void HwndTerminal::SendOutput(std::wstring_view data)
-{
- if (!_terminal)
+ catch (...)
{
- return;
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
}
- const auto lock = _terminal->LockForWriting();
- _terminal->Write(data);
-}
-
-void _stdcall AvoidBuggyTSFConsoleFlags()
-{
- Microsoft::Console::TSF::Handle::AvoidBuggyTSFConsoleFlags();
-}
-
-HRESULT _stdcall CreateTerminal(HWND parentHwnd, _Out_ void** hwnd, _Out_ void** terminal)
-{
- auto publicTerminal = std::make_unique<HwndTerminal>(parentHwnd);
-
- RETURN_IF_FAILED(publicTerminal->Initialize());
- *hwnd = publicTerminal->GetHwnd();
- *terminal = publicTerminal.release();
-
- return S_OK;
-}
-
-void _stdcall TerminalRegisterScrollCallback(void* terminal, void __stdcall callback(int, int, int))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterScrollCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalRegisterWriteCallback(void* terminal, const void __stdcall callback(wchar_t*))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterWriteCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalSendOutput(void* terminal, LPCWSTR data)
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->SendOutput(data);
-}
-CATCH_LOG()
-
-/// <summary>
-/// Triggers a terminal resize using the new width and height in pixel.
-/// </summary>
-/// <param name="terminal">Terminal pointer.</param>
-/// <param name="width">New width of the terminal in pixels.</param>
-/// <param name="height">New height of the terminal in pixels</param>
-/// <param name="dimensions">Out parameter containing the columns and rows that fit the new size.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResize(_In_ void* terminal, _In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
-
- LOG_IF_WIN32_BOOL_FALSE(SetWindowPos(
- publicTerminal->GetHwnd(),
- nullptr,
- 0,
- 0,
- static_cast<int>(width),
- static_cast<int>(height),
- 0));
-
- const til::size windowSize{ width, height };
- return publicTerminal->Refresh(windowSize, dimensions);
-}
-
-/// <summary>
-/// Helper method for resizing the terminal using character column and row counts
-/// </summary>
-/// <param name="terminal">Pointer to the terminal object.</param>
-/// <param name="dimensionsInCharacters">New terminal size in row and column count.</param>
-/// <param name="dimensionsInPixels">Out parameter with the new size of the renderer.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResizeWithDimension(_In_ void* terminal, _In_ til::size dimensionsInCharacters, _Out_ til::size* dimensionsInPixels)
-try
-{
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensionsInPixels);
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
- const auto publicTerminal = static_cast<const HwndTerminal*>(terminal);
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
- Viewport viewInPixels;
- {
- const auto viewInCharacters = Viewport::FromDimensions({}, dimensionsInCharacters);
- const auto lock = publicTerminal->_terminal->LockForReading();
- viewInPixels = publicTerminal->_renderEngine->GetViewportInPixels(viewInCharacters);
+ return RegisterClassW(&wc) != 0;
}
- dimensionsInPixels->width = viewInPixels.Width();
- dimensionsInPixels->height = viewInPixels.Height();
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
- til::size unused;
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
- return TerminalTriggerResize(terminal, viewInPixels.Width(), viewInPixels.Height(), &unused);
-}
-CATCH_RETURN()
-
-/// <summary>
-/// Calculates the amount of rows and columns that fit in the provided width and height.
-/// </summary>
-/// <param name="terminal">Terminal pointer</param>
-/// <param name="width">Width of the terminal area to calculate.</param>
-/// <param name="height">Height of the terminal area to calculate.</param>
-/// <param name="dimensions">Out parameter containing the columns and rows that fit the new size.</param>
-/// <returns>HRESULT of the calculation.</returns>
-HRESULT _stdcall TerminalCalculateResize(_In_ void* terminal, _In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
-try
-{
- const auto publicTerminal = static_cast<const HwndTerminal*>(terminal);
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
- const auto viewInPixels = Viewport::FromDimensions({}, { width, height });
- const auto lock = publicTerminal->_terminal->LockForReading();
- const auto viewInCharacters = publicTerminal->_renderEngine->GetViewportInCharacters(viewInPixels);
+ wil::unique_hwnd _hwnd;
- dimensions->width = std::max(viewInCharacters.Width(), MINIMUM_VISIBLE_CELLS);
- dimensions->height = std::max(viewInCharacters.Height(), MINIMUM_VISIBLE_CELLS);
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
- return S_OK;
-}
-CATCH_RETURN()
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
Why all these flags? We're a swap chain so we aren't subject to GDI in the first place, aren't we?
@@ -2,1183 +2,861 @@
// Licensed under the MIT license.
#include "pch.h"
-#include "HwndTerminal.hpp"
-#include <DefaultSettings.h>
-#include <windowsx.h>
-
-#include "HwndTerminalAutomationPeer.hpp"
-#include "../../cascadia/TerminalCore/Terminal.hpp"
-#include "../../renderer/atlas/AtlasEngine.h"
-#include "../../renderer/base/renderer.hpp"
-#include "../../renderer/uia/UiaRenderer.hpp"
-#include "../../types/viewport.cpp"
+#include "HwndTerminal.h"
+#include "winrt/Microsoft.Terminal.Control.h"
+#include "winrt/Microsoft.Terminal.Core.h"
+#include "../TerminalCore/ControlKeyStates.hpp"
+#include "../types/inc/colorTable.hpp"
+#include "../inc/DefaultSettings.h"
+#include "../inc/cppwinrt_utils.h"
+#include "../../tsf/Handle.h"
+#include "../inc/ControlProperties.h"
-using namespace ::Microsoft::Console::VirtualTerminal;
-using namespace ::Microsoft::Terminal::Core;
+#include "ControlCore.h"
+#include "ControlInteractivity.h"
-static LPCWSTR term_window_class = L"HwndTerminalClass";
+#include "HwndTerminalAutomationPeer.hpp"
-STDMETHODIMP HwndTerminal::TsfDataProvider::QueryInterface(REFIID, void**) noexcept
-{
- return E_NOTIMPL;
-}
+#include <windows.system.h>
+#include <windowsx.h>
+#include <UIAutomationCoreApi.h>
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::AddRef() noexcept
-{
- return 1;
-}
+#pragma warning(disable : 4100)
-ULONG STDMETHODCALLTYPE HwndTerminal::TsfDataProvider::Release() noexcept
+namespace MT
{
- return 1;
+ namespace Control = winrt::Microsoft::Terminal::Control;
+ namespace Core = winrt::Microsoft::Terminal::Core;
}
-HWND HwndTerminal::TsfDataProvider::GetHwnd()
+static auto getControlKeyState() noexcept
{
- return _terminal->GetHwnd();
-}
-
-RECT HwndTerminal::TsfDataProvider::GetViewport()
-{
- const auto hwnd = GetHwnd();
-
- RECT rc;
- GetClientRect(hwnd, &rc);
+ using ControlKeyStates = ::Microsoft::Terminal::Core::ControlKeyStates;
+ struct KeyModifier
+ {
+ int vkey;
+ ControlKeyStates flags;
+ };
- // https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getclientrect
- // > The left and top members are zero. The right and bottom members contain the width and height of the window.
- // --> We can turn the client rect into a screen-relative rect by adding the left/top position.
- ClientToScreen(hwnd, reinterpret_cast<POINT*>(&rc));
- rc.right += rc.left;
- rc.bottom += rc.top;
+ constexpr std::array<KeyModifier, 5> modifiers{ {
+ { VK_RMENU, ControlKeyStates::RightAltPressed },
+ { VK_LMENU, ControlKeyStates::LeftAltPressed },
+ { VK_RCONTROL, ControlKeyStates::RightCtrlPressed },
+ { VK_LCONTROL, ControlKeyStates::LeftCtrlPressed },
+ { VK_SHIFT, ControlKeyStates::ShiftPressed },
+ } };
- return rc;
-}
+ ControlKeyStates flags;
-RECT HwndTerminal::TsfDataProvider::GetCursorPosition()
-{
- // Convert from columns/rows to pixels.
- til::point cursorPos;
- til::size fontSize;
+ for (const auto& mod : modifiers)
{
- const auto lock = _terminal->_terminal->LockForReading();
- cursorPos = _terminal->_terminal->GetTextBuffer().GetCursor().GetPosition(); // measured in terminal cells
- fontSize = _terminal->_actualFont.GetSize(); // measured in pixels, not DIP
- }
- POINT ptSuggestion = {
- .x = cursorPos.x * fontSize.width,
- .y = cursorPos.y * fontSize.height,
- };
-
- ClientToScreen(GetHwnd(), &ptSuggestion);
+ const auto state = GetKeyState(mod.vkey);
+ const auto isDown = state < 0;
- // Final measurement should be in pixels
- return {
- .left = ptSuggestion.x,
- .top = ptSuggestion.y,
- .right = ptSuggestion.x + fontSize.width,
- .bottom = ptSuggestion.y + fontSize.height,
- };
-}
+ if (isDown)
+ {
+ flags |= mod.flags;
+ }
+ }
-void HwndTerminal::TsfDataProvider::HandleOutput(std::wstring_view text)
-{
- _terminal->_WriteTextToConnection(text);
+ return flags;
}
-Microsoft::Console::Render::Renderer* HwndTerminal::TsfDataProvider::GetRenderer()
+static MT::Control::MouseButtonState MouseButtonStateFromWParam(WPARAM wParam)
{
- return _terminal->_renderer.get();
+ MT::Control::MouseButtonState state{};
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsLeftButtonDown, WI_IsFlagSet(wParam, MK_LBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsMiddleButtonDown, WI_IsFlagSet(wParam, MK_MBUTTON));
+ WI_UpdateFlag(state, MT::Control::MouseButtonState::IsRightButtonDown, WI_IsFlagSet(wParam, MK_RBUTTON));
+ return state;
}
-// This magic flag is "documented" at https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301(v=vs.85).aspx
-// "If the high-order bit is 1, the key is down; otherwise, it is up."
-static constexpr short KeyPressed{ gsl::narrow_cast<short>(0x8000) };
-
-static constexpr bool _IsMouseMessage(UINT uMsg)
+static MT::Core::Point PointFromLParam(LPARAM lParam)
{
- return uMsg == WM_LBUTTONDOWN || uMsg == WM_LBUTTONUP || uMsg == WM_LBUTTONDBLCLK ||
- uMsg == WM_MBUTTONDOWN || uMsg == WM_MBUTTONUP || uMsg == WM_MBUTTONDBLCLK ||
- uMsg == WM_RBUTTONDOWN || uMsg == WM_RBUTTONUP || uMsg == WM_RBUTTONDBLCLK ||
- uMsg == WM_MOUSEMOVE || uMsg == WM_MOUSEWHEEL || uMsg == WM_MOUSEHWHEEL;
+ return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
}
-LRESULT CALLBACK HwndTerminal::HwndTerminalWndProc(
- HWND hwnd,
- UINT uMsg,
- WPARAM wParam,
- LPARAM lParam) noexcept
-try
+struct CallbackBasedConnection : public winrt::implements<CallbackBasedConnection, winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection>
{
- if (WM_NCCREATE == uMsg)
+ void WriteInput(winrt::array_view<const char16_t> d)
{
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
- HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
- that->_hwnd = wil::unique_hwnd(hwnd);
-
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
- return DefWindowProc(hwnd, WM_NCCREATE, wParam, lParam);
- }
-#pragma warning(suppress : 26490) // Win32 APIs can only store void*, have to use reinterpret_cast
- const auto publicTerminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
-
- if (publicTerminal)
- {
- if (_IsMouseMessage(uMsg))
+ if (_pfnWriteCallback)
{
- if (publicTerminal->_CanSendVTMouseInput() && publicTerminal->_SendMouseEvent(uMsg, wParam, lParam))
- {
- // GH#6401: Capturing the mouse ensures that we get drag/release events
- // even if the user moves outside the window.
- // _SendMouseEvent returns false if the terminal's not in VT mode, so we'll
- // fall through to release the capture.
- switch (uMsg)
- {
- case WM_LBUTTONDOWN:
- case WM_MBUTTONDOWN:
- case WM_RBUTTONDOWN:
- SetCapture(hwnd);
- break;
- case WM_LBUTTONUP:
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- default:
- break;
- }
-
- // Suppress all mouse events that made it into the terminal.
- return 0;
- }
- }
-
- switch (uMsg)
- {
- case WM_GETOBJECT:
- if (lParam == UiaRootObjectId)
- {
- return UiaReturnRawElementProvider(hwnd, wParam, lParam, publicTerminal->_GetUiaProvider());
- }
- break;
- case WM_LBUTTONDOWN:
- LOG_IF_FAILED(publicTerminal->_StartSelection(lParam));
- return 0;
- case WM_LBUTTONUP:
- publicTerminal->_singleClickTouchdownPos = std::nullopt;
- [[fallthrough]];
- case WM_MBUTTONUP:
- case WM_RBUTTONUP:
- ReleaseCapture();
- break;
- case WM_MOUSEMOVE:
- if (WI_IsFlagSet(wParam, MK_LBUTTON))
- {
- LOG_IF_FAILED(publicTerminal->_MoveSelection(lParam));
- return 0;
- }
- break;
- case WM_RBUTTONDOWN:
- try
- {
- if (publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- if (publicTerminal->_terminal->IsSelectionActive())
- {
- const auto bufferData = publicTerminal->_terminal->RetrieveSelectedTextFromBuffer(false, false, true, true);
- LOG_IF_FAILED(publicTerminal->_CopyTextToSystemClipboard(bufferData.plainText, bufferData.html, bufferData.rtf));
- publicTerminal->_ClearSelection();
- return 0;
- }
- }
- publicTerminal->_PasteTextFromClipboard();
- return 0;
- }
- CATCH_LOG();
- case WM_DESTROY:
- // Release Terminal's hwnd so Teardown doesn't try to destroy it again
- publicTerminal->_hwnd.release();
- publicTerminal->Teardown();
- return 0;
- default:
- break;
+ _pfnWriteCallback(reinterpret_cast<const wchar_t*>(d.data()));
}
}
- return DefWindowProc(hwnd, uMsg, wParam, lParam);
-}
-catch (...)
-{
- LOG_CAUGHT_EXCEPTION();
- return 0;
-}
-static bool RegisterTermClass(HINSTANCE hInstance) noexcept
-{
- WNDCLASSW wc;
- if (GetClassInfoW(hInstance, term_window_class, &wc))
- {
- return true;
- }
+ // Stubs
+ void Initialize(const IInspectable&) {}
+ void Start() {}
+ void Resize(uint32_t r, uint32_t c) {}
+ void Close() {}
+ winrt::guid SessionId() { return {}; }
+ void SessionId(const winrt::guid&) {}
- wc.style = 0;
- wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
- wc.cbClsExtra = 0;
- wc.cbWndExtra = 0;
- wc.hInstance = hInstance;
- wc.hIcon = nullptr;
- wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
- wc.hbrBackground = nullptr;
- wc.lpszMenuName = nullptr;
- wc.lpszClassName = term_window_class;
-
- return RegisterClassW(&wc) != 0;
-}
+ winrt::Microsoft::Terminal::TerminalConnection::ConnectionState State() const noexcept { return winrt::Microsoft::Terminal::TerminalConnection::ConnectionState::Connected; }
-HwndTerminal::HwndTerminal(HWND parentHwnd) noexcept :
- _desiredFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, 14, CP_UTF8 },
- _actualFont{ L"Consolas", 0, DEFAULT_FONT_WEIGHT, { 0, 14 }, CP_UTF8, false },
- _uiaProvider{ nullptr },
- _currentDpi{ USER_DEFAULT_SCREEN_DPI },
- _pfnWriteCallback{ nullptr },
- _multiClickTime{ 500 } // this will be overwritten by the windows system double-click time
-{
- auto hInstance = wil::GetModuleInstanceHandle();
+ til::event<winrt::Microsoft::Terminal::TerminalConnection::TerminalOutputHandler> TerminalOutput;
+ til::typed_event<winrt::Microsoft::Terminal::TerminalConnection::ITerminalConnection> StateChanged;
- if (RegisterTermClass(hInstance))
+public:
+ PWRITECB _pfnWriteCallback{ nullptr };
+ void OriginateOutputFromConnection(const wchar_t* data)
{
- // The WS_EX_NOREDIRECTIONBITMAP flag is used to disable the GDI redirection surface
- // for reduced memory usage, because the window is fully rendered in DX.
- CreateWindowExW(
- WS_EX_NOREDIRECTIONBITMAP,
- term_window_class,
- nullptr,
- WS_CHILD |
- WS_CLIPCHILDREN |
- WS_CLIPSIBLINGS |
- WS_VISIBLE,
- 0,
- 0,
- 0,
- 0,
- parentHwnd,
- nullptr,
- hInstance,
- this);
+ std::wstring_view str{ data };
+ TerminalOutput.raise(winrt::array_view<const char16_t>(reinterpret_cast<const char16_t*>(str.data()), static_cast<uint32_t>(str.size())));
}
-}
-
-HwndTerminal::~HwndTerminal()
-{
- Teardown();
-}
+};
-HRESULT HwndTerminal::Initialize()
+struct BasicTerminalSettings : winrt::implements<BasicTerminalSettings, MT::Control::IControlSettings, MT::Core::ICoreSettings, MT::Control::IControlAppearance, MT::Core::ICoreAppearance, MT::Core::ICoreScheme>
{
- _terminal = std::make_unique<::Microsoft::Terminal::Core::Terminal>();
- const auto lock = _terminal->LockForWriting();
-
- auto& renderSettings = _terminal->GetRenderSettings();
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_BACKGROUND, RGB(12, 12, 12));
- renderSettings.SetColorTableEntry(TextColor::DEFAULT_FOREGROUND, RGB(204, 204, 204));
- _renderer = std::make_unique<::Microsoft::Console::Render::Renderer>(renderSettings, _terminal.get());
-
- auto engine = std::make_unique<::Microsoft::Console::Render::AtlasEngine>();
- RETURN_IF_FAILED(engine->SetHwnd(_hwnd.get()));
- _renderer->AddRenderEngine(engine.get());
-
- _UpdateFont(USER_DEFAULT_SCREEN_DPI);
- RECT windowRect;
- GetWindowRect(_hwnd.get(), &windowRect);
-
- const til::size windowSize{ windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
-
- // Fist set up the dx engine with the window size in pixels.
- // Then, using the font, get the number of characters that can fit.
- const auto viewInPixels = Viewport::FromDimensions({ 0, 0 }, windowSize);
- RETURN_IF_FAILED(engine->SetWindowSize({ viewInPixels.Width(), viewInPixels.Height() }));
-
- _renderEngine = std::move(engine);
-
- _terminal->Create({ 80, 25 }, 9001, *_renderer);
- _terminal->SetWriteInputCallback([=](std::wstring_view input) noexcept { _WriteTextToConnection(input); });
- _terminal->SetCopyToClipboardCallback([=](wil::zwstring_view text) noexcept { _CopyTextToSystemClipboard(text, {}, {}); });
- _renderer->EnablePainting();
-
- _multiClickTime = std::chrono::milliseconds{ GetDoubleClickTime() };
-
- return S_OK;
-}
-
-void HwndTerminal::Teardown() noexcept
-try
-{
- // As a rule, detach resources from the Terminal before shutting them down.
- // This ensures that teardown is reentrant.
- _tsfHandle = {};
+ using IFontAxesMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ using IFontFeatureMap = winrt::Windows::Foundation::Collections::IMap<winrt::hstring, float>;
+ BasicTerminalSettings()
+ {
+ const auto campbellSpan = Microsoft::Console::Utils::CampbellColorTable();
+ std::transform(campbellSpan.begin(), campbellSpan.end(), std::begin(_theme.ColorTable), [](auto&& color) {
+ return color;
+ });
+ }
+ ~BasicTerminalSettings() = default;
- // Shut down the renderer (and therefore the thread) before we implode
- _renderer.reset();
- _renderEngine.reset();
+ void GetColorTable(winrt::com_array<::winrt::Microsoft::Terminal::Core::Color>& table) noexcept
+ {
+ std::array<winrt::Microsoft::Terminal::Core::Color, COLOR_TABLE_SIZE> colorTable{};
+ std::transform(&_theme.ColorTable[0], &_theme.ColorTable[16], colorTable.begin(), [](auto&& color) {
+ return static_cast<winrt::Microsoft::Terminal::Core::Color>(til::color{ color });
+ });
- // These two callbacks have a dangling reference to `this`; let's just clear them
- _terminal->SetWriteInputCallback(nullptr);
- _terminal->SetCopyToClipboardCallback(nullptr);
+ table = winrt::com_array(colorTable.begin(), colorTable.end());
+ }
- if (auto localHwnd{ _hwnd.release() })
+ til::color DynamicDefaultForeground() const
{
- // If we're being called through WM_DESTROY, we won't get here (hwnd is already released)
- // If we're not, we may end up in Teardown _again_... but by the time we do, all other
- // resources have been released and will not be released again.
- DestroyWindow(localHwnd);
+ return _theme.DefaultForeground;
}
-}
-CATCH_LOG();
-
-void HwndTerminal::RegisterScrollCallback(std::function<void(int, int, int)> callback)
-{
- if (!_terminal)
+ til::color DynamicDefaultBackground() const
{
- return;
+ return _theme.DefaultBackground;
}
- _terminal->SetScrollPositionChangedCallback(callback);
-}
-
-void HwndTerminal::_WriteTextToConnection(const std::wstring_view input) noexcept
-{
- if (input.empty() || !_pfnWriteCallback)
+ til::color DynamicSelectionBackground() const
{
- return;
+ return til::color{ _theme.DefaultSelectionBackground };
}
-
- try
+ winrt::hstring DynamicFontFace() const
{
- auto callingText{ wil::make_cotaskmem_string(input.data(), input.size()) };
- _pfnWriteCallback(callingText.release());
+ return _fontFace;
+ }
+ float DynamicFontSize() const
+ {
+ return _fontSize;
+ }
+ winrt::Microsoft::Terminal::Core::CursorStyle DynamicCursorShape() const
+ {
+ return static_cast<winrt::Microsoft::Terminal::Core::CursorStyle>(_theme.CursorStyle);
}
- CATCH_LOG();
-}
-
-void HwndTerminal::RegisterWriteCallback(const void _stdcall callback(wchar_t*))
-{
- _pfnWriteCallback = callback;
-}
-::Microsoft::Console::Render::IRenderData* HwndTerminal::GetRenderData() const noexcept
-{
- return _terminal.get();
-}
+#define DYNAMIC_PROPERTY(type, name, ...) \
+ auto name() \
+ { \
+ return [](auto t) { \
+ if constexpr (std::bool_constant<requires { t->Dynamic##name(); }>::value) \
+ { \
+ return t->Dynamic##name(); \
+ } \
+ return type{ __VA_ARGS__ }; \
+ }(this); \
+ }
-HWND HwndTerminal::GetHwnd() const noexcept
-{
- return _hwnd.get();
-}
+ CONTROL_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_SETTINGS(DYNAMIC_PROPERTY);
+ CONTROL_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+ CORE_APPEARANCE_SETTINGS(DYNAMIC_PROPERTY);
+#undef DYNAMIC_PROPERTY
-void HwndTerminal::_UpdateFont(int newDpi)
-{
- if (!_terminal)
+public:
+ void SetTheme(TerminalTheme theme, LPCWSTR fontFamily, til::CoordType fontSize, int newDpi)
{
- return;
+ _theme = std::move(theme);
+ _fontFace = fontFamily;
+ _fontSize = static_cast<float>(fontSize);
}
- _currentDpi = newDpi;
- // TODO: MSFT:20895307 If the font doesn't exist, this doesn't
- // actually fail. We need a way to gracefully fallback.
- _renderer->TriggerFontChange(newDpi, _desiredFont, _actualFont);
-}
+private:
+ TerminalTheme _theme;
+ winrt::hstring _fontFace{ L"Cascadia Mono" };
+ float _fontSize = 12.0f;
+};
-IRawElementProviderSimple* HwndTerminal::_GetUiaProvider() noexcept
+struct HwndTerminal : public Microsoft::Console::Types::IControlAccessibilityInfo
{
- // If TermControlUiaProvider throws during construction,
- // we don't want to try constructing an instance again and again.
- if (!_uiaProvider)
+ static constexpr LPCWSTR term_window_class = L"HwndTerminalClass";
+
+ static LRESULT CALLBACK HwndTerminalWndProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ try
{
- try
+#pragma warning(push)
+#pragma warning(disable : 26490) // Win32 APIs can only store void*/LONG_PTR, have to use reinterpret_cast
+ if (uMsg == WM_NCCREATE)
{
- if (!_terminal)
- {
- return nullptr;
- }
- LOG_IF_FAILED(::Microsoft::WRL::MakeAndInitialize<HwndTerminalAutomationPeer>(&_uiaProvider, this->GetRenderData(), this));
- _uiaEngine = std::make_unique<::Microsoft::Console::Render::UiaEngine>(_uiaProvider.Get());
- LOG_IF_FAILED(_uiaEngine->Enable());
- const auto lock = _terminal->LockForWriting();
- _renderer->AddRenderEngine(_uiaEngine.get());
+ // Set the GWLP_USERDATA pointer based on the param passed into CreateWindowEx
+ const auto cs = reinterpret_cast<CREATESTRUCT*>(lParam);
+ HwndTerminal* that = static_cast<HwndTerminal*>(cs->lpCreateParams);
+ SetWindowLongPtrW(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that));
}
- catch (...)
+ else if (HwndTerminal* terminal = reinterpret_cast<HwndTerminal*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)))
{
- LOG_HR(wil::ResultFromCaughtException());
- _uiaProvider = nullptr;
+ return terminal->WindowProc(hwnd, uMsg, wParam, lParam);
}
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+#pragma warning(pop)
}
-
- return _uiaProvider.Get();
-}
-
-HRESULT HwndTerminal::Refresh(const til::size windowSize, _Out_ til::size* dimensions)
-{
- RETURN_HR_IF_NULL(E_NOT_VALID_STATE, _terminal);
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensions);
-
- const auto lock = _terminal->LockForWriting();
-
- _terminal->ClearSelection();
-
- RETURN_IF_FAILED(_renderEngine->SetWindowSize(windowSize));
-
- // Invalidate everything
- _renderer->TriggerRedrawAll();
-
- // Convert our new dimensions to characters
- const auto viewInPixels = Viewport::FromDimensions({}, windowSize);
- const auto vp = _renderEngine->GetViewportInCharacters(viewInPixels);
-
- // Guard against resizing below the visible minimum (GH#19996).
- auto size = vp.Dimensions();
- size.width = std::max(size.width, MINIMUM_VISIBLE_CELLS);
- size.height = std::max(size.height, MINIMUM_VISIBLE_CELLS);
-
- // If this function succeeds with S_FALSE, then the terminal didn't
- // actually change size. No need to notify the connection of this
- // no-op.
- // TODO: MSFT:20642295 Resizing the buffer will corrupt it
- // I believe we'll need support for CSI 2J, and additionally I think
- // we're resetting the viewport to the top
- RETURN_IF_FAILED(_terminal->UserResize(size));
- dimensions->width = size.width;
- dimensions->height = size.height;
-
- return S_OK;
-}
-
-void HwndTerminal::SendOutput(std::wstring_view data)
-{
- if (!_terminal)
+ catch (...)
{
- return;
+ LOG_CAUGHT_EXCEPTION();
+ return 0;
}
- const auto lock = _terminal->LockForWriting();
- _terminal->Write(data);
-}
-
-void _stdcall AvoidBuggyTSFConsoleFlags()
-{
- Microsoft::Console::TSF::Handle::AvoidBuggyTSFConsoleFlags();
-}
-
-HRESULT _stdcall CreateTerminal(HWND parentHwnd, _Out_ void** hwnd, _Out_ void** terminal)
-{
- auto publicTerminal = std::make_unique<HwndTerminal>(parentHwnd);
-
- RETURN_IF_FAILED(publicTerminal->Initialize());
- *hwnd = publicTerminal->GetHwnd();
- *terminal = publicTerminal.release();
-
- return S_OK;
-}
-
-void _stdcall TerminalRegisterScrollCallback(void* terminal, void __stdcall callback(int, int, int))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterScrollCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalRegisterWriteCallback(void* terminal, const void __stdcall callback(wchar_t*))
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->RegisterWriteCallback(callback);
-}
-CATCH_LOG()
-
-void _stdcall TerminalSendOutput(void* terminal, LPCWSTR data)
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- publicTerminal->SendOutput(data);
-}
-CATCH_LOG()
-
-/// <summary>
-/// Triggers a terminal resize using the new width and height in pixel.
-/// </summary>
-/// <param name="terminal">Terminal pointer.</param>
-/// <param name="width">New width of the terminal in pixels.</param>
-/// <param name="height">New height of the terminal in pixels</param>
-/// <param name="dimensions">Out parameter containing the columns and rows that fit the new size.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResize(_In_ void* terminal, _In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
-
- LOG_IF_WIN32_BOOL_FALSE(SetWindowPos(
- publicTerminal->GetHwnd(),
- nullptr,
- 0,
- 0,
- static_cast<int>(width),
- static_cast<int>(height),
- 0));
-
- const til::size windowSize{ width, height };
- return publicTerminal->Refresh(windowSize, dimensions);
-}
-
-/// <summary>
-/// Helper method for resizing the terminal using character column and row counts
-/// </summary>
-/// <param name="terminal">Pointer to the terminal object.</param>
-/// <param name="dimensionsInCharacters">New terminal size in row and column count.</param>
-/// <param name="dimensionsInPixels">Out parameter with the new size of the renderer.</param>
-/// <returns>HRESULT of the attempted resize.</returns>
-HRESULT _stdcall TerminalTriggerResizeWithDimension(_In_ void* terminal, _In_ til::size dimensionsInCharacters, _Out_ til::size* dimensionsInPixels)
-try
-{
- RETURN_HR_IF_NULL(E_INVALIDARG, dimensionsInPixels);
+ static bool RegisterTermClass(HINSTANCE hInstance) noexcept
+ {
+ WNDCLASSW wc;
+ if (GetClassInfoW(hInstance, term_window_class, &wc))
+ {
+ return true;
+ }
- const auto publicTerminal = static_cast<const HwndTerminal*>(terminal);
+ wc.style = 0;
+ wc.lpfnWndProc = HwndTerminal::HwndTerminalWndProc;
+ wc.cbClsExtra = 0;
+ wc.cbWndExtra = 0;
+ wc.hInstance = hInstance;
+ wc.hIcon = nullptr;
+ wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
+ wc.hbrBackground = nullptr;
+ wc.lpszMenuName = nullptr;
+ wc.lpszClassName = term_window_class;
- Viewport viewInPixels;
- {
- const auto viewInCharacters = Viewport::FromDimensions({}, dimensionsInCharacters);
- const auto lock = publicTerminal->_terminal->LockForReading();
- viewInPixels = publicTerminal->_renderEngine->GetViewportInPixels(viewInCharacters);
+ return RegisterClassW(&wc) != 0;
}
- dimensionsInPixels->width = viewInPixels.Width();
- dimensionsInPixels->height = viewInPixels.Height();
+ LRESULT WindowProc(
+ HWND hwnd,
+ UINT uMsg,
+ WPARAM wParam,
+ LPARAM lParam) noexcept
+ {
+ switch (uMsg)
+ {
+ case WM_GETOBJECT:
+ if (lParam == UiaRootObjectId)
+ {
+ return UiaReturnRawElementProvider(hwnd, wParam, lParam, _getUiaProvider());
+ }
+ break;
+ case WM_LBUTTONDOWN:
+ case WM_MBUTTONDOWN:
+ case WM_RBUTTONDOWN:
+ SetCapture(_hwnd.get());
+ _interactivity->PointerPressed(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count(),
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_MOUSEMOVE:
+ _interactivity->PointerMoved(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ WM_MOUSEMOVE,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ return 0;
+ case WM_LBUTTONUP:
+ case WM_MBUTTONUP:
+ case WM_RBUTTONUP:
+ _interactivity->PointerReleased(
+ 0, // Mouse
+ MouseButtonStateFromWParam(wParam),
+ uMsg,
+ getControlKeyState(),
+ PointFromLParam(lParam));
+ ReleaseCapture();
+ return 0;
+ case WM_POINTERDOWN:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ SetCapture(_hwnd.get());
+ _interactivity->TouchPressed(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUPDATE:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchMoved(PointFromLParam(lParam));
+ return 0;
+ case WM_POINTERUP:
+ if (!IS_POINTER_INCONTACT_WPARAM(wParam))
+ {
+ break;
+ }
+ _interactivity->TouchReleased();
+ ReleaseCapture();
+ return 0;
+ case WM_MOUSEWHEEL:
+ case WM_MOUSEHWHEEL:
+ {
+ winrt::Microsoft::Terminal::Core::Point delta{ 0, GET_WHEEL_DELTA_WPARAM(wParam) };
+ if (uMsg == WM_MOUSEHWHEEL)
+ {
+ std::swap(delta.X, delta.Y);
+ }
- til::size unused;
+ if (_interactivity->MouseWheel(getControlKeyState(), delta, PointFromLParam(lParam), MouseButtonStateFromWParam(wParam)))
+ {
+ return 0;
+ }
+ break;
+ }
+ case WM_SETFOCUS:
+ if (!_tsfHandle)
+ {
+ _tsfHandle = Microsoft::Console::TSF::Handle::Create();
+ _tsfHandle.AssociateFocus(&_tsfDataProvider);
+ }
+ _interactivity->GotFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ case WM_KILLFOCUS:
+ _interactivity->LostFocus();
+ _focused = true;
+ _core->ApplyAppearance(_focused);
+ break;
+ }
- return TerminalTriggerResize(terminal, viewInPixels.Width(), viewInPixels.Height(), &unused);
-}
-CATCH_RETURN()
-
-/// <summary>
-/// Calculates the amount of rows and columns that fit in the provided width and height.
-/// </summary>
-/// <param name="terminal">Terminal pointer</param>
-/// <param name="width">Width of the terminal area to calculate.</param>
-/// <param name="height">Height of the terminal area to calculate.</param>
-/// <param name="dimensions">Out parameter containing the columns and rows that fit the new size.</param>
-/// <returns>HRESULT of the calculation.</returns>
-HRESULT _stdcall TerminalCalculateResize(_In_ void* terminal, _In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
-try
-{
- const auto publicTerminal = static_cast<const HwndTerminal*>(terminal);
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+ }
- const auto viewInPixels = Viewport::FromDimensions({}, { width, height });
- const auto lock = publicTerminal->_terminal->LockForReading();
- const auto viewInCharacters = publicTerminal->_renderEngine->GetViewportInCharacters(viewInPixels);
+ wil::unique_hwnd _hwnd;
- dimensions->width = std::max(viewInCharacters.Width(), MINIMUM_VISIBLE_CELLS);
- dimensions->height = std::max(viewInCharacters.Height(), MINIMUM_VISIBLE_CELLS);
+ HwndTerminal(HWND parentHwnd, winrt::Windows::System::DispatcherQueue dispatcher)
+ {
+ HINSTANCE hInstance = wil::GetModuleInstanceHandle();
- return S_OK;
-}
-CATCH_RETURN()
+ if (RegisterTermClass(hInstance))
+ {
+ _hwnd.reset(CreateWindowExW(
+ 0,
+ term_window_class,
+ nullptr,
+ WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE,
+ 0,
+ 0,
+ 0,
+ 0,
+ parentHwnd,
+ nullptr,
+ hInstance,
+ this));
+ }
-void _stdcall TerminalDpiChanged(void* terminal, int newDpi)
-try
-{
- const auto publicTerminal = static_cast<HwndTerminal*>(terminal);
- const auto lock = publicTerminal->_terminal->LockForWriting();
- publicTerminal->_UpdateFont(newDpi);
-}
-CATCH_LOG()
+ _settingsBridge = winrt::make_self<BasicTerminalSettings>();
+ _connection = winrt::make_self<CallbackBasedConnection>();
+ _interactivity = winrt::make_self<MT::Control::implementation::ControlInteractivity>(*_settingsBridge, nullptr, *_connection, dispatcher);
+ _core = _interactivity->Core();
-void _stdcall TerminalUserScroll(void* terminal, int viewTop)
-try
-{
- if (const auto publicTerminal = static_cast<const HwndTerminal*>(terminal); publicTerminal && publicTerminal->_terminal)
- {
- const auto lock = publicTerminal->_terminal->LockForWriting();
- publicTerminal->_terminal->UserScrollViewport(viewTop);
+ _core->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
+ _interactivity->ScrollPositionChanged({ this, &HwndTerminal::_scrollPositionChanged });
}
-}
-CATCH_LOG()
-const unsigned int HwndTerminal::_NumberOfClicks(til::point point, std::chrono::steady_clock::time_point timestamp) noexcept
-{
- // if click occurred at a different location or past the multiClickTimer...
- const auto delta{ timestamp - _lastMouseClickTimestamp };
- if (point != _lastMouseClickPos || delta > _multiClickTime)
+ /*( PUBLIC API )*/
+ HRESULT SendOutput(LPCWSTR data)
{
- // exit early. This is a single click.
- _multiClickCounter = 1;
+ _connection->OriginateOutputFromConnection(data);
+ return S_OK;
}
- else
+
+ HRESULT RegisterScrollCallback(PSCROLLCB callback)
{
- _multiClickCounter++;
+ _scrollCallback = callback;
+ return S_OK;
}
- return _multiClickCounter;
-}
-HRESULT HwndTerminal::_StartSelection(LPARAM lParam) noexcept
-try
-{
- RETURN_HR_IF_NULL(E_NOT_VALID_STATE, _terminal);
- const til::point cursorPosition{
- GET_X_LPARAM(lParam),
- GET_Y_LPARAM(lParam),
- };
+ HRESULT TriggerResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
+ {
+ if (!_initialized)
+ return S_FALSE;
- const auto lock = _terminal->LockForWriting();
- const auto altPressed = GetKeyState(VK_MENU) < 0;
- const til::size fontSize{ this->_actualFont.GetSize() };
+ SetWindowPos(_hwnd.get(), nullptr, 0, 0, width, height, 0);
- this->_terminal->SetBlockSelection(altPressed);
+ // **NOTE** The sizes we get here are unscaled ...
+ auto dpi = GetDpiForWindow(_hwnd.get());
+ float w = static_cast<float>(width * USER_DEFAULT_SCREEN_DPI) / dpi;
+ float h = static_cast<float>(height * USER_DEFAULT_SCREEN_DPI) / dpi;
+ // ... but ControlCore expects scaled sizes.
+ _core->SizeChanged(w, h);
- const auto clickCount{ _NumberOfClicks(cursorPosition, std::chrono::steady_clock::now()) };
+ wil::assign_to_opt_param(dimensions, til::size{ _core->ViewportSize() });
- // This formula enables the number of clicks to cycle properly between single-, double-, and triple-click.
- // To increase the number of acceptable click states, simply increment MAX_CLICK_COUNT and add another if-statement
- const unsigned int MAX_CLICK_COUNT = 3;
- const auto multiClickMapper = clickCount > MAX_CLICK_COUNT ? ((clickCount + MAX_CLICK_COUNT - 1) % MAX_CLICK_COUNT) + 1 : clickCount;
+ return S_OK;
+ }
- if (multiClickMapper == 3)
+ HRESULT TriggerResizeWithDimension(_In_ til::size dimensions, _Out_ til::size* dimensionsInPixels)
{
- _terminal->MultiClickSelection(cursorPosition / fontSize, ::Terminal::SelectionExpansion::Line);
+ if (!_initialized)
+ return S_FALSE;
+
+ winrt::Windows::Foundation::Size outSizeInPixels;
+ _core->ResizeToDimensions(dimensions.width, dimensions.height, outSizeInPixels);
+ wil::assign_to_opt_param(dimensionsInPixels, til::size{ til::math::rounding, outSizeInPixels });
+ return S_OK;
}
- else if (multiClickMapper == 2)
+
+ HRESULT CalculateResize(_In_ til::CoordType width, _In_ til::CoordType height, _Out_ til::size* dimensions)
{
- _terminal->MultiClickSelection(cursorPosition / fontSize, ::Terminal::SelectionExpansion::Word);
+ // TODO(DH): It seems weird to have to do this manually.
+ auto fontSizeInPx = _core->FontSize();
+ wil::assign_to_opt_param(dimensions, til::size{
+ static_cast<til::CoordType>(width / fontSizeInPx.Width),
+ static_cast<til::CoordType>(height / fontSizeInPx.Height),
+ });
Odd indentation.
Typing literally lags by up to 5s while in the diff view.
GitHub, this is the most awful experience imaginable and it's been going even further downhill for years.
If you were to make a graph of website performance, it would be a vertical line through the floor. That takes some special talent.
Had an LLM go through it and found some definitive bugs and some parts where I'm a bit puzzled as well.
Approved these changes.
DHowett
Residual = Change × (1 − Confidence)
lhecker
This pull request replaces all of HwndTerminal, which used to be a thin layer on top of TerminalCore.lib, with a new implementation that relies on the Interactivity and Core layers in TerminalControl.lib.
We used to spend a lot of time reimplementing interactivity components for HwndTerminal or--if I'm being honest--letting it rot and never giving it the improvements the rest of the application got.
Among those improvements:
This pull request seeks to get HwndTerminal back to where it was (plus the things we naturally get from switching over). In the future, we can more easily add:
Implementation Details
----------------------
The WPF control is backed by a flat "C" API, which takes in a
void*and does some stuff to it. We call that aPTERM. References to "Flat C" in this commit body describe the body of work below WPF.X-macros are used to fill out the definintions of every C API and bridge it to a properly typed C++ member function. Ugh. No more crap where we split the implementation into half C export and half C++ member.
ControlCore and ControlInteractivity require something that looks like TerminalSettings. The WPF control only supports the most basic settings, in
struct TerminalTheme, and so I've added a bridge WinRT type to adapt TerminalTheme toIXxxSettings. Most of the values it returns are our "defaults", and some of them are overridden.
Core requires an
ITerminalConnection, but the WPF API uses a pair of "write output" and "send input" callbacks. Flat C provides an ITerminalConnection that bridges those callbacks. It does not communicate connection state or anythingelse. Resizing is probably going to be a problem.
Core requires a dispatcher queue to ensure that some operations happen on the UI thread. I have stubbed out an implementation of
IDispatcherQueuethat calls a couple function pointers with a context pointer; the WPF code hooks up to thatand bridges it into the WPF dispatcher. Yes, the Core's dispatcher queue _is_ the WPF main UI thread. It has to be, otherwise we'll explode the first time we try to update the scroll bar. Prep work was done in #20713.
To make the above easier, I removed all use of DispatcherTimer (see #20711). Attempts to use it will almost certainly cause the WPF control to implode.
Core needed to be taught a couple tricks to start up targeting an HWND instead of a composition handle. See #20722 for more.
Refs #20710
Refs #20711
Refs #20713
Refs #20722
Required #20721
Refs #20745
Related to #6999