# fontcache.cpp

Go to the documentation of this file.

    00001 /* $Id: fontcache.cpp 18712 2010-01-04 16:37:53Z peter1138 $ */
    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   const char *english_name = GetEnglishFontName(logfont);
    00317   const char *font_name = WIDE_TO_MB((const TCHAR*)logfont->elfFullName);
    00318   DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
    00319
    00320   strecpy(info->settings->small_font,  font_name, lastof(info->settings->small_font));
    00321   strecpy(info->settings->medium_font, font_name, lastof(info->settings->medium_font));
    00322   strecpy(info->settings->large_font,  font_name, lastof(info->settings->large_font));
    00323
    00324   /* Add english name after font name */
    00325   strecpy(info->settings->small_font + strlen(info->settings->small_font) + 1, english_name, lastof(info->settings->small_font));
    00326   strecpy(info->settings->medium_font + strlen(info->settings->medium_font) + 1, english_name, lastof(info->settings->medium_font));
    00327   strecpy(info->settings->large_font + strlen(info->settings->large_font) + 1, english_name, lastof(info->settings->large_font));
    00328   return 0; // stop enumerating
    00329 }
    00330
    00331 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00332 {
    00333   EFCParam langInfo;
    00334   if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(TCHAR)) == 0) {
    00335     /* Invalid langid or some other mysterious error, can't determine fallback font. */
    00336     DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid);
    00337     return false;
    00338   }
    00339   langInfo.settings = settings;
    00340
    00341   LOGFONT font;
    00342   /* Enumerate all fonts. */
    00343   font.lfCharSet = DEFAULT_CHARSET;
    00344   font.lfFaceName[0] = '\0';
    00345   font.lfPitchAndFamily = 0;
    00346
    00347   HDC dc = GetDC(NULL);
    00348   int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
    00349   ReleaseDC(NULL, dc);
    00350   return ret == 0;
    00351 }
    00352
    00353 #elif defined(__APPLE__)
    00354
    00355 #include "os/macosx/macos.h"
    00356 #include <ApplicationServices/ApplicationServices.h>
    00357
    00358 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
    00359 {
    00360   FT_Error err = FT_Err_Cannot_Open_Resource;
    00361
    00362   /* Get font reference from name. */
    00363   CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name, kCFStringEncodingUTF8);
    00364   ATSFontRef font = ATSFontFindFromName(name, kATSOptionFlagsDefault);
    00365   CFRelease(name);
    00366   if (font == kInvalidFont) return err;
    00367
    00368   /* Get a file system reference for the font. */
    00369   FSRef ref;
    00370   OSStatus os_err = -1;
    00371 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
    00372   if (MacOSVersionIsAtLeast(10, 5, 0)) {
    00373     os_err = ATSFontGetFileReference(font, &ref);
    00374   } else
    00375 #endif
    00376   {
    00377 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
    00378     /* This type was introduced with the 10.5 SDK. */
    00379 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
    00380   #define ATSFSSpec FSSpec
    00381 #endif
    00382     FSSpec spec;
    00383     os_err = ATSFontGetFileSpecification(font, (ATSFSSpec *)&spec);
    00384     if (os_err == noErr) os_err = FSpMakeFSRef(&spec, &ref);
    00385 #endif
    00386   }
    00387
    00388   if (os_err == noErr) {
    00389     /* Get unix path for file. */
    00390     UInt8 file_path[PATH_MAX];
    00391     if (FSRefMakePath(&ref, file_path, sizeof(file_path)) == noErr) {
    00392       DEBUG(freetype, 3, "Font path for %s: %s", font_name, file_path);
    00393       err = FT_New_Face(_library, (const char *)file_path, 0, face);
    00394     }
    00395   }
    00396
    00397   return err;
    00398 }
    00399
    00400 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00401 {
    00402   bool result = false;
    00403
    00404 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
    00405   if (MacOSVersionIsAtLeast(10, 5, 0)) {
    00406     /* Determine fallback font using CoreText. This uses the language isocode
    00407      * to find a suitable font. CoreText is available from 10.5 onwards. */
    00408     char lang[16];
    00409     if (strcmp(language_isocode, "zh_TW") == 0) {
    00410       /* Traditional Chinese */
    00411       strecpy(lang, "zh-Hant", lastof(lang));
    00412     } else if (strcmp(language_isocode, "zh_CN") == 0) {
    00413       /* Simplified Chinese */
    00414       strecpy(lang, "zh-Hans", lastof(lang));
    00415     } else if (strncmp(language_isocode, "ur", 2) == 0) {
    00416       /* The urdu alphabet is variant of persian. As OS X has no default
    00417        * font that advertises an urdu language code, search for persian
    00418        * support instead. */
    00419       strecpy(lang, "fa", lastof(lang));
    00420     } else {
    00421       /* Just copy the first part of the isocode. */
    00422       strecpy(lang, language_isocode, lastof(lang));
    00423       char *sep = strchr(lang, '_');
    00424       if (sep != NULL) *sep = '\0';
    00425     }
    00426
    00427     CFStringRef lang_code;
    00428     lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);
    00429
    00430     /* Create a font iterator and iterate over all fonts that
    00431      * are available to the application. */
    00432     ATSFontIterator itr;
    00433     ATSFontRef font;
    00434     ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);
    00435     while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
    00436       /* Get CoreText font handle. */
    00437       CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);
    00438       CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);
    00439       if (langs != NULL) {
    00440         /* Font has a list of supported languages. */
    00441         for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) {
    00442           CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
    00443           if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) {
    00444             /* Lang code is supported by font, get full font name. */
    00445             CFStringRef font_name = CTFontCopyFullName(font_ref);
    00446             char name[128];
    00447             CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);
    00448             CFRelease(font_name);
    00449             /* Skip some inappropriate or ugly looking fonts that have better alternatives. */
    00450             if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 ||
    00451               strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 ||
    00452               strncmp(name, "GB18030 Bitmap", 14) == 0) continue;
    00453
    00454             /* Save result. */
    00455             strecpy(settings->small_font,  name, lastof(settings->small_font));
    00456             strecpy(settings->medium_font, name, lastof(settings->medium_font));
    00457             strecpy(settings->large_font,  name, lastof(settings->large_font));
    00458             DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);
    00459             result = true;
    00460             break;
    00461           }
    00462         }
    00463         CFRelease(langs);
    00464       }
    00465       CFRelease(font_ref);
    00466     }
    00467     ATSFontIteratorRelease(&itr);
    00468     CFRelease(lang_code);
    00469   } else
    00470 #endif
    00471   {
    00472 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
    00473     /* Determine fallback font using ATSUI. This uses a string sample with
    00474      * missing characters. This is not failure-proof, but a better way like
    00475      * using the isocode as in the CoreText code path is not available.
    00476      * ATSUI was deprecated with 10.6 and is only partially available in
    00477      * 64-bit mode. */
    00478
    00479     /* Extract a UniChar represenation of the sample string. */
    00480     CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, str, kCFStringEncodingUTF8);
    00481     if (cf_str == NULL) {
    00482       /* Something went wrong. Corrupt/invalid sample string? */
    00483       return false;
    00484     }
    00485     CFIndex str_len = CFStringGetLength(cf_str);
    00486     UniChar string[str_len];
    00487     CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string);
    00488
    00489     /* Create a default text style with the default font. */
    00490     ATSUStyle style;
    00491     ATSUCreateStyle(&style);
    00492
    00493     /* Create a text layout object from the sample string using the text style. */
    00494     UniCharCount run_len = kATSUToTextEnd;
    00495     ATSUTextLayout text_layout;
    00496     ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout);
    00497
    00498     /* Try to match a font for the sample text. ATSUMatchFontsToText stops after
    00499      * it finds the first continous character run not renderable with the currently
    00500      * selected font starting at offset. The matching needs to be repeated until
    00501      * the end of the string is reached to make sure the fallback font matches for
    00502      * all characters in the string and not only the first run. */
    00503     UniCharArrayOffset offset = kATSUFromTextBeginning;
    00504     OSStatus os_err;
    00505     do {
    00506       ATSUFontID font;
    00507       UniCharCount run_len;
    00508       os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len);
    00509       if (os_err == kATSUFontsMatched) {
    00510         /* Found a better fallback font. Update the text layout
    00511          * object with the new font. */
    00512         ATSUAttributeTag tag = kATSUFontTag;
    00513         ByteCount size = sizeof(font);
    00514         ATSUAttributeValuePtr val = &font;
    00515         ATSUSetAttributes(style, 1, &tag, &size, &val);
    00516         offset += run_len;
    00517       }
    00518       /* Exit if the end of the string is reached or some other error occured. */
    00519     } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len);
    00520
    00521     if (os_err == noErr || os_err == kATSUFontsMatched) {
    00522       /* ATSUMatchFontsToText exited normally. Extract font
    00523        * out of the text layout object. */
    00524       ATSUFontID font;
    00525       ByteCount act_len;
    00526       ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len);
    00527
    00528       /* Get unique font name. The result is not a c-string, we have
    00529        * to leave space for a \0 and terminate it ourselves. */
    00530       char name[128];
    00531       ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL);
    00532       name[act_len > 127 ? 127 : act_len] = '\0';
    00533
    00534       /* Save Result. */
    00535       strecpy(settings->small_font,  name, lastof(settings->small_font));
    00536       strecpy(settings->medium_font, name, lastof(settings->medium_font));
    00537       strecpy(settings->large_font,  name, lastof(settings->large_font));
    00538       DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name);
    00539       result = true;
    00540     }
    00541
    00542     ATSUDisposeTextLayout(text_layout);
    00543     ATSUDisposeStyle(style);
    00544     CFRelease(cf_str);
    00545 #endif
    00546   }
    00547
    00548   if (result && strncmp(settings->medium_font, "Geeza Pro", 9) == 0) {
    00549     /* The font 'Geeza Pro' is often found for arabic characters, but
    00550      * it has the 'tiny' problem of not having any latin characters.
    00551      * 'Arial Unicode MS' on the other hand has arabic and latin glyphs,
    00552      * but seems to 'forget' to inform the OS about this fact. Manually
    00553      * substitute the latter for the former if it is loadable. */
    00554     bool ft_init = _library != NULL;
    00555     FT_Face face;
    00556     /* Init FreeType if needed. */
    00557     if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) {
    00558       FT_Done_Face(face);
    00559       strecpy(settings->small_font,  "Arial Unicode MS", lastof(settings->small_font));
    00560       strecpy(settings->medium_font, "Arial Unicode MS", lastof(settings->medium_font));
    00561       strecpy(settings->large_font,  "Arial Unicode MS", lastof(settings->large_font));
    00562       DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'");
    00563     }
    00564     if (!ft_init) {
    00565       /* Uninit FreeType if we did the init. */
    00566       FT_Done_FreeType(_library);
    00567       _library = NULL;
    00568     }
    00569    }
    00570
    00571   return result;
    00572 }
    00573
    00574 #elif defined(WITH_FONTCONFIG)
    00575 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
    00576 {
    00577   FT_Error err = FT_Err_Cannot_Open_Resource;
    00578
    00579   if (!FcInit()) {
    00580     ShowInfoF("Unable to load font configuration");
    00581   } else {
    00582     FcPattern *match;
    00583     FcPattern *pat;
    00584     FcFontSet *fs;
    00585     FcResult  result;
    00586     char *font_style;
    00587     char *font_family;
    00588
    00589     /* Split & strip the font's style */
    00590     font_family = strdup(font_name);
    00591     font_style = strchr(font_family, ',');
    00592     if (font_style != NULL) {
    00593       font_style[0] = '\0';
    00594       font_style++;
    00595       while (*font_style == ' ' || *font_style == '\t') font_style++;
    00596     }
    00597
    00598     /* Resolve the name and populate the information structure */
    00599     pat = FcNameParse((FcChar8*)font_family);
    00600     if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
    00601     FcConfigSubstitute(0, pat, FcMatchPattern);
    00602     FcDefaultSubstitute(pat);
    00603     fs = FcFontSetCreate();
    00604     match = FcFontMatch(0, pat, &result);
    00605
    00606     if (fs != NULL && match != NULL) {
    00607       int i;
    00608       FcChar8 *family;
    00609       FcChar8 *style;
    00610       FcChar8 *file;
    00611       FcFontSetAdd(fs, match);
    00612
    00613       for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
    00614         /* Try the new filename */
    00615         if (FcPatternGetString(fs->fonts[i], FC_FILE,   0, &file)   == FcResultMatch &&
    00616             FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
    00617             FcPatternGetString(fs->fonts[i], FC_STYLE,  0, &style)  == FcResultMatch) {
    00618
    00619           /* The correct style? */
    00620           if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
    00621
    00622           /* Font config takes the best shot, which, if the family name is spelled
    00623            * wrongly a 'random' font, so check whether the family name is the
    00624            * same as the supplied name */
    00625           if (strcasecmp(font_family, (char*)family) == 0) {
    00626             err = FT_New_Face(_library, (char *)file, 0, face);
    00627           }
    00628         }
    00629       }
    00630     }
    00631
    00632     free(font_family);
    00633     FcPatternDestroy(pat);
    00634     FcFontSetDestroy(fs);
    00635     FcFini();
    00636   }
    00637
    00638   return err;
    00639 }
    00640
    00641 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str)
    00642 {
    00643   if (!FcInit()) return false;
    00644
    00645   bool ret = false;
    00646
    00647   /* Fontconfig doesn't handle full language isocodes, only the part
    00648    * before the _ of e.g. en_GB is used, so "remove" everything after
    00649    * the _. */
    00650   char lang[16];
    00651   strecpy(lang, language_isocode, lastof(lang));
    00652   char *split = strchr(lang, '_');
    00653   if (split != NULL) *split = '\0';
    00654
    00655   FcPattern *pat;
    00656   FcPattern *match;
    00657   FcResult result;
    00658   FcChar8 *file;
    00659   FcFontSet *fs;
    00660   FcValue val;
    00661   val.type = FcTypeString;
    00662   val.u.s = (FcChar8*)lang;
    00663
    00664   /* First create a pattern to match the wanted language */
    00665   pat = FcPatternCreate();
    00666   /* And fill it with the language and other defaults */
    00667   if (pat == NULL ||
    00668       !FcPatternAdd(pat, "lang", val, false) ||
    00669       !FcConfigSubstitute(0, pat, FcMatchPattern)) {
    00670     goto error_pattern;
    00671   }
    00672
    00673   FcDefaultSubstitute(pat);
    00674
    00675   /* Then create a font set and match that */
    00676   match = FcFontMatch(0, pat, &result);
    00677
    00678   if (match == NULL) {
    00679     goto error_pattern;
    00680   }
    00681
    00682   /* Find all fonts that do match */
    00683   fs = FcFontSetCreate();
    00684   FcFontSetAdd(fs, match);
    00685
    00686   /* And take the first, if it exists */
    00687   if (fs->nfont <= 0 || FcPatternGetString(fs->fonts[0], FC_FILE, 0, &file)) {
    00688     goto error_fontset;
    00689   }
    00690
    00691   strecpy(settings->small_font,  (const char*)file, lastof(settings->small_font));
    00692   strecpy(settings->medium_font, (const char*)file, lastof(settings->medium_font));
    00693   strecpy(settings->large_font,  (const char*)file, lastof(settings->large_font));
    00694
    00695   ret = true;
    00696
    00697 error_fontset:
    00698   FcFontSetDestroy(fs);
    00699 error_pattern:
    00700   if (pat != NULL) FcPatternDestroy(pat);
    00701   FcFini();
    00702   return ret;
    00703 }
    00704
    00705 #else /* without WITH_FONTCONFIG */
    00706 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
    00707 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, const char *str) { return false; }
    00708 #endif /* WITH_FONTCONFIG */
    00709
    00710 static void SetFontGeometry(FT_Face face, FontSize size, int pixels)
    00711 {
    00712   FT_Set_Pixel_Sizes(face, 0, pixels);
    00713
    00714   if (FT_IS_SCALABLE(face)) {
    00715     int asc = face->ascender * pixels / face->units_per_EM;
    00716     int dec = face->descender * pixels / face->units_per_EM;
    00717
    00718     _ascender[size] = asc;
    00719     _font_height[size] = asc - dec;
    00720   } else {
    00721     _ascender[size] = pixels;
    00722     _font_height[size] = pixels;
    00723   }
    00724 }
    00725
    00732 static void LoadFreeTypeFont(const char *font_name, FT_Face *face, const char *type)
    00733 {
    00734   FT_Error error;
    00735
    00736   if (StrEmpty(font_name)) return;
    00737
    00738   error = FT_New_Face(_library, font_name, 0, face);
    00739
    00740   if (error != FT_Err_Ok) error = GetFontByFaceName(font_name, face);
    00741
    00742   if (error == FT_Err_Ok) {
    00743     DEBUG(freetype, 2, "Requested '%s', using '%s %s'", font_name, (*face)->family_name, (*face)->style_name);
    00744
    00745     /* Attempt to select the unicode character map */
    00746     error = FT_Select_Charmap(*face, ft_encoding_unicode);
    00747     if (error == FT_Err_Ok) return; // Success
    00748
    00749     if (error == FT_Err_Invalid_CharMap_Handle) {
    00750       /* Try to pick a different character map instead. We default to
    00751        * the first map, but platform_id 0 encoding_id 0 should also
    00752        * be unicode (strange system...) */
    00753       FT_CharMap found = (*face)->charmaps[0];
    00754       int i;
    00755
    00756       for (i = 0; i < (*face)->num_charmaps; i++) {
    00757         FT_CharMap charmap = (*face)->charmaps[i];
    00758         if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
    00759           found = charmap;
    00760         }
    00761       }
    00762
    00763       if (found != NULL) {
    00764         error = FT_Set_Charmap(*face, found);
    00765         if (error == FT_Err_Ok) return;
    00766       }
    00767     }
    00768   }
    00769
    00770   FT_Done_Face(*face);
    00771   *face = NULL;
    00772
    00773   ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, type, error);
    00774 }
    00775
    00776
    00777 void InitFreeType()
    00778 {
    00779   ResetFontSizes();
    00780
    00781   if (StrEmpty(_freetype.small_font) && StrEmpty(_freetype.medium_font) && StrEmpty(_freetype.large_font)) {
    00782     DEBUG(freetype, 1, "No font faces specified, using sprite fonts instead");
    00783     return;
    00784   }
    00785
    00786   if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
    00787     ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
    00788     return;
    00789   }
    00790
    00791   DEBUG(freetype, 2, "Initialized");
    00792
    00793   /* Load each font */
    00794   LoadFreeTypeFont(_freetype.small_font,  &_face_small,  "small");
    00795   LoadFreeTypeFont(_freetype.medium_font, &_face_medium, "medium");
    00796   LoadFreeTypeFont(_freetype.large_font,  &_face_large,  "large");
    00797
    00798   /* Set each font size */
    00799   if (_face_small != NULL) {
    00800     SetFontGeometry(_face_small, FS_SMALL, _freetype.small_size);
    00801   }
    00802   if (_face_medium != NULL) {
    00803     SetFontGeometry(_face_medium, FS_NORMAL, _freetype.medium_size);
    00804   }
    00805   if (_face_large != NULL) {
    00806     SetFontGeometry(_face_large, FS_LARGE, _freetype.large_size);
    00807   }
    00808 }
    00809
    00810 static void ResetGlyphCache();
    00811
    00816 static void UnloadFace(FT_Face *face)
    00817 {
    00818   if (*face == NULL) return;
    00819
    00820   FT_Done_Face(*face);
    00821   *face = NULL;
    00822 }
    00823
    00827 void UninitFreeType()
    00828 {
    00829   ResetFontSizes();
    00830   ResetGlyphCache();
    00831
    00832   UnloadFace(&_face_small);
    00833   UnloadFace(&_face_medium);
    00834   UnloadFace(&_face_large);
    00835
    00836   FT_Done_FreeType(_library);
    00837   _library = NULL;
    00838 }
    00839
    00840
    00841 static FT_Face GetFontFace(FontSize size)
    00842 {
    00843   switch (size) {
    00844     default: NOT_REACHED();
    00845     case FS_NORMAL: return _face_medium;
    00846     case FS_SMALL:  return _face_small;
    00847     case FS_LARGE:  return _face_large;
    00848   }
    00849 }
    00850
    00851
    00852 struct GlyphEntry {
    00853   Sprite *sprite;
    00854   byte width;
    00855 };
    00856
    00857
    00858 /* The glyph cache. This is structured to reduce memory consumption.
    00859  * 1) There is a 'segment' table for each font size.
    00860  * 2) Each segment table is a discrete block of characters.
    00861  * 3) Each block contains 256 (aligned) characters sequential characters.
    00862  *
    00863  * The cache is accessed in the following way:
    00864  * For character 0x0041  ('A'): _glyph_ptr[FS_NORMAL][0x00][0x41]
    00865  * For character 0x20AC (Euro): _glyph_ptr[FS_NORMAL][0x20][0xAC]
    00866  *
    00867  * Currently only 256 segments are allocated, "limiting" us to 65536 characters.
    00868  * This can be simply changed in the two functions Get & SetGlyphPtr.
    00869  */
    00870 static GlyphEntry **_glyph_ptr[FS_END];
    00871
    00873 static void ResetGlyphCache()
    00874 {
    00875   for (FontSize i = FS_BEGIN; i < FS_END; i++) {
    00876     if (_glyph_ptr[i] == NULL) continue;
    00877
    00878     for (int j = 0; j < 256; j++) {
    00879       if (_glyph_ptr[i][j] == NULL) continue;
    00880
    00881       for (int k = 0; k < 256; k++) {
    00882         free(_glyph_ptr[i][j][k].sprite);
    00883       }
    00884
    00885       free(_glyph_ptr[i][j]);
    00886     }
    00887
    00888     free(_glyph_ptr[i]);
    00889     _glyph_ptr[i] = NULL;
    00890   }
    00891 }
    00892
    00893 static GlyphEntry *GetGlyphPtr(FontSize size, WChar key)
    00894 {
    00895   if (_glyph_ptr[size] == NULL) return NULL;
    00896   if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) return NULL;
    00897   return &_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)];
    00898 }
    00899
    00900
    00901 static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph)
    00902 {
    00903   if (_glyph_ptr[size] == NULL) {
    00904     DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
    00905     _glyph_ptr[size] = CallocT<GlyphEntry*>(256);
    00906   }
    00907
    00908   if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
    00909     DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
    00910     _glyph_ptr[size][GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
    00911   }
    00912
    00913   DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
    00914   _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
    00915   _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].width  = glyph->width;
    00916 }
    00917
    00918 static void *AllocateFont(size_t size)
    00919 {
    00920   return MallocT<byte>(size);
    00921 }
    00922
    00923
    00924 /* Check if a glyph should be rendered with antialiasing */
    00925 static bool GetFontAAState(FontSize size)
    00926 {
    00927   /* AA is only supported for 32 bpp */
    00928   if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
    00929
    00930   switch (size) {
    00931     default: NOT_REACHED();
    00932     case FS_NORMAL: return _freetype.medium_aa;
    00933     case FS_SMALL:  return _freetype.small_aa;
    00934     case FS_LARGE:  return _freetype.large_aa;
    00935   }
    00936 }
    00937
    00938
    00939 const Sprite *GetGlyph(FontSize size, WChar key)
    00940 {
    00941   FT_Face face = GetFontFace(size);
    00942   FT_GlyphSlot slot;
    00943   GlyphEntry new_glyph;
    00944   GlyphEntry *glyph;
    00945   SpriteLoader::Sprite sprite;
    00946   int width;
    00947   int height;
    00948   int x;
    00949   int y;
    00950
    00951   assert(IsPrintable(key));
    00952
    00953   /* Bail out if no face loaded, or for our special characters */
    00954   if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
    00955     SpriteID sprite = GetUnicodeGlyph(size, key);
    00956     if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
    00957     return GetSprite(sprite, ST_FONT);
    00958   }
    00959
    00960   /* Check for the glyph in our cache */
    00961   glyph = GetGlyphPtr(size, key);
    00962   if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
    00963
    00964   slot = face->glyph;
    00965
    00966   bool aa = GetFontAAState(size);
    00967
    00968   FT_Load_Char(face, key, FT_LOAD_DEFAULT);
    00969   FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
    00970
    00971   /* Despite requesting a normal glyph, FreeType may have returned a bitmap */
    00972   aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
    00973
    00974   /* Add 1 pixel for the shadow on the medium font. Our sprite must be at least 1x1 pixel */
    00975   width  = max(1, slot->bitmap.width + (size == FS_NORMAL));
    00976   height = max(1, slot->bitmap.rows  + (size == FS_NORMAL));
    00977
    00978   /* FreeType has rendered the glyph, now we allocate a sprite and copy the image into it */
    00979   sprite.AllocateData(width * height);
    00980   sprite.width = width;
    00981   sprite.height = height;
    00982   sprite.x_offs = slot->bitmap_left;
    00983   sprite.y_offs = _ascender[size] - slot->bitmap_top;
    00984
    00985   /* Draw shadow for medium size */
    00986   if (size == FS_NORMAL) {
    00987     for (y = 0; y < slot->bitmap.rows; y++) {
    00988       for (x = 0; x < slot->bitmap.width; x++) {
    00989         if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
    00990           sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
    00991           sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
    00992         }
    00993       }
    00994     }
    00995   }
    00996
    00997   for (y = 0; y < slot->bitmap.rows; y++) {
    00998     for (x = 0; x < slot->bitmap.width; x++) {
    00999       if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
    01000         sprite.data[x + y * sprite.width].m = FACE_COLOUR;
    01001         sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
    01002       }
    01003     }
    01004   }
    01005
    01006   new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
    01007   new_glyph.width  = slot->advance.x >> 6;
    01008
    01009   SetGlyphPtr(size, key, &new_glyph);
    01010
    01011   return new_glyph.sprite;
    01012 }
    01013
    01014
    01015 uint GetGlyphWidth(FontSize size, WChar key)
    01016 {
    01017   FT_Face face = GetFontFace(size);
    01018   GlyphEntry *glyph;
    01019
    01020   if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
    01021     SpriteID sprite = GetUnicodeGlyph(size, key);
    01022     if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
    01023     return SpriteExists(sprite) ? GetSprite(sprite, ST_FONT)->width + (size != FS_NORMAL) : 0;
    01024   }
    01025
    01026   glyph = GetGlyphPtr(size, key);
    01027   if (glyph == NULL || glyph->sprite == NULL) {
    01028     GetGlyph(size, key);
    01029     glyph = GetGlyphPtr(size, key);
    01030   }
    01031
    01032   return glyph->width;
    01033 }
    01034
    01035
    01036 #endif /* WITH_FREETYPE */
    01037
    01039 void ResetFontSizes()
    01040 {
    01041   _font_height[FS_SMALL]  =  6;
    01042   _font_height[FS_NORMAL] = 10;
    01043   _font_height[FS_LARGE]  = 18;
    01044 }
    01045
    01046 /* Sprite based glyph mapping */
    01047
    01048 #include "table/unicode.h"
    01049
    01050 static SpriteID **_unicode_glyph_map[FS_END];
    01051
    01052
    01054 static SpriteID GetFontBase(FontSize size)
    01055 {
    01056   switch (size) {
    01057     default: NOT_REACHED();
    01058     case FS_NORMAL: return SPR_ASCII_SPACE;
    01059     case FS_SMALL:  return SPR_ASCII_SPACE_SMALL;
    01060     case FS_LARGE:  return SPR_ASCII_SPACE_BIG;
    01061   }
    01062 }
    01063
    01064
    01065 SpriteID GetUnicodeGlyph(FontSize size, uint32 key)
    01066 {
    01067   if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) return 0;
    01068   return _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)];
    01069 }
    01070
    01071
    01072 void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
    01073 {
    01074   if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = CallocT<SpriteID*>(256);
    01075   if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = CallocT<SpriteID>(256);
    01076   _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
    01077 }
    01078
    01079
    01080 void InitializeUnicodeGlyphMap()
    01081 {
    01082   for (FontSize size = FS_BEGIN; size != FS_END; size++) {
    01083     /* Clear out existing glyph map if it exists */
    01084     if (_unicode_glyph_map[size] != NULL) {
    01085       for (uint i = 0; i < 256; i++) {
    01086         free(_unicode_glyph_map[size][i]);
    01087       }
    01088       free(_unicode_glyph_map[size]);
    01089       _unicode_glyph_map[size] = NULL;
    01090     }
    01091
    01092     SpriteID base = GetFontBase(size);
    01093
    01094     for (uint i = ASCII_LETTERSTART; i < 256; i++) {
    01095       SpriteID sprite = base + i - ASCII_LETTERSTART;
    01096       if (!SpriteExists(sprite)) continue;
    01097       SetUnicodeGlyph(size, i, sprite);
    01098       SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
    01099     }
    01100
    01101     for (uint i = 0; i < lengthof(_default_unicode_map); i++) {
    01102       byte key = _default_unicode_map[i].key;
    01103       if (key == CLRA || key == CLRL) {
    01104         /* Clear the glyph. This happens if the glyph at this code point
    01105          * is non-standard and should be accessed by an SCC_xxx enum
    01106          * entry only. */
    01107         if (key == CLRA || size == FS_LARGE) {
    01108           SetUnicodeGlyph(size, _default_unicode_map[i].code, 0);
    01109         }
    01110       } else {
    01111         SpriteID sprite = base + key - ASCII_LETTERSTART;
    01112         SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
    01113       }
    01114     }
    01115   }
    01116 }