00001
00002
00003
00004
00005
00006
00007
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 static const byte FACE_COLOUR = 1;
00043 static const byte SHADOW_COLOUR = 2;
00044
00050
00051
00052
00053
00054 #ifdef WIN32
00055 #include <windows.h>
00056 #include <shlobj.h>
00057 #include "os/windows/win32.h"
00058
00069 char *GetShortPath(const char *long_path)
00070 {
00071 static char short_path[MAX_PATH];
00072 #ifdef UNICODE
00073
00074
00075
00076 wchar_t long_path_w[MAX_PATH];
00077 MultiByteToWideChar(CP_UTF8, 0, long_path, -1, long_path_w, MAX_PATH);
00078
00079 wchar_t short_path_w[MAX_PATH];
00080 GetShortPathNameW(long_path_w, short_path_w, MAX_PATH);
00081
00082 WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, MAX_PATH, NULL, NULL);
00083 #else
00084
00085 GetShortPathNameA(long_path, short_path, MAX_PATH);
00086 #endif
00087 return short_path;
00088 }
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098 #define FONT_DIR_NT "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"
00099 #define FONT_DIR_9X "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Fonts"
00100 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
00101 {
00102 FT_Error err = FT_Err_Cannot_Open_Resource;
00103 HKEY hKey;
00104 LONG ret;
00105 TCHAR vbuffer[MAX_PATH], dbuffer[256];
00106 TCHAR *font_namep;
00107 char *font_path;
00108 uint index;
00109
00110
00111
00112
00113 ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_NT), 0, KEY_READ, &hKey);
00114 if (ret != ERROR_SUCCESS) ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T(FONT_DIR_9X), 0, KEY_READ, &hKey);
00115
00116 if (ret != ERROR_SUCCESS) {
00117 DEBUG(freetype, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows (NT)\\CurrentVersion\\Fonts");
00118 return err;
00119 }
00120
00121
00122
00123
00124 #if defined(UNICODE)
00125 font_namep = MallocT<TCHAR>(MAX_PATH);
00126 MB_TO_WIDE_BUFFER(font_name, font_namep, MAX_PATH * sizeof(TCHAR));
00127 #else
00128 font_namep = const_cast<char *>(font_name);
00129 #endif
00130
00131 for (index = 0;; index++) {
00132 TCHAR *s;
00133 DWORD vbuflen = lengthof(vbuffer);
00134 DWORD dbuflen = lengthof(dbuffer);
00135
00136 ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, NULL, NULL, (byte*)dbuffer, &dbuflen);
00137 if (ret != ERROR_SUCCESS) goto registry_no_font_found;
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148 s = _tcschr(vbuffer, _T('('));
00149 if (s != NULL) s[-1] = '\0';
00150
00151 if (_tcschr(vbuffer, _T('&')) == NULL) {
00152 if (_tcsicmp(vbuffer, font_namep) == 0) break;
00153 } else {
00154 if (_tcsstr(vbuffer, font_namep) != NULL) break;
00155 }
00156 }
00157
00158 if (!SUCCEEDED(SHGetFolderPath(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, vbuffer))) {
00159 DEBUG(freetype, 0, "SHGetFolderPath cannot return fonts directory");
00160 goto folder_error;
00161 }
00162
00163
00164
00165
00166
00167
00168 #if defined(UNICODE)
00169
00170
00171
00172 font_path = (char*)font_namep;
00173 WIDE_TO_MB_BUFFER(vbuffer, font_path, MAX_PATH * sizeof(TCHAR));
00174 #else
00175 font_path = vbuffer;
00176 #endif
00177
00178 ttd_strlcat(font_path, "\\", MAX_PATH * sizeof(TCHAR));
00179 ttd_strlcat(font_path, WIDE_TO_MB(dbuffer), MAX_PATH * sizeof(TCHAR));
00180
00181
00182 font_path = GetShortPath(font_path);
00183
00184 index = 0;
00185 do {
00186 err = FT_New_Face(_library, font_path, index, face);
00187 if (err != FT_Err_Ok) break;
00188
00189 if (strncasecmp(font_name, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
00190
00191 if (strncasecmp(font_name + strlen(font_name) + 1, (*face)->family_name, strlen((*face)->family_name)) == 0) break;
00192 err = FT_Err_Cannot_Open_Resource;
00193
00194 } while ((FT_Long)++index != (*face)->num_faces);
00195
00196
00197 folder_error:
00198 registry_no_font_found:
00199 #if defined(UNICODE)
00200 free(font_namep);
00201 #endif
00202 RegCloseKey(hKey);
00203 return err;
00204 }
00205
00219 static const char *GetEnglishFontName(const ENUMLOGFONTEX *logfont)
00220 {
00221 static char font_name[MAX_PATH];
00222 const char *ret_font_name = NULL;
00223 uint pos = 0;
00224 HDC dc;
00225 HGDIOBJ oldfont;
00226 byte *buf;
00227 DWORD dw;
00228 uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
00229
00230 HFONT font = CreateFontIndirect(&logfont->elfLogFont);
00231 if (font == NULL) goto err1;
00232
00233 dc = GetDC(NULL);
00234 oldfont = SelectObject(dc, font);
00235 dw = GetFontData(dc, 'eman', 0, NULL, 0);
00236 if (dw == GDI_ERROR) goto err2;
00237
00238 buf = MallocT<byte>(dw);
00239 dw = GetFontData(dc, 'eman', 0, buf, dw);
00240 if (dw == GDI_ERROR) goto err3;
00241
00242 format = buf[pos++] << 8;
00243 format += buf[pos++];
00244 assert(format == 0);
00245 count = buf[pos++] << 8;
00246 count += buf[pos++];
00247 stringOffset = buf[pos++] << 8;
00248 stringOffset += buf[pos++];
00249 for (uint i = 0; i < count; i++) {
00250 platformId = buf[pos++] << 8;
00251 platformId += buf[pos++];
00252 encodingId = buf[pos++] << 8;
00253 encodingId += buf[pos++];
00254 languageId = buf[pos++] << 8;
00255 languageId += buf[pos++];
00256 nameId = buf[pos++] << 8;
00257 nameId += buf[pos++];
00258 if (nameId != 1) {
00259 pos += 4;
00260 continue;
00261 }
00262 length = buf[pos++] << 8;
00263 length += buf[pos++];
00264 offset = buf[pos++] << 8;
00265 offset += buf[pos++];
00266
00267
00268 length = min(length, MAX_PATH - 1);
00269 for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
00270 font_name[length] = '\0';
00271
00272 if ((platformId == 1 && languageId == 0) ||
00273 (platformId == 3 && languageId == 0x0409)) {
00274 ret_font_name = font_name;
00275 break;
00276 }
00277 }
00278
00279 err3:
00280 free(buf);
00281 err2:
00282 SelectObject(dc, oldfont);
00283 ReleaseDC(NULL, dc);
00284 DeleteObject(font);
00285 err1:
00286 return ret_font_name == NULL ? WIDE_TO_MB((const TCHAR*)logfont->elfFullName) : ret_font_name;
00287 }
00288
00289 struct EFCParam {
00290 FreeTypeSettings *settings;
00291 LOCALESIGNATURE locale;
00292 SetFallbackFontCallback *callback;
00293 };
00294
00295 static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXTMETRICEX *metric, DWORD type, LPARAM lParam)
00296 {
00297 EFCParam *info = (EFCParam *)lParam;
00298
00299
00300 if (!(type & TRUETYPE_FONTTYPE)) return 1;
00301
00302 if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1;
00303
00304
00305 if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) {
00306
00307 FONTSIGNATURE fs;
00308 memset(&fs, 0, sizeof(fs));
00309 HFONT font = CreateFontIndirect(&logfont->elfLogFont);
00310 if (font != NULL) {
00311 HDC dc = GetDC(NULL);
00312 HGDIOBJ oldfont = SelectObject(dc, font);
00313 GetTextCharsetInfo(dc, &fs, 0);
00314 SelectObject(dc, oldfont);
00315 ReleaseDC(NULL, dc);
00316 DeleteObject(font);
00317 }
00318 if ((fs.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (fs.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) return 1;
00319 }
00320
00321 char font_name[MAX_PATH];
00322 #if defined(UNICODE)
00323 WIDE_TO_MB_BUFFER((const TCHAR*)logfont->elfFullName, font_name, lengthof(font_name));
00324 #else
00325 strecpy(font_name, (const TCHAR*)logfont->elfFullName, lastof(font_name));
00326 #endif
00327
00328
00329 const char *english_name = GetEnglishFontName(logfont);
00330 strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name));
00331
00332
00333 bool ft_init = _library != NULL;
00334 bool found = false;
00335 FT_Face face;
00336
00337 if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName(font_name, &face) == FT_Err_Ok) {
00338 FT_Done_Face(face);
00339 found = true;
00340 }
00341 if (!ft_init) {
00342
00343 FT_Done_FreeType(_library);
00344 _library = NULL;
00345 }
00346
00347 if (!found) return 1;
00348
00349 strecpy(info->settings->small_font, font_name, lastof(info->settings->small_font));
00350 strecpy(info->settings->medium_font, font_name, lastof(info->settings->medium_font));
00351 strecpy(info->settings->large_font, font_name, lastof(info->settings->large_font));
00352 if (info->callback(NULL)) return 1;
00353 DEBUG(freetype, 1, "Fallback font: %s (%s)", font_name, english_name);
00354 return 0;
00355 }
00356
00357 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, SetFallbackFontCallback *callback)
00358 {
00359 DEBUG(freetype, 1, "Trying fallback fonts");
00360 EFCParam langInfo;
00361 if (GetLocaleInfo(MAKELCID(winlangid, SORT_DEFAULT), LOCALE_FONTSIGNATURE, (LPTSTR)&langInfo.locale, sizeof(langInfo.locale) / sizeof(TCHAR)) == 0) {
00362
00363 DEBUG(freetype, 1, "Can't get locale info for fallback font (langid=0x%x)", winlangid);
00364 return false;
00365 }
00366 langInfo.settings = settings;
00367 langInfo.callback = callback;
00368
00369 LOGFONT font;
00370
00371 font.lfCharSet = DEFAULT_CHARSET;
00372 font.lfFaceName[0] = '\0';
00373 font.lfPitchAndFamily = 0;
00374
00375 HDC dc = GetDC(NULL);
00376 int ret = EnumFontFamiliesEx(dc, &font, (FONTENUMPROC)&EnumFontCallback, (LPARAM)&langInfo, 0);
00377 ReleaseDC(NULL, dc);
00378 return ret == 0;
00379 }
00380
00381 #elif defined(__APPLE__)
00382
00383
00384
00385
00386 #include "os/macosx/macos.h"
00387 #include <ApplicationServices/ApplicationServices.h>
00388
00389 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
00390 {
00391 FT_Error err = FT_Err_Cannot_Open_Resource;
00392
00393
00394 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name, kCFStringEncodingUTF8);
00395 ATSFontRef font = ATSFontFindFromName(name, kATSOptionFlagsDefault);
00396 CFRelease(name);
00397 if (font == kInvalidFont) return err;
00398
00399
00400 FSRef ref;
00401 OSStatus os_err = -1;
00402 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
00403 if (MacOSVersionIsAtLeast(10, 5, 0)) {
00404 os_err = ATSFontGetFileReference(font, &ref);
00405 } else
00406 #endif
00407 {
00408 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
00409
00410 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
00411 #define ATSFSSpec FSSpec
00412 #endif
00413 FSSpec spec;
00414 os_err = ATSFontGetFileSpecification(font, (ATSFSSpec *)&spec);
00415 if (os_err == noErr) os_err = FSpMakeFSRef(&spec, &ref);
00416 #endif
00417 }
00418
00419 if (os_err == noErr) {
00420
00421 UInt8 file_path[PATH_MAX];
00422 if (FSRefMakePath(&ref, file_path, sizeof(file_path)) == noErr) {
00423 DEBUG(freetype, 3, "Font path for %s: %s", font_name, file_path);
00424 err = FT_New_Face(_library, (const char *)file_path, 0, face);
00425 }
00426 }
00427
00428 return err;
00429 }
00430
00431 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, SetFallbackFontCallback *callback)
00432 {
00433 const char *str;
00434 bool result = false;
00435
00436 callback(&str);
00437
00438 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
00439 if (MacOSVersionIsAtLeast(10, 5, 0)) {
00440
00441
00442 char lang[16];
00443 if (strcmp(language_isocode, "zh_TW") == 0) {
00444
00445 strecpy(lang, "zh-Hant", lastof(lang));
00446 } else if (strcmp(language_isocode, "zh_CN") == 0) {
00447
00448 strecpy(lang, "zh-Hans", lastof(lang));
00449 } else if (strncmp(language_isocode, "ur", 2) == 0) {
00450
00451
00452
00453 strecpy(lang, "fa", lastof(lang));
00454 } else {
00455
00456 strecpy(lang, language_isocode, lastof(lang));
00457 char *sep = strchr(lang, '_');
00458 if (sep != NULL) *sep = '\0';
00459 }
00460
00461 CFStringRef lang_code;
00462 lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);
00463
00464
00465
00466 ATSFontIterator itr;
00467 ATSFontRef font;
00468 ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);
00469 while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
00470
00471 CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);
00472 CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);
00473 if (langs != NULL) {
00474
00475 for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) {
00476 CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
00477 if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) {
00478
00479 CFStringRef font_name = CTFontCopyFullName(font_ref);
00480 char name[128];
00481 CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);
00482 CFRelease(font_name);
00483
00484 if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 ||
00485 strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 ||
00486 strncmp(name, "GB18030 Bitmap", 14) == 0) continue;
00487
00488
00489 strecpy(settings->small_font, name, lastof(settings->small_font));
00490 strecpy(settings->medium_font, name, lastof(settings->medium_font));
00491 strecpy(settings->large_font, name, lastof(settings->large_font));
00492 DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);
00493 result = true;
00494 break;
00495 }
00496 }
00497 CFRelease(langs);
00498 }
00499 CFRelease(font_ref);
00500 }
00501 ATSFontIteratorRelease(&itr);
00502 CFRelease(lang_code);
00503 } else
00504 #endif
00505 {
00506 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
00507
00508
00509
00510
00511
00512
00513
00514
00515
00516 char buff[256];
00517 strecpy(buff, str, lastof(buff));
00518 str_validate(buff, lastof(buff), true, false);
00519
00520
00521 CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, buff, kCFStringEncodingUTF8);
00522 if (cf_str == NULL) {
00523
00524 return false;
00525 }
00526 CFIndex str_len = CFStringGetLength(cf_str);
00527 UniChar string[str_len];
00528 CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string);
00529
00530
00531 ATSUStyle style;
00532 ATSUCreateStyle(&style);
00533
00534
00535 UniCharCount run_len = kATSUToTextEnd;
00536 ATSUTextLayout text_layout;
00537 ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout);
00538
00539
00540
00541
00542
00543
00544 UniCharArrayOffset offset = kATSUFromTextBeginning;
00545 OSStatus os_err;
00546 do {
00547 ATSUFontID font;
00548 UniCharCount run_len;
00549 os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len);
00550 if (os_err == kATSUFontsMatched) {
00551
00552
00553 ATSUAttributeTag tag = kATSUFontTag;
00554 ByteCount size = sizeof(font);
00555 ATSUAttributeValuePtr val = &font;
00556 ATSUSetAttributes(style, 1, &tag, &size, &val);
00557 offset += run_len;
00558 }
00559
00560 } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len);
00561
00562 if (os_err == noErr || os_err == kATSUFontsMatched) {
00563
00564
00565 ATSUFontID font;
00566 ByteCount act_len;
00567 ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len);
00568
00569
00570
00571 char name[128];
00572 ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL);
00573 name[act_len > 127 ? 127 : act_len] = '\0';
00574
00575
00576 strecpy(settings->small_font, name, lastof(settings->small_font));
00577 strecpy(settings->medium_font, name, lastof(settings->medium_font));
00578 strecpy(settings->large_font, name, lastof(settings->large_font));
00579 DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name);
00580 result = true;
00581 }
00582
00583 ATSUDisposeTextLayout(text_layout);
00584 ATSUDisposeStyle(style);
00585 CFRelease(cf_str);
00586 #endif
00587 }
00588
00589 if (result && strncmp(settings->medium_font, "Geeza Pro", 9) == 0) {
00590
00591
00592
00593
00594
00595 bool ft_init = _library != NULL;
00596 FT_Face face;
00597
00598 if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) {
00599 FT_Done_Face(face);
00600 strecpy(settings->small_font, "Arial Unicode MS", lastof(settings->small_font));
00601 strecpy(settings->medium_font, "Arial Unicode MS", lastof(settings->medium_font));
00602 strecpy(settings->large_font, "Arial Unicode MS", lastof(settings->large_font));
00603 DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'");
00604 }
00605 if (!ft_init) {
00606
00607 FT_Done_FreeType(_library);
00608 _library = NULL;
00609 }
00610 }
00611
00612 callback(NULL);
00613 return result;
00614 }
00615
00616 #elif defined(WITH_FONTCONFIG)
00617
00618
00619
00620 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
00621 {
00622 FT_Error err = FT_Err_Cannot_Open_Resource;
00623
00624 if (!FcInit()) {
00625 ShowInfoF("Unable to load font configuration");
00626 } else {
00627 FcPattern *match;
00628 FcPattern *pat;
00629 FcFontSet *fs;
00630 FcResult result;
00631 char *font_style;
00632 char *font_family;
00633
00634
00635 font_family = strdup(font_name);
00636 font_style = strchr(font_family, ',');
00637 if (font_style != NULL) {
00638 font_style[0] = '\0';
00639 font_style++;
00640 while (*font_style == ' ' || *font_style == '\t') font_style++;
00641 }
00642
00643
00644 pat = FcNameParse((FcChar8*)font_family);
00645 if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
00646 FcConfigSubstitute(0, pat, FcMatchPattern);
00647 FcDefaultSubstitute(pat);
00648 fs = FcFontSetCreate();
00649 match = FcFontMatch(0, pat, &result);
00650
00651 if (fs != NULL && match != NULL) {
00652 int i;
00653 FcChar8 *family;
00654 FcChar8 *style;
00655 FcChar8 *file;
00656 FcFontSetAdd(fs, match);
00657
00658 for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
00659
00660 if (FcPatternGetString(fs->fonts[i], FC_FILE, 0, &file) == FcResultMatch &&
00661 FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
00662 FcPatternGetString(fs->fonts[i], FC_STYLE, 0, &style) == FcResultMatch) {
00663
00664
00665 if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
00666
00667
00668
00669
00670 if (strcasecmp(font_family, (char*)family) == 0) {
00671 err = FT_New_Face(_library, (char *)file, 0, face);
00672 }
00673 }
00674 }
00675 }
00676
00677 free(font_family);
00678 FcPatternDestroy(pat);
00679 FcFontSetDestroy(fs);
00680 FcFini();
00681 }
00682
00683 return err;
00684 }
00685
00686 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, SetFallbackFontCallback *callback)
00687 {
00688 if (!FcInit()) return false;
00689
00690 bool ret = false;
00691
00692
00693
00694
00695 char lang[16];
00696 seprintf(lang, lastof(lang), ":lang=%s", language_isocode);
00697 char *split = strchr(lang, '_');
00698 if (split != NULL) *split = '\0';
00699
00700
00701 FcPattern *pat = FcNameParse((FcChar8*)lang);
00702
00703 FcObjectSet *os = FcObjectSetBuild(FC_FILE, NULL);
00704
00705 FcFontSet *fs = FcFontList(NULL, pat, os);
00706
00707
00708 FcObjectSetDestroy(os);
00709 FcPatternDestroy(pat);
00710
00711 if (fs != NULL) {
00712 for (int i = 0; i < fs->nfont; i++) {
00713 FcPattern *font = fs->fonts[i];
00714
00715 FcChar8 *file = NULL;
00716 FcResult res = FcPatternGetString(font, FC_FILE, 0, &file);
00717 if (res != FcResultMatch || file == NULL) {
00718 continue;
00719 }
00720
00721 strecpy(settings->small_font, (const char*)file, lastof(settings->small_font));
00722 strecpy(settings->medium_font, (const char*)file, lastof(settings->medium_font));
00723 strecpy(settings->large_font, (const char*)file, lastof(settings->large_font));
00724
00725 bool missing = callback(NULL);
00726 DEBUG(freetype, 1, "Font \"%s\" misses%s glyphs", file, missing ? "" : " no");
00727
00728 if (!missing) {
00729 ret = true;
00730 break;
00731 }
00732 }
00733
00734
00735 FcFontSetDestroy(fs);
00736 }
00737
00738 FcFini();
00739 return ret;
00740 }
00741
00742 #else
00743 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
00744 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, SetFallbackFontCallback *callback) { return false; }
00745 #endif
00746
00747 static void SetFontGeometry(FT_Face face, FontSize size, int pixels)
00748 {
00749 FT_Set_Pixel_Sizes(face, 0, pixels);
00750
00751 if (FT_IS_SCALABLE(face)) {
00752 int asc = face->ascender * pixels / face->units_per_EM;
00753 int dec = face->descender * pixels / face->units_per_EM;
00754
00755 _ascender[size] = asc;
00756 _font_height[size] = asc - dec;
00757 } else {
00758 _ascender[size] = pixels;
00759 _font_height[size] = pixels;
00760 }
00761 }
00762
00769 static void LoadFreeTypeFont(const char *font_name, FT_Face *face, const char *type)
00770 {
00771 FT_Error error;
00772
00773 if (StrEmpty(font_name)) return;
00774
00775 error = FT_New_Face(_library, font_name, 0, face);
00776
00777 if (error != FT_Err_Ok) error = GetFontByFaceName(font_name, face);
00778
00779 if (error == FT_Err_Ok) {
00780 DEBUG(freetype, 2, "Requested '%s', using '%s %s'", font_name, (*face)->family_name, (*face)->style_name);
00781
00782
00783 error = FT_Select_Charmap(*face, ft_encoding_unicode);
00784 if (error == FT_Err_Ok) return;
00785
00786 if (error == FT_Err_Invalid_CharMap_Handle) {
00787
00788
00789
00790 FT_CharMap found = (*face)->charmaps[0];
00791 int i;
00792
00793 for (i = 0; i < (*face)->num_charmaps; i++) {
00794 FT_CharMap charmap = (*face)->charmaps[i];
00795 if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
00796 found = charmap;
00797 }
00798 }
00799
00800 if (found != NULL) {
00801 error = FT_Set_Charmap(*face, found);
00802 if (error == FT_Err_Ok) return;
00803 }
00804 }
00805 }
00806
00807 FT_Done_Face(*face);
00808 *face = NULL;
00809
00810 ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, type, error);
00811 }
00812
00813
00814 void InitFreeType()
00815 {
00816 ResetFontSizes();
00817
00818 if (StrEmpty(_freetype.small_font) && StrEmpty(_freetype.medium_font) && StrEmpty(_freetype.large_font)) {
00819 DEBUG(freetype, 1, "No font faces specified, using sprite fonts instead");
00820 return;
00821 }
00822
00823 if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
00824 ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
00825 return;
00826 }
00827
00828 DEBUG(freetype, 2, "Initialized");
00829
00830
00831 LoadFreeTypeFont(_freetype.small_font, &_face_small, "small");
00832 LoadFreeTypeFont(_freetype.medium_font, &_face_medium, "medium");
00833 LoadFreeTypeFont(_freetype.large_font, &_face_large, "large");
00834
00835
00836 if (_face_small != NULL) {
00837 SetFontGeometry(_face_small, FS_SMALL, _freetype.small_size);
00838 }
00839 if (_face_medium != NULL) {
00840 SetFontGeometry(_face_medium, FS_NORMAL, _freetype.medium_size);
00841 }
00842 if (_face_large != NULL) {
00843 SetFontGeometry(_face_large, FS_LARGE, _freetype.large_size);
00844 }
00845 }
00846
00847 static void ResetGlyphCache();
00848
00853 static void UnloadFace(FT_Face *face)
00854 {
00855 if (*face == NULL) return;
00856
00857 FT_Done_Face(*face);
00858 *face = NULL;
00859 }
00860
00864 void UninitFreeType()
00865 {
00866 ResetFontSizes();
00867 ResetGlyphCache();
00868
00869 UnloadFace(&_face_small);
00870 UnloadFace(&_face_medium);
00871 UnloadFace(&_face_large);
00872
00873 FT_Done_FreeType(_library);
00874 _library = NULL;
00875 }
00876
00877
00878 static FT_Face GetFontFace(FontSize size)
00879 {
00880 switch (size) {
00881 default: NOT_REACHED();
00882 case FS_NORMAL: return _face_medium;
00883 case FS_SMALL: return _face_small;
00884 case FS_LARGE: return _face_large;
00885 }
00886 }
00887
00888
00889 struct GlyphEntry {
00890 Sprite *sprite;
00891 byte width;
00892 bool duplicate;
00893 };
00894
00895
00896
00897
00898
00899
00900
00901
00902
00903
00904
00905
00906
00907
00908 static GlyphEntry **_glyph_ptr[FS_END];
00909
00911 static void ResetGlyphCache()
00912 {
00913 for (FontSize i = FS_BEGIN; i < FS_END; i++) {
00914 if (_glyph_ptr[i] == NULL) continue;
00915
00916 for (int j = 0; j < 256; j++) {
00917 if (_glyph_ptr[i][j] == NULL) continue;
00918
00919 for (int k = 0; k < 256; k++) {
00920 if (_glyph_ptr[i][j][k].duplicate) continue;
00921 free(_glyph_ptr[i][j][k].sprite);
00922 }
00923
00924 free(_glyph_ptr[i][j]);
00925 }
00926
00927 free(_glyph_ptr[i]);
00928 _glyph_ptr[i] = NULL;
00929 }
00930 }
00931
00932 static GlyphEntry *GetGlyphPtr(FontSize size, WChar key)
00933 {
00934 if (_glyph_ptr[size] == NULL) return NULL;
00935 if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) return NULL;
00936 return &_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)];
00937 }
00938
00939
00940 static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph, bool duplicate = false)
00941 {
00942 if (_glyph_ptr[size] == NULL) {
00943 DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
00944 _glyph_ptr[size] = CallocT<GlyphEntry*>(256);
00945 }
00946
00947 if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
00948 DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
00949 _glyph_ptr[size][GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
00950 }
00951
00952 DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
00953 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
00954 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].width = glyph->width;
00955 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].duplicate = duplicate;
00956 }
00957
00958 static void *AllocateFont(size_t size)
00959 {
00960 return MallocT<byte>(size);
00961 }
00962
00963
00964
00965 static bool GetFontAAState(FontSize size)
00966 {
00967
00968 if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
00969
00970 switch (size) {
00971 default: NOT_REACHED();
00972 case FS_NORMAL: return _freetype.medium_aa;
00973 case FS_SMALL: return _freetype.small_aa;
00974 case FS_LARGE: return _freetype.large_aa;
00975 }
00976 }
00977
00978
00979 const Sprite *GetGlyph(FontSize size, WChar key)
00980 {
00981 FT_Face face = GetFontFace(size);
00982 FT_GlyphSlot slot;
00983 GlyphEntry new_glyph;
00984 GlyphEntry *glyph;
00985 SpriteLoader::Sprite sprite;
00986 int width;
00987 int height;
00988 int x;
00989 int y;
00990
00991 assert(IsPrintable(key));
00992
00993
00994 if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
00995 SpriteID sprite = GetUnicodeGlyph(size, key);
00996 if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
00997 return GetSprite(sprite, ST_FONT);
00998 }
00999
01000
01001 glyph = GetGlyphPtr(size, key);
01002 if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
01003
01004 slot = face->glyph;
01005
01006 bool aa = GetFontAAState(size);
01007
01008 FT_UInt glyph_index = FT_Get_Char_Index(face, key);
01009 if (glyph_index == 0) {
01010 if (key == '?') {
01011
01012 SpriteID sprite = GetUnicodeGlyph(size, key);
01013 Sprite *spr = (Sprite*)GetRawSprite(sprite, ST_FONT, AllocateFont);
01014 assert(spr != NULL);
01015 new_glyph.sprite = spr;
01016 new_glyph.width = spr->width + (size != FS_NORMAL);
01017 SetGlyphPtr(size, key, &new_glyph, false);
01018 return new_glyph.sprite;
01019 } else {
01020
01021 GetGlyph(size, '?');
01022 glyph = GetGlyphPtr(size, '?');
01023 SetGlyphPtr(size, key, glyph, true);
01024 return glyph->sprite;
01025 }
01026 }
01027 FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
01028 FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
01029
01030
01031 aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
01032
01033
01034 width = max(1, slot->bitmap.width + (size == FS_NORMAL));
01035 height = max(1, slot->bitmap.rows + (size == FS_NORMAL));
01036
01037
01038 sprite.AllocateData(width * height);
01039 sprite.width = width;
01040 sprite.height = height;
01041 sprite.x_offs = slot->bitmap_left;
01042 sprite.y_offs = _ascender[size] - slot->bitmap_top;
01043
01044
01045 if (size == FS_NORMAL) {
01046 for (y = 0; y < slot->bitmap.rows; y++) {
01047 for (x = 0; x < slot->bitmap.width; x++) {
01048 if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
01049 sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
01050 sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
01051 }
01052 }
01053 }
01054 }
01055
01056 for (y = 0; y < slot->bitmap.rows; y++) {
01057 for (x = 0; x < slot->bitmap.width; x++) {
01058 if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
01059 sprite.data[x + y * sprite.width].m = FACE_COLOUR;
01060 sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
01061 }
01062 }
01063 }
01064
01065 new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
01066 new_glyph.width = slot->advance.x >> 6;
01067
01068 SetGlyphPtr(size, key, &new_glyph);
01069
01070 return new_glyph.sprite;
01071 }
01072
01073
01074 uint GetGlyphWidth(FontSize size, WChar key)
01075 {
01076 FT_Face face = GetFontFace(size);
01077 GlyphEntry *glyph;
01078
01079 if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
01080 SpriteID sprite = GetUnicodeGlyph(size, key);
01081 if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
01082 return SpriteExists(sprite) ? GetSprite(sprite, ST_FONT)->width + (size != FS_NORMAL) : 0;
01083 }
01084
01085 glyph = GetGlyphPtr(size, key);
01086 if (glyph == NULL || glyph->sprite == NULL) {
01087 GetGlyph(size, key);
01088 glyph = GetGlyphPtr(size, key);
01089 }
01090
01091 return glyph->width;
01092 }
01093
01094
01095 #endif
01096
01098 void ResetFontSizes()
01099 {
01100 _font_height[FS_SMALL] = 6;
01101 _font_height[FS_NORMAL] = 10;
01102 _font_height[FS_LARGE] = 18;
01103 }
01104
01105
01106
01107 #include "table/unicode.h"
01108
01109 static SpriteID **_unicode_glyph_map[FS_END];
01110
01111
01113 static SpriteID GetFontBase(FontSize size)
01114 {
01115 switch (size) {
01116 default: NOT_REACHED();
01117 case FS_NORMAL: return SPR_ASCII_SPACE;
01118 case FS_SMALL: return SPR_ASCII_SPACE_SMALL;
01119 case FS_LARGE: return SPR_ASCII_SPACE_BIG;
01120 }
01121 }
01122
01123
01124 SpriteID GetUnicodeGlyph(FontSize size, uint32 key)
01125 {
01126 if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) return 0;
01127 return _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)];
01128 }
01129
01130
01131 void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
01132 {
01133 if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = CallocT<SpriteID*>(256);
01134 if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = CallocT<SpriteID>(256);
01135 _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
01136 }
01137
01138
01139 void InitializeUnicodeGlyphMap()
01140 {
01141 for (FontSize size = FS_BEGIN; size != FS_END; size++) {
01142
01143 if (_unicode_glyph_map[size] != NULL) {
01144 for (uint i = 0; i < 256; i++) {
01145 free(_unicode_glyph_map[size][i]);
01146 }
01147 free(_unicode_glyph_map[size]);
01148 _unicode_glyph_map[size] = NULL;
01149 }
01150
01151 SpriteID base = GetFontBase(size);
01152
01153 for (uint i = ASCII_LETTERSTART; i < 256; i++) {
01154 SpriteID sprite = base + i - ASCII_LETTERSTART;
01155 if (!SpriteExists(sprite)) continue;
01156 SetUnicodeGlyph(size, i, sprite);
01157 SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
01158 }
01159
01160 for (uint i = 0; i < lengthof(_default_unicode_map); i++) {
01161 byte key = _default_unicode_map[i].key;
01162 if (key == CLRA || key == CLRL) {
01163
01164
01165
01166 if (key == CLRA || size == FS_LARGE) {
01167 SetUnicodeGlyph(size, _default_unicode_map[i].code, 0);
01168 }
01169 } else {
01170 SpriteID sprite = base + key - ASCII_LETTERSTART;
01171 SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
01172 }
01173 }
01174 }
01175 }