diff options
author | Michael Lutz <michi@icosahedron.de> | 2021-02-13 17:34:22 +0100 |
---|---|---|
committer | Michael Lutz <michi@icosahedron.de> | 2021-02-13 20:09:14 +0100 |
commit | c6af8f16f63d878371d1a823c12fbf21423505b5 (patch) | |
tree | bd0e33995d016b99d39187f2da04ccbee847504f /src/fontdetection.cpp | |
parent | 5ad16409847a17534389054a1b7f5fb83703fb4d (diff) | |
download | openttd-c6af8f16f63d878371d1a823c12fbf21423505b5.tar.xz |
Codechange: [Win32] Move Win32-specific font code to a seperate file.
Diffstat (limited to 'src/fontdetection.cpp')
-rw-r--r-- | src/fontdetection.cpp | 361 |
1 files changed, 8 insertions, 353 deletions
diff --git a/src/fontdetection.cpp b/src/fontdetection.cpp index dfb27a35d..ca9f620b9 100644 --- a/src/fontdetection.cpp +++ b/src/fontdetection.cpp @@ -24,357 +24,7 @@ extern FT_Library _library; * If no appropriate font is found, the function returns an error */ -/* ======================================================================================== - * Windows support - * ======================================================================================== */ - -#ifdef _WIN32 -#include "core/alloc_func.hpp" -#include "core/math_func.hpp" -#include <windows.h> -#include <shlobj.h> /* SHGetFolderPath */ -#include "os/windows/win32.h" - -#include "safeguards.h" - -#ifdef WITH_FREETYPE -/** - * Get the short DOS 8.3 format for paths. - * FreeType doesn't support Unicode filenames and Windows' fopen (as used - * by FreeType) doesn't support UTF-8 filenames. So we have to convert the - * filename into something that isn't UTF-8 but represents the Unicode file - * name. This is the short DOS 8.3 format. This does not contain any - * characters that fopen doesn't support. - * @param long_path the path in system encoding. - * @return the short path in ANSI (ASCII). - */ -const char *GetShortPath(const TCHAR *long_path) -{ - static char short_path[MAX_PATH]; -#ifdef UNICODE - WCHAR short_path_w[MAX_PATH]; - GetShortPathName(long_path, short_path_w, lengthof(short_path_w)); - WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, lengthof(short_path), nullptr, nullptr); -#else - /* Technically not needed, but do it for consistency. */ - GetShortPathName(long_path, short_path, lengthof(short_path)); -#endif - return short_path; -} - -/* Get the font file to be loaded into Freetype by looping the registry - * location where windows lists all installed fonts. Not very nice, will - * surely break if the registry path changes, but it works. Much better - * solution would be to use CreateFont, and extract the font data from it - * by GetFontData. The problem with this is that the font file needs to be - * kept in memory then until the font is no longer needed. This could mean - * an additional memory usage of 30MB (just for fonts!) when using an eastern - * font for all font sizes */ -#define FONT_DIR_NT "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts" -#define FONT_DIR_9X "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts" -FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) -{ - FT_Error err = FT_Err_Cannot_Open_Resource; - HKEY hKey; - LONG ret; - TCHAR vbuffer[MAX_PATH], dbuffer[256]; - TCHAR *pathbuf; - const char *font_path; - uint index; - size_t path_len; - - /* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the - * "Windows NT" key, on Windows 9x in the Windows key. To save us having - * to retrieve the windows version, we'll just query both */ - ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey); - if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey); - - if (ret != ERROR_SUCCESS) { - DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts"); - return err; - } - - /* Convert font name to file system encoding. */ - TCHAR *font_namep = _tcsdup(OTTD2FS(font_name)); - - for (index = 0;; index++) { - TCHAR *s; - DWORD vbuflen = lengthof(vbuffer); - DWORD dbuflen = lengthof(dbuffer); - - ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, nullptr, nullptr, (byte*)dbuffer, &dbuflen); - if (ret != ERROR_SUCCESS) goto registry_no_font_found; - - /* The font names in the registry are of the following 3 forms: - * - ADMUI3.fon - * - Book Antiqua Bold (TrueType) - * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType) - * We will strip the font-type '()' if any and work with the font name - * itself, which must match exactly; if... - * TTC files, font files which contain more than one font are separated - * by '&'. Our best bet will be to do substr match for the fontname - * and then let FreeType figure out which index to load */ - s = _tcschr(vbuffer, _T('(')); - if (s != nullptr) s[-1] = '\0'; - - if (_tcschr(vbuffer, _T('&')) == nullptr) { - if (_tcsicmp(vbuffer, font_namep) == 0) break; - } else { - if (_tcsstr(vbuffer, font_namep) != nullptr) break; - } - } - - if (!SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_FONTS, nullptr, SHGFP_TYPE_CURRENT, vbuffer))) { - DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory"); - goto folder_error; - } - - /* Some fonts are contained in .ttc files, TrueType Collection fonts. These - * contain multiple fonts inside this single file. GetFontData however - * returns the whole file, so we need to check each font inside to get the - * proper font. */ - path_len = _tcslen(vbuffer) + _tcslen(dbuffer) + 2; // '\' and terminating nul. - pathbuf = AllocaM(TCHAR, path_len); - _sntprintf(pathbuf, path_len, _T("%s\\%s"), vbuffer, dbuffer); - - /* Convert the path into something that FreeType understands. */ - font_path = GetShortPath(pathbuf); - - index = 0; - do { - err = FT_New_Face(_library, font_path, index, face); - if (err != FT_Err_Ok) break; - - if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break; - /* Try english name if font name failed */ - if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break; - err = FT_Err_Cannot_Open_Resource; - - } while ((FT_Long)++index != (*face)->num_faces); - - -folder_error: -registry_no_font_found: - free(font_namep); - RegCloseKey(hKey); - return err; -} - -/** - * Fonts can have localised names and when the system locale is the same as - * one of those localised names Windows will always return that localised name - * instead of allowing to get the non-localised (English US) name of the font. - * This will later on give problems as freetype uses the non-localised name of - * the font and we need to compare based on that name. - * Windows furthermore DOES NOT have an API to get the non-localised name nor - * can we override the system locale. This means that we have to actually read - * the font itself to gather the font name we want. - * Based on: http://blogs.msdn.com/michkap/archive/2006/02/13/530814.aspx - * @param logfont the font information to get the english name of. - * @return the English name (if it could be found). - */ -static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont) -{ - static char font_name[MAX_PATH]; - const char *ret_font_name = nullptr; - uint pos = 0; - HDC dc; - HGDIOBJ oldfont; - byte *buf; - DWORD dw; - uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset; - - HFONT font = CreateFontIndirect(&logfont->elfLogFont); - if (font == nullptr) goto err1; - - dc = GetDC(nullptr); - oldfont = SelectObject(dc, font); - dw = GetFontData(dc, 'eman', 0, nullptr, 0); - if (dw == GDI_ERROR) goto err2; - - buf = MallocT<byte>(dw); - dw = GetFontData(dc, 'eman', 0, buf, dw); - if (dw == GDI_ERROR) goto err3; - - format = buf[pos++] << 8; - format += buf[pos++]; - assert(format == 0); - count = buf[pos++] << 8; - count += buf[pos++]; - stringOffset = buf[pos++] << 8; - stringOffset += buf[pos++]; - for (uint i = 0; i < count; i++) { - platformId = buf[pos++] << 8; - platformId += buf[pos++]; - encodingId = buf[pos++] << 8; - encodingId += buf[pos++]; - languageId = buf[pos++] << 8; - languageId += buf[pos++]; - nameId = buf[pos++] << 8; - nameId += buf[pos++]; - if (nameId != 1) { - pos += 4; // skip length and offset - continue; - } - length = buf[pos++] << 8; - length += buf[pos++]; - offset = buf[pos++] << 8; - offset += buf[pos++]; - - /* Don't buffer overflow */ - length = std::min(length, MAX_PATH - 1); - for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j]; - font_name[length] = '\0'; - - if ((platformId == 1 && languageId == 0) || // Macintosh English - (platformId == 3 && languageId == 0x0409)) { // Microsoft English (US) - ret_font_name = font_name; - break; - } - } - -err3: - free(buf); -err2: - SelectObject(dc, oldfont); - ReleaseDC(nullptr, dc); - DeleteObject(font); -err1: - return ret_font_name == nullptr ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name; -} -#endif /* WITH_FREETYPE */ - -class FontList { -protected: - TCHAR **fonts; - uint items; - uint capacity; - -public: - FontList() : fonts(nullptr), items(0), capacity(0) { }; - - ~FontList() { - if (this->fonts == nullptr) return; - - for (uint i = 0; i < this->items; i++) { - free(this->fonts[i]); - } - - free(this->fonts); - } - - bool Add(const TCHAR *font) { - for (uint i = 0; i < this->items; i++) { - if (_tcscmp(this->fonts[i], font) == 0) return false; - } - - if (this->items == this->capacity) { - this->capacity += 10; - this->fonts = ReallocT(this->fonts, this->capacity); - } - - this->fonts[this->items++] = _tcsdup(font); - - return true; - } -}; - -struct EFCParam { - FreeTypeSettings *settings; - LOCALESIGNATURE locale; - MissingGlyphSearcher *callback; - FontList fonts; -}; - -static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXTMETRICEX *metric, DWORD type, LPARAM lParam) -{ - EFCParam *info = (EFCParam *)lParam; - - /* Skip duplicates */ - if (!info->fonts.Add((const TCHAR*)logfont->elfFullName)) return 1; - /* Only use TrueType fonts */ - if (!(type & TRUETYPE_FONTTYPE)) return 1; - /* Don't use SYMBOL fonts */ - if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1; - /* Use monospaced fonts when asked for it. */ - if (info->callback->Monospace() && (logfont->elfLogFont.lfPitchAndFamily & (FF_MODERN | FIXED_PITCH)) != (FF_MODERN | FIXED_PITCH)) return 1; - - /* The font has to have at least one of the supported locales to be usable. */ - if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) { - /* On win9x metric->ntmFontSig seems to contain garbage. */ - FONTSIGNATURE fs; - memset(&fs, 0, sizeof(fs)); - HFONT font = CreateFontIndirect(&logfont->elfLogFont); - if (font != nullptr) { - HDC dc = GetDC(nullptr); - HGDIOBJ oldfont = SelectObject(dc, font); - GetTextCharsetInfo(dc, &fs, 0); - SelectObject(dc, oldfont); - ReleaseDC(nullptr, dc); - DeleteObject(font); - } - if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1; - } - - char font_name[MAX_PATH]; - convert_from_fs((const TCHAR *)logfont->elfFullName, font_name, lengthof(font_name)); - -#ifdef WITH_FREETYPE - /* Add english name after font name */ - const char *english_name = GetEnglishFontName(logfont); - strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name)); - - /* Check whether we can actually load the font. */ - bool ft_init = _library != nullptr; - bool found = false; - FT_Face face; - /* Init FreeType if needed. */ - if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName(font_name, &face) == FT_Err_Ok) { - FT_Done_Face(face); - found = true; - } - if (!ft_init) { - /* Uninit FreeType if we did the init. */ - FT_Done_FreeType(_library); - _library = nullptr; - } - - if (!found) return 1; -#else - const char *english_name = font_name; -#endif /* WITH_FREETYPE */ - - info->callback->SetFontNames(info->settings, font_name, &logfont->elfLogFont); - if (info->callback->FindMissingGlyphs()) return 1; - DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name); - return 0; // stop enumerating -} - -bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback) -{ - DEBUG(freetype, 1, "Trying fallback fonts"); - EFCParam langInfo; - if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(TCHAR)) == 0) { - /* Invalid langid or some other mysterious error, can't determine fallback font. */ - DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid); - return false; - } - langInfo.settings = settings; - langInfo.callback = callback; - - LOGFONT font; - /* Enumerate all fonts. */ - font.lfCharSet = DEFAULT_CHARSET; - font.lfFaceName[0] = '\0'; - font.lfPitchAndFamily = 0; - - HDC dc = GetDC(nullptr); - int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0); - ReleaseDC(nullptr, dc); - return ret == 0; -} - -#elif defined(__APPLE__) /* end ifdef Win32 */ +#if defined(__APPLE__) /* ======================================================================================== * OSX support * ======================================================================================== */ @@ -643,10 +293,15 @@ bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, i FcFini(); return ret; } +#endif /* end ifdef WITH_FONTCONFIG */ -#else /* without WITH_FONTCONFIG */ +#if !defined(_WIN32) && !defined(__APPLE__) && !defined(WITH_FONTCONFIG) + +#ifdef WITH_FREETYPE FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;} +#endif /* WITH_FREETYPE */ + bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback) { return false; } -#endif /* WITH_FONTCONFIG */ +#endif /* !defined(_WIN32) && !defined(__APPLE__) && !defined(WITH_FONTCONFIG) */ #endif /* WITH_FREETYPE */ |