-
Notifications
You must be signed in to change notification settings - Fork 60
/
ScintillaWin.cxx
3472 lines (3062 loc) · 102 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 <cassert>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <climits>
#include <stdexcept>
#include <new>
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
#include <chrono>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#undef WINVER
#define WINVER 0x0500
#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 "Platform.h"
#include "ILoader.h"
#include "ILexer.h"
#include "Scintilla.h"
#ifdef SCI_LEXER
#include "SciLexer.h"
#endif
#include "CharacterCategory.h"
#ifdef SCI_LEXER
#include "LexerModule.h"
#endif
#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"
#ifdef SCI_LEXER
#include "ExternalLexer.h"
#endif
#include "PlatWin.h"
#include "HanjaDic.h"
#include "ScintillaWin.h"
#ifndef SPI_GETWHEELSCROLLLINES
#define SPI_GETWHEELSCROLLLINES 104
#endif
#ifndef WM_UNICHAR
#define WM_UNICHAR 0x0109
#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
// 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;
#define SC_INDICATOR_INPUT INDIC_IME
#define SC_INDICATOR_TARGET INDIC_IME+1
#define SC_INDICATOR_CONVERTED INDIC_IME+2
#define SC_INDICATOR_UNKNOWN INDIC_IME_MAX
#ifndef SCS_CAP_SETRECONVERTSTRING
#define SCS_CAP_SETRECONVERTSTRING 0x00000004
#define SCS_QUERYRECONVERTSTRING 0x00020000
#define SCS_SETRECONVERTSTRING 0x00010000
#endif
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;
namespace {
const TCHAR callClassName[] = TEXT("CallTip");
void *PointerFromWindow(HWND hWnd) noexcept {
return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
}
void SetWindowPointer(HWND hWnd, void *ptr) noexcept {
::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
}
void SetWindowID(HWND hWnd, int identifier) noexcept {
::SetWindowLongPtr(hWnd, GWLP_ID, identifier);
}
Point PointFromPOINT(POINT pt) noexcept {
return Point::FromInts(pt.x, pt.y);
}
Point PointFromLParam(sptr_t lpoint) noexcept {
return Point::FromInts(GET_X_LPARAM(lpoint), GET_Y_LPARAM(lpoint));
}
constexpr POINT POINTFromPoint(Point pt) noexcept {
return POINT{ static_cast<LONG>(pt.x), static_cast<LONG>(pt.y) };
}
bool KeyboardIsKeyDown(int key) noexcept {
return (::GetKeyState(key) & 0x80000000) != 0;
}
}
class ScintillaWin; // Forward declaration for COM interface subobjects
typedef void VFunction(void);
/**
*/
class FormatEnumerator {
public:
VFunction **vtbl;
int ref;
unsigned int pos;
std::vector<CLIPFORMAT> formats;
FormatEnumerator(int pos_, CLIPFORMAT formats_[], size_t formatsLen_);
};
/**
*/
class DropSource {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropSource() noexcept;
};
/**
*/
class DataObject {
public:
VFunction **vtbl;
ScintillaWin *sci;
DataObject() noexcept;
};
/**
*/
class DropTarget {
public:
VFunction **vtbl;
ScintillaWin *sci;
DropTarget() noexcept;
};
namespace {
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;
}
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 ScintillaWin :
public ScintillaBase {
bool lastKeyDownConsumed;
wchar_t lastHighSurrogateChar;
bool capturedMouse;
bool trackedMouseLeave;
SetCoalescableTimerSig SetCoalescableTimerFn;
unsigned int linesPerScroll; ///< Intellimouse support
int wheelDelta; ///< Wheel delta from roll
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;
#if defined(USE_D2D)
ID2D1RenderTarget *pRenderTarget;
bool renderTargetValid;
#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 Init();
void Finalise() override;
#if defined(USE_D2D)
void EnsureRenderTarget(HDC hdc);
void DropRenderTarget();
#endif
HWND MainHWND() const noexcept;
static sptr_t DirectFunction(
sptr_t ptr, UINT iMessage, uptr_t wParam, sptr_t lParam);
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 { invalidTimerID, standardTimerID, idleTimerID, fineTimerStart };
bool DragThreshold(Point ptStart, Point ptNow) override;
void StartDrag() override;
static int MouseModifiers(uptr_t wParam) noexcept;
Sci::Position TargetAsUTF8(char *text) const;
Sci::Position EncodedFromUTF8(const char *utf8, char *encoded) const;
sptr_t WndPaint();
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);
void DrawImeIndicator(int indicator, int len);
void SetCandidateWindowPos();
void SelectionToHangul();
void EscapeHanja();
void ToggleHanja();
void AddWString(std::wstring_view wsv);
UINT CodePageOfDocument() const;
bool ValidCodePage(int codePage) const override;
sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override;
void IdleWork() override;
void QueueIdleWork(WorkNeeded::workItems items, Sci::Position upTo) override;
bool SetIdle(bool on) override;
UINT_PTR timers[tickDwell+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;
bool PaintContains(PRectangle rc) override;
void ScrollText(Sci::Line linesToMove) override;
void NotifyCaretMove() override;
void UpdateSystemCaret() override;
void SetVerticalScrollPos() override;
void SetHorizontalScrollPos() override;
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(SCNotification scn) override;
void NotifyDoubleClick(Point pt, int modifiers) override;
CaseFolder *CaseFolderForEncoding() override;
std::string CaseMapString(const std::string &s, int caseMapping) override;
void Copy() override;
void CopyAllowLine() 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;
// DBCS
void ImeStartComposition();
void ImeEndComposition();
LRESULT ImeOnReconvert(LPARAM lParam);
void GetIntelliMouseParameters() noexcept;
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;
int SetScrollInfo(int nBar, LPCSCROLLINFO lpsi, BOOL bRedraw) noexcept;
bool GetScrollInfo(int nBar, LPSCROLLINFO lpsi) noexcept;
void ChangeScrollPos(int barType, Sci::Position pos);
sptr_t GetTextLength();
sptr_t GetText(uptr_t wParam, sptr_t lParam);
public:
~ScintillaWin() override;
// Public for benefit of Scintilla_DirectFunction
sptr_t WndProc(unsigned int 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 bool Register(HINSTANCE hInstance_) noexcept;
static bool Unregister() noexcept;
friend class DropSource;
friend class DataObject;
friend class DropTarget;
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;
SetCoalescableTimerFn = nullptr;
linesPerScroll = 0;
wheelDelta = 0; // Wheel delta from roll
hRgnUpdate = 0;
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 = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVColumnSelect")));
cfBorlandIDEBlockType = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("Borland IDE Block Type")));
// Likewise for line-copy (copies a full line when no text is selected)
cfLineSelect = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("MSDEVLineSelect")));
cfVSLineTag = static_cast<CLIPFORMAT>(
::RegisterClipboardFormat(TEXT("VisualStudioEditorOperationsLineCutCopyClipboardTag")));
hrOle = E_FAIL;
wMain = hwnd;
dob.sci = this;
ds.sci = this;
dt.sci = this;
sysCaretBitmap = 0;
sysCaretWidth = 0;
sysCaretHeight = 0;
styleIdleInQueue = false;
#if defined(USE_D2D)
pRenderTarget = nullptr;
renderTargetValid = true;
#endif
caret.period = ::GetCaretBlinkTime();
if (caret.period < 0)
caret.period = 0;
Init();
}
ScintillaWin::~ScintillaWin() {}
void ScintillaWin::Init() {
// 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 = ::GetModuleHandle(TEXT("user32.dll"));
if (user32) {
SetCoalescableTimerFn = reinterpret_cast<SetCoalescableTimerSig>(
::GetProcAddress(user32, "SetCoalescableTimer"));
}
vs.indicators[SC_INDICATOR_UNKNOWN] = Indicator(INDIC_HIDDEN, ColourDesired(0, 0, 0xff));
vs.indicators[SC_INDICATOR_INPUT] = Indicator(INDIC_DOTS, ColourDesired(0, 0, 0xff));
vs.indicators[SC_INDICATOR_CONVERTED] = Indicator(INDIC_COMPOSITIONTHICK, ColourDesired(0, 0, 0xff));
vs.indicators[SC_INDICATOR_TARGET] = Indicator(INDIC_STRAIGHTBOX, ColourDesired(0, 0, 0xff));
}
void ScintillaWin::Finalise() {
ScintillaBase::Finalise();
for (TickReason tr = tickCaret; tr <= tickDwell; tr = static_cast<TickReason>(tr + 1)) {
FineTickerCancel(tr);
}
SetIdle(false);
#if defined(USE_D2D)
DropRenderTarget();
#endif
::RevokeDragDrop(MainHWND());
if (SUCCEEDED(hrOle)) {
::OleUninitialize();
}
}
#if defined(USE_D2D)
void ScintillaWin::EnsureRenderTarget(HDC hdc) {
if (!renderTargetValid) {
DropRenderTarget();
renderTargetValid = true;
}
if (pD2DFactory && !pRenderTarget) {
HWND hw = MainHWND();
RECT rc;
GetClientRect(hw, &rc);
const D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
// Create a Direct2D render target.
#if 1
D2D1_RENDER_TARGET_PROPERTIES drtp;
drtp.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
drtp.pixelFormat.format = DXGI_FORMAT_UNKNOWN;
drtp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_UNKNOWN;
drtp.dpiX = 96.0;
drtp.dpiY = 96.0;
drtp.usage = D2D1_RENDER_TARGET_USAGE_NONE;
drtp.minLevel = D2D1_FEATURE_LEVEL_DEFAULT;
if (technology == SC_TECHNOLOGY_DIRECTWRITEDC) {
// 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%x\n", hr);
pRenderTarget = nullptr;
}
} else {
D2D1_HWND_RENDER_TARGET_PROPERTIES dhrtp;
dhrtp.hwnd = hw;
dhrtp.pixelSize = size;
dhrtp.presentOptions = (technology == SC_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%x\n", hr);
pRenderTarget = nullptr;
}
}
#else
pD2DFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(
D2D1_RENDER_TARGET_TYPE_DEFAULT ,
D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
96.0f, 96.0f, D2D1_RENDER_TARGET_USAGE_NONE, D2D1_FEATURE_LEVEL_DEFAULT),
D2D1::HwndRenderTargetProperties(hw, size),
&pRenderTarget);
#endif
// Pixmaps were created to be compatible with previous render target so
// need to be recreated.
DropGraphics(false);
}
if ((technology == SC_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%x\n", hr);
DropRenderTarget();
}
}
}
void ScintillaWin::DropRenderTarget() {
if (pRenderTarget) {
pRenderTarget->Release();
pRenderTarget = nullptr;
}
}
#endif
HWND ScintillaWin::MainHWND() const noexcept {
return static_cast<HWND>(wMain.GetID());
}
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 > ::GetSystemMetrics(SM_CXDRAG)) ||
(yMove > ::GetSystemMetrics(SM_CYDRAG));
}
void ScintillaWin::StartDrag() {
inDragDrop = ddDragging;
DWORD dwEffect = 0;
dropWentOutside = true;
IDataObject *pDataObject = reinterpret_cast<IDataObject *>(&dob);
IDropSource *pDropSource = reinterpret_cast<IDropSource *>(&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 = ddNone;
SetDragPosition(SelectionPosition(Sci::invalidPosition));
}
int 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 SCK_ form. */
int KeyTranslate(int keyIn) noexcept {
//PLATFORM_ASSERT(!keyIn);
switch (keyIn) {
case VK_DOWN: return SCK_DOWN;
case VK_UP: return SCK_UP;
case VK_LEFT: return SCK_LEFT;
case VK_RIGHT: return SCK_RIGHT;
case VK_HOME: return SCK_HOME;
case VK_END: return SCK_END;
case VK_PRIOR: return SCK_PRIOR;
case VK_NEXT: return SCK_NEXT;
case VK_DELETE: return SCK_DELETE;
case VK_INSERT: return SCK_INSERT;
case VK_ESCAPE: return SCK_ESCAPE;
case VK_BACK: return SCK_BACK;
case VK_TAB: return SCK_TAB;
case VK_RETURN: return SCK_RETURN;
case VK_ADD: return SCK_ADD;
case VK_SUBTRACT: return SCK_SUBTRACT;
case VK_DIVIDE: return SCK_DIVIDE;
case VK_LWIN: return SCK_WIN;
case VK_RWIN: return SCK_RWIN;
case VK_APPS: return SCK_MENU;
case VK_OEM_2: return '/';
case VK_OEM_3: return '`';
case VK_OEM_4: return '[';
case VK_OEM_5: return '\\';
case VK_OEM_6: return ']';
default: return 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 = targetEnd - targetStart;
if (IsUnicodeMode()) {
if (text) {
pdoc->GetCharRange(text, targetStart, targetLength);
}
} else {
// Need to convert
const std::string s = RangeText(targetStart, targetEnd);
const std::wstring characters = StringDecode(s, CodePageOfDocument());
const int utf8Len = MultiByteLenFromWideChar(CP_UTF8, characters);
if (text) {
MultiByteFromWideChar(CP_UTF8, characters, text, utf8Len);
text[utf8Len] = '\0';
}
return utf8Len;
}
return targetLength;
}
// Translates a nul terminated UTF8 string into the document encoding.
// Return the length of the result in bytes.
Sci::Position ScintillaWin::EncodedFromUTF8(const char *utf8, char *encoded) const {
const Sci::Position inputLength = (lengthForEncode >= 0) ? lengthForEncode : strlen(utf8);
if (IsUnicodeMode()) {
if (encoded) {
memcpy(encoded, utf8, inputLength);
}
return inputLength;
} else {
// Need to convert
const std::string_view utf8Input(utf8, inputLength);
const int charsLen = WideCharLenFromMultiByte(CP_UTF8, utf8Input);
std::wstring characters(charsLen, L'\0');
WideCharFromMultiByte(CP_UTF8, utf8Input, &characters[0], charsLen);
const int encodedLen = MultiByteLenFromWideChar(CodePageOfDocument(), characters);
if (encoded) {
MultiByteFromWideChar(CodePageOfDocument(), characters, encoded, encodedLen);
encoded[encodedLen] = '\0';
}
return encodedLen;
}
}
sptr_t ScintillaWin::WndPaint() {
//ElapsedPeriod ep;
// Redirect assertions to debug output and save current state
const bool assertsPopup = Platform::ShowAssertionPopUps(false);
paintState = painting;
PAINTSTRUCT ps = {};
// Removed since this interferes with reporting other assertions as it occurs repeatedly
//PLATFORM_ASSERT(hRgnUpdate == NULL);
hRgnUpdate = ::CreateRectRgn(0, 0, 0, 0);
::GetUpdateRgn(MainHWND(), hRgnUpdate, FALSE);
::BeginPaint(MainHWND(), &ps);
rcPaint = PRectangle::FromInts(ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom);
const PRectangle rcClient = GetClientRectangle();
paintingAllText = BoundsContains(rcPaint, hRgnUpdate, rcClient);
if (technology == SC_TECHNOLOGY_DEFAULT) {
AutoSurface surfaceWindow(ps.hdc, this);
if (surfaceWindow) {
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
}
} else {
#if defined(USE_D2D)
EnsureRenderTarget(ps.hdc);
AutoSurface surfaceWindow(pRenderTarget, this);
if (surfaceWindow) {
pRenderTarget->BeginDraw();
Paint(surfaceWindow, rcPaint);
surfaceWindow->Release();
const HRESULT hr = pRenderTarget->EndDraw();
if (hr == static_cast<HRESULT>(D2DERR_RECREATE_TARGET)) {
DropRenderTarget();
paintState = paintAbandoned;
}
}
#endif
}
if (hRgnUpdate) {
::DeleteRgn(hRgnUpdate);
hRgnUpdate = 0;
}
::EndPaint(MainHWND(), &ps);
if (paintState == paintAbandoned) {
// Painting area was insufficient to cover new styling or brace highlight positions
FullPaint();
::ValidateRect(MainHWND(), nullptr);
}
paintState = notPainting;
// Restore debug output state
Platform::ShowAssertionPopUps(assertsPopup);
//Platform::DebugPrintf("Paint took %g\n", ep.Duration());
return 0;
}
sptr_t ScintillaWin::HandleCompositionWindowed(uptr_t wParam, sptr_t lParam) {
if (lParam & GCS_RESULTSTR) {
IMContext imc(MainHWND());
if (imc.hIMC) {
AddWString(imc.GetCompositionString(GCS_RESULTSTR));
// Set new position after converted
const Point pos = PointMainCaret();
COMPOSITIONFORM CompForm;
CompForm.dwStyle = CFS_POINT;
CompForm.ptCurrentPos = POINTFromPoint(pos);
::ImmSetCompositionWindow(imc.hIMC, &CompForm);
}
return 0;
}
return ::DefWindowProc(MainHWND(), WM_IME_COMPOSITION, wParam, lParam);
}
bool ScintillaWin::KoreanIME() noexcept {
const int codePage = InputCodePage();
return codePage == 949 || codePage == 1361;
}
void ScintillaWin::MoveImeCarets(Sci::Position offset) {
// Move carets relatively by bytes.
for (size_t r=0; r<sel.Count(); r++) {
const Sci::Position positionInsert = sel.Range(r).Start().Position();
sel.Range(r).caret.SetPosition(positionInsert + offset);
sel.Range(r).anchor.SetPosition(positionInsert + offset);
}
}
void ScintillaWin::DrawImeIndicator(int indicator, int len) {
// Emulate the visual style of IME characters with indicators.
// Draw an indicator on the character before caret by the character bytes of len
// so it should be called after addCharUTF().
// It does not affect caret positions.
if (indicator < 8 || indicator > INDIC_MAX) {
return;
}
pdoc->DecorationSetCurrentIndicator(indicator);
for (size_t r=0; r<sel.Count(); r++) {
const Sci::Position positionInsert = sel.Range(r).Start().Position();
pdoc->DecorationFillRange(positionInsert - len, 1, len);
}
}
void ScintillaWin::SetCandidateWindowPos() {
IMContext imc(MainHWND());
if (imc.hIMC) {
const Point pos = PointMainCaret();
CANDIDATEFORM CandForm;
CandForm.dwIndex = 0;
CandForm.dwStyle = CFS_CANDIDATEPOS;
CandForm.ptCurrentPos.x = static_cast<int>(pos.x);
CandForm.ptCurrentPos.y = static_cast<int>(pos.y + vs.lineHeight);
::ImmSetCandidateWindow(imc.hIMC, &CandForm);
}
}
void ScintillaWin::SelectionToHangul() {
// Convert every hanja to hangul within the main range.
const Sci::Position selStart = sel.RangeMain().Start().Position();
const Sci::Position documentStrLen = sel.RangeMain().Length();
const Sci::Position selEnd = selStart + documentStrLen;
const Sci::Position utf16Len = pdoc->CountUTF16(selStart, selEnd);
if (utf16Len > 0) {
std::string documentStr(documentStrLen, '\0');
pdoc->GetCharRange(&documentStr[0], selStart, documentStrLen);
std::wstring uniStr = StringDecode(documentStr, CodePageOfDocument());
const int converted = HanjaDict::GetHangulOfHanja(&uniStr[0]);
documentStr = StringEncode(uniStr, CodePageOfDocument());
if (converted > 0) {
pdoc->BeginUndoAction();
ClearSelection();
InsertPaste(&documentStr[0], documentStr.size());
pdoc->EndUndoAction();
}
}
}
void ScintillaWin::EscapeHanja() {
// The candidate box pops up to user to select a hanja.
// It comes into WM_IME_COMPOSITION with GCS_RESULTSTR.
// The existing hangul or hanja is replaced with it.
if (sel.Count() > 1) {
return; // Do not allow multi carets.
}
const Sci::Position currentPos = CurrentPosition();
const int oneCharLen = pdoc->LenChar(currentPos);
if (oneCharLen < 2) {
return; // No need to handle SBCS.
}
// ImmEscapeW() may overwrite uniChar[] with a null terminated string.
// So enlarge it enough to Maximum 4 as in UTF-8.
unsigned int const safeLength = UTF8MaxBytes+1;
std::string oneChar(safeLength, '\0');
pdoc->GetCharRange(&oneChar[0], currentPos, oneCharLen);
std::wstring uniChar = StringDecode(oneChar, CodePageOfDocument());
IMContext imc(MainHWND());
if (imc.hIMC) {
// Set the candidate box position since IME may show it.