-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathWindowsTextInputComponentView.cpp
More file actions
1704 lines (1449 loc) · 60.3 KB
/
WindowsTextInputComponentView.cpp
File metadata and controls
1704 lines (1449 loc) · 60.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#pragma once
#include "WindowsTextInputComponentView.h"
#include <AutoDraw.h>
#include <Fabric/Composition/CompositionDynamicAutomationProvider.h>
#include <Fabric/Composition/UiaHelpers.h>
#include <Utils/ValueUtils.h>
#include <react/renderer/components/textinput/TextInputState.h>
#include <react/renderer/textlayoutmanager/WindowsTextLayoutManager.h>
#include <tom.h>
#include <unicode.h>
#include <winrt/Microsoft.UI.Input.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.UI.h>
#include "../CompositionHelpers.h"
#include "../RootComponentView.h"
#include "JSValueReader.h"
#include "WindowsTextInputShadowNode.h"
#include "guid/msoGuid.h"
#include <unicode.h>
// convert a BSTR to a std::string.
std::string &BstrToStdString(const BSTR bstr, std::string &dst, int cp = CP_UTF8) {
if (!bstr) {
// define NULL functionality. I just clear the target.
dst.clear();
return dst;
}
// request content length in single-chars through a terminating
// nullchar in the BSTR. note: BSTR's support imbedded nullchars,
// so this will only convert through the first nullchar.
int res = WideCharToMultiByte(cp, 0, bstr, -1, NULL, 0, NULL, NULL);
if (res > 0) {
dst.resize(res);
WideCharToMultiByte(cp, 0, bstr, -1, &dst[0], res, NULL, NULL);
} else { // no content. clear target
dst.clear();
}
return dst;
}
// conversion with temp.
std::string BstrToStdString(BSTR bstr, int cp = CP_UTF8) {
std::string str;
BstrToStdString(bstr, str, cp);
return str;
}
MSO_CLASS_GUID(ITextHost, "13E670F4-1A5A-11cf-ABEB-00AA00B65EA1") // IID_ITextHost
MSO_CLASS_GUID(ITextServices, "8D33F740-CF58-11CE-A89D-00AA006CADC5") // IID_ITextServices
MSO_CLASS_GUID(ITextServices2, "8D33F741-CF58-11CE-A89D-00AA006CADC5") // IID_ITextServices2
namespace winrt::Microsoft::ReactNative::Composition::implementation {
// RichEdit doesn't handle us calling Draw during the middle of a TxTranslateMessage call.
WindowsTextInputComponentView::DrawBlock::DrawBlock(WindowsTextInputComponentView &view) : m_view(view) {
m_view.m_cDrawBlock++;
}
WindowsTextInputComponentView::DrawBlock::~DrawBlock() {
m_view.m_cDrawBlock--;
if (!m_view.m_cDrawBlock && m_view.m_needsRedraw) {
m_view.DrawText();
}
}
// Msftedit.dll vs "Riched20.dll"?
static HINSTANCE g_hInstRichEdit = nullptr;
static PCreateTextServices g_pfnCreateTextServices;
HRESULT HrEnsureRichEd20Loaded() noexcept {
if (g_hInstRichEdit == nullptr) {
g_hInstRichEdit = LoadLibrary(L"Msftedit.dll");
if (!g_hInstRichEdit)
return E_FAIL;
// Create the windowless control (text services object)
g_pfnCreateTextServices = (PCreateTextServices)GetProcAddress(g_hInstRichEdit, "CreateTextServices");
if (!g_pfnCreateTextServices)
return E_FAIL;
/*
// Calling the REExtendedRegisterClass() function is required for
// registering the REComboboxW and REListBoxW window classes.
PFNREGISTER pfnRegister = (PFNREGISTER)GetProcAddress(g_hInstRichEdit, "REExtendedRegisterClass");
if (pfnRegister) {
pfnRegister();
return S_OK;
} else
return E_FAIL;
*/
}
return NOERROR;
}
struct CompTextHost : public winrt::implements<CompTextHost, ITextHost> {
CompTextHost(WindowsTextInputComponentView *outer) : m_outer(outer) {}
//@cmember Get the DC for the host
HDC TxGetDC() override {
assert(false);
return {};
}
//@cmember Release the DC gotten from the host
INT TxReleaseDC(HDC hdc) override {
assert(false);
return {};
}
//@cmember Show the scroll bar
BOOL TxShowScrollBar(INT fnBar, BOOL fShow) override {
// assert(false);
return {};
}
//@cmember Enable the scroll bar
BOOL TxEnableScrollBar(INT fuSBFlags, INT fuArrowflags) override {
// assert(false);
return {};
}
//@cmember Set the scroll range
BOOL TxSetScrollRange(INT fnBar, LONG nMinPos, INT nMaxPos, BOOL fRedraw) override {
// assert(false);
return {};
}
//@cmember Set the scroll position
BOOL TxSetScrollPos(INT fnBar, INT nPos, BOOL fRedraw) override {
// assert(false);
return {};
}
//@cmember InvalidateRect
void TxInvalidateRect(LPCRECT prc, BOOL fMode) override {
if (m_outer->m_drawing)
return;
m_outer->DrawText();
}
//@cmember Send a WM_PAINT to the window
void TxViewChange(BOOL fUpdate) override {
// When keyboard scrolling without scrollbar, TxInvalidateRect is not called.
// Instead TxViewChange is called with fUpdate = true
// if (fUpdate && !OnInnerViewerExtentChanged())
{
// If inner viewer size changed, a redraw will have be queued.
// If not, we need to redraw at least once here.
m_outer->DrawText();
}
}
//@cmember Create the caret
BOOL TxCreateCaret(HBITMAP hbmp, INT xWidth, INT yHeight) override {
m_outer->m_caretVisual.Size({static_cast<float>(xWidth), static_cast<float>(yHeight)});
return true;
}
//@cmember Show the caret
BOOL TxShowCaret(BOOL fShow) override {
// Only show the caret if we have focus
if (fShow && !m_outer->m_hasFocus) {
return false;
}
m_outer->ShowCaret(m_outer->windowsTextInputProps().caretHidden ? false : fShow);
return true;
}
//@cmember Set the caret position
BOOL TxSetCaretPos(INT x, INT y) override {
if (x < 0 && y < 0) {
// RichEdit sends (-32000,-32000) when the caret is not currently visible.
return false;
}
auto pt = m_outer->getClientOffset();
m_outer->m_caretVisual.Position({x - pt.x, y - pt.y});
return true;
}
//@cmember Create a timer with the specified timeout
BOOL TxSetTimer(UINT idTimer, UINT uTimeout) override {
// TODO timers
// assert(false);
// return {};
return false;
}
//@cmember Destroy a timer
void TxKillTimer(UINT idTimer) override {
// TODO timers
}
//@cmember Scroll the content of the specified window's client area
void TxScrollWindowEx(
INT dx,
INT dy,
LPCRECT lprcScroll,
LPCRECT lprcClip,
HRGN hrgnUpdate,
LPRECT lprcUpdate,
UINT fuScroll) override {
assert(false);
}
//@cmember Get mouse capture
void TxSetCapture(BOOL fCapture) override {
// assert(false);
// TODO capture?
/*
if (fCapture) {
::SetCapture(m_hwndHost);
} else {
::ReleaseCapture();
}
*/
}
//@cmember Set the focus to the text window
void TxSetFocus() override {
winrt::Microsoft::ReactNative::ComponentView view{nullptr};
winrt::check_hresult(
m_outer->QueryInterface(winrt::guid_of<winrt::Microsoft::ReactNative::ComponentView>(), winrt::put_abi(view)));
m_outer->rootComponentView()->TrySetFocusedComponent(
view, winrt::Microsoft::ReactNative::FocusNavigationDirection::None);
// assert(false);
// TODO focus
}
//@cmember Establish a new cursor shape
void TxSetCursor(HCURSOR hcur, BOOL fText) override {
m_outer->m_hcursor = hcur;
}
//@cmember Converts screen coordinates of a specified point to the client coordinates
BOOL TxScreenToClient(LPPOINT lppt) override {
winrt::Windows::Foundation::Point pt{static_cast<float>(lppt->x), static_cast<float>(lppt->y)};
auto localpt = m_outer->ScreenToLocal(pt);
lppt->x = static_cast<LONG>(localpt.X);
lppt->y = static_cast<LONG>(localpt.Y);
return true;
}
//@cmember Converts the client coordinates of a specified point to screen coordinates
BOOL TxClientToScreen(LPPOINT lppt) override {
winrt::Windows::Foundation::Point pt{static_cast<float>(lppt->x), static_cast<float>(lppt->y)};
auto screenpt = m_outer->LocalToScreen(pt);
lppt->x = static_cast<LONG>(screenpt.X);
lppt->y = static_cast<LONG>(screenpt.Y);
return true;
}
//@cmember Request host to activate text services
HRESULT TxActivate(LONG *plOldState) override {
assert(false);
return {};
}
//@cmember Request host to deactivate text services
HRESULT TxDeactivate(LONG lNewState) override {
assert(false);
return {};
}
//@cmember Retrieves the coordinates of a window's client area
HRESULT TxGetClientRect(LPRECT prc) override {
*prc = m_outer->getClientRect();
return S_OK;
}
//@cmember Get the view rectangle relative to the inset
HRESULT TxGetViewInset(LPRECT prc) override {
// Inset is in HIMETRIC
constexpr float HmPerInchF = 2540.0f;
constexpr float PointsPerInch = 96.0f;
constexpr float dipToHm = HmPerInchF / PointsPerInch;
prc->left = static_cast<LONG>(m_outer->m_layoutMetrics.contentInsets.left * dipToHm);
prc->top = static_cast<LONG>(m_outer->m_layoutMetrics.contentInsets.top * dipToHm);
prc->bottom = static_cast<LONG>(m_outer->m_layoutMetrics.contentInsets.bottom * dipToHm);
prc->right = static_cast<LONG>(m_outer->m_layoutMetrics.contentInsets.right * dipToHm);
return NOERROR;
}
//@cmember Get the default character format for the text
HRESULT TxGetCharFormat(const CHARFORMATW **ppCF) override {
m_outer->UpdateCharFormat();
*ppCF = &(m_outer->m_cf);
return S_OK;
}
//@cmember Get the default paragraph format for the text
HRESULT TxGetParaFormat(const PARAFORMAT **ppPF) override {
m_outer->UpdateParaFormat();
*ppPF = &(m_outer->m_pf);
return S_OK;
}
//@cmember Get the background color for the window
COLORREF TxGetSysColor(int nIndex) override {
// if (/* !m_isDisabled || */ nIndex != COLOR_WINDOW && nIndex != COLOR_WINDOWTEXT && nIndex != COLOR_GRAYTEXT) {
// This window is either not disabled or the color isn't interesting
// in the disabled case.
COLORREF cr = (COLORREF)tomAutoColor;
switch (nIndex) {
case COLOR_WINDOWTEXT:
if (m_outer->windowsTextInputProps().textAttributes.foregroundColor)
return (*m_outer->windowsTextInputProps().textAttributes.foregroundColor).AsColorRefNoAlpha();
// cr = 0x000000FF;
break;
case COLOR_WINDOW:
if (m_outer->viewProps()->backgroundColor)
return (*m_outer->viewProps()->backgroundColor).AsColorRefNoAlpha();
break;
case COLOR_HIGHLIGHT:
if (m_outer->windowsTextInputProps().selectionColor)
return (*m_outer->windowsTextInputProps().selectionColor).AsColorRefNoAlpha();
break;
case COLOR_HIGHLIGHTTEXT:
// For selected text color, we use the same color as the selection background
// or the text color if selection color is not specified
if (m_outer->windowsTextInputProps().selectionColor) {
// Calculate appropriate text color based on selection background
auto selectionColor = (*m_outer->windowsTextInputProps().selectionColor).AsColorRefNoAlpha();
// Use white text for dark selection, black text for light selection
int r = GetRValue(selectionColor);
int g = GetGValue(selectionColor);
int b = GetBValue(selectionColor);
int brightness = (r * 299 + g * 587 + b * 114) / 1000;
return brightness > 125 ? RGB(0, 0, 0) : RGB(255, 255, 255);
}
break;
// case COLOR_GRAYTEXT:
// cr = RGB(128, 128, 128);
// cr = 0x777777FF;
// break;
}
return GetSysColor(nIndex);
// return GetSysColor(nIndex);
// assert(false);
// return 0xFF00FF00;
/*
// Disabled case. When the richedit control is disabled, both the placeholder text and input text should appear as
// disabled text.
if (COLOR_WINDOWTEXT == nIndex || COLOR_GRAYTEXT == nIndex) {
// Color of text for disabled window
return m_crDisabledText == (COLORREF)tomAutoColor ? MsoCrSysColorGet(COLOR_GRAYTEXT) : m_crDisabledText;
}
// Background color for disabled window
return m_crDisabledBackground == (COLORREF)tomAutoColor ? MsoCrSysColorGet(COLOR_3DFACE) : m_crDisabledBackground;
*/
}
//@cmember Get the background (either opaque or transparent)
HRESULT TxGetBackStyle(TXTBACKSTYLE *pstyle) override {
// We draw the background color as part of the composition visual, not the text
*pstyle = TXTBACK_TRANSPARENT;
return S_OK;
}
//@cmember Get the maximum length for the text
HRESULT TxGetMaxLength(DWORD *plength) override {
auto length = m_outer->windowsTextInputProps().maxLength;
if (length > static_cast<decltype(m_outer->windowsTextInputProps().maxLength)>(std::numeric_limits<DWORD>::max())) {
length = std::numeric_limits<DWORD>::max();
}
*plength = static_cast<DWORD>(length);
return S_OK;
}
//@cmember Get the bits representing requested scroll bars for the window
HRESULT TxGetScrollBars(DWORD *pdwScrollBar) override {
if (m_outer->m_multiline) {
*pdwScrollBar = WS_VSCROLL | WS_HSCROLL | ES_AUTOVSCROLL | ES_AUTOHSCROLL;
} else {
*pdwScrollBar = WS_HSCROLL | ES_AUTOHSCROLL;
}
return S_OK;
}
//@cmember Get the character to display for password input
HRESULT TxGetPasswordChar(_Out_ wchar_t *pch) override {
*pch = L'\u2022';
return S_OK;
}
//@cmember Get the accelerator character
HRESULT TxGetAcceleratorPos(LONG *pcp) override {
assert(false);
return {};
}
//@cmember Get the native size
HRESULT TxGetExtent(LPSIZEL lpExtent) override {
return E_NOTIMPL;
// This shouldn't be implemented
}
//@cmember Notify host that default character format has changed
HRESULT OnTxCharFormatChange(const CHARFORMATW *pCF) override {
assert(false);
return {};
}
//@cmember Notify host that default paragraph format has changed
HRESULT OnTxParaFormatChange(const PARAFORMAT *pPF) override {
assert(false);
return {};
}
//@cmember Bulk access to bit properties
HRESULT TxGetPropertyBits(DWORD dwMask, DWORD *pdwBits) override {
DWORD dwProperties = TXTBIT_RICHTEXT | TXTBIT_WORDWRAP | TXTBIT_D2DDWRITE | TXTBIT_D2DSIMPLETYPOGRAPHY;
*pdwBits = dwProperties & dwMask;
return NOERROR;
}
//@cmember Notify host of events
HRESULT TxNotify(DWORD iNotify, void *pv) override {
// TODO
switch (iNotify) {
case EN_UPDATE:
if (!m_outer->m_drawing) {
m_outer->DrawText();
}
break;
case EN_CHANGE:
m_outer->OnTextUpdated();
break;
case EN_SELCHANGE: {
auto selChange = (SELCHANGE *)pv;
m_outer->OnSelectionChanged(selChange->chrg.cpMin, selChange->chrg.cpMax);
break;
}
}
return S_OK;
}
// East Asia Methods for getting the Input Context
HIMC TxImmGetContext() override {
assert(false);
return {};
}
void TxImmReleaseContext(HIMC himc) override {
assert(false);
}
//@cmember Returns HIMETRIC size of the control bar.
HRESULT TxGetSelectionBarWidth(LONG *lSelBarWidth) override {
*lSelBarWidth = 0;
return S_OK;
}
WindowsTextInputComponentView *m_outer;
};
int WINAPI
AutoCorrectOffCallback(LANGID langid, const WCHAR *pszBefore, WCHAR *pszAfter, LONG cchAfter, LONG *pcchReplaced) {
wcsncpy_s(pszAfter, cchAfter, pszBefore, _TRUNCATE);
*pcchReplaced = static_cast<LONG>(wcslen(pszAfter));
return ATP_CHANGE;
}
facebook::react::AttributedString WindowsTextInputComponentView::getAttributedString() const {
// Use BaseTextShadowNode to get attributed string from children
auto childTextAttributes = facebook::react::TextAttributes::defaultTextAttributes();
childTextAttributes.fontSizeMultiplier = m_fontSizeMultiplier;
childTextAttributes.apply(windowsTextInputProps().textAttributes);
auto attributedString = facebook::react::AttributedString{};
// auto attachments = facebook::react::BaseTextShadowNode::Attachments{};
// BaseTextShadowNode only gets children. We must detect and prepend text
// value attributes manually.
auto text = GetTextFromRichEdit();
if (!text.empty()) {
auto textAttributes = facebook::react::TextAttributes::defaultTextAttributes();
textAttributes.fontSizeMultiplier = m_fontSizeMultiplier;
textAttributes.apply(windowsTextInputProps().textAttributes);
auto fragment = facebook::react::AttributedString::Fragment{};
fragment.string = text;
// fragment.string = m_props->text;
fragment.textAttributes = textAttributes;
// If the TextInput opacity is 0 < n < 1, the opacity of the TextInput and
// text value's background will stack. This is a hack/workaround to prevent
// that effect.
fragment.textAttributes.backgroundColor = facebook::react::clearColor();
// fragment.parentShadowView = facebook::react::ShadowView(*this);
attributedString.prependFragment(std::move(fragment));
}
return attributedString;
}
WindowsTextInputComponentView::WindowsTextInputComponentView(
const winrt::Microsoft::ReactNative::Composition::Experimental::ICompositionContext &compContext,
facebook::react::Tag tag,
winrt::Microsoft::ReactNative::ReactContext const &reactContext)
: Super(
WindowsTextInputComponentView::defaultProps(),
compContext,
tag,
reactContext,
ComponentViewFeatures::Default & ~ComponentViewFeatures::Background) {}
void WindowsTextInputComponentView::HandleCommand(
const winrt::Microsoft::ReactNative::HandleCommandArgs &args) noexcept {
Super::HandleCommand(args);
if (args.Handled())
return;
auto commandName = args.CommandName();
if (commandName == L"setTextAndSelection") {
int eventCount, begin, end;
std::optional<winrt::hstring> text;
winrt::Microsoft::ReactNative::ReadArgs(args.CommandArgs(), eventCount, text, begin, end);
if (eventCount >= m_nativeEventCount) {
m_comingFromJS = true;
{
if (text.has_value()) {
DrawBlock db(*this);
UpdateText(winrt::to_string(text.value()));
}
SELCHANGE sc;
memset(&sc, 0, sizeof(sc));
sc.chrg.cpMin = static_cast<LONG>(begin);
sc.chrg.cpMax = static_cast<LONG>(end);
sc.seltyp = (begin == end) ? SEL_EMPTY : SEL_TEXT;
LRESULT res;
winrt::check_hresult(
m_textServices->TxSendMessage(EM_SETSEL, static_cast<WPARAM>(begin), static_cast<LPARAM>(end), &res));
}
m_comingFromJS = false;
}
}
}
WPARAM PointerPointToPointerWParam(const winrt::Microsoft::ReactNative::Composition::Input::PointerPoint &pp) noexcept {
WPARAM wParam = pp.PointerId();
wParam |= (POINTER_MESSAGE_FLAG_NEW << 16);
auto ppp = pp.Properties();
if (ppp.IsInRange()) {
wParam |= (POINTER_MESSAGE_FLAG_INRANGE << 16);
}
if (pp.IsInContact()) {
wParam |= (POINTER_MESSAGE_FLAG_INCONTACT << 16);
}
if (ppp.IsLeftButtonPressed()) {
wParam |= (POINTER_MESSAGE_FLAG_FIRSTBUTTON << 16);
}
if (ppp.IsRightButtonPressed()) {
wParam |= (POINTER_MESSAGE_FLAG_SECONDBUTTON << 16);
}
if (ppp.IsMiddleButtonPressed()) {
wParam |= (POINTER_MESSAGE_FLAG_THIRDBUTTON << 16);
}
if (ppp.IsXButton1Pressed()) {
wParam |= (POINTER_MESSAGE_FLAG_FOURTHBUTTON << 16);
}
if (ppp.IsXButton2Pressed()) {
wParam |= (POINTER_MESSAGE_FLAG_FIFTHBUTTON << 16);
}
if (ppp.IsPrimary()) {
wParam |= (POINTER_MESSAGE_FLAG_PRIMARY << 16);
}
if (ppp.TouchConfidence()) {
wParam |= (POINTER_MESSAGE_FLAG_CONFIDENCE << 16);
}
if (ppp.IsCanceled()) {
wParam |= (POINTER_MESSAGE_FLAG_CANCELED << 16);
}
return wParam;
}
WPARAM PointerRoutedEventArgsToMouseWParam(
const winrt::Microsoft::ReactNative::Composition::Input::PointerRoutedEventArgs &args) noexcept {
WPARAM wParam = 0;
auto pp = args.GetCurrentPoint(-1);
auto keyModifiers = args.KeyModifiers();
if ((keyModifiers & winrt::Windows::System::VirtualKeyModifiers::Control) ==
winrt::Windows::System::VirtualKeyModifiers::Control) {
wParam |= MK_CONTROL;
}
if ((keyModifiers & winrt::Windows::System::VirtualKeyModifiers::Shift) ==
winrt::Windows::System::VirtualKeyModifiers::Shift) {
wParam |= MK_SHIFT;
}
auto ppp = pp.Properties();
if (ppp.IsLeftButtonPressed()) {
wParam |= MK_LBUTTON;
}
if (ppp.IsMiddleButtonPressed()) {
wParam |= MK_MBUTTON;
}
if (ppp.IsRightButtonPressed()) {
wParam |= MK_RBUTTON;
}
if (ppp.IsXButton1Pressed()) {
wParam |= MK_XBUTTON1;
}
if (ppp.IsXButton2Pressed()) {
wParam |= MK_XBUTTON2;
}
return wParam;
}
bool WindowsTextInputComponentView::IsDoubleClick() {
using namespace std::chrono;
auto now = steady_clock::now();
auto duration = duration_cast<milliseconds>(now - m_lastClickTime).count();
const int DOUBLE_CLICK_TIME_MS = ::GetDoubleClickTime();
m_lastClickTime = now;
return (duration < DOUBLE_CLICK_TIME_MS);
}
void WindowsTextInputComponentView::OnPointerPressed(
const winrt::Microsoft::ReactNative::Composition::Input::PointerRoutedEventArgs &args) noexcept {
UINT msg = 0;
LPARAM lParam = 0;
WPARAM wParam = 0;
auto pp = args.GetCurrentPoint(-1); // TODO use local coords?
auto position = pp.Position();
POINT ptContainer = {
static_cast<LONG>(position.X * m_layoutMetrics.pointScaleFactor),
static_cast<LONG>(position.Y * m_layoutMetrics.pointScaleFactor)};
lParam = static_cast<LPARAM>(POINTTOPOINTS(ptContainer));
if (pp.PointerDeviceType() == winrt::Microsoft::ReactNative::Composition::Input::PointerDeviceType::Mouse) {
switch (pp.Properties().PointerUpdateKind()) {
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::LeftButtonPressed:
if (IsDoubleClick()) {
msg = WM_LBUTTONDBLCLK;
} else {
msg = WM_LBUTTONDOWN;
}
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::MiddleButtonPressed:
msg = WM_MBUTTONDOWN;
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::RightButtonPressed:
msg = WM_RBUTTONDOWN;
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::XButton1Pressed:
msg = WM_XBUTTONDOWN;
wParam |= (XBUTTON1 << 16);
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::XButton2Pressed:
msg = WM_XBUTTONDOWN;
wParam |= (XBUTTON2 << 16);
break;
}
wParam = PointerRoutedEventArgsToMouseWParam(args);
} else {
msg = WM_POINTERDOWN;
wParam = PointerPointToPointerWParam(pp);
}
if (m_textServices && msg) {
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(msg, static_cast<WPARAM>(wParam), static_cast<LPARAM>(lParam), &lresult);
args.Handled(hr != S_FALSE);
}
// Emits the OnPressIn event
if (m_eventEmitter && !m_comingFromJS) {
auto emitter = std::static_pointer_cast<const facebook::react::WindowsTextInputEventEmitter>(m_eventEmitter);
float offsetX = position.X - m_layoutMetrics.frame.origin.x;
float offsetY = position.Y - m_layoutMetrics.frame.origin.y;
facebook::react::GestureResponderEvent pressInArgs;
pressInArgs.target = m_tag;
pressInArgs.pagePoint = {position.X, position.Y};
pressInArgs.offsetPoint = {offsetX, offsetY}; //{LocationX,LocationY}
pressInArgs.timestamp = static_cast<double>(pp.Timestamp()) / 1000.0;
pressInArgs.identifier = pp.PointerId();
emitter->onPressIn(pressInArgs);
}
}
void WindowsTextInputComponentView::OnPointerReleased(
const winrt::Microsoft::ReactNative::Composition::Input::PointerRoutedEventArgs &args) noexcept {
UINT msg = 0;
LPARAM lParam = 0;
WPARAM wParam = 0;
auto pp = args.GetCurrentPoint(-1);
auto position = pp.Position();
POINT ptContainer = {
static_cast<LONG>(position.X * m_layoutMetrics.pointScaleFactor),
static_cast<LONG>(position.Y * m_layoutMetrics.pointScaleFactor)};
lParam = static_cast<LPARAM>(POINTTOPOINTS(ptContainer));
if (pp.PointerDeviceType() == winrt::Microsoft::ReactNative::Composition::Input::PointerDeviceType::Mouse) {
switch (pp.Properties().PointerUpdateKind()) {
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::LeftButtonReleased:
msg = WM_LBUTTONUP;
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::MiddleButtonReleased:
msg = WM_MBUTTONUP;
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::RightButtonReleased:
msg = WM_RBUTTONUP;
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::XButton1Released:
msg = WM_XBUTTONUP;
wParam |= (XBUTTON1 << 16);
break;
case winrt::Microsoft::ReactNative::Composition::Input::PointerUpdateKind::XButton2Released:
msg = WM_XBUTTONUP;
wParam |= (XBUTTON2 << 16);
break;
}
wParam = PointerRoutedEventArgsToMouseWParam(args);
} else {
msg = WM_POINTERUP;
wParam = PointerPointToPointerWParam(pp);
}
if (m_textServices && msg) {
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(msg, static_cast<WPARAM>(wParam), static_cast<LPARAM>(lParam), &lresult);
args.Handled(hr != S_FALSE);
}
// Emits the OnPressOut event
if (m_eventEmitter && !m_comingFromJS) {
auto emitter = std::static_pointer_cast<const facebook::react::WindowsTextInputEventEmitter>(m_eventEmitter);
float offsetX = position.X - m_layoutMetrics.frame.origin.x;
float offsetY = position.Y - m_layoutMetrics.frame.origin.y;
facebook::react::GestureResponderEvent pressOutArgs;
pressOutArgs.target = m_tag;
pressOutArgs.pagePoint = {position.X, position.Y};
pressOutArgs.offsetPoint = {offsetX, offsetY};
pressOutArgs.timestamp = static_cast<double>(pp.Timestamp()) / 1000.0;
pressOutArgs.identifier = pp.PointerId();
emitter->onPressOut(pressOutArgs);
}
}
void WindowsTextInputComponentView::OnPointerMoved(
const winrt::Microsoft::ReactNative::Composition::Input::PointerRoutedEventArgs &args) noexcept {
UINT msg = 0;
LPARAM lParam = 0;
WPARAM wParam = 0;
auto pp = args.GetCurrentPoint(-1);
auto position = pp.Position();
POINT ptContainer = {
static_cast<LONG>(position.X * m_layoutMetrics.pointScaleFactor),
static_cast<LONG>(position.Y * m_layoutMetrics.pointScaleFactor)};
lParam = static_cast<LPARAM>(POINTTOPOINTS(ptContainer));
if (pp.PointerDeviceType() == winrt::Microsoft::ReactNative::Composition::Input::PointerDeviceType::Mouse) {
msg = WM_MOUSEMOVE;
wParam = PointerRoutedEventArgsToMouseWParam(args);
} else {
msg = WM_POINTERUPDATE;
wParam = PointerPointToPointerWParam(pp);
}
if (m_textServices) {
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(msg, static_cast<WPARAM>(wParam), static_cast<LPARAM>(lParam), &lresult);
args.Handled(hr != S_FALSE);
}
m_textServices->OnTxSetCursor(
DVASPECT_CONTENT, -1, nullptr, nullptr, nullptr, nullptr, nullptr, ptContainer.x, ptContainer.y);
}
void WindowsTextInputComponentView::OnKeyDown(
const winrt::Microsoft::ReactNative::Composition::Input::KeyRoutedEventArgs &args) noexcept {
// Do not forward tab keys into the TextInput, since we want that to do the tab loop instead. This aligns with WinUI
// behavior We do forward Ctrl+Tab to the textinput.
if (args.Key() != winrt::Windows::System::VirtualKey::Tab ||
(args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Control) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) == winrt::Microsoft::UI::Input::VirtualKeyStates::Down) {
WPARAM wParam = static_cast<WPARAM>(args.Key());
LPARAM lParam = 0;
lParam = args.KeyStatus().RepeatCount; // bits 0-15
lParam |= args.KeyStatus().ScanCode << 16; // bits 16-23
if (args.KeyStatus().IsExtendedKey)
lParam |= 0x01000000; // bit 24
// if sysKey - bit 29 = 1, otherwise 0
if (args.KeyStatus().WasKeyDown)
lParam |= 0x40000000; // bit 30
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(
args.KeyStatus().IsMenuKeyDown ? WM_SYSKEYDOWN : WM_KEYDOWN, wParam, lParam, &lresult);
if (hr == S_OK) { // S_FALSE or S_MSG_KEY_IGNORED means RichEdit didn't handle the key
args.Handled(true);
}
}
Super::OnKeyDown(args);
}
void WindowsTextInputComponentView::OnKeyUp(
const winrt::Microsoft::ReactNative::Composition::Input::KeyRoutedEventArgs &args) noexcept {
// Do not forward tab keys into the TextInput, since we want that to do the tab loop instead. This aligns with WinUI
// behavior We do forward Ctrl+Tab to the textinput.
if (args.Key() != winrt::Windows::System::VirtualKey::Tab ||
(args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Control) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) == winrt::Microsoft::UI::Input::VirtualKeyStates::Down) {
WPARAM wParam = static_cast<WPARAM>(args.Key());
LPARAM lParam = 1;
lParam = args.KeyStatus().RepeatCount; // bits 0-15
lParam |= args.KeyStatus().ScanCode << 16; // bits 16-23
if (args.KeyStatus().IsExtendedKey)
lParam |= 0x01000000; // bit 24
// if sysKey - bit 29 = 1, otherwise 0
if (args.KeyStatus().WasKeyDown)
lParam |= 0x40000000; // bit 30
lParam |= 0x80000000; // bit 31 always 1 for WM_KEYUP
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(
args.KeyStatus().IsMenuKeyDown ? WM_SYSKEYUP : WM_KEYUP, wParam, lParam, &lresult);
if (hr == S_OK) { // S_FALSE or S_MSG_KEY_IGNORED means RichEdit didn't handle the key
args.Handled(true);
}
}
Super::OnKeyUp(args);
}
bool WindowsTextInputComponentView::ShouldSubmit(
const winrt::Microsoft::ReactNative::Composition::Input::CharacterReceivedRoutedEventArgs &args) noexcept {
bool shouldSubmit = true;
if (shouldSubmit) {
if (!m_multiline && m_submitKeyEvents.size() == 0) {
// If no 'submitKeyEvents' are supplied, use the default behavior for single-line TextInput
shouldSubmit = args.KeyCode() == '\r';
} else if (m_submitKeyEvents.size() > 0) {
auto submitKeyEvent = m_submitKeyEvents.at(0);
// If 'submitKeyEvents' are supplied, use them to determine whether to emit onSubmitEditing' for either
// single-line or multi-line TextInput
if (args.KeyCode() == '\r') {
bool shiftDown = (args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Shift) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) ==
winrt::Microsoft::UI::Input::VirtualKeyStates::Down;
bool ctrlDown = (args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Control) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) ==
winrt::Microsoft::UI::Input::VirtualKeyStates::Down;
bool altDown = (args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Control) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) ==
winrt::Microsoft::UI::Input::VirtualKeyStates::Down;
bool metaDown = (args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::LeftWindows) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) ==
winrt::Microsoft::UI::Input::VirtualKeyStates::Down ||
(args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::RightWindows) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) ==
winrt::Microsoft::UI::Input::VirtualKeyStates::Down;
return (submitKeyEvent.shiftKey && shiftDown) || (submitKeyEvent.ctrlKey && ctrlDown) ||
(submitKeyEvent.altKey && altDown) || (submitKeyEvent.metaKey && metaDown) ||
(!submitKeyEvent.shiftKey && !submitKeyEvent.altKey && !submitKeyEvent.metaKey && !submitKeyEvent.altKey &&
!shiftDown && !ctrlDown && !altDown && !metaDown);
} else {
shouldSubmit = false;
}
} else {
shouldSubmit = false;
}
}
return shouldSubmit;
}
void WindowsTextInputComponentView::OnCharacterReceived(
const winrt::Microsoft::ReactNative::Composition::Input::CharacterReceivedRoutedEventArgs &args) noexcept {
// Do not forward tab keys into the TextInput, since we want that to do the tab loop instead. This aligns with WinUI
// behavior We do forward Ctrl+Tab to the textinput.
if ((args.KeyCode() == '\t') &&
((args.KeyboardSource().GetKeyState(winrt::Windows::System::VirtualKey::Control) &
winrt::Microsoft::UI::Input::VirtualKeyStates::Down) != winrt::Microsoft::UI::Input::VirtualKeyStates::Down)) {
return;
}
// Logic for submit events
if (ShouldSubmit(args)) {
// call onSubmitEditing event
if (m_eventEmitter && !m_comingFromJS) {
auto emitter = std::static_pointer_cast<const facebook::react::WindowsTextInputEventEmitter>(m_eventEmitter);
facebook::react::WindowsTextInputEventEmitter::OnSubmitEditing onSubmitEditingArgs;
onSubmitEditingArgs.text = GetTextFromRichEdit();
onSubmitEditingArgs.eventCount = ++m_nativeEventCount;
emitter->onSubmitEditing(onSubmitEditingArgs);
}
if (m_clearTextOnSubmit) {
// clear text from RichEdit
m_textServices->TxSetText(L"");
}
return;
}
// convert keyCode to std::string
wchar_t key[2] = L" ";
key[0] = static_cast<wchar_t>(args.KeyCode());
std::string keyString = ::Microsoft::Common::Unicode::Utf16ToUtf8(key, 1);
// Call onKeyPress event
auto emitter = std::static_pointer_cast<const facebook::react::WindowsTextInputEventEmitter>(m_eventEmitter);
facebook::react::WindowsTextInputEventEmitter::OnKeyPress onKeyPressArgs;
if (keyString.compare("\r") == 0) {
onKeyPressArgs.key = "Enter";
} else if (keyString.compare("\b") == 0) {
onKeyPressArgs.key = "Backspace";
} else {
onKeyPressArgs.key = keyString;
}
emitter->onKeyPress(onKeyPressArgs);
WPARAM wParam = static_cast<WPARAM>(args.KeyCode());
LPARAM lParam = 0;
lParam = args.KeyStatus().RepeatCount; // bits 0-15
lParam |= args.KeyStatus().ScanCode << 16; // bits 16-23
if (args.KeyStatus().IsExtendedKey)
lParam |= 0x01000000; // bit 24
// bit 25-28 reserved.
if (args.KeyStatus().IsMenuKeyDown)
lParam |= 0x20000000; // bit 29
// if sysKey - bit 29 = 1, otherwise 0
if (args.KeyStatus().WasKeyDown)
lParam |= 0x40000000; // bit 30
if (args.KeyStatus().IsKeyReleased)
lParam |= 0x80000000; // bit 31
LRESULT lresult;
DrawBlock db(*this);
auto hr = m_textServices->TxSendMessage(WM_CHAR, wParam, lParam, &lresult);
if (hr >= 0) {
args.Handled(true);
}
}
void WindowsTextInputComponentView::MountChildComponentView(
const winrt::Microsoft::ReactNative::ComponentView &childComponentView,
uint32_t index) noexcept {
assert(false);
base_type::MountChildComponentView(childComponentView, index);
}
void WindowsTextInputComponentView::UnmountChildComponentView(
const winrt::Microsoft::ReactNative::ComponentView &childComponentView,
uint32_t index) noexcept {
assert(false);
base_type::UnmountChildComponentView(childComponentView, index);
}
void WindowsTextInputComponentView::onLostFocus(
const winrt::Microsoft::ReactNative::Composition::Input::RoutedEventArgs &args) noexcept {
m_hasFocus = false;
Super::onLostFocus(args);
if (m_textServices) {
LRESULT lresult;
DrawBlock db(*this);
m_textServices->TxSendMessage(WM_KILLFOCUS, 0, 0, &lresult);