-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathFontManagerWindows.cc
490 lines (394 loc) · 12.4 KB
/
FontManagerWindows.cc
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
#define WINVER 0x0600
#include "FontDescriptor.h"
#include <dwrite.h>
#include <dwrite_1.h>
#include <unordered_set>
// throws a JS error when there is some exception in DirectWrite
#define HR(hr) \
if (FAILED(hr)) throw "Font loading error";
WCHAR *utf8ToUtf16(const char *input) {
unsigned int len = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0);
WCHAR *output = new WCHAR[len];
MultiByteToWideChar(CP_UTF8, 0, input, -1, output, len);
return output;
}
char *utf16ToUtf8(const WCHAR *input) {
unsigned int len = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL);
char *output = new char[len];
WideCharToMultiByte(CP_UTF8, 0, input, -1, output, len, NULL, NULL);
return output;
}
// returns the index of the user's locale in the set of localized strings
unsigned int getLocaleIndex(IDWriteLocalizedStrings *strings) {
unsigned int index = 0;
BOOL exists = false;
wchar_t localeName[LOCALE_NAME_MAX_LENGTH];
// Get the default locale for this user.
int success = GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH);
// If the default locale is returned, find that locale name, otherwise use "en-us".
if (success) {
HR(strings->FindLocaleName(localeName, &index, &exists));
}
// if the above find did not find a match, retry with US English
if (!exists) {
HR(strings->FindLocaleName(L"en-us", &index, &exists));
}
if (!exists)
index = 0;
return index;
}
// gets a localized string for a font
char *getString(IDWriteFont *font, DWRITE_INFORMATIONAL_STRING_ID string_id) {
char *res = NULL;
IDWriteLocalizedStrings *strings = NULL;
BOOL exists = false;
HR(font->GetInformationalStrings(
string_id,
&strings,
&exists
));
if (exists) {
unsigned int index = getLocaleIndex(strings);
unsigned int len = 0;
WCHAR *str = NULL;
HR(strings->GetStringLength(index, &len));
str = new WCHAR[len + 1];
HR(strings->GetString(index, str, len + 1));
// convert to utf8
res = utf16ToUtf8(str);
delete str;
strings->Release();
}
if (!res) {
res = new char[1];
res[0] = '\0';
}
return res;
}
FontDescriptor *resultFromFont(IDWriteFont *font) {
FontDescriptor *res = NULL;
IDWriteFontFace *face = NULL;
unsigned int numFiles = 0;
HR(font->CreateFontFace(&face));
// get the font files from this font face
IDWriteFontFile *files = NULL;
HR(face->GetFiles(&numFiles, NULL));
HR(face->GetFiles(&numFiles, &files));
// return the first one
if (numFiles > 0) {
IDWriteFontFileLoader *loader = NULL;
IDWriteLocalFontFileLoader *fileLoader = NULL;
unsigned int nameLength = 0;
const void *referenceKey = NULL;
unsigned int referenceKeySize = 0;
WCHAR *name = NULL;
HR(files[0].GetLoader(&loader));
// check if this is a local font file
HRESULT hr = loader->QueryInterface(__uuidof(IDWriteLocalFontFileLoader), (void **)&fileLoader);
if (SUCCEEDED(hr)) {
// get the file path
HR(files[0].GetReferenceKey(&referenceKey, &referenceKeySize));
HR(fileLoader->GetFilePathLengthFromKey(referenceKey, referenceKeySize, &nameLength));
name = new WCHAR[nameLength + 1];
HR(fileLoader->GetFilePathFromKey(referenceKey, referenceKeySize, name, nameLength + 1));
char *psName = utf16ToUtf8(name);
char *postscriptName = getString(font, DWRITE_INFORMATIONAL_STRING_POSTSCRIPT_NAME);
char *family = getString(font, DWRITE_INFORMATIONAL_STRING_WIN32_FAMILY_NAMES);
char *style = getString(font, DWRITE_INFORMATIONAL_STRING_WIN32_SUBFAMILY_NAMES);
bool monospace = false;
// this method requires windows 7, so we need to cast to an IDWriteFontFace1
IDWriteFontFace1 *face1;
HRESULT hr = face->QueryInterface(__uuidof(IDWriteFontFace1), (void **)&face1);
if (SUCCEEDED(hr)) {
monospace = face1->IsMonospacedFont() == TRUE;
}
res = new FontDescriptor(
psName,
postscriptName,
family,
style,
(FontWeight) font->GetWeight(),
(FontWidth) font->GetStretch(),
font->GetStyle() == DWRITE_FONT_STYLE_ITALIC,
monospace
);
delete psName;
delete name;
delete postscriptName;
delete family;
delete style;
fileLoader->Release();
}
loader->Release();
}
face->Release();
files->Release();
return res;
}
ResultSet *getAvailableFonts() {
ResultSet *res = new ResultSet();
int count = 0;
IDWriteFactory *factory = NULL;
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&factory)
));
// Get the system font collection.
IDWriteFontCollection *collection = NULL;
HR(factory->GetSystemFontCollection(&collection));
// Get the number of font families in the collection.
int familyCount = collection->GetFontFamilyCount();
// track postscript names we've already added
// using a set so we don't get any duplicates.
std::unordered_set<std::string> psNames;
for (int i = 0; i < familyCount; i++) {
IDWriteFontFamily *family = NULL;
// Get the font family.
HR(collection->GetFontFamily(i, &family));
int fontCount = family->GetFontCount();
for (int j = 0; j < fontCount; j++) {
IDWriteFont *font = NULL;
HR(family->GetFont(j, &font));
FontDescriptor *result = resultFromFont(font);
if (psNames.count(result->postscriptName) == 0) {
res->push_back(resultFromFont(font));
psNames.insert(result->postscriptName);
}
}
family->Release();
}
collection->Release();
factory->Release();
return res;
}
bool resultMatches(FontDescriptor *result, FontDescriptor *desc) {
if (desc->postscriptName && strcmp(desc->postscriptName, result->postscriptName) != 0)
return false;
if (desc->family && strcmp(desc->family, result->family) != 0)
return false;
if (desc->style && strcmp(desc->style, result->style) != 0)
return false;
if (desc->weight && desc->weight != result->weight)
return false;
if (desc->width && desc->width != result->width)
return false;
if (desc->italic != result->italic)
return false;
if (desc->monospace != result->monospace)
return false;
return true;
}
ResultSet *findFonts(FontDescriptor *desc) {
ResultSet *fonts = getAvailableFonts();
for (ResultSet::iterator it = fonts->begin(); it != fonts->end();) {
if (!resultMatches(*it, desc)) {
delete *it;
it = fonts->erase(it);
} else {
it++;
}
}
return fonts;
}
FontDescriptor *findFont(FontDescriptor *desc) {
ResultSet *fonts = findFonts(desc);
// if we didn't find anything, try again with only the font traits, no string names
if (fonts->size() == 0) {
delete fonts;
FontDescriptor *fallback = new FontDescriptor(
NULL, NULL, NULL, NULL,
desc->weight, desc->width, desc->italic, false
);
fonts = findFonts(fallback);
}
// ok, nothing. shouldn't happen often.
// just return the first available font
if (fonts->size() == 0) {
delete fonts;
fonts = getAvailableFonts();
}
// hopefully we found something now.
// copy and return the first result
if (fonts->size() > 0) {
FontDescriptor *res = new FontDescriptor(fonts->front());
delete fonts;
return res;
}
// whoa, weird. no fonts installed or something went wrong.
delete fonts;
return NULL;
}
// custom text renderer used to determine the fallback font for a given char
class FontFallbackRenderer : public IDWriteTextRenderer {
public:
IDWriteFontCollection *systemFonts;
IDWriteFont *font;
unsigned long refCount;
FontFallbackRenderer(IDWriteFontCollection *collection) {
refCount = 0;
collection->AddRef();
systemFonts = collection;
font = NULL;
}
~FontFallbackRenderer() {
if (systemFonts)
systemFonts->Release();
if (font)
font->Release();
}
// IDWriteTextRenderer methods
IFACEMETHOD(DrawGlyphRun)(
void *clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_MEASURING_MODE measuringMode,
DWRITE_GLYPH_RUN const *glyphRun,
DWRITE_GLYPH_RUN_DESCRIPTION const *glyphRunDescription,
IUnknown *clientDrawingEffect) {
// save the font that was actually rendered
return systemFonts->GetFontFromFontFace(glyphRun->fontFace, &font);
}
IFACEMETHOD(DrawUnderline)(
void *clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_UNDERLINE const *underline,
IUnknown *clientDrawingEffect) {
return E_NOTIMPL;
}
IFACEMETHOD(DrawStrikethrough)(
void *clientDrawingContext,
FLOAT baselineOriginX,
FLOAT baselineOriginY,
DWRITE_STRIKETHROUGH const *strikethrough,
IUnknown *clientDrawingEffect) {
return E_NOTIMPL;
}
IFACEMETHOD(DrawInlineObject)(
void *clientDrawingContext,
FLOAT originX,
FLOAT originY,
IDWriteInlineObject *inlineObject,
BOOL isSideways,
BOOL isRightToLeft,
IUnknown *clientDrawingEffect) {
return E_NOTIMPL;
}
// IDWritePixelSnapping methods
IFACEMETHOD(IsPixelSnappingDisabled)(void *clientDrawingContext, BOOL *isDisabled) {
*isDisabled = FALSE;
return S_OK;
}
IFACEMETHOD(GetCurrentTransform)(void *clientDrawingContext, DWRITE_MATRIX *transform) {
const DWRITE_MATRIX ident = {1.0, 0.0, 0.0, 1.0, 0.0, 0.0};
*transform = ident;
return S_OK;
}
IFACEMETHOD(GetPixelsPerDip)(void *clientDrawingContext, FLOAT *pixelsPerDip) {
*pixelsPerDip = 1.0f;
return S_OK;
}
// IUnknown methods
IFACEMETHOD_(unsigned long, AddRef)() {
return InterlockedIncrement(&refCount);
}
IFACEMETHOD_(unsigned long, Release)() {
unsigned long newCount = InterlockedDecrement(&refCount);
if (newCount == 0) {
delete this;
return 0;
}
return newCount;
}
IFACEMETHOD(QueryInterface)(IID const& riid, void **ppvObject) {
if (__uuidof(IDWriteTextRenderer) == riid) {
*ppvObject = this;
} else if (__uuidof(IDWritePixelSnapping) == riid) {
*ppvObject = this;
} else if (__uuidof(IUnknown) == riid) {
*ppvObject = this;
} else {
*ppvObject = nullptr;
return E_FAIL;
}
this->AddRef();
return S_OK;
}
};
FontDescriptor *substituteFont(char *postscriptName, char *string) {
FontDescriptor *res = NULL;
IDWriteFactory *factory = NULL;
HR(DWriteCreateFactory(
DWRITE_FACTORY_TYPE_SHARED,
__uuidof(IDWriteFactory),
reinterpret_cast<IUnknown**>(&factory)
));
// Get the system font collection.
IDWriteFontCollection *collection = NULL;
HR(factory->GetSystemFontCollection(&collection));
// find the font for the given postscript name
FontDescriptor *desc = new FontDescriptor();
desc->postscriptName = postscriptName;
FontDescriptor *font = findFont(desc);
// create a text format object for this font
IDWriteTextFormat *format = NULL;
if (font) {
WCHAR *familyName = utf8ToUtf16(font->family);
// create a text format
HR(factory->CreateTextFormat(
familyName,
collection,
(DWRITE_FONT_WEIGHT) font->weight,
font->italic ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL,
(DWRITE_FONT_STRETCH) font->width,
12.0,
L"en-us",
&format
));
delete familyName;
delete font;
} else {
// this should never happen, but just in case, let the system
// decide the default font in case findFont returned nothing.
HR(factory->CreateTextFormat(
L"",
collection,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
12.0,
L"en-us",
&format
));
}
// convert utf8 string for substitution to utf16
WCHAR *str = utf8ToUtf16(string);
// create a text layout for the substitution string
IDWriteTextLayout *layout = NULL;
HR(factory->CreateTextLayout(
str,
wcslen(str),
format,
100.0,
100.0,
&layout
));
// render it using a custom renderer that saves the physical font being used
FontFallbackRenderer *renderer = new FontFallbackRenderer(collection);
HR(layout->Draw(NULL, renderer, 100.0, 100.0));
// if we found something, create a result object
if (renderer->font) {
res = resultFromFont(renderer->font);
}
// free all the things
delete renderer;
layout->Release();
format->Release();
desc->postscriptName = NULL;
delete desc;
delete str;
collection->Release();
factory->Release();
return res;
}