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(SHGetFolderPath(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 #include <ApplicationServices/ApplicationServices.h>
00444
00445 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
00446 {
00447 FT_Error err = FT_Err_Cannot_Open_Resource;
00448
00449
00450 CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, font_name, kCFStringEncodingUTF8);
00451 ATSFontRef font = ATSFontFindFromName(name, kATSOptionFlagsDefault);
00452 CFRelease(name);
00453 if (font == kInvalidFont) return err;
00454
00455
00456 FSRef ref;
00457 OSStatus os_err = -1;
00458 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
00459 if (MacOSVersionIsAtLeast(10, 5, 0)) {
00460 os_err = ATSFontGetFileReference(font, &ref);
00461 } else
00462 #endif
00463 {
00464 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
00465
00466 #if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5)
00467 #define ATSFSSpec FSSpec
00468 #endif
00469 FSSpec spec;
00470 os_err = ATSFontGetFileSpecification(font, (ATSFSSpec *)&spec);
00471 if (os_err == noErr) os_err = FSpMakeFSRef(&spec, &ref);
00472 #endif
00473 }
00474
00475 if (os_err == noErr) {
00476
00477 UInt8 file_path[PATH_MAX];
00478 if (FSRefMakePath(&ref, file_path, sizeof(file_path)) == noErr) {
00479 DEBUG(freetype, 3, "Font path for %s: %s", font_name, file_path);
00480 err = FT_New_Face(_library, (const char *)file_path, 0, face);
00481 }
00482 }
00483
00484 return err;
00485 }
00486
00487 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
00488 {
00489 const char *str;
00490 bool result = false;
00491
00492 callback->FindMissingGlyphs(&str);
00493
00494 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
00495 if (MacOSVersionIsAtLeast(10, 5, 0)) {
00496
00497
00498 char lang[16];
00499 if (strcmp(language_isocode, "zh_TW") == 0) {
00500
00501 strecpy(lang, "zh-Hant", lastof(lang));
00502 } else if (strcmp(language_isocode, "zh_CN") == 0) {
00503
00504 strecpy(lang, "zh-Hans", lastof(lang));
00505 } else if (strncmp(language_isocode, "ur", 2) == 0) {
00506
00507
00508
00509 strecpy(lang, "fa", lastof(lang));
00510 } else {
00511
00512 strecpy(lang, language_isocode, lastof(lang));
00513 char *sep = strchr(lang, '_');
00514 if (sep != NULL) *sep = '\0';
00515 }
00516
00517 CFStringRef lang_code;
00518 lang_code = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);
00519
00520
00521
00522 ATSFontIterator itr;
00523 ATSFontRef font;
00524 ATSFontIteratorCreate(kATSFontContextLocal, NULL, NULL, kATSOptionFlagsUnRestrictedScope, &itr);
00525 while (!result && ATSFontIteratorNext(itr, &font) == noErr) {
00526
00527 CTFontRef font_ref = CTFontCreateWithPlatformFont(font, 0.0, NULL, NULL);
00528 CFArrayRef langs = CTFontCopySupportedLanguages(font_ref);
00529 if (langs != NULL) {
00530
00531 for (CFIndex i = 0; i < CFArrayGetCount(langs); i++) {
00532 CFStringRef lang = (CFStringRef)CFArrayGetValueAtIndex(langs, i);
00533 if (CFStringCompare(lang, lang_code, kCFCompareAnchored) == kCFCompareEqualTo) {
00534
00535 CFStringRef font_name = CTFontCopyFullName(font_ref);
00536 char name[128];
00537 CFStringGetCString(font_name, name, lengthof(name), kCFStringEncodingUTF8);
00538 CFRelease(font_name);
00539
00540 if (strncmp(name, "Courier", 7) == 0 || strncmp(name, "Apple Symbols", 13) == 0 ||
00541 strncmp(name, ".Aqua", 5) == 0 || strncmp(name, "LastResort", 10) == 0 ||
00542 strncmp(name, "GB18030 Bitmap", 14) == 0) continue;
00543
00544
00545 callback->SetFontNames(settings, name);
00546 DEBUG(freetype, 2, "CT-Font for %s: %s", language_isocode, name);
00547 result = true;
00548 break;
00549 }
00550 }
00551 CFRelease(langs);
00552 }
00553 CFRelease(font_ref);
00554 }
00555 ATSFontIteratorRelease(&itr);
00556 CFRelease(lang_code);
00557 } else
00558 #endif
00559 {
00560 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) && !__LP64__
00561
00562
00563
00564
00565
00566
00567
00568
00569
00570 char buff[256];
00571 strecpy(buff, str, lastof(buff));
00572 str_validate(buff, lastof(buff), true, false);
00573
00574
00575 CFStringRef cf_str = CFStringCreateWithCString(kCFAllocatorDefault, buff, kCFStringEncodingUTF8);
00576 if (cf_str == NULL) {
00577
00578 return false;
00579 }
00580 CFIndex str_len = CFStringGetLength(cf_str);
00581 UniChar string[str_len];
00582 CFStringGetCharacters(cf_str, CFRangeMake(0, str_len), string);
00583
00584
00585 ATSUStyle style;
00586 ATSUCreateStyle(&style);
00587
00588
00589 UniCharCount run_len = kATSUToTextEnd;
00590 ATSUTextLayout text_layout;
00591 ATSUCreateTextLayoutWithTextPtr(string, kATSUFromTextBeginning, kATSUToTextEnd, str_len, 1, &run_len, &style, &text_layout);
00592
00593
00594
00595
00596
00597
00598 UniCharArrayOffset offset = kATSUFromTextBeginning;
00599 OSStatus os_err;
00600 do {
00601 ATSUFontID font;
00602 UniCharCount run_len;
00603 os_err = ATSUMatchFontsToText(text_layout, offset, kATSUToTextEnd, &font, &offset, &run_len);
00604 if (os_err == kATSUFontsMatched) {
00605
00606
00607 ATSUAttributeTag tag = kATSUFontTag;
00608 ByteCount size = sizeof(font);
00609 ATSUAttributeValuePtr val = &font;
00610 ATSUSetAttributes(style, 1, &tag, &size, &val);
00611 offset += run_len;
00612 }
00613
00614 } while (os_err == kATSUFontsMatched && offset < (UniCharArrayOffset)str_len);
00615
00616 if (os_err == noErr || os_err == kATSUFontsMatched) {
00617
00618
00619 ATSUFontID font;
00620 ByteCount act_len;
00621 ATSUGetAttribute(style, kATSUFontTag, sizeof(font), &font, &act_len);
00622
00623
00624
00625 char name[128];
00626 ATSUFindFontName(font, kFontUniqueName, kFontNoPlatformCode, kFontNoScriptCode, kFontNoLanguageCode, 127, name, &act_len, NULL);
00627 name[act_len > 127 ? 127 : act_len] = '\0';
00628
00629
00630 callback->SetFontNames(settings, name);
00631 DEBUG(freetype, 2, "ATSUI-Font for %s: %s", language_isocode, name);
00632 result = true;
00633 }
00634
00635 ATSUDisposeTextLayout(text_layout);
00636 ATSUDisposeStyle(style);
00637 CFRelease(cf_str);
00638 #endif
00639 }
00640
00641 if (result && strncmp(settings->medium_font, "Geeza Pro", 9) == 0) {
00642
00643
00644
00645
00646
00647 bool ft_init = _library != NULL;
00648 FT_Face face;
00649
00650 if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName("Arial Unicode MS", &face) == FT_Err_Ok) {
00651 FT_Done_Face(face);
00652 callback->SetFontNames(settings, "Arial Unicode MS");
00653 DEBUG(freetype, 1, "Replacing font 'Geeza Pro' with 'Arial Unicode MS'");
00654 }
00655 if (!ft_init) {
00656
00657 FT_Done_FreeType(_library);
00658 _library = NULL;
00659 }
00660 }
00661
00662 callback->FindMissingGlyphs(NULL);
00663 return result;
00664 }
00665
00666 #elif defined(WITH_FONTCONFIG)
00667
00668
00669
00670 static FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
00671 {
00672 FT_Error err = FT_Err_Cannot_Open_Resource;
00673
00674 if (!FcInit()) {
00675 ShowInfoF("Unable to load font configuration");
00676 } else {
00677 FcPattern *match;
00678 FcPattern *pat;
00679 FcFontSet *fs;
00680 FcResult result;
00681 char *font_style;
00682 char *font_family;
00683
00684
00685 font_family = strdup(font_name);
00686 font_style = strchr(font_family, ',');
00687 if (font_style != NULL) {
00688 font_style[0] = '\0';
00689 font_style++;
00690 while (*font_style == ' ' || *font_style == '\t') font_style++;
00691 }
00692
00693
00694 pat = FcNameParse((FcChar8*)font_family);
00695 if (font_style != NULL) FcPatternAddString(pat, FC_STYLE, (FcChar8*)font_style);
00696 FcConfigSubstitute(0, pat, FcMatchPattern);
00697 FcDefaultSubstitute(pat);
00698 fs = FcFontSetCreate();
00699 match = FcFontMatch(0, pat, &result);
00700
00701 if (fs != NULL && match != NULL) {
00702 int i;
00703 FcChar8 *family;
00704 FcChar8 *style;
00705 FcChar8 *file;
00706 FcFontSetAdd(fs, match);
00707
00708 for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
00709
00710 if (FcPatternGetString(fs->fonts[i], FC_FILE, 0, &file) == FcResultMatch &&
00711 FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
00712 FcPatternGetString(fs->fonts[i], FC_STYLE, 0, &style) == FcResultMatch) {
00713
00714
00715 if (font_style != NULL && strcasecmp(font_style, (char*)style) != 0) continue;
00716
00717
00718
00719
00720 if (strcasecmp(font_family, (char*)family) == 0) {
00721 err = FT_New_Face(_library, (char *)file, 0, face);
00722 }
00723 }
00724 }
00725 }
00726
00727 free(font_family);
00728 FcPatternDestroy(pat);
00729 FcFontSetDestroy(fs);
00730 FcFini();
00731 }
00732
00733 return err;
00734 }
00735
00736 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
00737 {
00738 if (!FcInit()) return false;
00739
00740 bool ret = false;
00741
00742
00743
00744
00745 char lang[16];
00746 seprintf(lang, lastof(lang), ":lang=%s", language_isocode);
00747 char *split = strchr(lang, '_');
00748 if (split != NULL) *split = '\0';
00749
00750
00751 FcPattern *pat = FcNameParse((FcChar8*)lang);
00752
00753 FcObjectSet *os = FcObjectSetBuild(FC_FILE, FC_SPACING, FC_SLANT, FC_WEIGHT, NULL);
00754
00755 FcFontSet *fs = FcFontList(NULL, pat, os);
00756
00757
00758 FcObjectSetDestroy(os);
00759 FcPatternDestroy(pat);
00760
00761 if (fs != NULL) {
00762 int best_weight = -1;
00763 const char *best_font = NULL;
00764
00765 for (int i = 0; i < fs->nfont; i++) {
00766 FcPattern *font = fs->fonts[i];
00767
00768 FcChar8 *file = NULL;
00769 FcResult res = FcPatternGetString(font, FC_FILE, 0, &file);
00770 if (res != FcResultMatch || file == NULL) {
00771 continue;
00772 }
00773
00774
00775 int value = 0;
00776 FcPatternGetInteger(font, FC_SPACING, 0, &value);
00777 if (callback->Monospace() != (value == FC_MONO) && value != FC_DUAL) continue;
00778
00779
00780 FcPatternGetInteger(font, FC_SLANT, 0, &value);
00781 if (value != 0) continue;
00782
00783
00784 FcPatternGetInteger(font, FC_WEIGHT, 0, &value);
00785 if (value <= best_weight) continue;
00786
00787 callback->SetFontNames(settings, (const char*)file);
00788
00789 bool missing = callback->FindMissingGlyphs(NULL);
00790 DEBUG(freetype, 1, "Font \"%s\" misses%s glyphs", file, missing ? "" : " no");
00791
00792 if (!missing) {
00793 best_weight = value;
00794 best_font = (const char *)file;
00795 }
00796 }
00797
00798 if (best_font != NULL) {
00799 ret = true;
00800 callback->SetFontNames(settings, best_font);
00801 InitFreeType(callback->Monospace());
00802 }
00803
00804
00805 FcFontSetDestroy(fs);
00806 }
00807
00808 FcFini();
00809 return ret;
00810 }
00811
00812 #else
00813 FT_Error GetFontByFaceName(const char *font_name, FT_Face *face) {return FT_Err_Cannot_Open_Resource;}
00814 bool SetFallbackFont(FreeTypeSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback) { return false; }
00815 #endif
00816
00817 static void SetFontGeometry(FT_Face face, FontSize size, int pixels)
00818 {
00819 FT_Error err = FT_Set_Pixel_Sizes(face, 0, pixels);
00820 if (err == FT_Err_Invalid_Pixel_Size) {
00821
00822
00823 FT_Bitmap_Size *bs = face->available_sizes;
00824 int i = face->num_fixed_sizes;
00825 int n = bs->height;
00826 for (; --i; bs++) {
00827 if (abs(pixels - bs->height) < abs(pixels - n)) n = bs->height;
00828 }
00829
00830 FT_Set_Pixel_Sizes(face, 0, n);
00831 }
00832
00833 int asc = face->size->metrics.ascender >> 6;
00834 int dec = face->size->metrics.descender >> 6;
00835
00836 _ascender[size] = asc;
00837 _font_height[size] = asc - dec;
00838 }
00839
00846 static void LoadFreeTypeFont(const char *font_name, FT_Face *face, const char *type)
00847 {
00848 FT_Error error;
00849
00850 if (StrEmpty(font_name)) return;
00851
00852 error = FT_New_Face(_library, font_name, 0, face);
00853
00854 if (error != FT_Err_Ok) error = GetFontByFaceName(font_name, face);
00855
00856 if (error == FT_Err_Ok) {
00857 DEBUG(freetype, 2, "Requested '%s', using '%s %s'", font_name, (*face)->family_name, (*face)->style_name);
00858
00859
00860 error = FT_Select_Charmap(*face, ft_encoding_unicode);
00861 if (error == FT_Err_Ok) return;
00862
00863 if (error == FT_Err_Invalid_CharMap_Handle) {
00864
00865
00866
00867 FT_CharMap found = (*face)->charmaps[0];
00868 int i;
00869
00870 for (i = 0; i < (*face)->num_charmaps; i++) {
00871 FT_CharMap charmap = (*face)->charmaps[i];
00872 if (charmap->platform_id == 0 && charmap->encoding_id == 0) {
00873 found = charmap;
00874 }
00875 }
00876
00877 if (found != NULL) {
00878 error = FT_Set_Charmap(*face, found);
00879 if (error == FT_Err_Ok) return;
00880 }
00881 }
00882 }
00883
00884 FT_Done_Face(*face);
00885 *face = NULL;
00886
00887 ShowInfoF("Unable to use '%s' for %s font, FreeType reported error 0x%X, using sprite font instead", font_name, type, error);
00888 }
00889
00890
00891 static void ResetGlyphCache(bool monospace);
00892
00897 static void UnloadFace(FT_Face *face)
00898 {
00899 if (*face == NULL) return;
00900
00901 FT_Done_Face(*face);
00902 *face = NULL;
00903 }
00904
00909 void InitFreeType(bool monospace)
00910 {
00911 ResetFontSizes(monospace);
00912 ResetGlyphCache(monospace);
00913
00914 if (monospace) {
00915 UnloadFace(&_face_mono);
00916 } else {
00917 UnloadFace(&_face_small);
00918 UnloadFace(&_face_medium);
00919 UnloadFace(&_face_large);
00920 }
00921
00922 if (StrEmpty(_freetype.small_font) && StrEmpty(_freetype.medium_font) && StrEmpty(_freetype.large_font) && StrEmpty(_freetype.mono_font)) {
00923 DEBUG(freetype, 1, "No font faces specified, using sprite fonts instead");
00924 return;
00925 }
00926
00927 if (_library == NULL) {
00928 if (FT_Init_FreeType(&_library) != FT_Err_Ok) {
00929 ShowInfoF("Unable to initialize FreeType, using sprite fonts instead");
00930 return;
00931 }
00932
00933 DEBUG(freetype, 2, "Initialized");
00934 }
00935
00936
00937 if (monospace) {
00938 LoadFreeTypeFont(_freetype.mono_font , &_face_mono, "mono");
00939
00940 if (_face_mono != NULL) {
00941 SetFontGeometry(_face_mono, FS_MONO, _freetype.mono_size);
00942 }
00943 } else {
00944 LoadFreeTypeFont(_freetype.small_font, &_face_small, "small");
00945 LoadFreeTypeFont(_freetype.medium_font, &_face_medium, "medium");
00946 LoadFreeTypeFont(_freetype.large_font, &_face_large, "large");
00947
00948
00949 if (_face_small != NULL) {
00950 SetFontGeometry(_face_small, FS_SMALL, _freetype.small_size);
00951 }
00952 if (_face_medium != NULL) {
00953 SetFontGeometry(_face_medium, FS_NORMAL, _freetype.medium_size);
00954 }
00955 if (_face_large != NULL) {
00956 SetFontGeometry(_face_large, FS_LARGE, _freetype.large_size);
00957 }
00958 }
00959 }
00960
00964 void UninitFreeType()
00965 {
00966 ResetGlyphCache(true);
00967 ResetGlyphCache(false);
00968
00969 UnloadFace(&_face_small);
00970 UnloadFace(&_face_medium);
00971 UnloadFace(&_face_large);
00972 UnloadFace(&_face_mono);
00973
00974 FT_Done_FreeType(_library);
00975 _library = NULL;
00976 }
00977
00978
00979 static FT_Face GetFontFace(FontSize size)
00980 {
00981 switch (size) {
00982 default: NOT_REACHED();
00983 case FS_NORMAL: return _face_medium;
00984 case FS_SMALL: return _face_small;
00985 case FS_LARGE: return _face_large;
00986 case FS_MONO: return _face_mono;
00987 }
00988 }
00989
00990
00991 struct GlyphEntry {
00992 Sprite *sprite;
00993 byte width;
00994 bool duplicate;
00995 };
00996
00997
00998
00999
01000
01001
01002
01003
01004
01005
01006
01007
01008
01009
01010 static GlyphEntry **_glyph_ptr[FS_END];
01011
01016 static void ResetGlyphCache(bool monospace)
01017 {
01018 for (FontSize i = FS_BEGIN; i < FS_END; i++) {
01019 if (monospace != (i == FS_MONO)) continue;
01020 if (_glyph_ptr[i] == NULL) continue;
01021
01022 for (int j = 0; j < 256; j++) {
01023 if (_glyph_ptr[i][j] == NULL) continue;
01024
01025 for (int k = 0; k < 256; k++) {
01026 if (_glyph_ptr[i][j][k].duplicate) continue;
01027 free(_glyph_ptr[i][j][k].sprite);
01028 }
01029
01030 free(_glyph_ptr[i][j]);
01031 }
01032
01033 free(_glyph_ptr[i]);
01034 _glyph_ptr[i] = NULL;
01035 }
01036 }
01037
01038 static GlyphEntry *GetGlyphPtr(FontSize size, WChar key)
01039 {
01040 if (_glyph_ptr[size] == NULL) return NULL;
01041 if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) return NULL;
01042 return &_glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)];
01043 }
01044
01045
01046 static void SetGlyphPtr(FontSize size, WChar key, const GlyphEntry *glyph, bool duplicate = false)
01047 {
01048 if (_glyph_ptr[size] == NULL) {
01049 DEBUG(freetype, 3, "Allocating root glyph cache for size %u", size);
01050 _glyph_ptr[size] = CallocT<GlyphEntry*>(256);
01051 }
01052
01053 if (_glyph_ptr[size][GB(key, 8, 8)] == NULL) {
01054 DEBUG(freetype, 3, "Allocating glyph cache for range 0x%02X00, size %u", GB(key, 8, 8), size);
01055 _glyph_ptr[size][GB(key, 8, 8)] = CallocT<GlyphEntry>(256);
01056 }
01057
01058 DEBUG(freetype, 4, "Set glyph for unicode character 0x%04X, size %u", key, size);
01059 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].sprite = glyph->sprite;
01060 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].width = glyph->width;
01061 _glyph_ptr[size][GB(key, 8, 8)][GB(key, 0, 8)].duplicate = duplicate;
01062 }
01063
01064 static void *AllocateFont(size_t size)
01065 {
01066 return MallocT<byte>(size);
01067 }
01068
01069
01070
01071 static bool GetFontAAState(FontSize size)
01072 {
01073
01074 if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() != 32) return false;
01075
01076 switch (size) {
01077 default: NOT_REACHED();
01078 case FS_NORMAL: return _freetype.medium_aa;
01079 case FS_SMALL: return _freetype.small_aa;
01080 case FS_LARGE: return _freetype.large_aa;
01081 case FS_MONO: return _freetype.mono_aa;
01082 }
01083 }
01084
01085
01086 const Sprite *GetGlyph(FontSize size, WChar key)
01087 {
01088 FT_Face face = GetFontFace(size);
01089 FT_GlyphSlot slot;
01090 GlyphEntry new_glyph;
01091 GlyphEntry *glyph;
01092 SpriteLoader::Sprite sprite;
01093 int width;
01094 int height;
01095 int x;
01096 int y;
01097
01098 assert(IsPrintable(key));
01099
01100
01101 if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
01102 SpriteID sprite = GetUnicodeGlyph(size, key);
01103 if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
01104
01105
01106 if (sprite != 0) return GetSprite(sprite, ST_FONT);
01107
01108
01109 if (face == NULL) error("No sprite font and no real font either... bailing!");
01110
01111
01112 key = '?';
01113 }
01114
01115
01116 glyph = GetGlyphPtr(size, key);
01117 if (glyph != NULL && glyph->sprite != NULL) return glyph->sprite;
01118
01119 slot = face->glyph;
01120
01121 bool aa = GetFontAAState(size);
01122
01123 FT_UInt glyph_index = FT_Get_Char_Index(face, key);
01124 if (glyph_index == 0) {
01125 if (key == '?') {
01126
01127 SpriteID sprite = GetUnicodeGlyph(size, key);
01128 Sprite *spr = (Sprite*)GetRawSprite(sprite, ST_FONT, AllocateFont);
01129 assert(spr != NULL);
01130 new_glyph.sprite = spr;
01131 new_glyph.width = spr->width + (size != FS_NORMAL);
01132 SetGlyphPtr(size, key, &new_glyph, false);
01133 return new_glyph.sprite;
01134 } else {
01135
01136 GetGlyph(size, '?');
01137 glyph = GetGlyphPtr(size, '?');
01138 SetGlyphPtr(size, key, glyph, true);
01139 return glyph->sprite;
01140 }
01141 }
01142 FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT);
01143 FT_Render_Glyph(face->glyph, aa ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO);
01144
01145
01146 aa = (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY);
01147
01148
01149 width = max(1, slot->bitmap.width + (size == FS_NORMAL));
01150 height = max(1, slot->bitmap.rows + (size == FS_NORMAL));
01151
01152
01153 if (width > 256 || height > 256) usererror("Font glyph is too large");
01154
01155
01156 sprite.AllocateData(width * height);
01157 sprite.type = ST_FONT;
01158 sprite.width = width;
01159 sprite.height = height;
01160 sprite.x_offs = slot->bitmap_left;
01161 sprite.y_offs = _ascender[size] - slot->bitmap_top;
01162
01163
01164 if (size == FS_NORMAL && !aa) {
01165 for (y = 0; y < slot->bitmap.rows; y++) {
01166 for (x = 0; x < slot->bitmap.width; x++) {
01167 if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
01168 sprite.data[1 + x + (1 + y) * sprite.width].m = SHADOW_COLOUR;
01169 sprite.data[1 + x + (1 + y) * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
01170 }
01171 }
01172 }
01173 }
01174
01175 for (y = 0; y < slot->bitmap.rows; y++) {
01176 for (x = 0; x < slot->bitmap.width; x++) {
01177 if (aa ? (slot->bitmap.buffer[x + y * slot->bitmap.pitch] > 0) : HasBit(slot->bitmap.buffer[(x / 8) + y * slot->bitmap.pitch], 7 - (x % 8))) {
01178 sprite.data[x + y * sprite.width].m = FACE_COLOUR;
01179 sprite.data[x + y * sprite.width].a = aa ? slot->bitmap.buffer[x + y * slot->bitmap.pitch] : 0xFF;
01180 }
01181 }
01182 }
01183
01184 new_glyph.sprite = BlitterFactoryBase::GetCurrentBlitter()->Encode(&sprite, AllocateFont);
01185 new_glyph.width = slot->advance.x >> 6;
01186
01187 SetGlyphPtr(size, key, &new_glyph);
01188
01189 return new_glyph.sprite;
01190 }
01191
01192
01193 bool GetDrawGlyphShadow()
01194 {
01195 return GetFontFace(FS_NORMAL) != NULL && GetFontAAState(FS_NORMAL);
01196 }
01197
01198
01199 uint GetGlyphWidth(FontSize size, WChar key)
01200 {
01201 FT_Face face = GetFontFace(size);
01202 GlyphEntry *glyph;
01203
01204 if (face == NULL || (key >= SCC_SPRITE_START && key <= SCC_SPRITE_END)) {
01205 SpriteID sprite = GetUnicodeGlyph(size, key);
01206 if (sprite == 0) sprite = GetUnicodeGlyph(size, '?');
01207 return SpriteExists(sprite) ? GetSprite(sprite, ST_FONT)->width + (size != FS_NORMAL && size != FS_MONO) : 0;
01208 }
01209
01210 glyph = GetGlyphPtr(size, key);
01211 if (glyph == NULL || glyph->sprite == NULL) {
01212 GetGlyph(size, key);
01213 glyph = GetGlyphPtr(size, key);
01214 }
01215
01216 return glyph->width;
01217 }
01218
01219
01220 #endif
01221
01222
01223
01224 #include "table/unicode.h"
01225
01226 static SpriteID **_unicode_glyph_map[FS_END];
01227
01228
01230 static SpriteID GetFontBase(FontSize size)
01231 {
01232 switch (size) {
01233 default: NOT_REACHED();
01234 case FS_NORMAL: return SPR_ASCII_SPACE;
01235 case FS_SMALL: return SPR_ASCII_SPACE_SMALL;
01236 case FS_LARGE: return SPR_ASCII_SPACE_BIG;
01237 case FS_MONO: return SPR_ASCII_SPACE;
01238 }
01239 }
01240
01241
01242 SpriteID GetUnicodeGlyph(FontSize size, uint32 key)
01243 {
01244 if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) return 0;
01245 return _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)];
01246 }
01247
01248
01249 void SetUnicodeGlyph(FontSize size, uint32 key, SpriteID sprite)
01250 {
01251 if (_unicode_glyph_map[size] == NULL) _unicode_glyph_map[size] = CallocT<SpriteID*>(256);
01252 if (_unicode_glyph_map[size][GB(key, 8, 8)] == NULL) _unicode_glyph_map[size][GB(key, 8, 8)] = CallocT<SpriteID>(256);
01253 _unicode_glyph_map[size][GB(key, 8, 8)][GB(key, 0, 8)] = sprite;
01254 }
01255
01256
01257 void InitializeUnicodeGlyphMap()
01258 {
01259 for (FontSize size = FS_BEGIN; size != FS_END; size++) {
01260
01261 if (_unicode_glyph_map[size] != NULL) {
01262 for (uint i = 0; i < 256; i++) {
01263 free(_unicode_glyph_map[size][i]);
01264 }
01265 free(_unicode_glyph_map[size]);
01266 _unicode_glyph_map[size] = NULL;
01267 }
01268
01269 SpriteID base = GetFontBase(size);
01270
01271 for (uint i = ASCII_LETTERSTART; i < 256; i++) {
01272 SpriteID sprite = base + i - ASCII_LETTERSTART;
01273 if (!SpriteExists(sprite)) continue;
01274 SetUnicodeGlyph(size, i, sprite);
01275 SetUnicodeGlyph(size, i + SCC_SPRITE_START, sprite);
01276 }
01277
01278 for (uint i = 0; i < lengthof(_default_unicode_map); i++) {
01279 byte key = _default_unicode_map[i].key;
01280 if (key == CLRA || key == CLRL) {
01281
01282
01283
01284 if (key == CLRA || size == FS_LARGE) {
01285 SetUnicodeGlyph(size, _default_unicode_map[i].code, 0);
01286 }
01287 } else {
01288 SpriteID sprite = base + key - ASCII_LETTERSTART;
01289 SetUnicodeGlyph(size, _default_unicode_map[i].code, sprite);
01290 }
01291 }
01292 }
01293 }