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 enum {
00043 FACE_COLOUR = 1,
00044 SHADOW_COLOUR = 2,
00045 };
00046
00049 #ifdef WIN32
00050 #include <windows.h>
00051 #include <shlobj.h>
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
00069
00070
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
00080 GetShortPathNameA(long_path, short_path, MAX_PATH);
00081 #endif
00082 return short_path;
00083 }
00084
00085
00086
00087
00088
00089
00090
00091
00092
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
00106
00107
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
00117
00118
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);
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
00135
00136
00137
00138
00139
00140
00141
00142
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
00159
00160
00161
00162
00163 #if defined(UNICODE)
00164
00165
00166
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
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
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;
00255 continue;
00256 }
00257 length = buf[pos++] << 8;
00258 length += buf[pos++];
00259 offset = buf[pos++] << 8;
00260 offset += buf[pos++];
00261
00262
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) ||
00268 (platformId == 3 && languageId == 0x0409)) {
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
00295 if (!(type & TRUETYPE_FONTTYPE)) return 1;
00296
00297 if (logfont->elfLogFont.lfCharSet == SYMBOL_CHARSET) return 1;
00298
00299
00300 if ((metric->ntmFontSig.fsCsb[0] & info->locale.lsCsbSupported[0]) == 0 && (metric->ntmFontSig.fsCsb[1] & info->locale.lsCsbSupported[1]) == 0) {
00301
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
00324 const char *english_name = GetEnglishFontName(logfont);
00325 strecpy(font_name + strlen(font_name) + 1, english_name, lastof(font_name));
00326
00327
00328 bool ft_init = _library != NULL;
00329 bool found = false;
00330 FT_Face face;
00331
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
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;
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
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
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
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
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
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
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
00428
00429 char lang[16];
00430 if (strcmp(language_isocode, "zh_TW") == 0) {
00431
00432 strecpy(lang, "zh-Hant", lastof(lang));
00433 } else if (strcmp(language_isocode, "zh_CN") == 0) {
00434
00435 strecpy(lang, "zh-Hans", lastof(lang));
00436 } else if (strncmp(language_isocode, "ur", 2) == 0) {
00437
00438
00439
00440 strecpy(lang, "fa", lastof(lang));
00441 } else {
00442
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
00452
00453 ATSFontIterator itr;
00454 ATSFontRef font;
00455 ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);
00456 while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
00457
00458 CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);
00459 CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);
00460 if (langs != NULL) {
00461
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
00466 CFStringRef font_name = CTFontCopyFullName(font_ref);
00467 char name[128];
00468 CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);
00469 CFRelease(font_name);
00470
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
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
00495
00496
00497
00498
00499
00500
00501 CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, str, kCFStringEncodingUTF8);
00502 if (cf_str == NULL) {
00503
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
00511 ATSUStyle style;
00512 ATSUCreateStyle(&style);
00513
00514
00515 UniCharCount run_len = kATSUToTextEnd;
00516 ATSUTextLayout text_layout;
00517 ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout);
00518
00519
00520
00521
00522
00523
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
00532
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
00540 } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len);
00541
00542 if (os_err == noErr || os_err == kATSUFontsMatched) {
00543
00544
00545 ATSUFontID font;
00546 ByteCount act_len;
00547 ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len);
00548
00549
00550
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
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
00571
00572
00573
00574
00575 bool ft_init = _library != NULL;
00576 FT_Face face;
00577
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
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
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
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
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
00641 if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
00642
00643
00644
00645
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
00669
00670
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
00686 pat = FcPatternCreate();
00687
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
00697 match = FcFontMatch(0, pat, &result);
00698
00699 if (match == NULL) {
00700 goto error_pattern;
00701 }
00702
00703
00704 fs = FcFontSetCreate();
00705 FcFontSetAdd(fs, match);
00706
00707
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
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
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
00767 error = FT_Select_Charmap(*face, ft_encoding_unicode);
00768 if (error == FT_Err_Ok) return;
00769
00770 if (error == FT_Err_Invalid_CharMap_Handle) {
00771
00772
00773
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
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
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
00880
00881
00882
00883
00884
00885
00886
00887
00888
00889
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
00946 static bool GetFontAAState(FontSize size)
00947 {
00948
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
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
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
00993 aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
00994
00995
00996 width = max(1, slot->bitmap.width + (size == FS_NORMAL));
00997 height = max(1, slot->bitmap.rows + (size == FS_NORMAL));
00998
00999
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
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
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
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
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
01126
01127
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 }