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