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