# fontcache.cpp

Go to the documentation of this file.

    00001 /* $Id: fontcache.cpp 19856 2010-05-18 21:38:09Z rubidium $ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00012 #include "stdafx.h"
    00013 #include "fontcache.h"
    00014 #include "blitter/factory.hpp"
    00015 #include "core/math_func.hpp"
    00016
    00017 #include "table/sprites.h"
    00018 #include "table/control_codes.h"
    00019
    00020 static const int ASCII_LETTERSTART = 32;
    00021
    00023 int _font_height[FS_END];
    00024
    00025 #ifdef WITH_FREETYPE
    00026 #include <ft2build.h>
    00027 #include FT_FREETYPE_H
    00028 #include FT_GLYPH_H
    00029
    00030 #ifdef WITH_FONTCONFIG
    00031 #include <fontconfig/fontconfig.h>
    00032 #endif
    00033
    00034 static FT_Library _library = NULL;
    00035 static FT_Face _face_small = NULL;
    00036 static FT_Face _face_medium = NULL;
    00037 static FT_Face _face_large = NULL;
    00038 static int _ascender[FS_END];
    00039
    00040 FreeTypeSettings _freetype;
    00041
    00042 enum {
    00043   FACE_COLOUR = 1,
    00044   SHADOW_COLOUR = 2,
    00045 };
    00046
    00049 #ifdef WIN32
    00050 #include <windows.h>
    00051 #include <shlobj.h> /* SHGetFolderPath */
    00052 #include "os/windows/win32.h"
    00053
    00064 char *GetShortPath(const char *long_path)
    00065 {
    00066   static char short_path[MAX_PATH];
    00067 #ifdef UNICODE
    00068   /* The non-unicode GetShortPath doesn't support UTF-8...,
    00069    * so convert the path to wide chars, then get the short
    00070    * path and convert it back again. */
    00071   wchar_t long_path_w[MAX_PATH];
    00072   MultiByteToWideChar(CP_UTF8, 0, long_path, -1, long_path_w, MAX_PATH);
    00073
    00074   wchar_t short_path_w[MAX_PATH];
    00075   GetShortPathNameW(long_path_w, short_path_w, MAX_PATH);
    00076
    00077   WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, MAX_PATH, NULL, NULL);
    00078 #else
    00079   /* Technically not needed, but do it for consistency. */
    00080   GetShortPathNameA(long_path, short_path, MAX_PATH);
    00081 #endif
    00082   return short_path;
    00083 }
    00084
    00085 /* Get the font file to be loaded into Freetype by looping the registry
    00086  * location where windows lists all installed fonts. Not very nice, will
    00087  * surely break if the registry path changes, but it works. Much better
    00088  * solution would be to use CreateFont, and extract the font data from it
    00089  * by GetFontData. The problem with this is that the font file needs to be
    00090  * kept in memory then until the font is no longer needed. This could mean
    00091  * an additional memory usage of 30MB (just for fonts!) when using an eastern
    00092  * font for all font sizes */
    00093 #define FONT_DIR_NT "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"
    00094 #define FONT_DIR_9X "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts"
    00095 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
    00096 {
    00097   FT_Error err = FT_Err_Cannot_Open_Resource;
    00098   HKEY hKey;
    00099   LONG ret;
    00100   TCHAR vbuffer[MAX_PATH], dbuffer[256];
    00101   TCHAR *font_namep;
    00102   char *font_path;
    00103   uint index;
    00104
    00105   /* On windows NT (2000, NT3.5, XP, etc.) the fonts are stored in the
    00106    * "Windows NT" key, on Windows 9x in the Windows key. To save us having
    00107    * to retrieve the windows version, we'll just query both */
    00108   ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
    00109   if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);
    00110
    00111   if (ret != ERROR_SUCCESS) {
    00112     DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
    00113     return err;
    00114   }
    00115
    00116   /* For Unicode we need some conversion between widechar and
    00117    * normal char to match the data returned by RegEnumValue,
    00118    * otherwise just use parameter */
    00119 #if defined(UNICODE)
    00120   font_namep = MallocT<TCHAR>(MAX_PATH);
    00121   MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
    00122 #else
    00123   font_namep = const_cast<char *>(font_name); // only cast because in unicode pointer is not const
    00124 #endif
    00125
    00126   for (index = 0;; index++) {
    00127     TCHAR *s;
    00128     DWORD vbuflen = lengthof(vbuffer);
    00129     DWORD dbuflen = lengthof(dbuffer);
    00130
    00131     ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
    00132     if (ret != ERROR_SUCCESS) goto registry_no_font_found;
    00133
    00134     /* The font names in the registry are of the following 3 forms:
    00135      * - ADMUI3.fon
    00136      * - Book Antiqua Bold (TrueType)
    00137      * - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
    00138      * We will strip the font-type '()' if any and work with the font name
    00139      * itself, which must match exactly; if...
    00140      * TTC files, font files which contain more than one font are seperated
    00141      * byt '&'. Our best bet will be to do substr match for the fontname
    00142      * and then let FreeType figure out which index to load */
    00143     s = _tcschr(vbuffer, _T('('));
    00144     if (s != NULL) s[-1] = '\0';
    00145
    00146     if (_tcschr(vbuffer, _T('&')) == NULL) {
    00147       if (_tcsicmp(vbuffer, font_namep) == 0) break;
    00148     } else {
    00149       if (_tcsstr(vbuffer, font_namep) != NULL) break;
    00150     }
    00151   }
    00152
    00153   if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
    00154     DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
    00155     goto folder_error;
    00156   }
    00157
    00158   /* Some fonts are contained in .ttc files, TrueType Collection fonts. These
    00159    * contain multiple fonts inside this single file. GetFontData however
    00160    * returns the whole file, so we need to check each font inside to get the
    00161    * proper font.
    00162    * Also note that FreeType does not support UNICODE filesnames! */
    00163 #if defined(UNICODE)
    00164   /* We need a cast here back from wide because FreeType doesn't support
    00165    * widechar filenames. Just use the buffer we allocated before for the
    00166    * font_name search */
    00167   font_path = (char*)font_namep;
    00168   WIDE_TO_MB_BUFFER(vbuffer, font_path, MAX_PATH * sizeof(TCHAR));
    00169 #else
    00170   font_path = vbuffer;
    00171 #endif
    00172
    00173   ttd_strlcat(font_path, "\\", MAX_PATH * sizeof(TCHAR));
    00174   ttd_strlcat(font_path, WIDE_TO_MB(dbuffer), MAX_PATH * sizeof(TCHAR));
    00175
    00176   /* Convert the path into something that FreeType understands */
    00177   font_path = GetShortPath(font_path);
    00178
    00179   index = 0;
    00180   do {
    00181     err = FT_New_Face(_library, font_path, index, face);
    00182     if (err != FT_Err_Ok) break;
    00183
    00184     if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
    00185     /* Try english name if font name failed */
    00186     if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
    00187     err = FT_Err_Cannot_Open_Resource;
    00188
    00189   } while ((FT_Long)++index != (*face)->num_faces);
    00190
    00191
    00192 folder_error:
    00193 registry_no_font_found:
    00194 #if defined(UNICODE)
    00195   free(font_namep);
    00196 #endif
    00197   RegCloseKey(hKey);
    00198   return err;
    00199 }
    00200
    00214 static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
    00215 {
    00216   static char font_name[MAX_PATH];
    00217   const char *ret_font_name = NULL;
    00218   uint pos = 0;
    00219   HDC dc;
    00220   HGDIOBJ oldfont;
    00221   byte *buf;
    00222   DWORD dw;
    00223   uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
    00224
    00225   HFONT font = CreateFontIndirect(&logfont->elfLogFont);
    00226   if (font == NULL) goto err1;
    00227
    00228   dc = GetDC(NULL);
    00229   oldfont = SelectObject(dc, font);
    00230   dw = GetFontData(dc, 'eman', 0, NULL, 0);
    00231   if (dw == GDI_ERROR) goto err2;
    00232
    00233   buf = MallocT<byte>(dw);
    00234   dw = GetFontData(dc, 'eman', 0, buf, dw);
    00235   if (dw == GDI_ERROR) goto err3;
    00236
    00237   format = buf[pos++] << 8;
    00238   format += buf[pos++];
    00239   assert(format == 0);
    00240   count = buf[pos++] << 8;
    00241   count += buf[pos++];
    00242   stringOffset = buf[pos++] << 8;
    00243   stringOffset += buf[pos++];
    00244   for (uint i = 0; i < count; i++) {
    00245     platformId = buf[pos++] << 8;
    00246     platformId += buf[pos++];
    00247     encodingId = buf[pos++] << 8;
    00248     encodingId += buf[pos++];
    00249     languageId = buf[pos++] << 8;
    00250     languageId += buf[pos++];
    00251     nameId = buf[pos++] << 8;
    00252     nameId += buf[pos++];
    00253     if (nameId != 1) {
    00254       pos += 4; // skip length and offset
    00255       continue;
    00256     }
    00257     length = buf[pos++] << 8;
    00258     length += buf[pos++];
    00259     offset = buf[pos++] << 8;
    00260     offset += buf[pos++];
    00261
    00262     /* Don't buffer overflow */
    00263     length = min(length, MAX_PATH - 1);
    00264     for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
    00265     font_name[length] = '\0';
    00266
    00267     if ((platformId == 1 && languageId == 0) ||      // Macintosh English
    00268       (platformId == 3 && languageId == 0x0409)) { // Microsoft English (US)
    00269       ret_font_name = font_name;
    00270       break;
    00271     }
    00272   }
    00273
    00274 err3:
    00275   free(buf);
    00276 err2:
    00277   SelectObject(dc, oldfont);
    00278   ReleaseDC(NULL, dc);
    00279 err1:
    00280   DeleteObject(font);
    00281
    00282   return ret_font_name == NULL ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name;
    00283 }
    00284
    00285 struct EFCParam {
    00286   FreeTypeSettings *settings;
    00287   LOCALESIGNATURE  locale;
    00288 };
    00289
    00290 static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXTMETRICEX *metric, DWORD type, LPARAM lParam)
    00291 {
    00292   EFCParam *info = (EFCParam *)lParam;
    00293
    00294   /* Only use TrueType fonts */
    00295   if (!(type & TRUETYPE_FONTTYPE)) return 1;
    00296   /* Don't use SYMBOL fonts */
    00297   if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1;
    00298
    00299   /* The font has to have at least one of the supported locales to be usable. */
    00300   if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) {
    00301     /* On win9x metric->ntmFontSig seems to contain garbage. */
    00302     FONTSIGNATURE fs;
    00303     memset(&fs, 0, sizeof(fs));
    00304     HFONT font = CreateFontIndirect(&logfont->elfLogFont);
    00305     if (font != NULL) {
    00306       HDC dc = GetDC(NULL);
    00307       HGDIOBJ oldfont = SelectObject(dc, font);
    00308       GetTextCharsetInfo(dc, &fs, 0);
    00309       SelectObject(dc, oldfont);
    00310       ReleaseDC(NULL, dc);
    00311       DeleteObject(font);
    00312     }
    00313     if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1;
    00314   }
    00315
    00316   char font_name[MAX_PATH];
    00317 #if defined(UNICODE)
    00318   WIDE_TO_MB_BUFFER((const TCHAR*)logfont->elfFullName, font_name, lengthof(font_name));
    00319 #else
    00320   strecpy(font_name, (const TCHAR*)logfont->elfFullName, lastof(font_name));
    00321 #endif
    00322
    00323   /* Add english name after font name */
    00324   const char *english_name = GetEnglishFontName(logfont);
    00325   strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name));
    00326
    00327   /* Check whether we can actually load the font. */
    00328   bool ft_init = _library != NULL;
    00329   bool found = false;
    00330   FT_Face face;
    00331   /* Init FreeType if needed. */
    00332   if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName(font_name, &face) == FT_Err_Ok) {
    00333     FT_Done_Face(face);
    00334     found = true;
    00335   }
    00336   if (!ft_init) {
    00337     /* Uninit FreeType if we did the init. */
    00338     FT_Done_FreeType(_library);
    00339     _library = NULL;
    00340   }
    00341
    00342   if (!found) return 1;
    00343
    00344   DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
    00345   strecpy(info->settings->small_font,  font_name, lastof(info->settings->small_font));
    00346   strecpy(info->settings->medium_font, font_name, lastof(info->settings->medium_font));
    00347   strecpy(info->settings->large_font,  font_name, lastof(info->settings->large_font));
    00348   return 0; // stop enumerating
    00349 }
    00350
    00351 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00352 {
    00353   DEBUG(freetype, 1, "Trying fallback fonts");
    00354   EFCParam langInfo;
    00355   if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(TCHAR)) == 0) {
    00356     /* Invalid langid or some other mysterious error, can't determine fallback font. */
    00357     DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid);
    00358     return false;
    00359   }
    00360   langInfo.settings = settings;
    00361
    00362   LOGFONT font;
    00363   /* Enumerate all fonts. */
    00364   font.lfCharSet = DEFAULT_CHARSET;
    00365   font.lfFaceName[0] = '\0';
    00366   font.lfPitchAndFamily = 0;
    00367
    00368   HDC dc = GetDC(NULL);
    00369   int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
    00370   ReleaseDC(NULL, dc);
    00371   return ret == 0;
    00372 }
    00373
    00374 #elif defined(__APPLE__)
    00375
    00376 #include "os/macosx/macos.h"
    00377 #include <ApplicationServices/ApplicationServices.h>
    00378
    00379 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
    00380 {
    00381   FT_Error err = FT_Err_Cannot_Open_Resource;
    00382
    00383   /* Get font reference from name. */
    00384   CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name, kCFStringEncodingUTF8);
    00385   ATSFontRef font = ATSFontFindFromName(name, kATSOptionFlagsDefault);
    00386   CFRelease(name);
    00387   if (font == kInvalidFont) return err;
    00388
    00389   /* Get a file system reference for the font. */
    00390   FSRef ref;
    00391   OSStatus os_err = -1;
    00392 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
    00393   if (MacOSVersionIsAtLeast(10, 5, 0)) {
    00394     os_err = ATSFontGetFileReference(font, &ref);
    00395   } else
    00396 #endif
    00397   {
    00398 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
    00399     /* This type was introduced with the 10.5 SDK. */
    00400 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
    00401   #define ATSFSSpec FSSpec
    00402 #endif
    00403     FSSpec spec;
    00404     os_err = ATSFontGetFileSpecification(font, (ATSFSSpec *)&spec);
    00405     if (os_err == noErr) os_err = FSpMakeFSRef(&spec, &ref);
    00406 #endif
    00407   }
    00408
    00409   if (os_err == noErr) {
    00410     /* Get unix path for file. */
    00411     UInt8 file_path[PATH_MAX];
    00412     if (FSRefMakePath(&ref, file_path, sizeof(file_path)) == noErr) {
    00413       DEBUG(freetype, 3, "Font path for %s: %s", font_name, file_path);
    00414       err = FT_New_Face(_library, (const char *)file_path, 0, face);
    00415     }
    00416   }
    00417
    00418   return err;
    00419 }
    00420
    00421 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00422 {
    00423   bool result = false;
    00424
    00425 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
    00426   if (MacOSVersionIsAtLeast(10, 5, 0)) {
    00427     /* Determine fallback font using CoreText. This uses the language isocode
    00428      * to find a suitable font. CoreText is available from 10.5 onwards. */
    00429     char lang[16];
    00430     if (strcmp(language_isocode, "zh_TW") == 0) {
    00431       /* Traditional Chinese */
    00432       strecpy(lang, "zh-Hant", lastof(lang));
    00433     } else if (strcmp(language_isocode, "zh_CN") == 0) {
    00434       /* Simplified Chinese */
    00435       strecpy(lang, "zh-Hans", lastof(lang));
    00436     } else if (strncmp(language_isocode, "ur", 2) == 0) {
    00437       /* The urdu alphabet is variant of persian. As OS X has no default
    00438        * font that advertises an urdu language code, search for persian
    00439        * support instead. */
    00440       strecpy(lang, "fa", lastof(lang));
    00441     } else {
    00442       /* Just copy the first part of the isocode. */
    00443       strecpy(lang, language_isocode, lastof(lang));
    00444       char *sep = strchr(lang, '_');
    00445       if (sep != NULL) *sep = '\0';
    00446     }
    00447
    00448     CFStringRef lang_code;
    00449     lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);
    00450
    00451     /* Create a font iterator and iterate over all fonts that
    00452      * are available to the application. */
    00453     ATSFontIterator itr;
    00454     ATSFontRef font;
    00455     ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);
    00456     while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
    00457       /* Get CoreText font handle. */
    00458       CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);
    00459       CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);
    00460       if (langs != NULL) {
    00461         /* Font has a list of supported languages. */
    00462         for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) {
    00463           CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
    00464           if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) {
    00465             /* Lang code is supported by font, get full font name. */
    00466             CFStringRef font_name = CTFontCopyFullName(font_ref);
    00467             char name[128];
    00468             CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);
    00469             CFRelease(font_name);
    00470             /* Skip some inappropriate or ugly looking fonts that have better alternatives. */
    00471             if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 ||
    00472               strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 ||
    00473               strncmp(name, "GB18030 Bitmap", 14) == 0) continue;
    00474
    00475             /* Save result. */
    00476             strecpy(settings->small_font,  name, lastof(settings->small_font));
    00477             strecpy(settings->medium_font, name, lastof(settings->medium_font));
    00478             strecpy(settings->large_font,  name, lastof(settings->large_font));
    00479             DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);
    00480             result = true;
    00481             break;
    00482           }
    00483         }
    00484         CFRelease(langs);
    00485       }
    00486       CFRelease(font_ref);
    00487     }
    00488     ATSFontIteratorRelease(&itr);
    00489     CFRelease(lang_code);
    00490   } else
    00491 #endif
    00492   {
    00493 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
    00494     /* Determine fallback font using ATSUI. This uses a string sample with
    00495      * missing characters. This is not failure-proof, but a better way like
    00496      * using the isocode as in the CoreText code path is not available.
    00497      * ATSUI was deprecated with 10.6 and is only partially available in
    00498      * 64-bit mode. */
    00499
    00500     /* Extract a UniChar represenation of the sample string. */
    00501     CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, str, kCFStringEncodingUTF8);
    00502     if (cf_str == NULL) {
    00503       /* Something went wrong. Corrupt/invalid sample string? */
    00504       return false;
    00505     }
    00506     CFIndex str_len = CFStringGetLength(cf_str);
    00507     UniChar string[str_len];
    00508     CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string);
    00509
    00510     /* Create a default text style with the default font. */
    00511     ATSUStyle style;
    00512     ATSUCreateStyle(&style);
    00513
    00514     /* Create a text layout object from the sample string using the text style. */
    00515     UniCharCount run_len = kATSUToTextEnd;
    00516     ATSUTextLayout text_layout;
    00517     ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout);
    00518
    00519     /* Try to match a font for the sample text. ATSUMatchFontsToText stops after
    00520      * it finds the first continous character run not renderable with the currently
    00521      * selected font starting at offset. The matching needs to be repeated until
    00522      * the end of the string is reached to make sure the fallback font matches for
    00523      * all characters in the string and not only the first run. */
    00524     UniCharArrayOffset offset = kATSUFromTextBeginning;
    00525     OSStatus os_err;
    00526     do {
    00527       ATSUFontID font;
    00528       UniCharCount run_len;
    00529       os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len);
    00530       if (os_err == kATSUFontsMatched) {
    00531         /* Found a better fallback font. Update the text layout
    00532          * object with the new font. */
    00533         ATSUAttributeTag tag = kATSUFontTag;
    00534         ByteCount size = sizeof(font);
    00535         ATSUAttributeValuePtr val = &font;
    00536         ATSUSetAttributes(style, 1, &tag, &size, &val);
    00537         offset += run_len;
    00538       }
    00539       /* Exit if the end of the string is reached or some other error occured. */
    00540     } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len);
    00541
    00542     if (os_err == noErr || os_err == kATSUFontsMatched) {
    00543       /* ATSUMatchFontsToText exited normally. Extract font
    00544        * out of the text layout object. */
    00545       ATSUFontID font;
    00546       ByteCount act_len;
    00547       ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len);
    00548
    00549       /* Get unique font name. The result is not a c-string, we have
    00550        * to leave space for a \0 and terminate it ourselves. */
    00551       char name[128];
    00552       ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL);
    00553       name[act_len > 127 ? 127 : act_len] = '\0';
    00554
    00555       /* Save Result. */
    00556       strecpy(settings->small_font,  name, lastof(settings->small_font));
    00557       strecpy(settings->medium_font, name, lastof(settings->medium_font));
    00558       strecpy(settings->large_font,  name, lastof(settings->large_font));
    00559       DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name);
    00560       result = true;
    00561     }
    00562
    00563     ATSUDisposeTextLayout(text_layout);
    00564     ATSUDisposeStyle(style);
    00565     CFRelease(cf_str);
    00566 #endif
    00567   }
    00568
    00569   if (result && strncmp(settings->medium_font, "Geeza Pro", 9) == 0) {
    00570     /* The font 'Geeza Pro' is often found for arabic characters, but
    00571      * it has the 'tiny' problem of not having any latin characters.
    00572      * 'Arial Unicode MS' on the other hand has arabic and latin glyphs,
    00573      * but seems to 'forget' to inform the OS about this fact. Manually
    00574      * substitute the latter for the former if it is loadable. */
    00575     bool ft_init = _library != NULL;
    00576     FT_Face face;
    00577     /* Init FreeType if needed. */
    00578     if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) {
    00579       FT_Done_Face(face);
    00580       strecpy(settings->small_font,  "Arial Unicode MS", lastof(settings->small_font));
    00581       strecpy(settings->medium_font, "Arial Unicode MS", lastof(settings->medium_font));
    00582       strecpy(settings->large_font,  "Arial Unicode MS", lastof(settings->large_font));
    00583       DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'");
    00584     }
    00585     if (!ft_init) {
    00586       /* Uninit FreeType if we did the init. */
    00587       FT_Done_FreeType(_library);
    00588       _library = NULL;
    00589     }
    00590    }
    00591
    00592   return result;
    00593 }
    00594
    00595 #elif defined(WITH_FONTCONFIG)
    00596 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
    00597 {
    00598   FT_Error err = FT_Err_Cannot_Open_Resource;
    00599
    00600   if (!FcInit()) {
    00601     ShowInfoF("Unable to load font configuration");
    00602   } else {
    00603     FcPattern *match;
    00604     FcPattern *pat;
    00605     FcFontSet *fs;
    00606     FcResult  result;
    00607     char *font_style;
    00608     char *font_family;
    00609
    00610     /* Split & strip the font's style */
    00611     font_family = strdup(font_name);
    00612     font_style = strchr(font_family, ',');
    00613     if (font_style != NULL) {
    00614       font_style[0] = '\0';
    00615       font_style++;
    00616       while (*font_style == ' ' || *font_style == '\t') font_style++;
    00617     }
    00618
    00619     /* Resolve the name and populate the information structure */
    00620     pat = FcNameParse((FcChar8*)font_family);
    00621     if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
    00622     FcConfigSubstitute(0, pat, FcMatchPattern);
    00623     FcDefaultSubstitute(pat);
    00624     fs = FcFontSetCreate();
    00625     match = FcFontMatch(0, pat, &result);
    00626
    00627     if (fs != NULL && match != NULL) {
    00628       int i;
    00629       FcChar8 *family;
    00630       FcChar8 *style;
    00631       FcChar8 *file;
    00632       FcFontSetAdd(fs, match);
    00633
    00634       for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
    00635         /* Try the new filename */
    00636         if (FcPatternGetString(fs->fonts[i], FC_FILE,   0, &file)   == FcResultMatch &&
    00637             FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
    00638             FcPatternGetString(fs->fonts[i], FC_STYLE,  0, &style)  == FcResultMatch) {
    00639
    00640           /* The correct style? */
    00641           if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
    00642
    00643           /* Font config takes the best shot, which, if the family name is spelled
    00644            * wrongly a 'random' font, so check whether the family name is the
    00645            * same as the supplied name */
    00646           if (strcasecmp(font_family, (char*)family) == 0) {
    00647             err = FT_New_Face(_library, (char *)file, 0, face);
    00648           }
    00649         }
    00650       }
    00651     }
    00652
    00653     free(font_family);
    00654     FcPatternDestroy(pat);
    00655     FcFontSetDestroy(fs);
    00656     FcFini();
    00657   }
    00658
    00659   return err;
    00660 }
    00661
    00662 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00663 {
    00664   if (!FcInit()) return false;
    00665
    00666   bool ret = false;
    00667
    00668   /* Fontconfig doesn't handle full language isocodes, only the part
    00669    * before the _ of e.g. en_GB is used, so "remove" everything after
    00670    * the _. */
    00671   char lang[16];
    00672   strecpy(lang, language_isocode, lastof(lang));
    00673   char *split = strchr(lang, '_');
    00674   if (split != NULL) *split = '\0';
    00675
    00676   FcPattern *pat;
    00677   FcPattern *match;
    00678   FcResult result;
    00679   FcChar8 *file;
    00680   FcFontSet *fs;
    00681   FcValue val;
    00682   val.type = FcTypeString;
    00683   val.u.s = (FcChar8*)lang;
    00684
    00685   /* First create a pattern to match the wanted language */
    00686   pat = FcPatternCreate();
    00687   /* And fill it with the language and other defaults */
    00688   if (pat == NULL ||
    00689       !FcPatternAdd(pat, "lang", val, false) ||
    00690       !FcConfigSubstitute(0, pat, FcMatchPattern)) {
    00691     goto error_pattern;
    00692   }
    00693
    00694   FcDefaultSubstitute(pat);
    00695
    00696   /* Then create a font set and match that */
    00697   match = FcFontMatch(0, pat, &result);
    00698
    00699   if (match == NULL) {
    00700     goto error_pattern;
    00701   }
    00702
    00703   /* Find all fonts that do match */
    00704   fs = FcFontSetCreate();
    00705   FcFontSetAdd(fs, match);
    00706
    00707   /* And take the first, if it exists */
    00708   if (fs->nfont <= 0 || FcPatternGetString(fs->fonts[0], FC_FILE, 0, &file)) {
    00709     goto error_fontset;
    00710   }
    00711
    00712   strecpy(settings->small_font,  (const char*)file, lastof(settings->small_font));
    00713   strecpy(settings->medium_font, (const char*)file, lastof(settings->medium_font));
    00714   strecpy(settings->large_font,  (const char*)file, lastof(settings->large_font));
    00715
    00716   ret = true;
    00717
    00718 error_fontset:
    00719   FcFontSetDestroy(fs);
    00720 error_pattern:
    00721   if (pat != NULL) FcPatternDestroy(pat);
    00722   FcFini();
    00723   return ret;
    00724 }
    00725
    00726 #else /* without WITH_FONTCONFIG */
    00727 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
    00728 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str) { return false; }
    00729 #endif /* WITH_FONTCONFIG */
    00730
    00731 static void SetFontGeometry(FT_Face face, FontSize size, int pixels)
    00732 {
    00733   FT_Set_Pixel_Sizes(face, 0, pixels);
    00734
    00735   if (FT_IS_SCALABLE(face)) {
    00736     int asc = face->ascender * pixels / face->units_per_EM;
    00737     int dec = face->descender * pixels / face->units_per_EM;
    00738
    00739     _ascender[size] = asc;
    00740     _font_height[size] = asc - dec;
    00741   } else {
    00742     _ascender[size] = pixels;
    00743     _font_height[size] = pixels;
    00744   }
    00745 }
    00746
    00753 static void LoadFreeTypeFont(const char *font_name, FT_Face *face, const char *type)
    00754 {
    00755   FT_Error error;
    00756
    00757   if (StrEmpty(font_name)) return;
    00758
    00759   error = FT_New_Face(_library, font_name, 0, face);
    00760
    00761   if (error != FT_Err_Ok) error = GetFontByFaceName(font_name, face);
    00762
    00763   if (error == FT_Err_Ok) {
    00764     DEBUG(freetype, 2, "Requested '%s', using '%s %s'", font_name, (*face)->family_name, (*face)->style_name);
    00765
    00766     /* Attempt to select the unicode character map */
    00767     error = FT_Select_Charmap(*face, ft_encoding_unicode);
    00768     if (error == FT_Err_Ok) return; // Success
    00769
    00770     if (error == FT_Err_Invalid_CharMap_Handle) {
    00771       /* Try to pick a different character map instead. We default to
    00772        * the first map, but platform_id 0 encoding_id 0 should also
    00773        * be unicode (strange system...) */
    00774       FT_CharMap found = (*face)->charmaps[0];
    00775       int i;
    00776
    00777       for (i = 0; i < (*face)->num_charmaps; i++) {
    00778         FT_CharMap charmap = (*face)->charmaps[i];
    00779         if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
    00780           found = charmap;
    00781         }
    00782       }
    00783
    00784       if (found != NULL) {
    00785         error = FT_Set_Charmap(*face, found);
    00786         if (error == FT_Err_Ok) return;
    00787       }
    00788     }
    00789   }
    00790
    00791   FT_Done_Face(*face);
    00792   *face = NULL;
    00793
    00794   ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, type, error);
    00795 }
    00796
    00797
    00798 void InitFreeType()
    00799 {
    00800   ResetFontSizes();
    00801
    00802   if (StrEmpty(_freetype.small_font) && StrEmpty(_freetype.medium_font) && StrEmpty(_freetype.large_font)) {
    00803     DEBUG(freetype, 1, "No font faces specified, using sprite fonts instead");
    00804     return;
    00805   }
    00806
    00807   if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
    00808     ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
    00809     return;
    00810   }
    00811
    00812   DEBUG(freetype, 2, "Initialized");
    00813
    00814   /* Load each font */
    00815   LoadFreeTypeFont(_freetype.small_font,  &_face_small,  "small");
    00816   LoadFreeTypeFont(_freetype.medium_font, &_face_medium, "medium");
    00817   LoadFreeTypeFont(_freetype.large_font,  &_face_large,  "large");
    00818
    00819   /* Set each font size */
    00820   if (_face_small != NULL) {
    00821     SetFontGeometry(_face_small, FS_SMALL, _freetype.small_size);
    00822   }
    00823   if (_face_medium != NULL) {
    00824     SetFontGeometry(_face_medium, FS_NORMAL, _freetype.medium_size);
    00825   }
    00826   if (_face_large != NULL) {
    00827     SetFontGeometry(_face_large, FS_LARGE, _freetype.large_size);
    00828   }
    00829 }
    00830
    00831 static void ResetGlyphCache();
    00832
    00837 static void UnloadFace(FT_Face *face)
    00838 {
    00839   if (*face == NULL) return;
    00840
    00841   FT_Done_Face(*face);
    00842   *face = NULL;
    00843 }
    00844
    00848 void UninitFreeType()
    00849 {
    00850   ResetFontSizes();
    00851   ResetGlyphCache();
    00852
    00853   UnloadFace(&_face_small);
    00854   UnloadFace(&_face_medium);
    00855   UnloadFace(&_face_large);
    00856
    00857   FT_Done_FreeType(_library);
    00858   _library = NULL;
    00859 }
    00860
    00861
    00862 static FT_Face GetFontFace(FontSize size)
    00863 {
    00864   switch (size) {
    00865     default: NOT_REACHED();
    00866     case FS_NORMAL: return _face_medium;
    00867     case FS_SMALL:  return _face_small;
    00868     case FS_LARGE:  return _face_large;
    00869   }
    00870 }
    00871
    00872
    00873 struct GlyphEntry {
    00874   Sprite *sprite;
    00875   byte width;
    00876 };
    00877
    00878
    00879 /* The glyph cache. This is structured to reduce memory consumption.
    00880  * 1) There is a 'segment' table for each font size.
    00881  * 2) Each segment table is a discrete block of characters.
    00882  * 3) Each block contains 256 (aligned) characters sequential characters.
    00883  *
    00884  * The cache is accessed in the following way:
    00885  * For character 0x0041  ('A'): _glyph_ptr[FS_NORMAL][0x00][0x41]
    00886  * For character 0x20AC (Euro): _glyph_ptr[FS_NORMAL][0x20][0xAC]
    00887  *
    00888  * Currently only 256 segments are allocated, "limiting" us to 65536 characters.
    00889  * This can be simply changed in the two functions Get & SetGlyphPtr.
    00890  */
    00891 static GlyphEntry **_glyph_ptr[FS_END];
    00892
    00894 static void ResetGlyphCache()
    00895 {
    00896   for (FontSize i = FS_BEGIN; i < FS_END; i++) {
    00897     if (_glyph_ptr[i] == NULL) continue;
    00898
    00899     for (int j = 0; j < 256; j++) {
    00900       if (_glyph_ptr[i][j] == NULL) continue;
    00901
    00902       for (int k = 0; k < 256; k++) {
    00903         free(_glyph_ptr[i][j][k].sprite);
    00904       }
    00905
    00906       free(_glyph_ptr[i][j]);
    00907     }
    00908
    00909     free(_glyph_ptr[i]);
    00910     _glyph_ptr[i] = NULL;
    00911   }
    00912 }
    00913
    00914 static GlyphEntry *GetGlyphPtr(FontSize size, WChar key)
    00915 {
    00916   if (_glyph_ptr[size] == NULL) return NULL;
    00917   if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) return NULL;
    00918   return &_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)];
    00919 }
    00920
    00921
    00922 static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph)
    00923 {
    00924   if (_glyph_ptr[size] == NULL) {
    00925     DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
    00926     _glyph_ptr[size] = CallocT<GlyphEntry*>(256);
    00927   }
    00928
    00929   if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
    00930     DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
    00931     _glyph_ptr[size][GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
    00932   }
    00933
    00934   DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
    00935   _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
    00936   _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].width  = glyph->width;
    00937 }
    00938
    00939 static void *AllocateFont(size_t size)
    00940 {
    00941   return MallocT<byte>(size);
    00942 }
    00943
    00944
    00945 /* Check if a glyph should be rendered with antialiasing */
    00946 static bool GetFontAAState(FontSize size)
    00947 {
    00948   /* AA is only supported for 32 bpp */
    00949   if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
    00950
    00951   switch (size) {
    00952     default: NOT_REACHED();
    00953     case FS_NORMAL: return _freetype.medium_aa;
    00954     case FS_SMALL:  return _freetype.small_aa;
    00955     case FS_LARGE:  return _freetype.large_aa;
    00956   }
    00957 }
    00958
    00959
    00960 const Sprite *GetGlyph(FontSize size, WChar key)
    00961 {
    00962   FT_Face face = GetFontFace(size);
    00963   FT_GlyphSlot slot;
    00964   GlyphEntry new_glyph;
    00965   GlyphEntry *glyph;
    00966   SpriteLoader::Sprite sprite;
    00967   int width;
    00968   int height;
    00969   int x;
    00970   int y;
    00971
    00972   assert(IsPrintable(key));
    00973
    00974   /* Bail out if no face loaded, or for our special characters */
    00975   if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
    00976     SpriteID sprite = GetUnicodeGlyph(size, key);
    00977     if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
    00978     return GetSprite(sprite, ST_FONT);
    00979   }
    00980
    00981   /* Check for the glyph in our cache */
    00982   glyph = GetGlyphPtr(size, key);
    00983   if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
    00984
    00985   slot = face->glyph;
    00986
    00987   bool aa = GetFontAAState(size);
    00988
    00989   FT_Load_Char(face, key, FT_LOAD_DEFAULT);
    00990   FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
    00991
    00992   /* Despite requesting a normal glyph, FreeType may have returned a bitmap */
    00993   aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
    00994
    00995   /* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
    00996   width  = max(1, slot->bitmap.width + (size == FS_NORMAL));
    00997   height = max(1, slot->bitmap.rows  + (size == FS_NORMAL));
    00998
    00999   /* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
    01000   sprite.AllocateData(width * height);
    01001   sprite.width = width;
    01002   sprite.height = height;
    01003   sprite.x_offs = slot->bitmap_left;
    01004   sprite.y_offs = _ascender[size] - slot->bitmap_top;
    01005
    01006   /* Draw shadow for medium size */
    01007   if (size == FS_NORMAL) {
    01008     for (y = 0; y < slot->bitmap.rows; y++) {
    01009       for (x = 0; x < slot->bitmap.width; x++) {
    01010         if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
    01011           sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
    01012           sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
    01013         }
    01014       }
    01015     }
    01016   }
    01017
    01018   for (y = 0; y < slot->bitmap.rows; y++) {
    01019     for (x = 0; x < slot->bitmap.width; x++) {
    01020       if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
    01021         sprite.data[x + y * sprite.width].m = FACE_COLOUR;
    01022         sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
    01023       }
    01024     }
    01025   }
    01026
    01027   new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
    01028   new_glyph.width  = slot->advance.x >> 6;
    01029
    01030   SetGlyphPtr(size, key, &new_glyph);
    01031
    01032   return new_glyph.sprite;
    01033 }
    01034
    01035
    01036 uint GetGlyphWidth(FontSize size, WChar key)
    01037 {
    01038   FT_Face face = GetFontFace(size);
    01039   GlyphEntry *glyph;
    01040
    01041   if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
    01042     SpriteID sprite = GetUnicodeGlyph(size, key);
    01043     if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
    01044     return SpriteExists(sprite) ? GetSprite(sprite, ST_FONT)->width + (size != FS_NORMAL) : 0;
    01045   }
    01046
    01047   glyph = GetGlyphPtr(size, key);
    01048   if (glyph == NULL || glyph->sprite == NULL) {
    01049     GetGlyph(size, key);
    01050     glyph = GetGlyphPtr(size, key);
    01051   }
    01052
    01053   return glyph->width;
    01054 }
    01055
    01056
    01057 #endif /* WITH_FREETYPE */
    01058
    01060 void ResetFontSizes()
    01061 {
    01062   _font_height[FS_SMALL]  =  6;
    01063   _font_height[FS_NORMAL] = 10;
    01064   _font_height[FS_LARGE]  = 18;
    01065 }
    01066
    01067 /* Sprite based glyph mapping */
    01068
    01069 #include "table/unicode.h"
    01070
    01071 static SpriteID **_unicode_glyph_map[FS_END];
    01072
    01073
    01075 static SpriteID GetFontBase(FontSize size)
    01076 {
    01077   switch (size) {
    01078     default: NOT_REACHED();
    01079     case FS_NORMAL: return SPR_ASCII_SPACE;
    01080     case FS_SMALL:  return SPR_ASCII_SPACE_SMALL;
    01081     case FS_LARGE:  return SPR_ASCII_SPACE_BIG;
    01082   }
    01083 }
    01084
    01085
    01086 SpriteID GetUnicodeGlyph(FontSize size, uint32 key)
    01087 {
    01088   if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) return 0;
    01089   return _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)];
    01090 }
    01091
    01092
    01093 void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
    01094 {
    01095   if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = CallocT<SpriteID*>(256);
    01096   if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = CallocT<SpriteID>(256);
    01097   _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
    01098 }
    01099
    01100
    01101 void InitializeUnicodeGlyphMap()
    01102 {
    01103   for (FontSize size = FS_BEGIN; size != FS_END; size++) {
    01104     /* Clear out existing glyph map if it exists */
    01105     if (_unicode_glyph_map[size] != NULL) {
    01106       for (uint i = 0; i < 256; i++) {
    01107         free(_unicode_glyph_map[size][i]);
    01108       }
    01109       free(_unicode_glyph_map[size]);
    01110       _unicode_glyph_map[size] = NULL;
    01111     }
    01112
    01113     SpriteID base = GetFontBase(size);
    01114
    01115     for (uint i = ASCII_LETTERSTART; i < 256; i++) {
    01116       SpriteID sprite = base + i - ASCII_LETTERSTART;
    01117       if (!SpriteExists(sprite)) continue;
    01118       SetUnicodeGlyph(size, i, sprite);
    01119       SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
    01120     }
    01121
    01122     for (uint i = 0; i < lengthof(_default_unicode_map); i++) {
    01123       byte key = _default_unicode_map[i].key;
    01124       if (key == CLRA || key == CLRL) {
    01125         /* Clear the glyph. This happens if the glyph at this code point
    01126          * is non-standard and should be accessed by an SCC_xxx enum
    01127          * entry only. */
    01128         if (key == CLRA || size == FS_LARGE) {
    01129           SetUnicodeGlyph(size, _default_unicode_map[i].code, 0);
    01130         }
    01131       } else {
    01132         SpriteID sprite = base + key - ASCII_LETTERSTART;
    01133         SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
    01134       }
    01135     }
    01136   }
    01137 }