-
Notifications
You must be signed in to change notification settings - Fork 170
/
PlatWin.cxx
3458 lines (3014 loc) · 106 KB
/
PlatWin.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 PlatWin.cxx
** Implementation of platform facilities on Windows.
**/
// 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 <cstring>
#include <cstdio>
#include <cstdarg>
#include <ctime>
#include <cmath>
#include <climits>
#include <stdexcept>
#include <string_view>
#include <vector>
#include <map>
#include <algorithm>
#include <memory>
// 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
#include <windows.h>
#include <commctrl.h>
#include <richedit.h>
#include <windowsx.h>
#include <shlwapi.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 "XPM.h"
#include "UniConversion.h"
#include "CharClassify.h"
#include "FontQuality.h"
#include "PlatWin.h"
#ifndef SPI_GETFONTSMOOTHINGCONTRAST
#define SPI_GETFONTSMOOTHINGCONTRAST 0x200C
#endif
#ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
#endif
#if _WIN32_WINNT < 0x0602 /*_WIN32_WINNT_WIN8 */
#if NP2_FORCE_COMPILE_C_AS_CPP
extern DWORD kSystemLibraryLoadFlags;
#else
extern "C" DWORD kSystemLibraryLoadFlags;
#endif
#else
#define kSystemLibraryLoadFlags LOAD_LIBRARY_SEARCH_SYSTEM32
#endif
namespace Scintilla {
UINT CodePageFromCharSet(DWORD characterSet, UINT documentCodePage) noexcept;
#if defined(USE_D2D)
IDWriteFactory *pIDWriteFactory = nullptr;
ID2D1Factory *pD2DFactory = nullptr;
IDWriteRenderingParams *defaultRenderingParams = nullptr;
IDWriteRenderingParams *customClearTypeRenderingParams = nullptr;
static HMODULE hDLLD2D {};
static HMODULE hDLLDWrite {};
bool LoadD2D() noexcept {
static bool triedLoadingD2D = false;
if (!triedLoadingD2D) {
// Availability of SetDefaultDllDirectories implies Windows 8+ or
// that KB2533623 has been installed so LoadLibraryEx can be called
// with LOAD_LIBRARY_SEARCH_SYSTEM32.
typedef HRESULT(WINAPI *D2D1CFSig)(D2D1_FACTORY_TYPE factoryType, REFIID riid,
CONST D2D1_FACTORY_OPTIONS *pFactoryOptions, IUnknown **factory);
typedef HRESULT(WINAPI *DWriteCFSig)(DWRITE_FACTORY_TYPE factoryType, REFIID iid,
IUnknown **factory);
hDLLD2D = ::LoadLibraryEx(L"D2D1.DLL", nullptr, kSystemLibraryLoadFlags);
if (hDLLD2D) {
D2D1CFSig fnD2DCF = reinterpret_cast<D2D1CFSig>(::GetProcAddress(hDLLD2D, "D2D1CreateFactory"));
if (fnD2DCF) {
// A single threaded factory as Scintilla always draw on the GUI thread
fnD2DCF(D2D1_FACTORY_TYPE_SINGLE_THREADED,
__uuidof(ID2D1Factory),
nullptr,
reinterpret_cast<IUnknown**>(&pD2DFactory));
}
}
hDLLDWrite = ::LoadLibraryEx(L"DWRITE.DLL", nullptr, kSystemLibraryLoadFlags);
if (hDLLDWrite) {
DWriteCFSig fnDWCF = reinterpret_cast<DWriteCFSig>(::GetProcAddress(hDLLDWrite, "DWriteCreateFactory"));
if (fnDWCF) {
fnDWCF(DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&pIDWriteFactory));
}
}
if (pIDWriteFactory) {
const HRESULT hr = pIDWriteFactory->CreateRenderingParams(&defaultRenderingParams);
if (SUCCEEDED(hr)) {
unsigned int clearTypeContrast;
if (::SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &clearTypeContrast, 0)) {
FLOAT gamma;
if (clearTypeContrast >= 1000 && clearTypeContrast <= 2200)
gamma = static_cast<FLOAT>(clearTypeContrast) / 1000.0f;
else
gamma = defaultRenderingParams->GetGamma();
pIDWriteFactory->CreateCustomRenderingParams(gamma, defaultRenderingParams->GetEnhancedContrast(), defaultRenderingParams->GetClearTypeLevel(),
defaultRenderingParams->GetPixelGeometry(), defaultRenderingParams->GetRenderingMode(), &customClearTypeRenderingParams);
}
}
}
}
triedLoadingD2D = true;
return pIDWriteFactory && pD2DFactory;
}
#endif
struct FormatAndMetrics {
int technology;
HFONT hfont;
#if defined(USE_D2D)
IDWriteTextFormat *pTextFormat;
#endif
int extraFontFlag;
int characterSet;
FLOAT yAscent;
FLOAT yDescent;
FLOAT yInternalLeading;
FormatAndMetrics(HFONT hfont_, int extraFontFlag_, int characterSet_) noexcept :
technology(SCWIN_TECH_GDI), hfont(hfont_),
#if defined(USE_D2D)
pTextFormat(nullptr),
#endif
extraFontFlag(extraFontFlag_), characterSet(characterSet_), yAscent(2), yDescent(1), yInternalLeading(0) {}
#if defined(USE_D2D)
FormatAndMetrics(IDWriteTextFormat *pTextFormat_,
int extraFontFlag_,
int characterSet_,
FLOAT yAscent_,
FLOAT yDescent_,
FLOAT yInternalLeading_) noexcept :
technology(SCWIN_TECH_DIRECTWRITE),
hfont{},
pTextFormat(pTextFormat_),
extraFontFlag(extraFontFlag_),
characterSet(characterSet_),
yAscent(yAscent_),
yDescent(yDescent_),
yInternalLeading(yInternalLeading_) {}
#endif
FormatAndMetrics(const FormatAndMetrics &) = delete;
FormatAndMetrics(FormatAndMetrics &&) = delete;
FormatAndMetrics &operator=(const FormatAndMetrics &) = delete;
FormatAndMetrics &operator=(FormatAndMetrics &&) = delete;
~FormatAndMetrics() {
if (hfont)
::DeleteObject(hfont);
#if defined(USE_D2D)
if (pTextFormat)
pTextFormat->Release();
pTextFormat = nullptr;
#endif
extraFontFlag = 0;
characterSet = 0;
yAscent = 2;
yDescent = 1;
yInternalLeading = 0;
}
HFONT HFont() const noexcept;
};
HFONT FormatAndMetrics::HFont() const noexcept {
LOGFONTW lf = {};
#if defined(USE_D2D)
if (technology == SCWIN_TECH_GDI) {
if (0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
return nullptr;
}
} else {
const HRESULT hr = pTextFormat->GetFontFamilyName(lf.lfFaceName, LF_FACESIZE);
if (!SUCCEEDED(hr)) {
return nullptr;
}
lf.lfWeight = pTextFormat->GetFontWeight();
lf.lfItalic = pTextFormat->GetFontStyle() == DWRITE_FONT_STYLE_ITALIC;
lf.lfHeight = -static_cast<int>(pTextFormat->GetFontSize());
}
#else
if (0 == ::GetObjectW(hfont, sizeof(lf), &lf)) {
return nullptr;
}
#endif
return ::CreateFontIndirectW(&lf);
}
#ifndef CLEARTYPE_QUALITY
#define CLEARTYPE_QUALITY 5
#endif
namespace {
inline void *PointerFromWindow(HWND hWnd) noexcept {
return reinterpret_cast<void *>(::GetWindowLongPtr(hWnd, 0));
}
inline void SetWindowPointer(HWND hWnd, void *ptr) noexcept {
::SetWindowLongPtr(hWnd, 0, reinterpret_cast<LONG_PTR>(ptr));
}
CRITICAL_SECTION crPlatformLock;
HINSTANCE hinstPlatformRes {};
HCURSOR reverseArrowCursor {};
inline FormatAndMetrics *FamFromFontID(void *fid) noexcept {
return static_cast<FormatAndMetrics *>(fid);
}
inline BYTE Win32MapFontQuality(int extraFontFlag) noexcept {
switch (extraFontFlag & SC_EFF_QUALITY_MASK) {
case SC_EFF_QUALITY_NON_ANTIALIASED:
return NONANTIALIASED_QUALITY;
case SC_EFF_QUALITY_ANTIALIASED:
return ANTIALIASED_QUALITY;
case SC_EFF_QUALITY_LCD_OPTIMIZED:
return CLEARTYPE_QUALITY;
default:
return SC_EFF_QUALITY_DEFAULT;
}
}
#if defined(USE_D2D)
inline D2D1_TEXT_ANTIALIAS_MODE DWriteMapFontQuality(int extraFontFlag) noexcept {
switch (extraFontFlag & SC_EFF_QUALITY_MASK) {
case SC_EFF_QUALITY_NON_ANTIALIASED:
return D2D1_TEXT_ANTIALIAS_MODE_ALIASED;
case SC_EFF_QUALITY_ANTIALIASED:
return D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE;
case SC_EFF_QUALITY_LCD_OPTIMIZED:
return D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE;
default:
return D2D1_TEXT_ANTIALIAS_MODE_DEFAULT;
}
}
#endif
void SetLogFont(LOGFONTW &lf, const char *faceName, int characterSet, float size, int weight, bool italic, int extraFontFlag) {
lf = LOGFONTW();
// The negative is to allow for leading
lf.lfHeight = -abs(lround(size));
lf.lfWeight = weight;
lf.lfItalic = italic ? 1 : 0;
lf.lfCharSet = static_cast<BYTE>(characterSet);
lf.lfQuality = Win32MapFontQuality(extraFontFlag);
UTF16FromUTF8(faceName, lf.lfFaceName, LF_FACESIZE);
}
/**
* Create a hash from the parameters for a font to allow easy checking for identity.
* If one font is the same as another, its hash will be the same, but if the hash is the
* same then they may still be different.
*/
int HashFont(const FontParameters &fp) noexcept {
return
static_cast<int>(fp.size) ^
(fp.characterSet << 10) ^
((fp.extraFontFlag & SC_EFF_QUALITY_MASK) << 9) ^
((fp.weight / 100) << 12) ^
(fp.italic ? 0x20000000 : 0) ^
(fp.technology << 15) ^
fp.faceName[0];
}
}
class FontCached : Font {
FontCached *next;
int usage;
float size;
LOGFONTW lf;
int technology;
int hash;
explicit FontCached(const FontParameters &fp);
bool SameAs(const FontParameters &fp) const;
void Release() noexcept override;
static FontCached *first;
public:
~FontCached() override = default;
static FontID FindOrCreate(const FontParameters &fp);
static void ReleaseId(FontID fid_) noexcept;
};
FontCached *FontCached::first = nullptr;
FontCached::FontCached(const FontParameters &fp) :
next(nullptr), usage(0), size(1.0), hash(0) {
SetLogFont(lf, fp.faceName, fp.characterSet, fp.size, fp.weight, fp.italic, fp.extraFontFlag);
technology = fp.technology;
hash = HashFont(fp);
fid = nullptr;
if (technology == SCWIN_TECH_GDI) {
HFONT hfont = ::CreateFontIndirectW(&lf);
fid = new FormatAndMetrics(hfont, fp.extraFontFlag, fp.characterSet);
} else {
#if defined(USE_D2D)
IDWriteTextFormat *pTextFormat = nullptr;
const int faceSize = 200;
WCHAR wszFace[faceSize] = L"";
UTF16FromUTF8(fp.faceName, wszFace, faceSize);
const FLOAT fHeight = fp.size;
const DWRITE_FONT_STYLE style = fp.italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
HRESULT hr = pIDWriteFactory->CreateTextFormat(wszFace, nullptr,
static_cast<DWRITE_FONT_WEIGHT>(fp.weight),
style,
DWRITE_FONT_STRETCH_NORMAL, fHeight, L"", &pTextFormat);
if (SUCCEEDED(hr)) {
pTextFormat->SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP);
FLOAT yAscent = 1.0f;
FLOAT yDescent = 1.0f;
FLOAT yInternalLeading = 0.0f;
IDWriteTextLayout *pTextLayout = nullptr;
hr = pIDWriteFactory->CreateTextLayout(L"X", 1, pTextFormat,
100.0f, 100.0f, &pTextLayout);
if (SUCCEEDED(hr)) {
const int maxLines = 2;
DWRITE_LINE_METRICS lineMetrics[maxLines]{};
UINT32 lineCount = 0;
hr = pTextLayout->GetLineMetrics(lineMetrics, maxLines, &lineCount);
if (SUCCEEDED(hr)) {
yAscent = lineMetrics[0].baseline;
yDescent = lineMetrics[0].height - lineMetrics[0].baseline;
FLOAT emHeight;
hr = pTextLayout->GetFontSize(0, &emHeight);
if (SUCCEEDED(hr)) {
yInternalLeading = lineMetrics[0].height - emHeight;
}
}
pTextLayout->Release();
pTextFormat->SetLineSpacing(DWRITE_LINE_SPACING_METHOD_UNIFORM, lineMetrics[0].height, lineMetrics[0].baseline);
}
fid = new FormatAndMetrics(pTextFormat, fp.extraFontFlag, fp.characterSet, yAscent, yDescent, yInternalLeading);
}
#endif
}
usage = 1;
}
bool FontCached::SameAs(const FontParameters &fp) const {
if (
(size == fp.size) &&
(lf.lfWeight == fp.weight) &&
(lf.lfItalic == (fp.italic ? 1 : 0)) &&
(lf.lfCharSet == fp.characterSet) &&
(lf.lfQuality == Win32MapFontQuality(fp.extraFontFlag)) &&
(technology == fp.technology)) {
wchar_t wszFace[LF_FACESIZE] = L"";
UTF16FromUTF8(fp.faceName, wszFace, LF_FACESIZE);
return 0 == wcscmp(lf.lfFaceName, wszFace);
}
return false;
}
void FontCached::Release() noexcept {
delete FamFromFontID(fid);
fid = nullptr;
}
FontID FontCached::FindOrCreate(const FontParameters &fp) {
FontID ret {};
::EnterCriticalSection(&crPlatformLock);
const int hashFind = HashFont(fp);
for (FontCached *cur = first; cur; cur = cur->next) {
if ((cur->hash == hashFind) &&
cur->SameAs(fp)) {
cur->usage++;
ret = cur->fid;
}
}
if (!ret) {
FontCached *fc = new FontCached(fp);
fc->next = first;
first = fc;
ret = fc->fid;
}
::LeaveCriticalSection(&crPlatformLock);
return ret;
}
void FontCached::ReleaseId(FontID fid_) noexcept {
::EnterCriticalSection(&crPlatformLock);
FontCached **pcur = &first;
for (FontCached *cur = first; cur; cur = cur->next) {
if (cur->fid == fid_) {
cur->usage--;
if (cur->usage == 0) {
*pcur = cur->next;
cur->Release();
cur->next = nullptr;
delete cur;
}
break;
}
pcur = &cur->next;
}
::LeaveCriticalSection(&crPlatformLock);
}
Font::Font() noexcept : fid{} {
}
Font::~Font() = default;
#define FONTS_CACHED
void Font::Create(const FontParameters &fp) {
Release();
if (fp.faceName)
fid = FontCached::FindOrCreate(fp);
}
void Font::Release() noexcept {
if (fid)
FontCached::ReleaseId(fid);
fid = nullptr;
}
// Buffer to hold strings and string position arrays without always allocating on heap.
// May sometimes have string too long to allocate on stack. So use a fixed stack-allocated buffer
// when less than safe size otherwise allocate on heap and free automatically.
template<typename T, int lengthStandard>
class VarBuffer {
T bufferStandard[lengthStandard];
public:
T * buffer;
explicit VarBuffer(size_t length) : buffer(nullptr) {
if (length > lengthStandard) {
buffer = new T[length];
} else {
buffer = bufferStandard;
}
}
// Deleted so VarBuffer objects can not be copied.
VarBuffer(const VarBuffer &) = delete;
VarBuffer(VarBuffer &&) = delete;
VarBuffer &operator=(const VarBuffer &) = delete;
VarBuffer &operator=(VarBuffer &&) = delete;
~VarBuffer() {
if (buffer != bufferStandard) {
delete[]buffer;
buffer = nullptr;
}
}
};
const int stackBufferLength = 1000;
class TextWide : public VarBuffer<wchar_t, stackBufferLength> {
public:
int tlen; // Using int instead of size_t as most Win32 APIs take int.
TextWide(std::string_view text, bool unicodeMode, int codePage = 0) :
VarBuffer<wchar_t, stackBufferLength>(text.length()) {
if (unicodeMode) {
tlen = static_cast<int>(UTF16FromUTF8(text, buffer, text.length()));
} else {
// Support Asian string display in 9x English
tlen = ::MultiByteToWideChar(codePage, 0, text.data(), static_cast<int>(text.length()),
buffer, static_cast<int>(text.length()));
}
}
};
typedef VarBuffer<XYPOSITION, stackBufferLength> TextPositions;
class SurfaceGDI : public Surface {
bool unicodeMode = false;
HDC hdc{};
bool hdcOwned = false;
HPEN pen{};
HPEN penOld{};
HBRUSH brush{};
HBRUSH brushOld{};
HFONT font{};
HFONT fontOld{};
HBITMAP bitmap{};
HBITMAP bitmapOld{};
int maxWidthMeasure = INT_MAX;
// There appears to be a 16 bit string length limit in GDI on NT.
int maxLenText = 65535;
int codePage = 0;
void BrushColor(ColourDesired back) noexcept;
void SetFont(const Font &font_) noexcept;
void Clear() noexcept;
public:
SurfaceGDI() noexcept = default;
// Deleted so SurfaceGDI objects can not be copied.
SurfaceGDI(const SurfaceGDI &) = delete;
SurfaceGDI(SurfaceGDI &&) = delete;
SurfaceGDI &operator=(const SurfaceGDI &) = delete;
SurfaceGDI &operator=(SurfaceGDI &&) = delete;
~SurfaceGDI() override;
void Init(WindowID wid) noexcept override;
void Init(SurfaceID sid, WindowID wid) noexcept override;
void InitPixMap(int width, int height, Surface *surface_, WindowID wid) noexcept override;
void Release() noexcept override;
bool Initialised() const noexcept override;
void PenColour(ColourDesired fore) noexcept override;
int LogPixelsY() const noexcept override;
int DeviceHeightFont(int points) const noexcept override;
void MoveTo(int x_, int y_) noexcept override;
void LineTo(int x_, int y_) noexcept override;
void Polygon(const Point *pts, size_t npts, ColourDesired fore, ColourDesired back) override;
void RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept override;
void FillRectangle(PRectangle rc, ColourDesired back) noexcept override;
void FillRectangle(PRectangle rc, Surface &surfacePattern) noexcept override;
void RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept override;
void AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
ColourDesired outline, int alphaOutline, int flags) noexcept override;
void GradientRectangle(PRectangle rc, const std::vector<ColourStop> &stops, GradientOptions options) override;
void DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) noexcept override;
void Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept override;
void Copy(PRectangle rc, Point from, Surface &surfaceSource) noexcept override;
std::unique_ptr<IScreenLineLayout> Layout(const IScreenLine *screenLine) noexcept override;
void DrawTextCommon(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text, UINT fuOptions);
void DrawTextNoClip(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text, ColourDesired fore, ColourDesired back) override;
void DrawTextClipped(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text, ColourDesired fore, ColourDesired back) override;
void DrawTextTransparent(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text, ColourDesired fore) override;
void MeasureWidths(const Font &font_, std::string_view text, XYPOSITION *positions) override;
XYPOSITION WidthText(const Font &font_, std::string_view text) override;
XYPOSITION Ascent(const Font &font_) noexcept override;
XYPOSITION Descent(const Font &font_) noexcept override;
XYPOSITION InternalLeading(const Font &font_) noexcept override;
XYPOSITION Height(const Font &font_) noexcept override;
XYPOSITION AverageCharWidth(const Font &font_) noexcept override;
void SetClip(PRectangle rc) noexcept override;
void FlushCachedState() noexcept override;
void SetUnicodeMode(bool unicodeMode_) noexcept override;
void SetDBCSMode(int codePage_) noexcept override;
void SetBidiR2L(bool bidiR2L_) noexcept override;
};
SurfaceGDI::~SurfaceGDI() {
Clear();
}
void SurfaceGDI::Clear() noexcept {
if (penOld) {
::SelectObject(hdc, penOld);
::DeleteObject(pen);
penOld = nullptr;
}
pen = nullptr;
if (brushOld) {
::SelectObject(hdc, brushOld);
::DeleteObject(brush);
brushOld = nullptr;
}
brush = nullptr;
if (fontOld) {
// Fonts are not deleted as they are owned by a Font object
::SelectObject(hdc, fontOld);
fontOld = nullptr;
}
font = nullptr;
if (bitmapOld) {
::SelectObject(hdc, bitmapOld);
::DeleteObject(bitmap);
bitmapOld = nullptr;
}
bitmap = nullptr;
if (hdcOwned) {
::DeleteDC(hdc);
hdc = nullptr;
hdcOwned = false;
}
}
void SurfaceGDI::Release() noexcept {
Clear();
}
bool SurfaceGDI::Initialised() const noexcept {
return hdc != nullptr;
}
void SurfaceGDI::Init(WindowID) noexcept {
Release();
hdc = ::CreateCompatibleDC(nullptr);
hdcOwned = true;
::SetTextAlign(hdc, TA_BASELINE);
}
void SurfaceGDI::Init(SurfaceID sid, WindowID) noexcept {
Release();
hdc = static_cast<HDC>(sid);
::SetTextAlign(hdc, TA_BASELINE);
}
void SurfaceGDI::InitPixMap(int width, int height, Surface *surface_, WindowID) noexcept {
Release();
SurfaceGDI *psurfOther = static_cast<SurfaceGDI *>(surface_);
hdc = ::CreateCompatibleDC(psurfOther->hdc);
hdcOwned = true;
bitmap = ::CreateCompatibleBitmap(psurfOther->hdc, width, height);
bitmapOld = SelectBitmap(hdc, bitmap);
::SetTextAlign(hdc, TA_BASELINE);
SetUnicodeMode(psurfOther->unicodeMode);
SetDBCSMode(psurfOther->codePage);
}
void SurfaceGDI::PenColour(ColourDesired fore) noexcept {
if (pen) {
::SelectObject(hdc, penOld);
::DeleteObject(pen);
pen = nullptr;
penOld = nullptr;
}
pen = ::CreatePen(0, 1, fore.AsInteger());
penOld = SelectPen(hdc, pen);
}
void SurfaceGDI::BrushColor(ColourDesired back) noexcept {
if (brush) {
::SelectObject(hdc, brushOld);
::DeleteObject(brush);
brush = nullptr;
brushOld = nullptr;
}
// Only ever want pure, non-dithered brushes
const ColourDesired colourNearest = ColourDesired(::GetNearestColor(hdc, back.AsInteger()));
brush = ::CreateSolidBrush(colourNearest.AsInteger());
brushOld = SelectBrush(hdc, brush);
}
void SurfaceGDI::SetFont(const Font &font_) noexcept {
if (font_.GetID() != font) {
const FormatAndMetrics *pfm = FamFromFontID(font_.GetID());
PLATFORM_ASSERT(pfm->technology == SCWIN_TECH_GDI);
if (fontOld) {
SelectFont(hdc, pfm->hfont);
} else {
fontOld = SelectFont(hdc, pfm->hfont);
}
font = pfm->hfont;
}
}
int SurfaceGDI::LogPixelsY() const noexcept {
return ::GetDeviceCaps(hdc, LOGPIXELSY);
}
int SurfaceGDI::DeviceHeightFont(int points) const noexcept {
return ::MulDiv(points, LogPixelsY(), 72);
}
void SurfaceGDI::MoveTo(int x_, int y_) noexcept {
::MoveToEx(hdc, x_, y_, nullptr);
}
void SurfaceGDI::LineTo(int x_, int y_) noexcept {
::LineTo(hdc, x_, y_);
}
void SurfaceGDI::Polygon(const Point *pts, size_t npts, ColourDesired fore, ColourDesired back) {
PenColour(fore);
BrushColor(back);
std::vector<POINT> outline;
outline.reserve(npts);
for (size_t i = 0; i < npts; i++) {
POINT pt = { static_cast<LONG>(pts[i].x), static_cast<LONG>(pts[i].y) };
outline.push_back(pt);
}
::Polygon(hdc, outline.data(), static_cast<int>(npts));
}
void SurfaceGDI::RectangleDraw(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept {
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::Rectangle(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
}
void SurfaceGDI::FillRectangle(PRectangle rc, ColourDesired back) noexcept {
// Using ExtTextOut rather than a FillRect ensures that no dithering occurs.
// There is no need to allocate a brush either.
const RECT rcw = RectFromPRectangle(rc);
::SetBkColor(hdc, back.AsInteger());
::ExtTextOut(hdc, rcw.left, rcw.top, ETO_OPAQUE, &rcw, L"", 0, nullptr);
}
void SurfaceGDI::FillRectangle(PRectangle rc, Surface &surfacePattern) noexcept {
HBRUSH br;
if (static_cast<SurfaceGDI &>(surfacePattern).bitmap)
br = ::CreatePatternBrush(static_cast<SurfaceGDI &>(surfacePattern).bitmap);
else // Something is wrong so display in red
br = ::CreateSolidBrush(RGB(0xff, 0, 0));
const RECT rcw = RectFromPRectangle(rc);
::FillRect(hdc, &rcw, br);
::DeleteObject(br);
}
void SurfaceGDI::RoundedRectangle(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept {
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::RoundRect(hdc,
rcw.left + 1, rcw.top,
rcw.right - 1, rcw.bottom,
8, 8);
}
namespace {
// Plot a point into a DWORD buffer symmetrically to all 4 quadrants
void AllFour(DWORD *pixels, int width, int height, int x, int y, DWORD val) noexcept {
pixels[y*width + x] = val;
pixels[y*width + width - 1 - x] = val;
pixels[(height - 1 - y)*width + x] = val;
pixels[(height - 1 - y)*width + width - 1 - x] = val;
}
constexpr DWORD dwordFromBGRA(byte b, byte g, byte r, byte a) noexcept {
#if 0
union {
byte pixVal[4];
DWORD val;
} converter;
converter.pixVal[0] = b;
converter.pixVal[1] = g;
converter.pixVal[2] = r;
converter.pixVal[3] = a;
return converter.val;
#else
return (b) | (g << 8) | (r << 16) | (a << 24);
#endif
}
DWORD dwordMultiplied(ColourDesired colour, unsigned int alpha) noexcept {
return dwordFromBGRA(
static_cast<byte>(colour.GetBlue() * alpha / 255),
static_cast<byte>(colour.GetGreen() * alpha / 255),
static_cast<byte>(colour.GetRed() * alpha / 255),
static_cast<byte>(alpha));
}
}
void SurfaceGDI::AlphaRectangle(PRectangle rc, int cornerSize, ColourDesired fill, int alphaFill,
ColourDesired outline, int alphaOutline, int /* flags*/) noexcept {
const RECT rcw = RectFromPRectangle(rc);
if (rc.Width() > 0) {
HDC hMemDC = ::CreateCompatibleDC(hdc);
const int width = rcw.right - rcw.left;
const int height = rcw.bottom - rcw.top;
// Ensure not distorted too much by corners when small
cornerSize = std::min(cornerSize, (std::min(width, height) / 2) - 2);
const BITMAPINFO bpih = { {sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0},
{{0, 0, 0, 0}} };
void *image = nullptr;
HBITMAP hbmMem = CreateDIBSection(hMemDC, &bpih,
DIB_RGB_COLORS, &image, nullptr, 0);
if (hbmMem) {
HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
constexpr DWORD valEmpty = dwordFromBGRA(0, 0, 0, 0);
const DWORD valFill = dwordMultiplied(fill, alphaFill);
const DWORD valOutline = dwordMultiplied(outline, alphaOutline);
DWORD *pixels = static_cast<DWORD *>(image);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if ((x == 0) || (x == width - 1) || (y == 0) || (y == height - 1)) {
pixels[y*width + x] = valOutline;
} else {
pixels[y*width + x] = valFill;
}
}
}
for (int c = 0; c < cornerSize; c++) {
for (int x = 0; x < c + 1; x++) {
AllFour(pixels, width, height, x, c - x, valEmpty);
}
}
for (int x = 1; x < cornerSize; x++) {
AllFour(pixels, width, height, x, cornerSize - x, valOutline);
}
const BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
GdiAlphaBlend(hdc, rcw.left, rcw.top, width, height, hMemDC, 0, 0, width, height, merge);
SelectBitmap(hMemDC, hbmOld);
::DeleteObject(hbmMem);
}
::DeleteDC(hMemDC);
} else {
BrushColor(outline);
FrameRect(hdc, &rcw, brush);
}
}
void SurfaceGDI::GradientRectangle(PRectangle rc, const std::vector<ColourStop> &stops, GradientOptions) {
// Would be better to average start and end.
const ColourAlpha colourAverage = stops[0].colour.MixedWith(stops[1].colour);
AlphaRectangle(rc, 0, colourAverage.GetColour(), colourAverage.GetAlpha(),
colourAverage.GetColour(), colourAverage.GetAlpha(), 0);
}
void SurfaceGDI::DrawRGBAImage(PRectangle rc, int width, int height, const unsigned char *pixelsImage) noexcept {
if (rc.Width() > 0) {
HDC hMemDC = ::CreateCompatibleDC(hdc);
if (rc.Width() > width)
rc.left += floor((rc.Width() - width) / 2);
rc.right = rc.left + width;
if (rc.Height() > height)
rc.top += floor((rc.Height() - height) / 2);
rc.bottom = rc.top + height;
const BITMAPINFO bpih = { {sizeof(BITMAPINFOHEADER), width, height, 1, 32, BI_RGB, 0, 0, 0, 0, 0},
{{0, 0, 0, 0}} };
void *image = nullptr;
HBITMAP hbmMem = CreateDIBSection(hMemDC, &bpih,
DIB_RGB_COLORS, &image, nullptr, 0);
if (hbmMem) {
HBITMAP hbmOld = SelectBitmap(hMemDC, hbmMem);
for (int y = height - 1; y >= 0; y--) {
for (int x = 0; x < width; x++) {
unsigned char *pixel = static_cast<unsigned char *>(image) + (y*width + x) * 4;
const unsigned char alpha = pixelsImage[3];
// Input is RGBA, output is BGRA with premultiplied alpha
pixel[2] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
pixel[1] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
pixel[0] = static_cast<unsigned char>((*pixelsImage++) * alpha / 255);
pixel[3] = *pixelsImage++;
}
}
const BLENDFUNCTION merge = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
GdiAlphaBlend(hdc, static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.Width()), static_cast<int>(rc.Height()), hMemDC, 0, 0, width, height, merge);
SelectBitmap(hMemDC, hbmOld);
::DeleteObject(hbmMem);
}
::DeleteDC(hMemDC);
}
}
void SurfaceGDI::Ellipse(PRectangle rc, ColourDesired fore, ColourDesired back) noexcept {
PenColour(fore);
BrushColor(back);
const RECT rcw = RectFromPRectangle(rc);
::Ellipse(hdc, rcw.left, rcw.top, rcw.right, rcw.bottom);
}
void SurfaceGDI::Copy(PRectangle rc, Point from, Surface &surfaceSource) noexcept {
::BitBlt(hdc,
static_cast<int>(rc.left), static_cast<int>(rc.top),
static_cast<int>(rc.Width()), static_cast<int>(rc.Height()),
static_cast<SurfaceGDI &>(surfaceSource).hdc,
static_cast<int>(from.x), static_cast<int>(from.y), SRCCOPY);
}
std::unique_ptr<IScreenLineLayout> SurfaceGDI::Layout(const IScreenLine *) noexcept {
return {};
}
typedef VarBuffer<int, stackBufferLength> TextPositionsI;
void SurfaceGDI::DrawTextCommon(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text, UINT fuOptions) {
SetFont(font_);
const RECT rcw = RectFromPRectangle(rc);
const int x = static_cast<int>(rc.left);
const int yBaseInt = static_cast<int>(ybase);
if (unicodeMode) {
const TextWide tbuf(text, unicodeMode, codePage);
::ExtTextOutW(hdc, x, yBaseInt, fuOptions, &rcw, tbuf.buffer, tbuf.tlen, nullptr);
} else {
::ExtTextOutA(hdc, x, yBaseInt, fuOptions, &rcw, text.data(), static_cast<UINT>(text.length()), nullptr);
}
}
void SurfaceGDI::DrawTextNoClip(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text,
ColourDesired fore, ColourDesired back) {
::SetTextColor(hdc, fore.AsInteger());
::SetBkColor(hdc, back.AsInteger());
DrawTextCommon(rc, font_, ybase, text, ETO_OPAQUE);
}
void SurfaceGDI::DrawTextClipped(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text,
ColourDesired fore, ColourDesired back) {
::SetTextColor(hdc, fore.AsInteger());
::SetBkColor(hdc, back.AsInteger());
DrawTextCommon(rc, font_, ybase, text, ETO_OPAQUE | ETO_CLIPPED);
}
void SurfaceGDI::DrawTextTransparent(PRectangle rc, const Font &font_, XYPOSITION ybase, std::string_view text,
ColourDesired fore) {
// Avoid drawing spaces in transparent mode
for (size_t i = 0; i < text.length(); i++) {
if (text[i] != ' ') {
::SetTextColor(hdc, fore.AsInteger());
::SetBkMode(hdc, TRANSPARENT);
DrawTextCommon(rc, font_, ybase, text, 0);
::SetBkMode(hdc, OPAQUE);
return;
}
}
}
XYPOSITION SurfaceGDI::WidthText(const Font &font_, std::string_view text) {
SetFont(font_);
SIZE sz = { 0, 0 };
if (!unicodeMode) {
::GetTextExtentPoint32A(hdc, text.data(), std::min(static_cast<int>(text.length()), maxLenText), &sz);
} else {
const TextWide tbuf(text, unicodeMode, codePage);
::GetTextExtentPoint32W(hdc, tbuf.buffer, tbuf.tlen, &sz);
}
return static_cast<XYPOSITION>(sz.cx);
}
void SurfaceGDI::MeasureWidths(const Font &font_, std::string_view text, XYPOSITION *positions) {
// Zero positions to avoid random behaviour on failure.
std::fill(positions, positions + text.length(), 0.0f);
SetFont(font_);
SIZE sz = { 0, 0 };
int fit = 0;
int i = 0;
const int len = static_cast<int>(text.length());
if (unicodeMode) {
const TextWide tbuf(text, unicodeMode, codePage);
TextPositionsI poses(tbuf.tlen);
if (!::GetTextExtentExPointW(hdc, tbuf.buffer, tbuf.tlen, maxWidthMeasure, &fit, poses.buffer, &sz)) {
// Failure
return;
}
// Map the widths given for UTF-16 characters back onto the UTF-8 input string
for (int ui = 0; ui < fit; ui++) {
const unsigned char uch = text[i];
const unsigned int byteCount = UTF8BytesOfLead(uch);
if (byteCount == 4) { // Non-BMP
ui++;
}
for (unsigned int bytePos = 0; (bytePos < byteCount) && (i < len); bytePos++) {
positions[i++] = static_cast<XYPOSITION>(poses.buffer[ui]);
}
}
} else {
TextPositionsI poses(len);
if (!::GetTextExtentExPointA(hdc, text.data(), len, maxWidthMeasure, &fit, poses.buffer, &sz)) {
// Eeek - a NULL DC or other foolishness could cause this.
return;
}