-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
ScintillaWin.cxx
3904 lines (3415 loc) · 119 KB
/
ScintillaWin.cxx
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
// Scintilla source code edit control
/** @file ScintillaWin.cxx
** Windows specific subclass of ScintillaBase.
**/
// Copyright 1998-2003 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <cstddef>
#include <cstdlib>
#include <cstdint>
#include <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <climits>
#include <stdexcept>
#include <new>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <set>
#include <optional>
#include <algorithm>
#include <memory>
#include <chrono>
#include <mutex>
// Want to use std::min and std::max so don't want Windows.h version of min and max
#if !defined(NOMINMAX)
#define NOMINMAX
#endif
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0A00
#undef WINVER
#define WINVER 0x0A00
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include <windowsx.h>
#include <zmouse.h>
#include <ole2.h>
#if !defined(DISABLE_D2D)
#define USE_D2D 1
#endif
#if defined(USE_D2D)
#include <d2d1.h>
#include <dwrite.h>
#endif
#include "ScintillaTypes.h"
#include "ScintillaMessages.h"
#include "ScintillaStructures.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Debugging.h"
#include "Geometry.h"
#include "Platform.h"
#include "CharacterCategoryMap.h"
#include "Position.h"
#include "UniqueString.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#include "CellBuffer.h"
#include "CallTip.h"
#include "KeyMap.h"
#include "Indicator.h"
#include "LineMarker.h"
#include "Style.h"
#include "ViewStyle.h"
#include "CharClassify.h"
#include "Decoration.h"
#include "CaseFolder.h"
#include "Document.h"
#include "CaseConvert.h"
#include "UniConversion.h"
#include "Selection.h"
#include "PositionCache.h"
#include "EditModel.h"
#include "MarginView.h"
#include "EditView.h"
#include "Editor.h"
#include "ElapsedPeriod.h"
#include "AutoComplete.h"
#include "ScintillaBase.h"
#include "WinTypes.h"
#include "PlatWin.h"
#include "HanjaDic.h"
#include "ScintillaWin.h"
#include "BoostRegexSearch.h"
//needed for gcc builds
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES 104
#endif
#ifndef WM_UNICHAR
#define WM_UNICHAR 0x0109
#endif
#ifndef WM_DPICHANGED
#define WM_DPICHANGED 0x02E0
#endif
#ifndef WM_DPICHANGED_AFTERPARENT
#define WM_DPICHANGED_AFTERPARENT 0x02E3
#endif
#ifndef UNICODE_NOCHAR
#define UNICODE_NOCHAR 0xFFFF
#endif
#ifndef IS_HIGH_SURROGATE
#define IS_HIGH_SURROGATE(x) ((x) >= SURROGATE_LEAD_FIRST && (x) <= SURROGATE_LEAD_LAST)
#endif
#ifndef IS_LOW_SURROGATE
#define IS_LOW_SURROGATE(x) ((x) >= SURROGATE_TRAIL_FIRST && (x) <= SURROGATE_TRAIL_LAST)
#endif
#ifndef MK_ALT
#define MK_ALT 32
#endif
namespace {
// Two idle messages SC_WIN_IDLE and SC_WORK_IDLE.
// SC_WIN_IDLE is low priority so should occur after the next WM_PAINT
// It is for lengthy actions like wrapping and background styling
constexpr UINT SC_WIN_IDLE = 5001;
// SC_WORK_IDLE is high priority and should occur before the next WM_PAINT
// It is for shorter actions like restyling the text just inserted
// and delivering SCN_UPDATEUI
constexpr UINT SC_WORK_IDLE = 5002;
constexpr int IndicatorInput = static_cast<int>(Scintilla::IndicatorNumbers::Ime);
constexpr int IndicatorTarget = IndicatorInput + 1;
constexpr int IndicatorConverted = IndicatorInput + 2;
constexpr int IndicatorUnknown = IndicatorInput + 3;
typedef UINT_PTR (WINAPI *SetCoalescableTimerSig)(HWND hwnd, UINT_PTR nIDEvent,
UINT uElapse, TIMERPROC lpTimerFunc, ULONG uToleranceDelay);
}
// GCC has trouble with the standard COM ABI so do it the old C way with explicit vtables.
using namespace Scintilla;
using namespace Scintilla::Internal;
namespace {
const TCHAR callClassName[] = TEXT("CallTip");
void SetWindowID(HWND hWnd, int identifier) noexcept {
::SetWindowLongPtr(hWnd, GWLP_ID, identifier);
}
constexpr POINT POINTFromLParam(sptr_t lParam) noexcept {
return { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
};
constexpr Point PointFromLParam(sptr_t lpoint) noexcept {
return Point::FromInts(GET_X_LPARAM(lpoint), GET_Y_LPARAM(lpoint));
}
bool KeyboardIsKeyDown(int key) noexcept {
return (::GetKeyState(key) & 0x80000000) != 0;
}
// Bit 24 is the extended keyboard flag and the numeric keypad is non-extended
constexpr sptr_t extendedKeyboard = 1 << 24;
constexpr bool KeyboardIsNumericKeypadFunction(uptr_t wParam, sptr_t lParam) {
if ((lParam & extendedKeyboard) != 0) {
// Not from the numeric keypad
return false;
}
switch (wParam) {
case VK_INSERT: // 0
case VK_END: // 1
case VK_DOWN: // 2
case VK_NEXT: // 3
case VK_LEFT: // 4
case VK_CLEAR: // 5
case VK_RIGHT: // 6
case VK_HOME: // 7
case VK_UP: // 8
case VK_PRIOR: // 9
return true;
default:
return false;
}
}
/**
*/
class FormatEnumerator final : public IEnumFORMATETC {
public:
ULONG ref;
ULONG pos;
std::vector<CLIPFORMAT> formats;
FormatEnumerator(ULONG pos_, const CLIPFORMAT formats_[], size_t formatsLen_);
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv) override;
STDMETHODIMP_(ULONG)AddRef() override;
STDMETHODIMP_(ULONG)Release() override;
// IEnumFORMATETC
STDMETHODIMP Next(ULONG celt, FORMATETC *rgelt, ULONG *pceltFetched) override;
STDMETHODIMP Skip(ULONG celt) override;
STDMETHODIMP Reset() override;
STDMETHODIMP Clone(IEnumFORMATETC **ppenum) override;
};
/**
*/
class DropSource final : public IDropSource {
public:
ScintillaWin *sci = nullptr;
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv) override;
STDMETHODIMP_(ULONG)AddRef() override;
STDMETHODIMP_(ULONG)Release() override;
// IDropSource
STDMETHODIMP QueryContinueDrag(BOOL fEsc, DWORD grfKeyState) override;
STDMETHODIMP GiveFeedback(DWORD) override;
};
/**
*/
class DataObject final : public IDataObject {
public:
ScintillaWin *sci = nullptr;
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv) override;
STDMETHODIMP_(ULONG)AddRef() override;
STDMETHODIMP_(ULONG)Release() override;
// IDataObject
STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM) override;
STDMETHODIMP GetDataHere(FORMATETC *, STGMEDIUM *) override;
STDMETHODIMP QueryGetData(FORMATETC *pFE) override;
STDMETHODIMP GetCanonicalFormatEtc(FORMATETC *, FORMATETC *pFEOut) override;
STDMETHODIMP SetData(FORMATETC *, STGMEDIUM *, BOOL) override;
STDMETHODIMP EnumFormatEtc(DWORD dwDirection, IEnumFORMATETC **ppEnum) override;
STDMETHODIMP DAdvise(FORMATETC *, DWORD, IAdviseSink *, PDWORD) override;
STDMETHODIMP DUnadvise(DWORD) override;
STDMETHODIMP EnumDAdvise(IEnumSTATDATA **) override;
};
/**
*/
class DropTarget final : public IDropTarget {
public:
ScintillaWin *sci = nullptr;
// IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv) override;
STDMETHODIMP_(ULONG)AddRef() override;
STDMETHODIMP_(ULONG)Release() override;
// IDropTarget
STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) override;
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) override;
STDMETHODIMP DragLeave() override;
STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState, POINTL pt, PDWORD pdwEffect) override;
};
class IMContext {
HWND hwnd;
public:
HIMC hIMC;
IMContext(HWND hwnd_) noexcept :
hwnd(hwnd_), hIMC(::ImmGetContext(hwnd_)) {
}
// Deleted so IMContext objects can not be copied.
IMContext(const IMContext &) = delete;
IMContext(IMContext &&) = delete;
IMContext &operator=(const IMContext &) = delete;
IMContext &operator=(IMContext &&) = delete;
~IMContext() {
if (hIMC)
::ImmReleaseContext(hwnd, hIMC);
}
unsigned int GetImeCaretPos() const noexcept {
return ImmGetCompositionStringW(hIMC, GCS_CURSORPOS, nullptr, 0);
}
std::vector<BYTE> GetImeAttributes() {
const int attrLen = ::ImmGetCompositionStringW(hIMC, GCS_COMPATTR, nullptr, 0);
std::vector<BYTE> attr(attrLen, 0);
::ImmGetCompositionStringW(hIMC, GCS_COMPATTR, &attr[0], static_cast<DWORD>(attr.size()));
return attr;
}
LONG GetCompositionStringLength(DWORD dwIndex) const noexcept {
const LONG byteLen = ::ImmGetCompositionStringW(hIMC, dwIndex, nullptr, 0);
return byteLen / sizeof(wchar_t);
}
std::wstring GetCompositionString(DWORD dwIndex) {
const LONG byteLen = ::ImmGetCompositionStringW(hIMC, dwIndex, nullptr, 0);
std::wstring wcs(byteLen / 2, 0);
::ImmGetCompositionStringW(hIMC, dwIndex, &wcs[0], byteLen);
return wcs;
}
};
class GlobalMemory;
class ReverseArrowCursor {
UINT dpi = USER_DEFAULT_SCREEN_DPI;
UINT cursorBaseSize = defaultCursorBaseSize;
HCURSOR cursor {};
public:
ReverseArrowCursor() noexcept {}
// Deleted so ReverseArrowCursor objects can not be copied.
ReverseArrowCursor(const ReverseArrowCursor &) = delete;
ReverseArrowCursor(ReverseArrowCursor &&) = delete;
ReverseArrowCursor &operator=(const ReverseArrowCursor &) = delete;
ReverseArrowCursor &operator=(ReverseArrowCursor &&) = delete;
~ReverseArrowCursor() {
if (cursor) {
::DestroyCursor(cursor);
}
}
HCURSOR Load(UINT dpi_, UINT cursorBaseSize_) noexcept {
if (cursor) {
if (dpi == dpi_ && cursorBaseSize == cursorBaseSize_) {
return cursor;
}
::DestroyCursor(cursor);
}
dpi = dpi_;
cursorBaseSize = cursorBaseSize_;
cursor = LoadReverseArrowCursor(dpi_, cursorBaseSize_);
return cursor ? cursor : ::LoadCursor({}, IDC_ARROW);
}
};
struct HorizontalScrollRange {
int pageWidth;
int documentWidth;
};
CLIPFORMAT RegisterClipboardType(LPCWSTR lpszFormat) noexcept {
// Registered clipboard format values are 0xC000 through 0xFFFF.
// RegisterClipboardFormatW returns 32-bit unsigned and CLIPFORMAT is 16-bit
// unsigned so choose the low 16-bits with &.
return ::RegisterClipboardFormatW(lpszFormat) & 0xFFFF;
}
}
namespace Scintilla::Internal {
/**
*/
class ScintillaWin :
public ScintillaBase {
bool lastKeyDownConsumed;
wchar_t lastHighSurrogateChar;
bool capturedMouse;
bool trackedMouseLeave;
BOOL typingWithoutCursor;
bool cursorIsHidden;
SetCoalescableTimerSig SetCoalescableTimerFn;
unsigned int linesPerScroll; ///< Intellimouse support
unsigned int charsPerScroll; ///< Intellimouse support
MouseWheelDelta verticalWheelDelta;
MouseWheelDelta horizontalWheelDelta;
UINT dpi = USER_DEFAULT_SCREEN_DPI;
UINT cursorBaseSize = defaultCursorBaseSize;
ReverseArrowCursor reverseArrowCursor;
PRectangle rectangleClient;
HRGN hRgnUpdate;
bool hasOKText;
CLIPFORMAT cfColumnSelect;
CLIPFORMAT cfBorlandIDEBlockType;
CLIPFORMAT cfLineSelect;
CLIPFORMAT cfVSLineTag;
HRESULT hrOle;
DropSource ds;
DataObject dob;
DropTarget dt;
static HINSTANCE hInstance;
static ATOM scintillaClassAtom;
static ATOM callClassAtom;
float deviceScaleFactor = 1.f;
int GetFirstIntegralMultipleDeviceScaleFactor() const noexcept {
return static_cast<int>(std::ceil(deviceScaleFactor));
}
#if defined(USE_D2D)
ID2D1RenderTarget *pRenderTarget;
bool renderTargetValid;
// rendering parameters for current monitor
HMONITOR hCurrentMonitor;
std::shared_ptr<RenderingParams> renderingParams;
#endif
explicit ScintillaWin(HWND hwnd);
// Deleted so ScintillaWin objects can not be copied.
ScintillaWin(const ScintillaWin &) = delete;
ScintillaWin(ScintillaWin &&) = delete;
ScintillaWin &operator=(const ScintillaWin &) = delete;
ScintillaWin &operator=(ScintillaWin &&) = delete;
// ~ScintillaWin() in public section
void Finalise() override;
#if defined(USE_D2D)
bool UpdateRenderingParams(bool force) noexcept;
void EnsureRenderTarget(HDC hdc);
#endif
void DropRenderTarget() noexcept;
HWND MainHWND() const noexcept;
static sptr_t DirectFunction(
sptr_t ptr, UINT iMessage, uptr_t wParam, sptr_t lParam);
static sptr_t DirectStatusFunction(
sptr_t ptr, UINT iMessage, uptr_t wParam, sptr_t lParam, int *pStatus);
static LRESULT PASCAL SWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
static LRESULT PASCAL CTWndProc(
HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam);
enum : UINT_PTR { invalidTimerID, standardTimerID, idleTimerID, fineTimerStart };
void DisplayCursor(Window::Cursor c) override;
bool DragThreshold(Point ptStart, Point ptNow) override;
void StartDrag() override;
static KeyMod MouseModifiers(uptr_t wParam) noexcept;
Sci::Position TargetAsUTF8(char *text) const;
Sci::Position EncodedFromUTF8(const char *utf8, char *encoded) const;
void SetRenderingParams(Surface *psurf) const;
bool PaintDC(HDC hdc);
sptr_t WndPaint();
// DBCS
void ImeStartComposition();
void ImeEndComposition();
LRESULT ImeOnReconvert(LPARAM lParam);
LRESULT ImeOnDocumentFeed(LPARAM lParam) const;
sptr_t HandleCompositionWindowed(uptr_t wParam, sptr_t lParam);
sptr_t HandleCompositionInline(uptr_t wParam, sptr_t lParam);
static bool KoreanIME() noexcept;
void MoveImeCarets(Sci::Position offset) noexcept;
void DrawImeIndicator(int indicator, Sci::Position len);
void SetCandidateWindowPos();
void SelectionToHangul();
void EscapeHanja();
void ToggleHanja();
void AddWString(std::wstring_view wsv, CharacterSource charSource);
UINT CodePageOfDocument() const noexcept;
bool ValidCodePage(int codePage) const override;
std::string UTF8FromEncoded(std::string_view encoded) const override;
std::string EncodedFromUTF8(std::string_view utf8) const override;
std::string EncodeWString(std::wstring_view wsv);
sptr_t DefWndProc(Message iMessage, uptr_t wParam, sptr_t lParam) override;
void IdleWork() override;
void QueueIdleWork(WorkItems items, Sci::Position upTo) override;
bool SetIdle(bool on) override;
UINT_PTR timers[static_cast<int>(TickReason::dwell)+1] {};
bool FineTickerRunning(TickReason reason) override;
void FineTickerStart(TickReason reason, int millis, int tolerance) override;
void FineTickerCancel(TickReason reason) override;
void SetMouseCapture(bool on) override;
bool HaveMouseCapture() override;
void SetTrackMouseLeaveEvent(bool on) noexcept;
void HideCursorIfPreferred() noexcept;
void UpdateBaseElements() override;
bool PaintContains(PRectangle rc) override;
void ScrollText(Sci::Line linesToMove) override;
void NotifyCaretMove() override;
void UpdateSystemCaret() override;
void SetVerticalScrollPos() override;
void SetHorizontalScrollPos() override;
void HorizontalScrollToClamped(int xPos);
HorizontalScrollRange GetHorizontalScrollRange() const;
bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) override;
void NotifyChange() override;
void NotifyFocus(bool focus) override;
void SetCtrlID(int identifier) override;
int GetCtrlID() override;
void NotifyParent(NotificationData scn) override;
void NotifyDoubleClick(Point pt, KeyMod modifiers) override;
std::unique_ptr<CaseFolder> CaseFolderForEncoding() override;
std::string CaseMapString(const std::string &s, CaseMapping caseMapping) override;
void Copy() override;
bool CanPaste() override;
void Paste() override;
void CreateCallTipWindow(PRectangle rc) override;
void AddToPopUp(const char *label, int cmd = 0, bool enabled = true) override;
void ClaimSelection() override;
void GetMouseParameters() noexcept;
void CopyToGlobal(GlobalMemory &gmUnicode, const SelectionText &selectedText);
void CopyToClipboard(const SelectionText &selectedText) override;
void ScrollMessage(WPARAM wParam);
void HorizontalScrollMessage(WPARAM wParam);
void FullPaint();
void FullPaintDC(HDC hdc);
bool IsCompatibleDC(HDC hOtherDC) noexcept;
DWORD EffectFromState(DWORD grfKeyState) const noexcept;
bool IsVisible() const noexcept;
int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) noexcept;
bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi) noexcept;
bool ChangeScrollRange(int nBar, int nMin, int nMax, UINT nPage) noexcept;
void ChangeScrollPos(int barType, Sci::Position pos);
sptr_t GetTextLength();
sptr_t GetText(uptr_t wParam, sptr_t lParam);
Window::Cursor ContextCursor(Point pt);
sptr_t ShowContextMenu(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
PRectangle GetClientRectangle() const override;
void SizeWindow();
sptr_t MouseMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t KeyMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t FocusMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t IMEMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t EditMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t IdleMessage(unsigned int iMessage, uptr_t wParam, sptr_t lParam);
sptr_t SciMessage(Message iMessage, uptr_t wParam, sptr_t lParam);
public:
~ScintillaWin() override;
// Public for benefit of Scintilla_DirectFunction
sptr_t WndProc(Message iMessage, uptr_t wParam, sptr_t lParam) override;
/// Implement IUnknown
STDMETHODIMP QueryInterface(REFIID riid, PVOID *ppv);
STDMETHODIMP_(ULONG)AddRef();
STDMETHODIMP_(ULONG)Release();
/// Implement IDropTarget
STDMETHODIMP DragEnter(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragOver(DWORD grfKeyState, POINTL pt, PDWORD pdwEffect);
STDMETHODIMP DragLeave();
STDMETHODIMP Drop(LPDATAOBJECT pIDataSource, DWORD grfKeyState,
POINTL pt, PDWORD pdwEffect);
/// Implement important part of IDataObject
STDMETHODIMP GetData(FORMATETC *pFEIn, STGMEDIUM *pSTM);
static void Prepare() noexcept;
static bool Register(HINSTANCE hInstance_) noexcept;
static bool Unregister() noexcept;
bool DragIsRectangularOK(CLIPFORMAT fmt) const noexcept {
return drag.rectangular && (fmt == cfColumnSelect);
}
private:
// For use in creating a system caret
bool HasCaretSizeChanged() const noexcept;
BOOL CreateSystemCaret();
BOOL DestroySystemCaret() noexcept;
HBITMAP sysCaretBitmap;
int sysCaretWidth;
int sysCaretHeight;
bool styleIdleInQueue;
};
HINSTANCE ScintillaWin::hInstance {};
ATOM ScintillaWin::scintillaClassAtom = 0;
ATOM ScintillaWin::callClassAtom = 0;
ScintillaWin::ScintillaWin(HWND hwnd) {
lastKeyDownConsumed = false;
lastHighSurrogateChar = 0;
capturedMouse = false;
trackedMouseLeave = false;
typingWithoutCursor = false;
cursorIsHidden = false;
SetCoalescableTimerFn = nullptr;
linesPerScroll = 0;
charsPerScroll = 0;
dpi = DpiForWindow(hwnd);
hRgnUpdate = {};
hasOKText = false;
// There does not seem to be a real standard for indicating that the clipboard
// contains a rectangular selection, so copy Developer Studio and Borland Delphi.
cfColumnSelect = RegisterClipboardType(L"MSDEVColumnSelect");
cfBorlandIDEBlockType = RegisterClipboardType(L"Borland IDE Block Type");
// Likewise for line-copy (copies a full line when no text is selected)
cfLineSelect = RegisterClipboardType(L"MSDEVLineSelect");
cfVSLineTag = RegisterClipboardType(L"VisualStudioEditorOperationsLineCutCopyClipboardTag");
hrOle = E_FAIL;
wMain = hwnd;
dob.sci = this;
ds.sci = this;
dt.sci = this;
sysCaretBitmap = {};
sysCaretWidth = 0;
sysCaretHeight = 0;
styleIdleInQueue = false;
#if defined(USE_D2D)
pRenderTarget = nullptr;
renderTargetValid = true;
hCurrentMonitor = {};
#endif
caret.period = ::GetCaretBlinkTime();
if (caret.period < 0)
caret.period = 0;
// Initialize COM. If the app has already done this it will have
// no effect. If the app hasn't, we really shouldn't ask them to call
// it just so this internal feature works.
hrOle = ::OleInitialize(nullptr);
// Find SetCoalescableTimer which is only available from Windows 8+
HMODULE user32 = ::GetModuleHandleW(L"user32.dll");
SetCoalescableTimerFn = DLLFunction<SetCoalescableTimerSig>(user32, "SetCoalescableTimer");
vs.indicators[IndicatorUnknown] = Indicator(IndicatorStyle::Hidden, colourIME);
vs.indicators[IndicatorInput] = Indicator(IndicatorStyle::Dots, colourIME);
vs.indicators[IndicatorConverted] = Indicator(IndicatorStyle::CompositionThick, colourIME);
vs.indicators[IndicatorTarget] = Indicator(IndicatorStyle::StraightBox, colourIME);
}
ScintillaWin::~ScintillaWin() {
if (sysCaretBitmap) {
::DeleteObject(sysCaretBitmap);
sysCaretBitmap = {};
}
}
void ScintillaWin::Finalise() {
ScintillaBase::Finalise();
for (TickReason tr = TickReason::caret; tr <= TickReason::dwell;
tr = static_cast<TickReason>(static_cast<int>(tr) + 1)) {
FineTickerCancel(tr);
}
SetIdle(false);
DropRenderTarget();
::RevokeDragDrop(MainHWND());
if (SUCCEEDED(hrOle)) {
::OleUninitialize();
}
}
#if defined(USE_D2D)
bool ScintillaWin::UpdateRenderingParams(bool force) noexcept {
if (!renderingParams) {
try {
renderingParams = std::make_shared<RenderingParams>();
} catch (const std::bad_alloc &) {
return false;
}
}
const HWND hRootWnd = ::GetAncestor(MainHWND(), GA_ROOT);
const HMONITOR monitor = Internal::MonitorFromWindowHandleScaling(hRootWnd);
if (!force && monitor == hCurrentMonitor && renderingParams->defaultRenderingParams) {
return false;
}
IDWriteRenderingParams *monitorRenderingParams = nullptr;
IDWriteRenderingParams *customClearTypeRenderingParams = nullptr;
const HRESULT hr = pIDWriteFactory->CreateMonitorRenderingParams(monitor, &monitorRenderingParams);
UINT clearTypeContrast = 0;
if (SUCCEEDED(hr) && ::SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &clearTypeContrast, 0) != 0) {
if (clearTypeContrast >= 1000 && clearTypeContrast <= 2200) {
const FLOAT gamma = static_cast<FLOAT>(clearTypeContrast) / 1000.0f;
pIDWriteFactory->CreateCustomRenderingParams(gamma,
monitorRenderingParams->GetEnhancedContrast(),
monitorRenderingParams->GetClearTypeLevel(),
monitorRenderingParams->GetPixelGeometry(),
monitorRenderingParams->GetRenderingMode(),
&customClearTypeRenderingParams);
}
}
hCurrentMonitor = monitor;
deviceScaleFactor = Internal::GetDeviceScaleFactorWhenGdiScalingActive(hRootWnd);
renderingParams->defaultRenderingParams.reset(monitorRenderingParams);
renderingParams->customRenderingParams.reset(customClearTypeRenderingParams);
return true;
}
namespace {
D2D1_SIZE_U GetSizeUFromRect(const RECT &rc, const int scaleFactor) noexcept {
const long width = rc.right - rc.left;
const long height = rc.bottom - rc.top;
const UINT32 scaledWidth = width * scaleFactor;
const UINT32 scaledHeight = height * scaleFactor;
return D2D1::SizeU(scaledWidth, scaledHeight);
}
}
void ScintillaWin::EnsureRenderTarget(HDC hdc) {
if (!renderTargetValid) {
DropRenderTarget();
renderTargetValid = true;
}
if (!pRenderTarget) {
HWND hw = MainHWND();
RECT rc;
::GetClientRect(hw, &rc);
// Create a Direct2D render target.
D2D1_RENDER_TARGET_PROPERTIES drtp {};
drtp.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
drtp.usage = D2D1_RENDER_TARGET_USAGE_NONE;
drtp.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
if (technology == Technology::DirectWriteDC) {
drtp.dpiX = 96.f;
drtp.dpiY = 96.f;
// Explicit pixel format needed.
drtp.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM,
D2D1_ALPHA_MODE_IGNORE);
ID2D1DCRenderTarget *pDCRT = nullptr;
const HRESULT hr = pD2DFactory->CreateDCRenderTarget(&drtp, &pDCRT);
if (SUCCEEDED(hr)) {
pRenderTarget = pDCRT;
} else {
Platform::DebugPrintf("Failed CreateDCRenderTarget 0x%lx\n", hr);
pRenderTarget = nullptr;
}
} else {
const int integralDeviceScaleFactor = GetFirstIntegralMultipleDeviceScaleFactor();
drtp.dpiX = 96.f * integralDeviceScaleFactor;
drtp.dpiY = 96.f * integralDeviceScaleFactor;
drtp.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN,
D2D1_ALPHA_MODE_UNKNOWN);
D2D1_HWND_RENDER_TARGET_PROPERTIES dhrtp {};
dhrtp.hwnd = hw;
dhrtp.pixelSize = ::GetSizeUFromRect(rc, integralDeviceScaleFactor);
dhrtp.presentOptions = (technology == Technology::DirectWriteRetain) ?
D2D1_PRESENT_OPTIONS_RETAIN_CONTENTS : D2D1_PRESENT_OPTIONS_NONE;
ID2D1HwndRenderTarget *pHwndRenderTarget = nullptr;
const HRESULT hr = pD2DFactory->CreateHwndRenderTarget(drtp, dhrtp, &pHwndRenderTarget);
if (SUCCEEDED(hr)) {
pRenderTarget = pHwndRenderTarget;
} else {
Platform::DebugPrintf("Failed CreateHwndRenderTarget 0x%lx\n", hr);
pRenderTarget = nullptr;
}
}
// Pixmaps were created to be compatible with previous render target so
// need to be recreated.
DropGraphics();
}
if ((technology == Technology::DirectWriteDC) && pRenderTarget) {
RECT rcWindow;
::GetClientRect(MainHWND(), &rcWindow);
const HRESULT hr = static_cast<ID2D1DCRenderTarget*>(pRenderTarget)->BindDC(hdc, &rcWindow);
if (FAILED(hr)) {
Platform::DebugPrintf("BindDC failed 0x%lx\n", hr);
DropRenderTarget();
}
}
}
#endif
void ScintillaWin::DropRenderTarget() noexcept {
#if defined(USE_D2D)
ReleaseUnknown(pRenderTarget);
#endif
}
HWND ScintillaWin::MainHWND() const noexcept {
return HwndFromWindow(wMain);
}
void ScintillaWin::DisplayCursor(Window::Cursor c) {
if (cursorMode != CursorShape::Normal) {
c = static_cast<Window::Cursor>(cursorMode);
}
if (c == Window::Cursor::reverseArrow) {
::SetCursor(reverseArrowCursor.Load(static_cast<UINT>(dpi * deviceScaleFactor), cursorBaseSize));
} else {
wMain.SetCursor(c);
}
}
bool ScintillaWin::DragThreshold(Point ptStart, Point ptNow) {
const Point ptDifference = ptStart - ptNow;
const XYPOSITION xMove = std::trunc(std::abs(ptDifference.x));
const XYPOSITION yMove = std::trunc(std::abs(ptDifference.y));
return (xMove > SystemMetricsForDpi(SM_CXDRAG, dpi)) ||
(yMove > SystemMetricsForDpi(SM_CYDRAG, dpi));
}
void ScintillaWin::StartDrag() {
inDragDrop = DragDrop::dragging;
DWORD dwEffect = 0;
dropWentOutside = true;
IDataObject *pDataObject = &dob;
IDropSource *pDropSource = &ds;
//Platform::DebugPrintf("About to DoDragDrop %x %x\n", pDataObject, pDropSource);
const HRESULT hr = ::DoDragDrop(
pDataObject,
pDropSource,
DROPEFFECT_COPY | DROPEFFECT_MOVE, &dwEffect);
//Platform::DebugPrintf("DoDragDrop = %x\n", hr);
if (SUCCEEDED(hr)) {
if ((hr == DRAGDROP_S_DROP) && (dwEffect == DROPEFFECT_MOVE) && dropWentOutside) {
// Remove dragged out text
ClearSelection();
}
}
inDragDrop = DragDrop::none;
SetDragPosition(SelectionPosition(Sci::invalidPosition));
}
KeyMod ScintillaWin::MouseModifiers(uptr_t wParam) noexcept {
return ModifierFlags(
(wParam & MK_SHIFT) != 0,
(wParam & MK_CONTROL) != 0,
KeyboardIsKeyDown(VK_MENU));
}
}
namespace {
int InputCodePage() noexcept {
HKL inputLocale = ::GetKeyboardLayout(0);
const LANGID inputLang = LOWORD(inputLocale);
char sCodePage[10];
const int res = ::GetLocaleInfoA(MAKELCID(inputLang, SORT_DEFAULT),
LOCALE_IDEFAULTANSICODEPAGE, sCodePage, sizeof(sCodePage));
if (!res)
return 0;
return atoi(sCodePage);
}
/** Map the key codes to their equivalent Keys:: form. */
Keys KeyTranslate(uptr_t keyIn) noexcept {
switch (keyIn) {
case VK_DOWN: return Keys::Down;
case VK_UP: return Keys::Up;
case VK_LEFT: return Keys::Left;
case VK_RIGHT: return Keys::Right;
case VK_HOME: return Keys::Home;
case VK_END: return Keys::End;
case VK_PRIOR: return Keys::Prior;
case VK_NEXT: return Keys::Next;
case VK_DELETE: return Keys::Delete;
case VK_INSERT: return Keys::Insert;
case VK_ESCAPE: return Keys::Escape;
case VK_BACK: return Keys::Back;
case VK_TAB: return Keys::Tab;
case VK_RETURN: return Keys::Return;
case VK_ADD: return Keys::Add;
case VK_SUBTRACT: return Keys::Subtract;
case VK_DIVIDE: return Keys::Divide;
case VK_LWIN: return Keys::Win;
case VK_RWIN: return Keys::RWin;
case VK_APPS: return Keys::Menu;
case VK_OEM_2: return static_cast<Keys>('/');
case VK_OEM_3: return static_cast<Keys>('`');
case VK_OEM_4: return static_cast<Keys>('[');
case VK_OEM_5: return static_cast<Keys>('\\');
case VK_OEM_6: return static_cast<Keys>(']');
default: return static_cast<Keys>(keyIn);
}
}
bool BoundsContains(PRectangle rcBounds, HRGN hRgnBounds, PRectangle rcCheck) noexcept {
bool contains = true;
if (!rcCheck.Empty()) {
if (!rcBounds.Contains(rcCheck)) {
contains = false;
} else if (hRgnBounds) {
// In bounding rectangle so check more accurately using region
const RECT rcw = RectFromPRectangle(rcCheck);
HRGN hRgnCheck = ::CreateRectRgnIndirect(&rcw);
if (hRgnCheck) {
HRGN hRgnDifference = ::CreateRectRgn(0, 0, 0, 0);
if (hRgnDifference) {
const int combination = ::CombineRgn(hRgnDifference, hRgnCheck, hRgnBounds, RGN_DIFF);
if (combination != NULLREGION) {
contains = false;
}
::DeleteRgn(hRgnDifference);
}
::DeleteRgn(hRgnCheck);
}
}
}
return contains;
}
// Simplify calling WideCharToMultiByte and MultiByteToWideChar by providing default parameters and using string view.
int MultiByteFromWideChar(UINT codePage, std::wstring_view wsv, LPSTR lpMultiByteStr, ptrdiff_t cbMultiByte) noexcept {
return ::WideCharToMultiByte(codePage, 0, wsv.data(), static_cast<int>(wsv.length()), lpMultiByteStr, static_cast<int>(cbMultiByte), nullptr, nullptr);
}
int MultiByteLenFromWideChar(UINT codePage, std::wstring_view wsv) noexcept {
return MultiByteFromWideChar(codePage, wsv, nullptr, 0);
}
int WideCharFromMultiByte(UINT codePage, std::string_view sv, LPWSTR lpWideCharStr, ptrdiff_t cchWideChar) noexcept {
return ::MultiByteToWideChar(codePage, 0, sv.data(), static_cast<int>(sv.length()), lpWideCharStr, static_cast<int>(cchWideChar));
}
int WideCharLenFromMultiByte(UINT codePage, std::string_view sv) noexcept {
return WideCharFromMultiByte(codePage, sv, nullptr, 0);
}
std::string StringEncode(std::wstring_view wsv, int codePage) {
const int cchMulti = wsv.length() ? MultiByteLenFromWideChar(codePage, wsv) : 0;
std::string sMulti(cchMulti, 0);
if (cchMulti) {
MultiByteFromWideChar(codePage, wsv, sMulti.data(), cchMulti);
}
return sMulti;
}
std::wstring StringDecode(std::string_view sv, int codePage) {
const int cchWide = sv.length() ? WideCharLenFromMultiByte(codePage, sv) : 0;
std::wstring sWide(cchWide, 0);
if (cchWide) {
WideCharFromMultiByte(codePage, sv, sWide.data(), cchWide);
}
return sWide;
}
std::wstring StringMapCase(std::wstring_view wsv, DWORD mapFlags) {
const int charsConverted = ::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
wsv.data(), static_cast<int>(wsv.length()), nullptr, 0);
std::wstring wsConverted(charsConverted, 0);
if (charsConverted) {
::LCMapStringW(LOCALE_SYSTEM_DEFAULT, mapFlags,
wsv.data(), static_cast<int>(wsv.length()), wsConverted.data(), charsConverted);
}
return wsConverted;
}
}
// Returns the target converted to UTF8.
// Return the length in bytes.
Sci::Position ScintillaWin::TargetAsUTF8(char *text) const {
const Sci::Position targetLength = targetRange.Length();
if (IsUnicodeMode()) {
if (text) {
pdoc->GetCharRange(text, targetRange.start.Position(), targetLength);