OpenTTD Source: src/os/windows/font_win32.cpp Source File

OpenTTD Source 1.11.0-RC1

font_win32.cpp
Go to the documentation of this file.
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
7
10 #include "../../stdafx.h"
11 #include "../../debug.h"
12 #include "font_win32.h"
13 #include "../../blitter/factory.hpp"
14 #include "../../core/alloc_func.hpp"
15 #include "../../core/math_func.hpp"
16 #include "../../fileio_func.h"
17 #include "../../fontdetection.h"
18 #include "../../fontcache.h"
19 #include "../../string_func.h"
20 #include "../../strings_func.h"
21 #include "../../zoom_func.h"
22
23 #include "../../table/control_codes.h"
24
25 #include <windows.h>
26 #include <shlobj.h> /* SHGetFolderPath */
27 #include "os/windows/win32.h"
28 #undef small // Say what, Windows?
29
30 #include "safeguards.h"
31
32 #ifdef WITH_FREETYPE
33
34 #include <ft2build.h>
35 #include FT_FREETYPE_H
36
37 extern FT_Library _library;
38
49 static const char *GetShortPath(const wchar_t *long_path)
50 {
51 static char short_path[MAX_PATH];
52 wchar_t short_path_w[MAX_PATH];
53 GetShortPathName(long_path, short_path_w, lengthof(short_path_w));
54 WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, lengthof(short_path), nullptr, nullptr);
55 return short_path;
56 }
57
58 /* Get the font file to be loaded into Freetype by looping the registry
59 * location where windows lists all installed fonts. Not very nice, will
60 * surely break if the registry path changes, but it works. Much better
61 * solution would be to use CreateFont, and extract the font data from it
62 * by GetFontData. The problem with this is that the font file needs to be
63 * kept in memory then until the font is no longer needed. This could mean
64 * an additional memory usage of 30MB (just for fonts!) when using an eastern
65 * font for all font sizes */
66 static const wchar_t *FONT_DIR_NT = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
67 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
68 {
69 FT_Error err = FT_Err_Cannot_Open_Resource;
70 HKEY hKey;
71 LONG ret;
72 wchar_t vbuffer[MAX_PATH], dbuffer[256];
73 wchar_t *pathbuf;
74 const char *font_path;
75 uint index;
76 size_t path_len;
77
78 ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, FONT_DIR_NT, 0, KEY_READ, &hKey);
79
80 if (ret != ERROR_SUCCESS) {
81 DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts");
82 return err;
83 }
84
85 /* Convert font name to file system encoding. */
86 wchar_t *font_namep = wcsdup(OTTD2FS(font_name));
87
88 for (index = 0;; index++) {
89 wchar_t *s;
90 DWORD vbuflen = lengthof(vbuffer);
91 DWORD dbuflen = lengthof(dbuffer);
92
93 ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, nullptr, nullptr, (byte *)dbuffer, &dbuflen);
94 if (ret != ERROR_SUCCESS) goto registry_no_font_found;
95
96 /* The font names in the registry are of the following 3 forms:
97 * - ADMUI3.fon
98 * - Book Antiqua Bold (TrueType)
99 * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
100 * We will strip the font-type '()' if any and work with the font name
101 * itself, which must match exactly; if...
102 * TTC files, font files which contain more than one font are separated
103 * by '&'. Our best bet will be to do substr match for the fontname
104 * and then let FreeType figure out which index to load */
105 s = wcschr(vbuffer, L'(');
106 if (s != nullptr) s[-1] = '\0';
107
108 if (wcschr(vbuffer, L'&') == nullptr) {
109 if (wcsicmp(vbuffer, font_namep) == 0) break;
110 } else {
111 if (wcsstr(vbuffer, font_namep) != nullptr) break;
112 }
113 }
114
115 if (!SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_FONTS, nullptr, SHGFP_TYPE_CURRENT, vbuffer))) {
116 DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
117 goto folder_error;
118 }
119
120 /* Some fonts are contained in .ttc files, TrueType Collection fonts. These
121 * contain multiple fonts inside this single file. GetFontData however
122 * returns the whole file, so we need to check each font inside to get the
123 * proper font. */
124 path_len = wcslen(vbuffer) + wcslen(dbuffer) + 2; // '\' and terminating nul.
125 pathbuf = AllocaM(wchar_t, path_len);
126 _snwprintf(pathbuf, path_len, L"%s\\%s", vbuffer, dbuffer);
127
128 /* Convert the path into something that FreeType understands. */
129 font_path = GetShortPath(pathbuf);
130
131 index = 0;
132 do {
133 err = FT_New_Face(_library, font_path, index, face);
134 if (err != FT_Err_Ok) break;
135
136 if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
137 /* Try english name if font name failed */
138 if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
139 err = FT_Err_Cannot_Open_Resource;
140
141 } while ((FT_Long)++index != (*face)->num_faces);
142
143
144 folder_error:
145 registry_no_font_found:
146 free(font_namep);
147 RegCloseKey(hKey);
148 return err;
149 }
150
164 static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
165 {
166 static char font_name[MAX_PATH];
167 const char *ret_font_name = nullptr;
168 uint pos = 0;
169 HDC dc;
170 HGDIOBJ oldfont;
171 byte *buf;
172 DWORD dw;
173 uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
174
175 HFONT font = CreateFontIndirect(&logfont->elfLogFont);
176 if (font == nullptr) goto err1;
177
178 dc = GetDC(nullptr);
179 oldfont = SelectObject(dc, font);
180 dw = GetFontData(dc, 'eman', 0, nullptr, 0);
181 if (dw == GDI_ERROR) goto err2;
182
183 buf = MallocT<byte>(dw);
184 dw = GetFontData(dc, 'eman', 0, buf, dw);
185 if (dw == GDI_ERROR) goto err3;
186
187 format = buf[pos++] << 8;
188 format += buf[pos++];
189 assert(format == 0);
190 count = buf[pos++] << 8;
191 count += buf[pos++];
192 stringOffset = buf[pos++] << 8;
193 stringOffset += buf[pos++];
194 for (uint i = 0; i < count; i++) {
195 platformId = buf[pos++] << 8;
196 platformId += buf[pos++];
197 encodingId = buf[pos++] << 8;
198 encodingId += buf[pos++];
199 languageId = buf[pos++] << 8;
200 languageId += buf[pos++];
201 nameId = buf[pos++] << 8;
202 nameId += buf[pos++];
203 if (nameId != 1) {
204 pos += 4; // skip length and offset
205 continue;
206 }
207 length = buf[pos++] << 8;
208 length += buf[pos++];
209 offset = buf[pos++] << 8;
210 offset += buf[pos++];
211
212 /* Don't buffer overflow */
213 length = std::min<uint16>(length, MAX_PATH - 1);
214 for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
215 font_name[length] = '\0';
216
217 if ((platformId == 1 && languageId == 0) || // Macintosh English
218 (platformId == 3 && languageId == 0x0409)) { // Microsoft English (US)
219 ret_font_name = font_name;
220 break;
221 }
222 }
223
224 err3:
225 free(buf);
226 err2:
227 SelectObject(dc, oldfont);
228 ReleaseDC(nullptr, dc);
229 DeleteObject(font);
230 err1:
231 return ret_font_name == nullptr ? FS2OTTD((const wchar_t *)logfont->elfFullName) : ret_font_name;
232 }
233 #endif /* WITH_FREETYPE */
234
235 class FontList {
236 protected:
237 wchar_t **fonts;
238 uint items;
239 uint capacity;
240
241 public:
242 FontList() : fonts(nullptr), items(0), capacity(0) { };
243
244 ~FontList() {
245 if (this->fonts == nullptr) return;
246
247 for (uint i = 0; i < this->items; i++) {
248 free(this->fonts[i]);
249 }
250
251 free(this->fonts);
252 }
253
254 bool Add(const wchar_t *font) {
255 for (uint i = 0; i < this->items; i++) {
256 if (wcscmp(this->fonts[i], font) == 0) return false;
257 }
258
259 if (this->items == this->capacity) {
260 this->capacity += 10;
261 this->fonts = ReallocT(this->fonts, this->capacity);
262 }
263
264 this->fonts[this->items++] = wcsdup(font);
265
266 return true;
267 }
268 };
269
270 struct EFCParam {
271 FreeTypeSettings *settings;
272 LOCALESIGNATURE locale;
273 MissingGlyphSearcher *callback;
274 FontList fonts;
275 };
276
277 static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXTMETRICEX *metric, DWORD type, LPARAM lParam)
278 {
279 EFCParam *info = (EFCParam *)lParam;
280
281 /* Skip duplicates */
282 if (!info->fonts.Add((const wchar_t *)logfont->elfFullName)) return 1;
283 /* Only use TrueType fonts */
284 if (!(type & TRUETYPE_FONTTYPE)) return 1;
285 /* Don't use SYMBOL fonts */
286 if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1;
287 /* Use monospaced fonts when asked for it. */
288 if (info->callback->Monospace() && (logfont->elfLogFont.lfPitchAndFamily & (FF_MODERN | FIXED_PITCH)) != (FF_MODERN | FIXED_PITCH)) return 1;
289
290 /* The font has to have at least one of the supported locales to be usable. */
291 if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) {
292 /* On win9x metric->ntmFontSig seems to contain garbage. */
293 FONTSIGNATURE fs;
294 memset(&fs, 0, sizeof(fs));
295 HFONT font = CreateFontIndirect(&logfont->elfLogFont);
296 if (font != nullptr) {
297 HDC dc = GetDC(nullptr);
298 HGDIOBJ oldfont = SelectObject(dc, font);
299 GetTextCharsetInfo(dc, &fs, 0);
300 SelectObject(dc, oldfont);
301 ReleaseDC(nullptr, dc);
302 DeleteObject(font);
303 }
304 if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1;
305 }
306
307 char font_name[MAX_PATH];
308 convert_from_fs((const wchar_t *)logfont->elfFullName, font_name, lengthof(font_name));
309
310 #ifdef WITH_FREETYPE
311 /* Add english name after font name */
312 const char *english_name = GetEnglishFontName(logfont);
313 strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name));
314
315 /* Check whether we can actually load the font. */
316 bool ft_init = _library != nullptr;
317 bool found = false;
318 FT_Face face;
319 /* Init FreeType if needed. */
320 if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName(font_name, &face) == FT_Err_Ok) {
321 FT_Done_Face(face);
322 found = true;
323 }
324 if (!ft_init) {
325 /* Uninit FreeType if we did the init. */
326 FT_Done_FreeType(_library);
327 _library = nullptr;
328 }
329
330 if (!found) return 1;
331 #else
332 const char *english_name = font_name;
333 #endif /* WITH_FREETYPE */
334
335 info->callback->SetFontNames(info->settings, font_name, &logfont->elfLogFont);
336 if (info->callback->FindMissingGlyphs()) return 1;
337 DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
338 return 0; // stop enumerating
339 }
340
341 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
342 {
343 DEBUG(freetype, 1, "Trying fallback fonts");
344 EFCParam langInfo;
345 if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(wchar_t)) == 0) {
346 /* Invalid langid or some other mysterious error, can't determine fallback font. */
347 DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid);
348 return false;
349 }
350 langInfo.settings = settings;
351 langInfo.callback = callback;
352
353 LOGFONT font;
354 /* Enumerate all fonts. */
355 font.lfCharSet = DEFAULT_CHARSET;
356 font.lfFaceName[0] = '\0';
357 font.lfPitchAndFamily = 0;
358
359 HDC dc = GetDC(nullptr);
360 int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
361 ReleaseDC(nullptr, dc);
362 return ret == 0;
363 }
364
365
366 #ifndef ANTIALIASED_QUALITY
367 #define ANTIALIASED_QUALITY 4
368 #endif
369
376 Win32FontCache::Win32FontCache(FontSize fs, const LOGFONT &logfont, int pixels) : TrueTypeFontCache(fs, pixels), logfont(logfont)
377 {
378 this->dc = CreateCompatibleDC(nullptr);
379 this->SetFontSize(fs, pixels);
380 }
381
382 Win32FontCache::~Win32FontCache()
383 {
384 this->ClearFontCache();
385 DeleteDC(this->dc);
386 DeleteObject(this->font);
387 }
388
389 void Win32FontCache::SetFontSize(FontSize fs, int pixels)
390 {
391 if (pixels == 0) {
392 /* Try to determine a good height based on the minimal height recommended by the font. */
393 int scaled_height = ScaleFontTrad(this->GetDefaultFontHeight(this->fs));
394 pixels = scaled_height;
395
396 HFONT temp = CreateFontIndirect(&this->logfont);
397 if (temp != nullptr) {
398 HGDIOBJ old = SelectObject(this->dc, temp);
399
400 UINT size = GetOutlineTextMetrics(this->dc, 0, nullptr);
401 LPOUTLINETEXTMETRIC otm = (LPOUTLINETEXTMETRIC)AllocaM(BYTE, size);
402 GetOutlineTextMetrics(this->dc, size, otm);
403
404 /* Font height is minimum height plus the difference between the default
405 * height for this font size and the small size. */
406 int diff = scaled_height - ScaleFontTrad(this->GetDefaultFontHeight(FS_SMALL));
407 pixels = Clamp(std::min(otm->otmusMinimumPPEM, MAX_FONT_MIN_REC_SIZE) + diff, scaled_height, MAX_FONT_SIZE);
408
409 SelectObject(dc, old);
410 DeleteObject(temp);
411 }
412 } else {
413 pixels = ScaleFontTrad(pixels);
414 }
415 this->used_size = pixels;
416
417 /* Create GDI font handle. */
418 this->logfont.lfHeight = -pixels;
419 this->logfont.lfWidth = 0;
420 this->logfont.lfOutPrecision = ANTIALIASED_QUALITY;
421
422 if (this->font != nullptr) {
423 SelectObject(dc, this->old_font);
424 DeleteObject(this->font);
425 }
426 this->font = CreateFontIndirect(&this->logfont);
427 this->old_font = SelectObject(this->dc, this->font);
428
429 /* Query the font metrics we needed. */
430 UINT otmSize = GetOutlineTextMetrics(this->dc, 0, nullptr);
431 POUTLINETEXTMETRIC otm = (POUTLINETEXTMETRIC)AllocaM(BYTE, otmSize);
432 GetOutlineTextMetrics(this->dc, otmSize, otm);
433
434 this->units_per_em = otm->otmEMSquare;
435 this->ascender = otm->otmTextMetrics.tmAscent;
436 this->descender = otm->otmTextMetrics.tmDescent;
437 this->height = this->ascender + this->descender;
438 this->glyph_size.cx = otm->otmTextMetrics.tmMaxCharWidth;
439 this->glyph_size.cy = otm->otmTextMetrics.tmHeight;
440
441 DEBUG(freetype, 2, "Loaded font '%s' with size %d", FS2OTTD((LPTSTR)((BYTE *)otm + (ptrdiff_t)otm->otmpFullName)), pixels);
442 }
443
447 void Win32FontCache::ClearFontCache()
448 {
449 /* GUI scaling might have changed, determine font size anew if it was automatically selected. */
450 if (this->font != nullptr) this->SetFontSize(this->fs, this->req_size);
451
452 this->TrueTypeFontCache::ClearFontCache();
453 }
454
455 /* virtual */ const Sprite *Win32FontCache::InternalGetGlyph(GlyphID key, bool aa)
456 {
457 GLYPHMETRICS gm;
458 MAT2 mat = { {0, 1}, {0, 0}, {0, 0}, {0, 1} };
459
460 /* Make a guess for the needed memory size. */
461 DWORD size = this->glyph_size.cy * Align(aa ? this->glyph_size.cx : std::max(this->glyph_size.cx / 8l, 1l), 4); // Bitmap data is DWORD-aligned rows.
462 byte *bmp = AllocaM(byte, size);
463 size = GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, size, bmp, &mat);
464
465 if (size == GDI_ERROR) {
466 /* No dice with the guess. First query size of needed glyph memory, then allocate the
467 * memory and query again. This dance is necessary as some glyphs will only render with
468 * the exact matching size; e.g. the space glyph has no pixels and must be requested
469 * with size == 0, anything else fails. Unfortunately, a failed call doesn't return any
470 * info about the size and thus the triple GetGlyphOutline()-call. */
471 size = GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, 0, nullptr, &mat);
472 if (size == GDI_ERROR) usererror("Unable to render font glyph");
473 bmp = AllocaM(byte, size);
474 GetGlyphOutline(this->dc, key, GGO_GLYPH_INDEX | (aa ? GGO_GRAY8_BITMAP : GGO_BITMAP), &gm, size, bmp, &mat);
475 }
476
477 /* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel. */
478 uint width = std::max(1U, (uint)gm.gmBlackBoxX + (this->fs == FS_NORMAL));
479 uint height = std::max(1U, (uint)gm.gmBlackBoxY + (this->fs == FS_NORMAL));
480
481 /* Limit glyph size to prevent overflows later on. */
482 if (width > MAX_GLYPH_DIM || height > MAX_GLYPH_DIM) usererror("Font glyph is too large");
483
484 /* GDI has rendered the glyph, now we allocate a sprite and copy the image into it. */
485 SpriteLoader::Sprite sprite;
486 sprite.AllocateData(ZOOM_LVL_NORMAL, width * height);
487 sprite.type = ST_FONT;
488 sprite.colours = (aa ? SCC_PAL | SCC_ALPHA : SCC_PAL);
489 sprite.width = width;
490 sprite.height = height;
491 sprite.x_offs = gm.gmptGlyphOrigin.x;
492 sprite.y_offs = this->ascender - gm.gmptGlyphOrigin.y;
493
494 if (size > 0) {
495 /* All pixel data returned by GDI is in the form of DWORD-aligned rows.
496 * For a non anti-aliased glyph, the returned bitmap has one bit per pixel.
497 * For anti-aliased rendering, GDI uses the strange value range of 0 to 64,
498 * inclusively. To map this to 0 to 255, we shift left by two and then
499 * subtract one. */
500 uint pitch = Align(aa ? gm.gmBlackBoxX : std::max(gm.gmBlackBoxX / 8u, 1u), 4);
501
502 /* Draw shadow for medium size. */
503 if (this->fs == FS_NORMAL && !aa) {
504 for (uint y = 0; y < gm.gmBlackBoxY; y++) {
505 for (uint x = 0; x < gm.gmBlackBoxX; x++) {
506 if (aa ? (bmp[x + y * pitch] > 0) : HasBit(bmp[(x / 8) + y * pitch], 7 - (x % 8))) {
507 sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
508 sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? (bmp[x + y * pitch] << 2) - 1 : 0xFF;
509 }
510 }
511 }
512 }
513
514 for (uint y = 0; y < gm.gmBlackBoxY; y++) {
515 for (uint x = 0; x < gm.gmBlackBoxX; x++) {
516 if (aa ? (bmp[x + y * pitch] > 0) : HasBit(bmp[(x / 8) + y * pitch], 7 - (x % 8))) {
517 sprite.data[x + y * sprite.width].m = FACE_COLOUR;
518 sprite.data[x + y * sprite.width].a = aa ? (bmp[x + y * pitch] << 2) - 1 : 0xFF;
519 }
520 }
521 }
522 }
523
524 GlyphEntry new_glyph;
525 new_glyph.sprite = BlitterFactory::GetCurrentBlitter()->Encode(&sprite, SimpleSpriteAlloc);
526 new_glyph.width = gm.gmCellIncX;
527
528 this->SetGlyphPtr(key, &new_glyph);
529
530 return new_glyph.sprite;
531 }
532
533 /* virtual */ GlyphID Win32FontCache::MapCharToGlyph(WChar key)
534 {
535 assert(IsPrintable(key));
536
537 if (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END) {
538 return this->parent->MapCharToGlyph(key);
539 }
540
541 /* Convert characters outside of the BMP into surrogate pairs. */
542 WCHAR chars[2];
543 if (key >= 0x010000U) {
544 chars[0] = (WCHAR)(((key - 0x010000U) >> 10) + 0xD800);
545 chars[1] = (WCHAR)(((key - 0x010000U) & 0x3FF) + 0xDC00);
546 } else {
547 chars[0] = (WCHAR)(key & 0xFFFF);
548 }
549
550 WORD glyphs[2] = { 0, 0 };
551 GetGlyphIndicesW(this->dc, chars, key >= 0x010000U ? 2 : 1, glyphs, GGI_MARK_NONEXISTING_GLYPHS);
552
553 return glyphs[0] != 0xFFFF ? glyphs[0] : 0;
554 }
555
556 /* virtual */ const void *Win32FontCache::InternalGetFontTable(uint32 tag, size_t &length)
557 {
558 DWORD len = GetFontData(this->dc, tag, 0, nullptr, 0);
559
560 void *result = nullptr;
561 if (len != GDI_ERROR && len > 0) {
562 result = MallocT<BYTE>(len);
563 GetFontData(this->dc, tag, 0, result, len);
564 }
565
566 length = len;
567 return result;
568 }
569
570
577 void LoadWin32Font(FontSize fs)
578 {
579 static const char *SIZE_TO_NAME[] = { "medium", "small", "large", "mono" };
580
581 FreeTypeSubSetting *settings = nullptr;
582 switch (fs) {
583 case FS_SMALL: settings = &_freetype.small; break;
584 case FS_NORMAL: settings = &_freetype.medium; break;
585 case FS_LARGE: settings = &_freetype.large; break;
586 case FS_MONO: settings = &_freetype.mono; break;
587 default: NOT_REACHED();
588 }
589
590 if (StrEmpty(settings->font)) return;
591
592 LOGFONT logfont;
593 MemSetT(&logfont, 0);
594 logfont.lfPitchAndFamily = fs == FS_MONO ? FIXED_PITCH : VARIABLE_PITCH;
595 logfont.lfCharSet = DEFAULT_CHARSET;
596 logfont.lfOutPrecision = OUT_OUTLINE_PRECIS;
597 logfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
598
599 if (settings->os_handle != nullptr) {
600 logfont = *(const LOGFONT *)settings->os_handle;
601 } else if (strchr(settings->font, '.') != nullptr) {
602 /* Might be a font file name, try load it. */
603
604 wchar_t fontPath[MAX_PATH] = {};
605
606 /* See if this is an absolute path. */
607 if (FileExists(settings->font)) {
608 convert_to_fs(settings->font, fontPath, lengthof(fontPath), false);
609 } else {
610 /* Scan the search-paths to see if it can be found. */
611 std::string full_font = FioFindFullPath(BASE_DIR, settings->font);
612 if (!full_font.empty()) {
613 convert_to_fs(full_font.c_str(), fontPath, lengthof(fontPath), false);
614 }
615 }
616
617 if (fontPath[0] != 0) {
618 if (AddFontResourceEx(fontPath, FR_PRIVATE, 0) != 0) {
619 /* Try a nice little undocumented function first for getting the internal font name.
620 * Some documentation is found at: http://www.undocprint.org/winspool/getfontresourceinfo */
621 typedef BOOL(WINAPI *PFNGETFONTRESOURCEINFO)(LPCTSTR, LPDWORD, LPVOID, DWORD);
622 static PFNGETFONTRESOURCEINFO GetFontResourceInfo = (PFNGETFONTRESOURCEINFO)GetProcAddress(GetModuleHandle(L"Gdi32"), "GetFontResourceInfoW");
623
624 if (GetFontResourceInfo != nullptr) {
625 /* Try to query an array of LOGFONTs that describe the file. */
626 DWORD len = 0;
627 if (GetFontResourceInfo(fontPath, &len, nullptr, 2) && len >= sizeof(LOGFONT)) {
628 LOGFONT *buf = (LOGFONT *)AllocaM(byte, len);
629 if (GetFontResourceInfo(fontPath, &len, buf, 2)) {
630 logfont = *buf; // Just use first entry.
631 }
632 }
633 }
634
635 /* No dice yet. Use the file name as the font face name, hoping it matches. */
636 if (logfont.lfFaceName[0] == 0) {
637 wchar_t fname[_MAX_FNAME];
638 _wsplitpath(fontPath, nullptr, nullptr, fname, nullptr);
639
640 wcsncpy_s(logfont.lfFaceName, lengthof(logfont.lfFaceName), fname, _TRUNCATE);
641 logfont.lfWeight = strcasestr(settings->font, " bold") != nullptr || strcasestr(settings->font, "-bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts.
642 }
643 } else {
644 ShowInfoF("Unable to load file '%s' for %s font, using default windows font selection instead", settings->font, SIZE_TO_NAME[fs]);
645 }
646 }
647 }
648
649 if (logfont.lfFaceName[0] == 0) {
650 logfont.lfWeight = strcasestr(settings->font, " bold") != nullptr ? FW_BOLD : FW_NORMAL; // Poor man's way to allow selecting bold fonts.
651 convert_to_fs(settings->font, logfont.lfFaceName, lengthof(logfont.lfFaceName), false);
652 }
653
654 HFONT font = CreateFontIndirect(&logfont);
655 if (font == nullptr) {
656 ShowInfoF("Unable to use '%s' for %s font, Win32 reported error 0x%lX, using sprite font instead", settings->font, SIZE_TO_NAME[fs], GetLastError());
657 return;
658 }
659 DeleteObject(font);
660
661 new Win32FontCache(fs, logfont, settings->size);
662 }
SpriteLoader::CommonPixel::m
uint8 m
Remap-channel.
Definition: spriteloader.hpp:38
SCC_PAL
@ SCC_PAL
Sprite has palette data.
Definition: spriteloader.hpp:24
GlyphID
uint32 GlyphID
Glyphs are characters from a font.
Definition: fontcache.h:17
Win32FontCache::Win32FontCache
Win32FontCache(FontSize fs, const LOGFONT &logfont, int pixels)
Create a new Win32FontCache.
Definition: font_win32.cpp:376
MissingGlyphSearcher::FindMissingGlyphs
bool FindMissingGlyphs()
Check whether there are glyphs missing in the current language.
Definition: strings.cpp:1987
GetShortPath
static const char * GetShortPath(const wchar_t *long_path)
Get the short DOS 8.3 format for paths.
Definition: font_win32.cpp:49
TrueTypeFontCache
Font cache for fonts that are based on a TrueType font.
Definition: fontcache_internal.h:23
WChar
char32_t WChar
Type for wide characters, i.e.
Definition: string_type.h:35
usererror
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:102
MissingGlyphSearcher
A searcher for missing glyphs.
Definition: strings_func.h:244
Win32FontCache::old_font
HGDIOBJ old_font
Old font selected into the GDI context.
Definition: font_win32.h:22
ScaleFontTrad
static int ScaleFontTrad(int value)
Scale traditional pixel dimensions to Font zoom level.
Definition: zoom_func.h:96
ST_FONT
@ ST_FONT
A sprite used for fonts.
Definition: gfx_type.h:304
FS2OTTD
const char * FS2OTTD(const wchar_t *name)
Convert to OpenTTD's encoding from wide characters.
Definition: win32.cpp:565
FreeTypeSettings::large
FreeTypeSubSetting large
The largest font; mostly used for newspapers.
Definition: fontcache.h:228
win32.h
GetEnglishFontName
static const char * GetEnglishFontName(const ENUMLOGFONTEX *logfont)
Fonts can have localised names and when the system locale is the same as one of those localised names...
Definition: font_win32.cpp:164
SpriteLoader::Sprite::AllocateData
void AllocateData(ZoomLevel zoom, size_t size)
Allocate the sprite data of this sprite.
Definition: spriteloader.hpp:61
FontCache::height
int height
The height of the font.
Definition: fontcache.h:27
font_win32.h
FreeTypeSettings::mono
FreeTypeSubSetting mono
The mono space font used for license/readme viewers.
Definition: fontcache.h:229
HasBit
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103
FS_LARGE
@ FS_LARGE
Index of the large font in the font tables.
Definition: gfx_type.h:209
Win32FontCache::dc
HDC dc
Cached GDI device context.
Definition: font_win32.h:21
SpriteEncoder::Encode
virtual Sprite * Encode(const SpriteLoader::Sprite *sprite, AllocatorProc *allocator)=0
Convert a sprite from the loader to our own format.
GetFontByFaceName
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
Load a freetype font face with the given font name.
Definition: font_win32.cpp:67
Win32FontCache::ClearFontCache
void ClearFontCache() override
Reset cached glyphs.
Definition: font_win32.cpp:447
EFCParam
Definition: font_win32.cpp:270
SpriteLoader::Sprite::data
SpriteLoader::CommonPixel * data
The sprite itself.
Definition: spriteloader.hpp:54
FontCache::units_per_em
int units_per_em
The units per EM value of the font.
Definition: fontcache.h:30
convert_from_fs
char * convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Definition: win32.cpp:595
BASE_DIR
@ BASE_DIR
Base directory for all subdirectories.
Definition: fileio_type.h:109
Align
static T Align(const T x, uint n)
Return the smallest multiple of n equal or greater than x.
Definition: math_func.hpp:35
TrueTypeFontCache::MAX_GLYPH_DIM
static constexpr int MAX_GLYPH_DIM
Maximum glyph dimensions.
Definition: fontcache_internal.h:25
FS_NORMAL
@ FS_NORMAL
Index of the normal font in the font tables.
Definition: gfx_type.h:207
LoadWin32Font
void LoadWin32Font(FontSize fs)
Loads the GDI font.
Definition: font_win32.cpp:577
SpriteLoader::Sprite::type
SpriteType type
The sprite type.
Definition: spriteloader.hpp:52
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
FS_SMALL
@ FS_SMALL
Index of the small font in the font tables.
Definition: gfx_type.h:208
FileExists
bool FileExists(const std::string &filename)
Test whether the given filename exists.
Definition: fileio.cpp:280
convert_to_fs
wchar_t * convert_to_fs(const char *name, wchar_t *system_buf, size_t buflen, bool console_cp)
Convert from OpenTTD's encoding to that of the environment in UNICODE.
Definition: win32.cpp:617
TrueTypeFontCache::MAX_FONT_MIN_REC_SIZE
static constexpr uint MAX_FONT_MIN_REC_SIZE
Upper limit for the recommended font size in case a font file contains nonsensical values.
Definition: fontcache_internal.h:26
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition: factory.hpp:140
safeguards.h
Sprite::width
uint16 width
Width of the sprite.
Definition: spritecache.h:19
SpriteLoader::Sprite::x_offs
int16 x_offs
The x-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:50
StrEmpty
static bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition: string_func.h:60
settings
fluid_settings_t * settings
FluidSynth settings handle.
Definition: fluidsynth.cpp:21
MissingGlyphSearcher::Monospace
virtual bool Monospace()=0
Whether to search for a monospace font or not.
FontCache::fs
const FontSize fs
The size of the font.
Definition: fontcache.h:26
Win32FontCache
Font cache for fonts that are based on a Win32 font.
Definition: font_win32.h:17
SpriteLoader::Sprite::colours
SpriteColourComponent colours
The colour components of the sprite with useful information.
Definition: spriteloader.hpp:53
TrueTypeFontCache::req_size
int req_size
Requested font size.
Definition: fontcache_internal.h:28
FontList
Definition: font_win32.cpp:235
FontCache::descender
int descender
The descender value of the font.
Definition: fontcache.h:29
Clamp
static T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:77
SpriteLoader::Sprite::width
uint16 width
Width of the sprite.
Definition: spriteloader.hpp:49
SetFallbackFont
bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
We would like to have a fallback font as the current one doesn't contain all characters we need.
Definition: font_win32.cpp:341
FreeTypeSubSetting
Settings for a single freetype font.
Definition: fontcache.h:216
FreeTypeSettings::medium
FreeTypeSubSetting medium
The normal font size.
Definition: fontcache.h:227
MAX_FONT_SIZE
static const int MAX_FONT_SIZE
Maximum font size.
Definition: fontcache_internal.h:17
FontCache::parent
FontCache * parent
The parent of this font cache.
Definition: fontcache.h:25
SCC_ALPHA
@ SCC_ALPHA
Sprite has alpha.
Definition: spriteloader.hpp:23
ShowInfoF
void CDECL ShowInfoF(const char *str,...)
Shows some information on the console/a popup box depending on the OS.
Definition: openttd.cpp:153
FontCache::ascender
int ascender
The ascender value of the font.
Definition: fontcache.h:28
TrueTypeFontCache::ClearFontCache
void ClearFontCache() override
Reset cached glyphs.
Definition: fontcache.cpp:233
ReallocT
static T * ReallocT(T *t_ptr, size_t num_elements)
Simplified reallocation function that allocates the specified number of elements of the given type.
Definition: alloc_func.hpp:111
SpriteLoader::Sprite
Structure for passing information from the sprite loader to the blitter.
Definition: spriteloader.hpp:47
TrueTypeFontCache::used_size
int used_size
Used font size.
Definition: fontcache_internal.h:29
Win32FontCache::glyph_size
SIZE glyph_size
Maximum size of regular glyphs.
Definition: font_win32.h:23
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:367
Win32FontCache::MapCharToGlyph
GlyphID MapCharToGlyph(WChar key) override
Map a character into a glyph.
Definition: font_win32.cpp:533
MemSetT
static void MemSetT(T *ptr, byte value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
FS_MONO
@ FS_MONO
Index of the monospaced font in the font tables.
Definition: gfx_type.h:210
SpriteLoader::CommonPixel::a
uint8 a
Alpha-channel.
Definition: spriteloader.hpp:37
ZOOM_LVL_NORMAL
@ ZOOM_LVL_NORMAL
The normal zoom level.
Definition: zoom_type.h:24
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:206
MissingGlyphSearcher::SetFontNames
virtual void SetFontNames(struct FreeTypeSettings *settings, const char *font_name, const void *os_data=nullptr)=0
Set the right font names.
SpriteLoader::Sprite::y_offs
int16 y_offs
The y-offset of where the sprite will be drawn.
Definition: spriteloader.hpp:51
SpriteLoader::Sprite::height
uint16 height
Height of the sprite.
Definition: spriteloader.hpp:48
FioFindFullPath
std::string FioFindFullPath(Subdirectory subdir, const char *filename)
Find a path to the filename in one of the search directories.
Definition: fileio.cpp:299
strecpy
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: string.cpp:112
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:454
SimpleSpriteAlloc
void * SimpleSpriteAlloc(size_t size)
Sprite allocator simply using malloc.
Definition: spritecache.cpp:815
FontCache::MapCharToGlyph
virtual GlyphID MapCharToGlyph(WChar key)=0
Map a character into a glyph.
FreeTypeSettings::small
FreeTypeSubSetting small
The smallest font; mostly used for zoomed out view.
Definition: fontcache.h:226
Sprite
Data structure describing a sprite.
Definition: spritecache.h:17
lastof
#define lastof(x)
Get the last element of an fixed size array.
Definition: stdafx.h:383
OTTD2FS
const wchar_t * OTTD2FS(const char *name, bool console_cp)
Convert from OpenTTD's encoding to wide characters.
Definition: win32.cpp:580
FreeTypeSettings
Settings for the freetype fonts.
Definition: fontcache.h:225
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132