25 #if (defined __MINGW32__) || (defined __CYGWIN__) 27 #undef __STRICT_ANSI__ 34 #include <sys/param.h> 45 #include "pango/pango.h" 46 #include "pango/pangocairo.h" 47 #include "pango/pangofc-font.h" 50 "Overrides fontconfig default temporary dir");
52 #ifndef USE_STD_NAMESPACE 53 #include "ocr/trainingdata/typesetting/legacy_fonts.h" 55 "Overrides --fonts_dir and sets the known universe of fonts to" 56 "the list in legacy_fonts.h");
59 "Overrides system default font location");
63 "If empty it use system default. Otherwise it overrides" 64 " system default font location");
73 string PangoFontInfo::fonts_dir_;
74 string PangoFontInfo::cache_dir_;
83 tprintf(
"ERROR: Could not parse %s\n", desc.c_str());
88 void PangoFontInfo::Clear() {
93 pango_font_description_free(desc_);
101 if (!desc_)
return "";
102 char* desc_str = pango_font_description_to_string(desc_);
103 string desc_name(desc_str);
113 if (fonts_dir_.empty()) {
115 FLAGS_fontconfig_tmpdir.c_str());
123 const string& cache_dir) {
124 if (!cache_dir_.empty()) {
128 const int MAX_FONTCONF_FILESIZE = 1024;
129 char fonts_conf_template[MAX_FONTCONF_FILESIZE];
130 cache_dir_ = cache_dir;
131 fonts_dir_ = fonts_dir;
132 snprintf(fonts_conf_template, MAX_FONTCONF_FILESIZE,
133 "<?xml version=\"1.0\"?>\n" 134 "<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n" 137 "<cachedir>%s</cachedir>\n" 138 "<config></config>\n" 140 fonts_dir.c_str(), cache_dir_.c_str());
141 string fonts_conf_file =
File::JoinPath(cache_dir_.c_str(),
"fonts.conf");
144 std::string env(
"FONTCONFIG_PATH=");
145 env.append(cache_dir_.c_str());
147 putenv(
"LANG=en_US.utf8");
149 setenv(
"FONTCONFIG_PATH", cache_dir_.c_str(),
true);
151 setenv(
"LANG",
"en_US.utf8",
true);
154 if (FcInitReinitialize() != FcTrue) {
155 tprintf(
"FcInitiReinitialize failed!!\n");
159 pango_cairo_font_map_set_default(NULL);
162 static void ListFontFamilies(PangoFontFamily*** families,
165 PangoFontMap* font_map = pango_cairo_font_map_get_default();
167 pango_font_map_list_families(font_map, families, n_families);
170 bool PangoFontInfo::ParseFontDescription(
const PangoFontDescription *desc) {
172 const char* family = pango_font_description_get_family(desc);
174 char* desc_str = pango_font_description_to_string(desc);
175 tprintf(
"WARNING: Could not parse family name from description: '%s'\n",
180 family_name_ = string(family);
181 desc_ = pango_font_description_copy(desc);
184 font_size_ = pango_font_description_get_size(desc);
185 if (!pango_font_description_get_size_is_absolute(desc)) {
186 font_size_ /= PANGO_SCALE;
193 PangoFontDescription *desc = pango_font_description_from_string(name.c_str());
194 bool success = ParseFontDescription(desc);
195 pango_font_description_free(desc);
202 PangoFont* PangoFontInfo::ToPangoFont()
const {
204 PangoFontMap* font_map = pango_cairo_font_map_get_default();
205 PangoContext* context = pango_context_new();
206 pango_cairo_context_set_resolution(context, resolution_);
207 pango_context_set_font_map(context, font_map);
208 PangoFont* font = NULL;
211 font = pango_font_map_load_font(font_map, context, desc_);
213 g_object_unref(context);
218 PangoFont* font = ToPangoFont();
219 PangoCoverage* coverage = pango_font_get_coverage(font, NULL);
225 if (pango_coverage_get(coverage, *it) != PANGO_COVERAGE_EXACT) {
227 int len = it.get_utf8(tmp);
229 tlog(2,
"'%s' (U+%x) not covered by font\n", tmp, *it);
238 static char* my_strnmove(
char* dest,
const char* src,
size_t n) {
247 }
while (n && src[0]);
259 PangoFont* font = ToPangoFont();
260 PangoCoverage* coverage = pango_font_get_coverage(font, NULL);
261 int num_dropped_chars = 0;
265 char* out =
const_cast<char*
>(utf8_text->c_str());
272 if (!it.is_legal()) {
278 const char* utf8_char = it.utf8_data();
281 if (!
IsWhitespace(unicode) && !pango_is_zero_width(unicode) &&
282 pango_coverage_get(coverage, unicode) != PANGO_COVERAGE_EXACT) {
286 tlog(2,
"'%s' (U+%x) not covered by font\n", str, unicode);
292 my_strnmove(out, utf8_char, utf8_len);
295 utf8_text->resize(out - utf8_text->c_str());
296 return num_dropped_chars;
300 int* x_bearing,
int* x_advance)
const {
302 PangoFont* font = ToPangoFont();
304 int total_advance = 0;
314 PangoGlyph glyph_index = pango_fc_font_get_glyph(
315 reinterpret_cast<PangoFcFont*>(font), *it);
321 PangoRectangle ink_rect, logical_rect;
322 pango_font_get_glyph_extents(font, glyph_index, &ink_rect, &logical_rect);
323 pango_extents_to_pixels(&ink_rect, NULL);
324 pango_extents_to_pixels(&logical_rect, NULL);
326 int bearing = total_advance + PANGO_LBEARING(ink_rect);
327 if (it == it_begin || bearing < min_bearing) {
328 min_bearing = bearing;
330 total_advance += PANGO_RBEARING(logical_rect);
332 *x_bearing = min_bearing;
333 *x_advance = total_advance;
338 vector<string> graphemes;
343 vector<string>* graphemes)
const {
344 if (graphemes) graphemes->clear();
353 const char32 kDottedCircleGlyph = 9676;
354 bool bad_glyph =
false;
355 PangoFontMap* font_map = pango_cairo_font_map_get_default();
356 PangoContext* context = pango_context_new();
357 pango_context_set_font_map(context, font_map);
362 layout = pango_layout_new(context);
365 pango_layout_set_font_description(layout, desc_);
367 PangoFontDescription *desc = pango_font_description_from_string(
369 pango_layout_set_font_description(layout, desc);
370 pango_font_description_free(desc);
372 pango_layout_set_text(layout, utf8_word, len);
373 PangoLayoutIter* run_iter = NULL;
376 run_iter = pango_layout_get_iter(layout);
379 PangoLayoutRun* run = pango_layout_iter_get_run_readonly(run_iter);
381 tlog(2,
"Found end of line NULL run marker\n");
384 PangoGlyph dotted_circle_glyph;
385 PangoFont* font = run->item->analysis.font;
387 #ifdef _WIN32 // Fixme! Leaks memory and breaks unittests. 388 PangoGlyphString* glyphs = pango_glyph_string_new();
389 char s[] =
"\xc2\xa7";
390 pango_shape(s,
sizeof(s), &(run->item->analysis), glyphs);
391 dotted_circle_glyph = glyphs->glyphs[0].glyph;
393 dotted_circle_glyph = pango_fc_font_get_glyph(
394 reinterpret_cast<PangoFcFont*>(font), kDottedCircleGlyph);
398 PangoFontDescription* desc = pango_font_describe(font);
399 char* desc_str = pango_font_description_to_string(desc);
400 tlog(2,
"Desc of font in run: %s\n", desc_str);
402 pango_font_description_free(desc);
405 PangoGlyphItemIter cluster_iter;
406 gboolean have_cluster;
407 for (have_cluster = pango_glyph_item_iter_init_start(&cluster_iter,
409 have_cluster && !bad_glyph;
410 have_cluster = pango_glyph_item_iter_next_cluster(&cluster_iter)) {
411 const int start_byte_index = cluster_iter.start_index;
412 const int end_byte_index = cluster_iter.end_index;
413 int start_glyph_index = cluster_iter.start_glyph;
414 int end_glyph_index = cluster_iter.end_glyph;
415 string cluster_text = string(utf8_word + start_byte_index,
416 end_byte_index - start_byte_index);
417 if (graphemes) graphemes->push_back(cluster_text);
419 tlog(2,
"Skipping whitespace\n");
423 printf(
"start_byte=%d end_byte=%d start_glyph=%d end_glyph=%d ",
424 start_byte_index, end_byte_index,
425 start_glyph_index, end_glyph_index);
427 for (
int i = start_glyph_index,
428 step = (end_glyph_index > start_glyph_index) ? 1 : -1;
429 !bad_glyph && i != end_glyph_index; i+= step) {
430 const bool unknown_glyph =
431 (cluster_iter.glyph_item->glyphs->glyphs[i].glyph &
432 PANGO_GLYPH_UNKNOWN_FLAG);
433 const bool illegal_glyph =
434 (cluster_iter.glyph_item->glyphs->glyphs[i].glyph ==
435 dotted_circle_glyph);
436 bad_glyph = unknown_glyph || illegal_glyph;
438 printf(
"(%d=%d)", cluster_iter.glyph_item->glyphs->glyphs[i].glyph,
443 printf(
" '%s'\n", cluster_text.c_str());
446 tlog(1,
"Found illegal glyph!\n");
448 }
while (!bad_glyph && pango_layout_iter_next_run(run_iter));
450 pango_layout_iter_free(run_iter);
451 g_object_unref(context);
452 g_object_unref(layout);
453 if (bad_glyph && graphemes) graphemes->clear();
459 vector<string> FontUtils::available_fonts_;
472 string* best_match) {
473 string query_desc(input_query_desc);
474 #if (PANGO_VERSION <= 12005) 476 query_desc.erase(std::remove(query_desc.begin(), query_desc.end(),
','),
478 const string kMediumStr =
" Medium";
479 std::size_t found = query_desc.find(kMediumStr);
480 if (found != std::string::npos) {
481 query_desc.erase(found, kMediumStr.length());
484 PangoFontDescription *desc = pango_font_description_from_string(
486 PangoFont* selected_font = NULL;
489 PangoFontMap* font_map = pango_cairo_font_map_get_default();
490 PangoContext* context = pango_context_new();
491 pango_context_set_font_map(context, font_map);
494 selected_font = pango_font_map_load_font(font_map, context, desc);
496 g_object_unref(context);
498 if (selected_font == NULL) {
499 pango_font_description_free(desc);
502 PangoFontDescription* selected_desc = pango_font_describe(selected_font);
504 bool equal = pango_font_description_equal(desc, selected_desc);
505 tlog(3,
"query weight = %d \t selected weight =%d\n",
506 pango_font_description_get_weight(desc),
507 pango_font_description_get_weight(selected_desc));
509 char* selected_desc_str = pango_font_description_to_string(selected_desc);
510 tlog(2,
"query_desc: '%s' Selected: '%s'\n", query_desc.c_str(),
512 if (!equal && best_match != NULL) {
513 *best_match = selected_desc_str;
516 int len = best_match->size();
517 if (len > 2 && best_match->at(len - 1) ==
'0' &&
518 best_match->at(len - 2) ==
' ') {
519 *best_match = best_match->substr(0, len - 2);
522 g_free(selected_desc_str);
523 pango_font_description_free(selected_desc);
524 g_object_unref(selected_font);
525 pango_font_description_free(desc);
529 static bool ShouldIgnoreFontFamilyName(
const char* query) {
530 static const char* kIgnoredFamilyNames[]
531 = {
"Sans",
"Serif",
"Monospace", NULL };
532 const char** list = kIgnoredFamilyNames;
533 for (; *list != NULL; ++list) {
534 if (!strcmp(*list, query))
543 if (!available_fonts_.empty()) {
544 return available_fonts_;
546 #ifndef USE_STD_NAMESPACE 547 if (FLAGS_use_only_legacy_fonts) {
549 tprintf(
"Using list of legacy fonts only\n");
550 const int kNumFontLists = 4;
551 for (
int i = 0; i < kNumFontLists; ++i) {
552 for (
int j = 0; kFontlists[i][j] != NULL; ++j) {
553 available_fonts_.push_back(kFontlists[i][j]);
556 return available_fonts_;
560 PangoFontFamily** families = 0;
562 ListFontFamilies(&families, &n_families);
563 for (
int i = 0; i < n_families; ++i) {
564 const char* family_name = pango_font_family_get_name(families[i]);
565 tlog(2,
"Listing family %s\n", family_name);
566 if (ShouldIgnoreFontFamilyName(family_name)) {
571 PangoFontFace** faces = NULL;
572 pango_font_family_list_faces(families[i], &faces, &n_faces);
573 for (
int j = 0; j < n_faces; ++j) {
574 PangoFontDescription* desc = pango_font_face_describe(faces[j]);
575 char* desc_str = pango_font_description_to_string(desc);
577 available_fonts_.push_back(desc_str);
579 pango_font_description_free(desc);
585 sort(available_fonts_.begin(), available_fonts_.end());
586 return available_fonts_;
590 static void CharCoverageMapToBitmap(PangoCoverage* coverage,
591 vector<bool>* unichar_bitmap) {
592 const int kMinUnicodeValue = 33;
593 const int kMaxUnicodeValue = 0x10FFFF;
594 unichar_bitmap->resize(kMaxUnicodeValue + 1,
false);
596 for (
int i = kMinUnicodeValue; i <= kMaxUnicodeValue; ++i) {
599 = (pango_coverage_get(coverage, i) == PANGO_COVERAGE_EXACT);
612 vector<bool>* unichar_bitmap) {
613 PangoFontInfo font_info(font_name);
614 PangoCoverage* coverage = pango_font_get_coverage(
615 font_info.ToPangoFont(), NULL);
616 CharCoverageMapToBitmap(coverage, unichar_bitmap);
621 vector<bool>* unichar_bitmap) {
623 PangoCoverage* all_coverage = pango_coverage_new();
624 tlog(1,
"Processing %d fonts\n", fonts.size());
625 for (
int i = 0; i < fonts.size(); ++i) {
626 PangoFontInfo font_info(fonts[i]);
627 PangoCoverage* coverage = pango_font_get_coverage(
628 font_info.ToPangoFont(), NULL);
630 pango_coverage_max(all_coverage, coverage);
632 CharCoverageMapToBitmap(all_coverage, unichar_bitmap);
633 pango_coverage_unref(all_coverage);
641 const string& fontname,
int* raw_score,
642 vector<bool>* ch_flags) {
645 tprintf(
"ERROR: Could not parse %s\n", fontname.c_str());
647 PangoFont* font = font_info.ToPangoFont();
648 PangoCoverage* coverage = pango_font_get_coverage(font, NULL);
652 ch_flags->reserve(ch_map.size());
656 for (TessHashMap<char32, inT64>::const_iterator it = ch_map.begin();
657 it != ch_map.end(); ++it) {
659 (pango_coverage_get(coverage, it->first)
660 == PANGO_COVERAGE_EXACT));
663 ok_chars += it->second;
666 ch_flags->push_back(covered);
675 vector<pair<
const char*, vector<bool> > >* fonts) {
676 const double kMinOKFraction = 0.99;
679 const double kMinWeightedFraction = 0.99995;
682 vector<vector<bool> > font_flags;
683 vector<int> font_scores;
684 vector<int> raw_scores;
685 int most_ok_chars = 0;
686 int best_raw_score = 0;
688 for (
int i = 0; i < font_names.size(); ++i) {
689 vector<bool> ch_flags;
691 int ok_chars =
FontScore(ch_map, font_names[i], &raw_score, &ch_flags);
692 most_ok_chars =
MAX(ok_chars, most_ok_chars);
693 best_raw_score =
MAX(raw_score, best_raw_score);
695 font_flags.push_back(ch_flags);
696 font_scores.push_back(ok_chars);
697 raw_scores.push_back(raw_score);
708 int least_good_enough =
static_cast<int>(most_ok_chars * kMinOKFraction);
709 int least_raw_enough =
static_cast<int>(best_raw_score * kMinOKFraction);
710 int override_enough =
static_cast<int>(most_ok_chars * kMinWeightedFraction);
713 for (
int i = 0; i < font_names.size(); ++i) {
714 int score = font_scores[i];
715 int raw_score = raw_scores[i];
716 if ((score >= least_good_enough && raw_score >= least_raw_enough) ||
717 score >= override_enough) {
718 fonts->push_back(make_pair(font_names[i].c_str(), font_flags[i]));
719 tlog(1,
"OK font %s = %.4f%%, raw = %d = %.2f%%\n",
720 font_names[i].c_str(),
721 100.0 * score / most_ok_chars,
722 raw_score, 100.0 * raw_score / best_raw_score);
723 font_list += font_names[i];
725 }
else if (score >= least_good_enough || raw_score >= least_raw_enough) {
726 tlog(1,
"Runner-up font %s = %.4f%%, raw = %d = %.2f%%\n",
727 font_names[i].c_str(),
728 100.0 * score / most_ok_chars,
729 raw_score, 100.0 * raw_score / best_raw_score);
737 string* font_name, vector<string>* graphemes) {
744 const vector<string>& all_fonts,
745 string* font_name, vector<string>* graphemes) {
746 if (font_name) font_name->clear();
747 if (graphemes) graphemes->clear();
748 for (
int i = 0; i < all_fonts.size(); ++i) {
750 vector<string> found_graphemes;
752 "Could not parse font desc name %s\n",
753 all_fonts[i].c_str());
755 if (graphemes) graphemes->swap(found_graphemes);
756 if (font_name) *font_name = all_fonts[i];
static bool DeleteMatchingFiles(const char *pattern)
bool GetSpacingProperties(const string &utf8_char, int *x_bearing, int *x_advance) const
bool CanRenderString(const char *utf8_word, int len, std::vector< string > *graphemes) const
bool ParseFontDescriptionName(const string &name)
static string BestFonts(const TessHashMap< char32, inT64 > &ch_map, std::vector< std::pair< const char *, std::vector< bool > > > *font_flag)
bool CoversUTF8Text(const char *utf8_text, int byte_length) const
bool IsUTF8Whitespace(const char *text)
#define TLOG_IS_ON(level)
static int FontScore(const TessHashMap< char32, inT64 > &ch_map, const string &fontname, int *raw_score, std::vector< bool > *ch_flags)
bool IsWhitespace(const char32 ch)
static void SoftInitFontConfig()
static const_iterator end(const char *utf8_str, const int byte_length)
BOOL_PARAM_FLAG(use_only_legacy_fonts, false, "Overrides --fonts_dir and sets the known universe of fonts to" "the list in legacy_fonts.h")
int DropUncoveredChars(string *utf8_text) const
static void GetAllRenderableCharacters(std::vector< bool > *unichar_bitmap)
#define ASSERT_HOST_MSG(x,...)
static const_iterator begin(const char *utf8_str, const int byte_length)
const int kDefaultResolution
static bool SelectFont(const char *utf8_word, const int utf8_len, string *font_name, std::vector< string > *graphemes)
bool IsInterchangeValid(const char32 ch)
static bool IsAvailableFont(const char *font_desc)
string DescriptionName() const
static string JoinPath(const string &prefix, const string &suffix)
static void HardInitFontConfig(const string &fonts_dir, const string &cache_dir)
static void WriteStringToFileOrDie(const string &str, const string &filename)
static const std::vector< string > & ListAvailableFonts()
#define DISABLE_HEAP_LEAK_CHECK
STRING_PARAM_FLAG(fontconfig_tmpdir, "/tmp", "Overrides fontconfig default temporary dir")