forked from google/skia
-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathSkFontHost_win.cpp
2499 lines (2188 loc) · 88.8 KB
/
SkFontHost_win.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2006 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#if defined(SK_BUILD_FOR_WIN)
#include "SkAdvancedTypefaceMetrics.h"
#include "SkBase64.h"
#include "SkColorData.h"
#include "SkData.h"
#include "SkDescriptor.h"
#include "SkFontDescriptor.h"
#include "SkGlyph.h"
#include "SkHRESULT.h"
#include "SkMakeUnique.h"
#include "SkMaskGamma.h"
#include "SkMatrix22.h"
#include "SkOnce.h"
#include "SkOTTable_OS_2.h"
#include "SkOTTable_maxp.h"
#include "SkOTTable_name.h"
#include "SkOTUtils.h"
#include "SkPath.h"
#include "SkSFNTHeader.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkTemplates.h"
#include "SkTypeface_win.h"
#include "SkTypefaceCache.h"
#include "SkUtils.h"
#include "SkTypes.h"
#include <tchar.h>
#include <usp10.h>
#include <objbase.h>
static void (*gEnsureLOGFONTAccessibleProc)(const LOGFONT&);
void SkTypeface_SetEnsureLOGFONTAccessibleProc(void (*proc)(const LOGFONT&)) {
gEnsureLOGFONTAccessibleProc = proc;
}
static void call_ensure_accessible(const LOGFONT& lf) {
if (gEnsureLOGFONTAccessibleProc) {
gEnsureLOGFONTAccessibleProc(lf);
}
}
///////////////////////////////////////////////////////////////////////////////
// always packed xxRRGGBB
typedef uint32_t SkGdiRGB;
// define this in your Makefile or .gyp to enforce AA requests
// which GDI ignores at small sizes. This flag guarantees AA
// for rotated text, regardless of GDI's notions.
//#define SK_ENFORCE_ROTATED_TEXT_AA_ON_WINDOWS
static bool isLCD(const SkScalerContextRec& rec) {
return SkMask::kLCD16_Format == rec.fMaskFormat;
}
static bool bothZero(SkScalar a, SkScalar b) {
return 0 == a && 0 == b;
}
// returns false if there is any non-90-rotation or skew
static bool isAxisAligned(const SkScalerContextRec& rec) {
return 0 == rec.fPreSkewX &&
(bothZero(rec.fPost2x2[0][1], rec.fPost2x2[1][0]) ||
bothZero(rec.fPost2x2[0][0], rec.fPost2x2[1][1]));
}
static bool needToRenderWithSkia(const SkScalerContextRec& rec) {
#ifdef SK_ENFORCE_ROTATED_TEXT_AA_ON_WINDOWS
// What we really want to catch is when GDI will ignore the AA request and give
// us BW instead. Smallish rotated text is one heuristic, so this code is just
// an approximation. We shouldn't need to do this for larger sizes, but at those
// sizes, the quality difference gets less and less between our general
// scanconverter and GDI's.
if (SkMask::kA8_Format == rec.fMaskFormat && !isAxisAligned(rec)) {
return true;
}
#endif
return rec.getHinting() == SkPaint::kNo_Hinting || rec.getHinting() == SkPaint::kSlight_Hinting;
}
static void tchar_to_skstring(const TCHAR t[], SkString* s) {
#ifdef UNICODE
size_t sSize = WideCharToMultiByte(CP_UTF8, 0, t, -1, nullptr, 0, nullptr, nullptr);
s->resize(sSize);
WideCharToMultiByte(CP_UTF8, 0, t, -1, s->writable_str(), sSize, nullptr, nullptr);
#else
s->set(t);
#endif
}
static void dcfontname_to_skstring(HDC deviceContext, const LOGFONT& lf, SkString* familyName) {
int fontNameLen; //length of fontName in TCHARS.
if (0 == (fontNameLen = GetTextFace(deviceContext, 0, nullptr))) {
call_ensure_accessible(lf);
if (0 == (fontNameLen = GetTextFace(deviceContext, 0, nullptr))) {
fontNameLen = 0;
}
}
SkAutoSTArray<LF_FULLFACESIZE, TCHAR> fontName(fontNameLen+1);
if (0 == GetTextFace(deviceContext, fontNameLen, fontName.get())) {
call_ensure_accessible(lf);
if (0 == GetTextFace(deviceContext, fontNameLen, fontName.get())) {
fontName[0] = 0;
}
}
tchar_to_skstring(fontName.get(), familyName);
}
static void make_canonical(LOGFONT* lf) {
lf->lfHeight = -64;
lf->lfWidth = 0; // lfWidth is related to lfHeight, not to the OS/2::usWidthClass.
lf->lfQuality = CLEARTYPE_QUALITY;//PROOF_QUALITY;
lf->lfCharSet = DEFAULT_CHARSET;
// lf->lfClipPrecision = 64;
}
static SkFontStyle get_style(const LOGFONT& lf) {
return SkFontStyle(lf.lfWeight,
SkFontStyle::kNormal_Width,
lf.lfItalic ? SkFontStyle::kItalic_Slant : SkFontStyle::kUpright_Slant);
}
static inline FIXED SkFixedToFIXED(SkFixed x) {
return *(FIXED*)(&x);
}
static inline SkFixed SkFIXEDToFixed(FIXED x) {
return *(SkFixed*)(&x);
}
static inline FIXED SkScalarToFIXED(SkScalar x) {
return SkFixedToFIXED(SkScalarToFixed(x));
}
static inline SkScalar SkFIXEDToScalar(FIXED x) {
return SkFixedToScalar(SkFIXEDToFixed(x));
}
static unsigned calculateGlyphCount(HDC hdc, const LOGFONT& lf) {
TEXTMETRIC textMetric;
if (0 == GetTextMetrics(hdc, &textMetric)) {
textMetric.tmPitchAndFamily = TMPF_VECTOR;
call_ensure_accessible(lf);
GetTextMetrics(hdc, &textMetric);
}
if (!(textMetric.tmPitchAndFamily & TMPF_VECTOR)) {
return textMetric.tmLastChar;
}
// The 'maxp' table stores the number of glyphs at offset 4, in 2 bytes.
uint16_t glyphs;
if (GDI_ERROR != GetFontData(hdc, SkOTTableMaximumProfile::TAG, 4, &glyphs, sizeof(glyphs))) {
return SkEndian_SwapBE16(glyphs);
}
// Binary search for glyph count.
static const MAT2 mat2 = {{0, 1}, {0, 0}, {0, 0}, {0, 1}};
int32_t max = SK_MaxU16 + 1;
int32_t min = 0;
GLYPHMETRICS gm;
while (min < max) {
int32_t mid = min + ((max - min) / 2);
if (GetGlyphOutlineW(hdc, mid, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0,
nullptr, &mat2) == GDI_ERROR) {
max = mid;
} else {
min = mid + 1;
}
}
SkASSERT(min == max);
return min;
}
static unsigned calculateUPEM(HDC hdc, const LOGFONT& lf) {
TEXTMETRIC textMetric;
if (0 == GetTextMetrics(hdc, &textMetric)) {
textMetric.tmPitchAndFamily = TMPF_VECTOR;
call_ensure_accessible(lf);
GetTextMetrics(hdc, &textMetric);
}
if (!(textMetric.tmPitchAndFamily & TMPF_VECTOR)) {
return textMetric.tmMaxCharWidth;
}
OUTLINETEXTMETRIC otm;
unsigned int otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm);
if (0 == otmRet) {
call_ensure_accessible(lf);
otmRet = GetOutlineTextMetrics(hdc, sizeof(otm), &otm);
}
return (0 == otmRet) ? 0 : otm.otmEMSquare;
}
class LogFontTypeface : public SkTypeface {
public:
LogFontTypeface(const SkFontStyle& style, const LOGFONT& lf, bool serializeAsStream)
: SkTypeface(style, false)
, fLogFont(lf)
, fSerializeAsStream(serializeAsStream)
{
HFONT font = CreateFontIndirect(&lf);
HDC deviceContext = ::CreateCompatibleDC(nullptr);
HFONT savefont = (HFONT)SelectObject(deviceContext, font);
TEXTMETRIC textMetric;
if (0 == GetTextMetrics(deviceContext, &textMetric)) {
call_ensure_accessible(lf);
if (0 == GetTextMetrics(deviceContext, &textMetric)) {
textMetric.tmPitchAndFamily = TMPF_TRUETYPE;
}
}
if (deviceContext) {
::SelectObject(deviceContext, savefont);
::DeleteDC(deviceContext);
}
if (font) {
::DeleteObject(font);
}
// The fixed pitch bit is set if the font is *not* fixed pitch.
this->setIsFixedPitch((textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH) == 0);
this->setFontStyle(SkFontStyle(textMetric.tmWeight, style.width(), style.slant()));
// Used a logfont on a memory context, should never get a device font.
// Therefore all TMPF_DEVICE will be PostScript (cubic) fonts.
// If the font has cubic outlines, it will not be rendered with ClearType.
fCanBeLCD = !((textMetric.tmPitchAndFamily & TMPF_VECTOR) &&
(textMetric.tmPitchAndFamily & TMPF_DEVICE));
}
LOGFONT fLogFont;
bool fSerializeAsStream;
bool fCanBeLCD;
static LogFontTypeface* Create(const LOGFONT& lf) {
return new LogFontTypeface(get_style(lf), lf, false);
}
static void EnsureAccessible(const SkTypeface* face) {
call_ensure_accessible(static_cast<const LogFontTypeface*>(face)->fLogFont);
}
protected:
SkStreamAsset* onOpenStream(int* ttcIndex) const override;
SkScalerContext* onCreateScalerContext(const SkScalerContextEffects&,
const SkDescriptor*) const override;
void onFilterRec(SkScalerContextRec*) const override;
void getGlyphToUnicodeMap(SkUnichar*) const override;
std::unique_ptr<SkAdvancedTypefaceMetrics> onGetAdvancedMetrics() const override;
void onGetFontDescriptor(SkFontDescriptor*, bool*) const override;
int onCharsToGlyphs(const void* chars, Encoding encoding,
uint16_t glyphs[], int glyphCount) const override;
int onCountGlyphs() const override;
int onGetUPEM() const override;
void onGetFamilyName(SkString* familyName) const override;
SkTypeface::LocalizedStrings* onCreateFamilyNameIterator() const override;
int onGetVariationDesignPosition(SkFontArguments::VariationPosition::Coordinate coordinates[],
int coordinateCount) const override
{
return -1;
}
int onGetTableTags(SkFontTableTag tags[]) const override;
size_t onGetTableData(SkFontTableTag, size_t offset, size_t length, void* data) const override;
};
class FontMemResourceTypeface : public LogFontTypeface {
public:
/**
* The created FontMemResourceTypeface takes ownership of fontMemResource.
*/
static FontMemResourceTypeface* Create(const LOGFONT& lf, HANDLE fontMemResource) {
return new FontMemResourceTypeface(get_style(lf), lf, fontMemResource);
}
protected:
void weak_dispose() const override {
RemoveFontMemResourceEx(fFontMemResource);
//SkTypefaceCache::Remove(this);
INHERITED::weak_dispose();
}
private:
/**
* Takes ownership of fontMemResource.
*/
FontMemResourceTypeface(const SkFontStyle& style, const LOGFONT& lf, HANDLE fontMemResource)
: LogFontTypeface(style, lf, true), fFontMemResource(fontMemResource)
{ }
HANDLE fFontMemResource;
typedef LogFontTypeface INHERITED;
};
static const LOGFONT& get_default_font() {
static LOGFONT gDefaultFont;
return gDefaultFont;
}
static bool FindByLogFont(SkTypeface* face, void* ctx) {
LogFontTypeface* lface = static_cast<LogFontTypeface*>(face);
const LOGFONT* lf = reinterpret_cast<const LOGFONT*>(ctx);
return !memcmp(&lface->fLogFont, lf, sizeof(LOGFONT));
}
/**
* This guy is public. It first searches the cache, and if a match is not found,
* it creates a new face.
*/
SkTypeface* SkCreateTypefaceFromLOGFONT(const LOGFONT& origLF) {
LOGFONT lf = origLF;
make_canonical(&lf);
SkTypeface* face = SkTypefaceCache::FindByProcAndRef(FindByLogFont, &lf);
if (nullptr == face) {
face = LogFontTypeface::Create(lf);
SkTypefaceCache::Add(face);
}
return face;
}
/**
* The created SkTypeface takes ownership of fontMemResource.
*/
SkTypeface* SkCreateFontMemResourceTypefaceFromLOGFONT(const LOGFONT& origLF, HANDLE fontMemResource) {
LOGFONT lf = origLF;
make_canonical(&lf);
// We'll never get a cache hit, so no point in putting this in SkTypefaceCache.
return FontMemResourceTypeface::Create(lf, fontMemResource);
}
/**
* This guy is public
*/
void SkLOGFONTFromTypeface(const SkTypeface* face, LOGFONT* lf) {
if (nullptr == face) {
*lf = get_default_font();
} else {
*lf = static_cast<const LogFontTypeface*>(face)->fLogFont;
}
}
// Construct Glyph to Unicode table.
// Unicode code points that require conjugate pairs in utf16 are not
// supported.
// TODO(arthurhsu): Add support for conjugate pairs. It looks like that may
// require parsing the TTF cmap table (platform 4, encoding 12) directly instead
// of calling GetFontUnicodeRange().
static void populate_glyph_to_unicode(HDC fontHdc, const unsigned glyphCount,
SkUnichar* glyphToUnicode) {
sk_bzero(glyphToUnicode, sizeof(SkUnichar) * glyphCount);
DWORD glyphSetBufferSize = GetFontUnicodeRanges(fontHdc, nullptr);
if (!glyphSetBufferSize) {
return;
}
std::unique_ptr<BYTE[]> glyphSetBuffer(new BYTE[glyphSetBufferSize]);
GLYPHSET* glyphSet =
reinterpret_cast<LPGLYPHSET>(glyphSetBuffer.get());
if (GetFontUnicodeRanges(fontHdc, glyphSet) != glyphSetBufferSize) {
return;
}
for (DWORD i = 0; i < glyphSet->cRanges; ++i) {
// There is no guarantee that within a Unicode range, the corresponding
// glyph id in a font file are continuous. So, even if we have ranges,
// we can't just use the first and last entry of the range to compute
// result. We need to enumerate them one by one.
int count = glyphSet->ranges[i].cGlyphs;
SkAutoTArray<WCHAR> chars(count + 1);
chars[count] = 0; // termintate string
SkAutoTArray<WORD> glyph(count);
for (USHORT j = 0; j < count; ++j) {
chars[j] = glyphSet->ranges[i].wcLow + j;
}
GetGlyphIndicesW(fontHdc, chars.get(), count, glyph.get(),
GGI_MARK_NONEXISTING_GLYPHS);
// If the glyph ID is valid, and the glyph is not mapped, then we will
// fill in the char id into the vector. If the glyph is mapped already,
// skip it.
// TODO(arthurhsu): better improve this. e.g. Get all used char ids from
// font cache, then generate this mapping table from there. It's
// unlikely to have collisions since glyph reuse happens mostly for
// different Unicode pages.
for (USHORT j = 0; j < count; ++j) {
if (glyph[j] != 0xFFFF && glyph[j] < glyphCount && glyphToUnicode[glyph[j]] == 0) {
glyphToUnicode[glyph[j]] = chars[j];
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
static int alignTo32(int n) {
return (n + 31) & ~31;
}
struct MyBitmapInfo : public BITMAPINFO {
RGBQUAD fMoreSpaceForColors[1];
};
class HDCOffscreen {
public:
HDCOffscreen() {
fFont = 0;
fDC = 0;
fBM = 0;
fBits = nullptr;
fWidth = fHeight = 0;
fIsBW = false;
}
~HDCOffscreen() {
if (fDC) {
DeleteDC(fDC);
}
if (fBM) {
DeleteObject(fBM);
}
}
void init(HFONT font, const XFORM& xform) {
fFont = font;
fXform = xform;
}
const void* draw(const SkGlyph&, bool isBW, size_t* srcRBPtr);
private:
HDC fDC;
HBITMAP fBM;
HFONT fFont;
XFORM fXform;
void* fBits; // points into fBM
int fWidth;
int fHeight;
bool fIsBW;
};
const void* HDCOffscreen::draw(const SkGlyph& glyph, bool isBW,
size_t* srcRBPtr) {
// Can we share the scalercontext's fDDC, so we don't need to create
// a separate fDC here?
if (0 == fDC) {
fDC = CreateCompatibleDC(0);
if (0 == fDC) {
return nullptr;
}
SetGraphicsMode(fDC, GM_ADVANCED);
SetBkMode(fDC, TRANSPARENT);
SetTextAlign(fDC, TA_LEFT | TA_BASELINE);
SelectObject(fDC, fFont);
COLORREF color = 0x00FFFFFF;
SkDEBUGCODE(COLORREF prev =) SetTextColor(fDC, color);
SkASSERT(prev != CLR_INVALID);
}
if (fBM && (fIsBW != isBW || fWidth < glyph.fWidth || fHeight < glyph.fHeight)) {
DeleteObject(fBM);
fBM = 0;
}
fIsBW = isBW;
fWidth = SkMax32(fWidth, glyph.fWidth);
fHeight = SkMax32(fHeight, glyph.fHeight);
int biWidth = isBW ? alignTo32(fWidth) : fWidth;
if (0 == fBM) {
MyBitmapInfo info;
sk_bzero(&info, sizeof(info));
if (isBW) {
RGBQUAD blackQuad = { 0, 0, 0, 0 };
RGBQUAD whiteQuad = { 0xFF, 0xFF, 0xFF, 0 };
info.bmiColors[0] = blackQuad;
info.bmiColors[1] = whiteQuad;
}
info.bmiHeader.biSize = sizeof(info.bmiHeader);
info.bmiHeader.biWidth = biWidth;
info.bmiHeader.biHeight = fHeight;
info.bmiHeader.biPlanes = 1;
info.bmiHeader.biBitCount = isBW ? 1 : 32;
info.bmiHeader.biCompression = BI_RGB;
if (isBW) {
info.bmiHeader.biClrUsed = 2;
}
fBM = CreateDIBSection(fDC, &info, DIB_RGB_COLORS, &fBits, 0, 0);
if (0 == fBM) {
return nullptr;
}
SelectObject(fDC, fBM);
}
// erase
size_t srcRB = isBW ? (biWidth >> 3) : (fWidth << 2);
size_t size = fHeight * srcRB;
memset(fBits, 0, size);
XFORM xform = fXform;
xform.eDx = (float)-glyph.fLeft;
xform.eDy = (float)-glyph.fTop;
SetWorldTransform(fDC, &xform);
uint16_t glyphID = glyph.getGlyphID();
BOOL ret = ExtTextOutW(fDC, 0, 0, ETO_GLYPH_INDEX, nullptr, reinterpret_cast<LPCWSTR>(&glyphID), 1, nullptr);
GdiFlush();
if (0 == ret) {
return nullptr;
}
*srcRBPtr = srcRB;
// offset to the start of the image
return (const char*)fBits + (fHeight - glyph.fHeight) * srcRB;
}
//////////////////////////////////////////////////////////////////////////////
#define BUFFERSIZE (1 << 13)
class SkScalerContext_GDI : public SkScalerContext {
public:
SkScalerContext_GDI(sk_sp<LogFontTypeface>,
const SkScalerContextEffects&,
const SkDescriptor* desc);
~SkScalerContext_GDI() override;
// Returns true if the constructor was able to complete all of its
// initializations (which may include calling GDI).
bool isValid() const;
protected:
unsigned generateGlyphCount() override;
uint16_t generateCharToGlyph(SkUnichar uni) override;
void generateAdvance(SkGlyph* glyph) override;
void generateMetrics(SkGlyph* glyph) override;
void generateImage(const SkGlyph& glyph) override;
bool generatePath(SkGlyphID glyph, SkPath* path) override;
void generateFontMetrics(SkPaint::FontMetrics*) override;
private:
DWORD getGDIGlyphPath(SkGlyphID glyph, UINT flags,
SkAutoSTMalloc<BUFFERSIZE, uint8_t>* glyphbuf);
HDCOffscreen fOffscreen;
/** fGsA is the non-rotational part of total matrix without the text height scale.
* Used to find the magnitude of advances.
*/
MAT2 fGsA;
/** The total matrix without the textSize. */
MAT2 fMat22;
/** Scales font to EM size. */
MAT2 fHighResMat22;
HDC fDDC;
HFONT fSavefont;
HFONT fFont;
SCRIPT_CACHE fSC;
int fGlyphCount;
/** The total matrix which also removes EM scale. */
SkMatrix fHiResMatrix;
/** fG_inv is the inverse of the rotational part of the total matrix.
* Used to set the direction of advances.
*/
SkMatrix fG_inv;
enum Type {
kTrueType_Type, kBitmap_Type, kLine_Type
} fType;
TEXTMETRIC fTM;
};
static FIXED float2FIXED(float x) {
return SkFixedToFIXED(SkFloatToFixed(x));
}
static inline float FIXED2float(FIXED x) {
return SkFixedToFloat(SkFIXEDToFixed(x));
}
static BYTE compute_quality(const SkScalerContextRec& rec) {
switch (rec.fMaskFormat) {
case SkMask::kBW_Format:
return NONANTIALIASED_QUALITY;
case SkMask::kLCD16_Format:
return CLEARTYPE_QUALITY;
default:
if (rec.fFlags & SkScalerContext::kGenA8FromLCD_Flag) {
return CLEARTYPE_QUALITY;
} else {
return ANTIALIASED_QUALITY;
}
}
}
SkScalerContext_GDI::SkScalerContext_GDI(sk_sp<LogFontTypeface> rawTypeface,
const SkScalerContextEffects& effects,
const SkDescriptor* desc)
: SkScalerContext(std::move(rawTypeface), effects, desc)
, fDDC(0)
, fSavefont(0)
, fFont(0)
, fSC(0)
, fGlyphCount(-1)
{
LogFontTypeface* typeface = static_cast<LogFontTypeface*>(this->getTypeface());
fDDC = ::CreateCompatibleDC(nullptr);
if (!fDDC) {
return;
}
SetGraphicsMode(fDDC, GM_ADVANCED);
SetBkMode(fDDC, TRANSPARENT);
// When GDI hinting, remove the entire Y scale from sA and GsA. (Prevents 'linear' metrics.)
// When not hinting, remove only the integer Y scale from sA and GsA. (Applied by GDI.)
SkScalerContextRec::PreMatrixScale scaleConstraints =
(fRec.getHinting() == SkPaint::kNo_Hinting || fRec.getHinting() == SkPaint::kSlight_Hinting)
? SkScalerContextRec::kVerticalInteger_PreMatrixScale
: SkScalerContextRec::kVertical_PreMatrixScale;
SkVector scale;
SkMatrix sA;
SkMatrix GsA;
SkMatrix A;
fRec.computeMatrices(scaleConstraints, &scale, &sA, &GsA, &fG_inv, &A);
fGsA.eM11 = SkScalarToFIXED(GsA.get(SkMatrix::kMScaleX));
fGsA.eM12 = SkScalarToFIXED(-GsA.get(SkMatrix::kMSkewY)); // This should be ~0.
fGsA.eM21 = SkScalarToFIXED(-GsA.get(SkMatrix::kMSkewX));
fGsA.eM22 = SkScalarToFIXED(GsA.get(SkMatrix::kMScaleY));
// When not hinting, scale was computed with kVerticalInteger, so is already an integer.
// The sA and GsA transforms will be used to create 'linear' metrics.
// When hinting, scale was computed with kVertical, stating that our port can handle
// non-integer scales. This is done so that sA and GsA are computed without any 'residual'
// scale in them, preventing 'linear' metrics. However, GDI cannot actually handle non-integer
// scales so we need to round in this case. This is fine, since all of the scale has been
// removed from sA and GsA, so GDI will be handling the scale completely.
SkScalar gdiTextSize = SkScalarRoundToScalar(scale.fY);
// GDI will not accept a size of zero, so round the range [0, 1] to 1.
// If the size was non-zero, the scale factors will also be non-zero and 1px tall text is drawn.
// If the size actually was zero, the scale factors will also be zero, so GDI will draw nothing.
if (gdiTextSize == 0) {
gdiTextSize = SK_Scalar1;
}
LOGFONT lf = typeface->fLogFont;
lf.lfHeight = -SkScalarTruncToInt(gdiTextSize);
lf.lfQuality = compute_quality(fRec);
fFont = CreateFontIndirect(&lf);
if (!fFont) {
return;
}
fSavefont = (HFONT)SelectObject(fDDC, fFont);
if (0 == GetTextMetrics(fDDC, &fTM)) {
call_ensure_accessible(lf);
if (0 == GetTextMetrics(fDDC, &fTM)) {
fTM.tmPitchAndFamily = TMPF_TRUETYPE;
}
}
XFORM xform;
if (fTM.tmPitchAndFamily & TMPF_VECTOR) {
// Used a logfont on a memory context, should never get a device font.
// Therefore all TMPF_DEVICE will be PostScript fonts.
// If TMPF_VECTOR is set, one of TMPF_TRUETYPE or TMPF_DEVICE means that
// we have an outline font. Otherwise we have a vector FON, which is
// scalable, but not an outline font.
// This was determined by testing with Type1 PFM/PFB and
// OpenTypeCFF OTF, as well as looking at Wine bugs and sources.
if (fTM.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_DEVICE)) {
// Truetype or PostScript.
fType = SkScalerContext_GDI::kTrueType_Type;
} else {
// Stroked FON.
fType = SkScalerContext_GDI::kLine_Type;
}
// fPost2x2 is column-major, left handed (y down).
// XFORM 2x2 is row-major, left handed (y down).
xform.eM11 = SkScalarToFloat(sA.get(SkMatrix::kMScaleX));
xform.eM12 = SkScalarToFloat(sA.get(SkMatrix::kMSkewY));
xform.eM21 = SkScalarToFloat(sA.get(SkMatrix::kMSkewX));
xform.eM22 = SkScalarToFloat(sA.get(SkMatrix::kMScaleY));
xform.eDx = 0;
xform.eDy = 0;
// MAT2 is row major, right handed (y up).
fMat22.eM11 = float2FIXED(xform.eM11);
fMat22.eM12 = float2FIXED(-xform.eM12);
fMat22.eM21 = float2FIXED(-xform.eM21);
fMat22.eM22 = float2FIXED(xform.eM22);
if (needToRenderWithSkia(fRec)) {
this->forceGenerateImageFromPath();
}
// Create a hires matrix if we need linear metrics.
if (this->isSubpixel()) {
OUTLINETEXTMETRIC otm;
UINT success = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm);
if (0 == success) {
call_ensure_accessible(lf);
success = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm);
}
if (0 != success) {
SkScalar upem = SkIntToScalar(otm.otmEMSquare);
SkScalar gdiTextSizeToEMScale = upem / gdiTextSize;
fHighResMat22.eM11 = float2FIXED(gdiTextSizeToEMScale);
fHighResMat22.eM12 = float2FIXED(0);
fHighResMat22.eM21 = float2FIXED(0);
fHighResMat22.eM22 = float2FIXED(gdiTextSizeToEMScale);
SkScalar removeEMScale = SkScalarInvert(upem);
fHiResMatrix = A;
fHiResMatrix.preScale(removeEMScale, removeEMScale);
}
}
} else {
// Assume bitmap
fType = SkScalerContext_GDI::kBitmap_Type;
xform.eM11 = 1.0f;
xform.eM12 = 0.0f;
xform.eM21 = 0.0f;
xform.eM22 = 1.0f;
xform.eDx = 0.0f;
xform.eDy = 0.0f;
// fPost2x2 is column-major, left handed (y down).
// MAT2 is row major, right handed (y up).
fMat22.eM11 = SkScalarToFIXED(fRec.fPost2x2[0][0]);
fMat22.eM12 = SkScalarToFIXED(-fRec.fPost2x2[1][0]);
fMat22.eM21 = SkScalarToFIXED(-fRec.fPost2x2[0][1]);
fMat22.eM22 = SkScalarToFIXED(fRec.fPost2x2[1][1]);
}
fOffscreen.init(fFont, xform);
}
SkScalerContext_GDI::~SkScalerContext_GDI() {
if (fDDC) {
::SelectObject(fDDC, fSavefont);
::DeleteDC(fDDC);
}
if (fFont) {
::DeleteObject(fFont);
}
if (fSC) {
::ScriptFreeCache(&fSC);
}
}
bool SkScalerContext_GDI::isValid() const {
return fDDC && fFont;
}
unsigned SkScalerContext_GDI::generateGlyphCount() {
if (fGlyphCount < 0) {
fGlyphCount = calculateGlyphCount(
fDDC, static_cast<const LogFontTypeface*>(this->getTypeface())->fLogFont);
}
return fGlyphCount;
}
uint16_t SkScalerContext_GDI::generateCharToGlyph(SkUnichar utf32) {
uint16_t index = 0;
WCHAR utf16[2];
// TODO(ctguil): Support characters that generate more than one glyph.
if (SkUTF16_FromUnichar(utf32, (uint16_t*)utf16) == 1) {
// Type1 fonts fail with uniscribe API. Use GetGlyphIndices for plane 0.
/** Real documentation for GetGlyphIndiciesW:
*
* When GGI_MARK_NONEXISTING_GLYPHS is not specified and a character does not map to a
* glyph, then the 'default character's glyph is returned instead. The 'default character'
* is available in fTM.tmDefaultChar. FON fonts have a default character, and there exists
* a usDefaultChar in the 'OS/2' table, version 2 and later. If there is no
* 'default character' specified by the font, then often the first character found is used.
*
* When GGI_MARK_NONEXISTING_GLYPHS is specified and a character does not map to a glyph,
* then the glyph 0xFFFF is used. In Windows XP and earlier, Bitmap/Vector FON usually use
* glyph 0x1F instead ('Terminal' appears to be special, returning 0xFFFF).
* Type1 PFM/PFB, TT, OT TT, OT CFF all appear to use 0xFFFF, even on XP.
*/
DWORD result = GetGlyphIndicesW(fDDC, utf16, 1, &index, GGI_MARK_NONEXISTING_GLYPHS);
if (result == GDI_ERROR
|| 0xFFFF == index
|| (0x1F == index &&
(fType == SkScalerContext_GDI::kBitmap_Type ||
fType == SkScalerContext_GDI::kLine_Type)
/*&& winVer < Vista */)
)
{
index = 0;
}
} else {
// Use uniscribe to detemine glyph index for non-BMP characters.
static const int numWCHAR = 2;
static const int maxItems = 2;
// MSDN states that this can be nullptr, but some things don't work then.
SCRIPT_CONTROL sc;
memset(&sc, 0, sizeof(sc));
// Add extra item to SCRIPT_ITEM to work around a bug (now documented).
// https://bugzilla.mozilla.org/show_bug.cgi?id=366643
SCRIPT_ITEM si[maxItems + 1];
int numItems;
HRZM(ScriptItemize(utf16, numWCHAR, maxItems, &sc, nullptr, si, &numItems),
"Could not itemize character.");
// Disable any attempt at shaping.
// Without this ScriptShape may return 0x80040200 (USP_E_SCRIPT_NOT_IN_FONT)
// when all that is desired here is a simple cmap lookup.
for (SCRIPT_ITEM& item : si) {
item.a.eScript = SCRIPT_UNDEFINED;
}
// Sometimes ScriptShape cannot find a glyph for a non-BMP and returns 2 space glyphs.
static const int maxGlyphs = 2;
SCRIPT_VISATTR vsa[maxGlyphs];
WORD outGlyphs[maxGlyphs];
WORD logClust[numWCHAR];
int numGlyphs;
HRZM(ScriptShape(fDDC, &fSC, utf16, numWCHAR, maxGlyphs, &si[0].a,
outGlyphs, logClust, vsa, &numGlyphs),
"Could not shape character.");
if (1 == numGlyphs) {
index = outGlyphs[0];
}
}
return index;
}
void SkScalerContext_GDI::generateAdvance(SkGlyph* glyph) {
this->generateMetrics(glyph);
}
void SkScalerContext_GDI::generateMetrics(SkGlyph* glyph) {
SkASSERT(fDDC);
if (fType == SkScalerContext_GDI::kBitmap_Type || fType == SkScalerContext_GDI::kLine_Type) {
SIZE size;
WORD glyphs = glyph->getGlyphID();
if (0 == GetTextExtentPointI(fDDC, &glyphs, 1, &size)) {
glyph->fWidth = SkToS16(fTM.tmMaxCharWidth);
} else {
glyph->fWidth = SkToS16(size.cx);
}
glyph->fHeight = SkToS16(size.cy);
glyph->fTop = SkToS16(-fTM.tmAscent);
// Bitmap FON cannot underhang, but vector FON may.
// There appears no means of determining underhang of vector FON.
glyph->fLeft = SkToS16(0);
glyph->fAdvanceX = glyph->fWidth;
glyph->fAdvanceY = 0;
// Vector FON will transform nicely, but bitmap FON do not.
if (fType == SkScalerContext_GDI::kLine_Type) {
SkRect bounds = SkRect::MakeXYWH(glyph->fLeft, glyph->fTop,
glyph->fWidth, glyph->fHeight);
SkMatrix m;
m.setAll(SkFIXEDToScalar(fMat22.eM11), -SkFIXEDToScalar(fMat22.eM21), 0,
-SkFIXEDToScalar(fMat22.eM12), SkFIXEDToScalar(fMat22.eM22), 0,
0, 0, 1);
m.mapRect(&bounds);
bounds.roundOut(&bounds);
glyph->fLeft = SkScalarTruncToInt(bounds.fLeft);
glyph->fTop = SkScalarTruncToInt(bounds.fTop);
glyph->fWidth = SkScalarTruncToInt(bounds.width());
glyph->fHeight = SkScalarTruncToInt(bounds.height());
}
// Apply matrix to advance.
glyph->fAdvanceY = -FIXED2float(fMat22.eM12) * glyph->fAdvanceX;
glyph->fAdvanceX *= FIXED2float(fMat22.eM11);
return;
}
UINT glyphId = glyph->getGlyphID();
GLYPHMETRICS gm;
sk_bzero(&gm, sizeof(gm));
DWORD status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, nullptr, &fMat22);
if (GDI_ERROR == status) {
LogFontTypeface::EnsureAccessible(this->getTypeface());
status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, nullptr, &fMat22);
if (GDI_ERROR == status) {
glyph->zeroMetrics();
return;
}
}
bool empty = false;
// The black box is either the embedded bitmap size or the outline extent.
// It is 1x1 if nothing is to be drawn, but will also be 1x1 if something very small
// is to be drawn, like a '.'. We need to outset '.' but do not wish to outset ' '.
if (1 == gm.gmBlackBoxX && 1 == gm.gmBlackBoxY) {
// If GetGlyphOutline with GGO_NATIVE returns 0, we know there was no outline.
DWORD bufferSize = GetGlyphOutlineW(fDDC, glyphId, GGO_NATIVE | GGO_GLYPH_INDEX, &gm, 0, nullptr, &fMat22);
empty = (0 == bufferSize);
}
glyph->fTop = SkToS16(-gm.gmptGlyphOrigin.y);
glyph->fLeft = SkToS16(gm.gmptGlyphOrigin.x);
if (empty) {
glyph->fWidth = 0;
glyph->fHeight = 0;
} else {
// Outset, since the image may bleed out of the black box.
// For embedded bitmaps the black box should be exact.
// For outlines we need to outset by 1 in all directions for bleed.
// For ClearType we need to outset by 2 for bleed.
glyph->fWidth = gm.gmBlackBoxX + 4;
glyph->fHeight = gm.gmBlackBoxY + 4;
glyph->fTop -= 2;
glyph->fLeft -= 2;
}
// TODO(benjaminwagner): What is the type of gm.gmCellInc[XY]?
glyph->fAdvanceX = (float)((int)gm.gmCellIncX);
glyph->fAdvanceY = (float)((int)gm.gmCellIncY);
if (this->isSubpixel()) {
sk_bzero(&gm, sizeof(gm));
status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, nullptr, &fHighResMat22);
if (GDI_ERROR != status) {
SkPoint advance;
fHiResMatrix.mapXY(SkIntToScalar(gm.gmCellIncX), SkIntToScalar(gm.gmCellIncY), &advance);
glyph->fAdvanceX = SkScalarToFloat(advance.fX);
glyph->fAdvanceY = SkScalarToFloat(advance.fY);
}
} else if (!isAxisAligned(this->fRec)) {
status = GetGlyphOutlineW(fDDC, glyphId, GGO_METRICS | GGO_GLYPH_INDEX, &gm, 0, nullptr, &fGsA);
if (GDI_ERROR != status) {
SkPoint advance;
fG_inv.mapXY(SkIntToScalar(gm.gmCellIncX), SkIntToScalar(gm.gmCellIncY), &advance);
glyph->fAdvanceX = SkScalarToFloat(advance.fX);
glyph->fAdvanceY = SkScalarToFloat(advance.fY);
}
}
}
static const MAT2 gMat2Identity = {{0, 1}, {0, 0}, {0, 0}, {0, 1}};
void SkScalerContext_GDI::generateFontMetrics(SkPaint::FontMetrics* metrics) {
if (nullptr == metrics) {
return;
}
sk_bzero(metrics, sizeof(*metrics));
SkASSERT(fDDC);
#ifndef SK_GDI_ALWAYS_USE_TEXTMETRICS_FOR_FONT_METRICS
if (fType == SkScalerContext_GDI::kBitmap_Type || fType == SkScalerContext_GDI::kLine_Type) {
#endif
metrics->fTop = SkIntToScalar(-fTM.tmAscent);
metrics->fAscent = SkIntToScalar(-fTM.tmAscent);
metrics->fDescent = SkIntToScalar(fTM.tmDescent);
metrics->fBottom = SkIntToScalar(fTM.tmDescent);
metrics->fLeading = SkIntToScalar(fTM.tmExternalLeading);
metrics->fAvgCharWidth = SkIntToScalar(fTM.tmAveCharWidth);
metrics->fMaxCharWidth = SkIntToScalar(fTM.tmMaxCharWidth);
metrics->fXMin = 0;
metrics->fXMax = metrics->fMaxCharWidth;
//metrics->fXHeight = 0;
#ifndef SK_GDI_ALWAYS_USE_TEXTMETRICS_FOR_FONT_METRICS
return;
}
#endif
OUTLINETEXTMETRIC otm;
uint32_t ret = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm);
if (0 == ret) {
LogFontTypeface::EnsureAccessible(this->getTypeface());
ret = GetOutlineTextMetrics(fDDC, sizeof(otm), &otm);
}
if (0 == ret) {