tesseract  4.00.00dev
pango_font_info.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: pango_font_info.cpp
3  * Description: Font-related objects and helper functions
4  * Author: Ranjith Unnikrishnan
5  * Created: Mon Nov 18 2013
6  *
7  * (C) Copyright 2013, Google Inc.
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * http://www.apache.org/licenses/LICENSE-2.0
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  **********************************************************************/
19 
20 // Include automatically generated configuration file if running autoconf.
21 #ifdef HAVE_CONFIG_H
22 #include "config_auto.h"
23 #endif
24 
25 #if (defined __MINGW32__) || (defined __CYGWIN__)
26 // workaround for stdlib.h and putenv
27 #undef __STRICT_ANSI__
28 #endif
29 
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <string.h>
33 #ifndef _MSC_VER
34 #include <sys/param.h>
35 #endif
36 #include <algorithm>
37 
38 #include "pango_font_info.h"
39 #include "commandlineflags.h"
40 #include "fileio.h"
41 #include "normstrngs.h"
42 #include "tlog.h"
43 #include "unichar.h"
44 #include "util.h"
45 #include "pango/pango.h"
46 #include "pango/pangocairo.h"
47 #include "pango/pangofc-font.h"
48 
49 STRING_PARAM_FLAG(fontconfig_tmpdir, "/tmp",
50  "Overrides fontconfig default temporary dir");
51 
52 #ifdef GOOGLE_TESSERACT
53 #include "ocr/trainingdata/typesetting/legacy_fonts.h"
54 BOOL_PARAM_FLAG(use_only_legacy_fonts, false,
55  "Overrides --fonts_dir and sets the known universe of fonts to"
56  "the list in legacy_fonts.h");
57 
58 STRING_PARAM_FLAG(fonts_dir, "/auto/ocr-data/tesstraining/fonts",
59  "Overrides system default font location");
60 #else
61 using std::pair;
62 STRING_PARAM_FLAG(fonts_dir, "",
63  "If empty it use system default. Otherwise it overrides"
64  " system default font location");
65 #endif
66 
67 namespace tesseract {
68 
69 // Default assumed output resolution. Required only for providing font metrics
70 // in pixels.
71 const int kDefaultResolution = 300;
72 
73 string PangoFontInfo::fonts_dir_;
74 string PangoFontInfo::cache_dir_;
75 
77  : desc_(nullptr), resolution_(kDefaultResolution) {
78  Clear();
79 }
80 
81 PangoFontInfo::PangoFontInfo(const string& desc)
82  : desc_(nullptr), resolution_(kDefaultResolution) {
83  if (!ParseFontDescriptionName(desc)) {
84  tprintf("ERROR: Could not parse %s\n", desc.c_str());
85  Clear();
86  }
87 }
88 
89 void PangoFontInfo::Clear() {
90  font_size_ = 0;
91  family_name_.clear();
92  font_type_ = UNKNOWN;
93  if (desc_) {
94  pango_font_description_free(desc_);
95  desc_ = nullptr;
96  }
97 }
98 
99 PangoFontInfo::~PangoFontInfo() { pango_font_description_free(desc_); }
100 
102  if (!desc_) return "";
103  char* desc_str = pango_font_description_to_string(desc_);
104  string desc_name(desc_str);
105  g_free(desc_str);
106  return desc_name;
107 }
108 
109 // If not already initialized, initializes FontConfig by setting its
110 // environment variable and creating a fonts.conf file that points to the
111 // FLAGS_fonts_dir and the cache to FLAGS_fontconfig_tmpdir.
112 /* static */
114  if (fonts_dir_.empty()) {
115  HardInitFontConfig(FLAGS_fonts_dir.c_str(),
116  FLAGS_fontconfig_tmpdir.c_str());
117  }
118 }
119 
120 // Re-initializes font config, whether or not already initialized.
121 // If already initialized, any existing cache is deleted, just to be sure.
122 /* static */
123 void PangoFontInfo::HardInitFontConfig(const string& fonts_dir,
124  const string& cache_dir) {
125  if (!cache_dir_.empty()) {
127  File::JoinPath(cache_dir_.c_str(), "*cache-?").c_str());
128  }
129  const int MAX_FONTCONF_FILESIZE = 1024;
130  char fonts_conf_template[MAX_FONTCONF_FILESIZE];
131  cache_dir_ = cache_dir;
132  fonts_dir_ = fonts_dir;
133  snprintf(fonts_conf_template, MAX_FONTCONF_FILESIZE,
134  "<?xml version=\"1.0\"?>\n"
135  "<!DOCTYPE fontconfig SYSTEM \"fonts.dtd\">\n"
136  "<fontconfig>\n"
137  "<dir>%s</dir>\n"
138  "<cachedir>%s</cachedir>\n"
139  "<config></config>\n"
140  "</fontconfig>",
141  fonts_dir.c_str(), cache_dir_.c_str());
142  string fonts_conf_file = File::JoinPath(cache_dir_.c_str(), "fonts.conf");
143  File::WriteStringToFileOrDie(fonts_conf_template, fonts_conf_file);
144 #ifdef _WIN32
145  std::string env("FONTCONFIG_PATH=");
146  env.append(cache_dir_.c_str());
147  putenv(env.c_str());
148  putenv("LANG=en_US.utf8");
149 #else
150  setenv("FONTCONFIG_PATH", cache_dir_.c_str(), true);
151  // Fix the locale so that the reported font names are consistent.
152  setenv("LANG", "en_US.utf8", true);
153 #endif // _WIN32
154 
155  if (FcInitReinitialize() != FcTrue) {
156  tprintf("FcInitiReinitialize failed!!\n");
157  }
159  // Clear Pango's font cache too.
160  pango_cairo_font_map_set_default(nullptr);
161 }
162 
163 static void ListFontFamilies(PangoFontFamily*** families,
164  int* n_families) {
166  PangoFontMap* font_map = pango_cairo_font_map_get_default();
168  pango_font_map_list_families(font_map, families, n_families);
169 }
170 
171 bool PangoFontInfo::ParseFontDescription(const PangoFontDescription *desc) {
172  Clear();
173  const char* family = pango_font_description_get_family(desc);
174  if (!family) {
175  char* desc_str = pango_font_description_to_string(desc);
176  tprintf("WARNING: Could not parse family name from description: '%s'\n",
177  desc_str);
178  g_free(desc_str);
179  return false;
180  }
181  family_name_ = string(family);
182  desc_ = pango_font_description_copy(desc);
183 
184  // Set font size in points
185  font_size_ = pango_font_description_get_size(desc);
186  if (!pango_font_description_get_size_is_absolute(desc)) {
187  font_size_ /= PANGO_SCALE;
188  }
189 
190  return true;
191 }
192 
193 bool PangoFontInfo::ParseFontDescriptionName(const string& name) {
194  PangoFontDescription *desc = pango_font_description_from_string(name.c_str());
195  bool success = ParseFontDescription(desc);
196  pango_font_description_free(desc);
197  return success;
198 }
199 
200 // Returns the PangoFont structure corresponding to the closest available font
201 // in the font map. Note that if the font is wholly missing, this could
202 // correspond to a completely different font family and face.
203 PangoFont* PangoFontInfo::ToPangoFont() const {
205  PangoFontMap* font_map = pango_cairo_font_map_get_default();
206  PangoContext* context = pango_context_new();
207  pango_cairo_context_set_resolution(context, resolution_);
208  pango_context_set_font_map(context, font_map);
209  PangoFont* font = nullptr;
210  {
212  font = pango_font_map_load_font(font_map, context, desc_);
213  }
214  g_object_unref(context);
215  return font;
216 }
217 
218 bool PangoFontInfo::CoversUTF8Text(const char* utf8_text, int byte_length) const {
219  PangoFont* font = ToPangoFont();
220  PangoCoverage* coverage = pango_font_get_coverage(font, nullptr);
221  for (UNICHAR::const_iterator it = UNICHAR::begin(utf8_text, byte_length);
222  it != UNICHAR::end(utf8_text, byte_length);
223  ++it) {
224  if (IsWhitespace(*it) || pango_is_zero_width(*it))
225  continue;
226  if (pango_coverage_get(coverage, *it) != PANGO_COVERAGE_EXACT) {
227  char tmp[5];
228  int len = it.get_utf8(tmp);
229  tmp[len] = '\0';
230  tlog(2, "'%s' (U+%x) not covered by font\n", tmp, *it);
231  return false;
232  }
233  }
234  pango_coverage_unref(coverage);
235  g_object_unref(font);
236  return true;
237 }
238 
239 // This variant of strncpy permits src and dest to overlap. It will copy the
240 // first byte first.
241 static char* my_strnmove(char* dest, const char* src, size_t n) {
242  char* ret = dest;
243 
244  // Copy characters until n reaches zero or the src byte is a nul.
245  do {
246  *dest = *src;
247  --n;
248  ++dest;
249  ++src;
250  } while (n && src[0]);
251 
252  // If we reached a nul byte and there are more 'n' left, zero them out.
253  while (n) {
254  *dest = '\0';
255  --n;
256  ++dest;
257  }
258  return ret;
259 }
260 
261 int PangoFontInfo::DropUncoveredChars(string* utf8_text) const {
262  PangoFont* font = ToPangoFont();
263  PangoCoverage* coverage = pango_font_get_coverage(font, nullptr);
264  int num_dropped_chars = 0;
265  // Maintain two iterators that point into the string. For space efficiency, we
266  // will repeatedly copy one covered UTF8 character from one to the other, and
267  // at the end resize the string to the right length.
268  char* out = const_cast<char*>(utf8_text->c_str());
269  const UNICHAR::const_iterator it_begin =
270  UNICHAR::begin(utf8_text->c_str(), utf8_text->length());
271  const UNICHAR::const_iterator it_end =
272  UNICHAR::end(utf8_text->c_str(), utf8_text->length());
273  for (UNICHAR::const_iterator it = it_begin; it != it_end;) {
274  // Skip bad utf-8.
275  if (!it.is_legal()) {
276  ++it; // One suitable error message will still be issued.
277  continue;
278  }
279  int unicode = *it;
280  int utf8_len = it.utf8_len();
281  const char* utf8_char = it.utf8_data();
282  // Move it forward before the data gets modified.
283  ++it;
284  if (!IsWhitespace(unicode) && !pango_is_zero_width(unicode) &&
285  pango_coverage_get(coverage, unicode) != PANGO_COVERAGE_EXACT) {
286  if (TLOG_IS_ON(2)) {
287  UNICHAR unichar(unicode);
288  char* str = unichar.utf8_str();
289  tlog(2, "'%s' (U+%x) not covered by font\n", str, unicode);
290  delete[] str;
291  }
292  ++num_dropped_chars;
293  continue;
294  }
295  my_strnmove(out, utf8_char, utf8_len);
296  out += utf8_len;
297  }
298  pango_coverage_unref(coverage);
299  g_object_unref(font);
300  utf8_text->resize(out - utf8_text->c_str());
301  return num_dropped_chars;
302 }
303 
304 bool PangoFontInfo::GetSpacingProperties(const string& utf8_char,
305  int* x_bearing, int* x_advance) const {
306  // Convert to equivalent PangoFont structure
307  PangoFont* font = ToPangoFont();
308  // Find the glyph index in the font for the supplied utf8 character.
309  int total_advance = 0;
310  int min_bearing = 0;
311  // Handle multi-unicode strings by reporting the left-most position of the
312  // x-bearing, and right-most position of the x-advance if the string were to
313  // be rendered.
314  const UNICHAR::const_iterator it_begin = UNICHAR::begin(utf8_char.c_str(),
315  utf8_char.length());
316  const UNICHAR::const_iterator it_end = UNICHAR::end(utf8_char.c_str(),
317  utf8_char.length());
318  for (UNICHAR::const_iterator it = it_begin; it != it_end; ++it) {
319  PangoGlyph glyph_index = pango_fc_font_get_glyph(
320  reinterpret_cast<PangoFcFont*>(font), *it);
321  if (!glyph_index) {
322  // Glyph for given unicode character doesn't exist in font.
323  g_object_unref(font);
324  return false;
325  }
326  // Find the ink glyph extents for the glyph
327  PangoRectangle ink_rect, logical_rect;
328  pango_font_get_glyph_extents(font, glyph_index, &ink_rect, &logical_rect);
329  pango_extents_to_pixels(&ink_rect, nullptr);
330  pango_extents_to_pixels(&logical_rect, nullptr);
331 
332  int bearing = total_advance + PANGO_LBEARING(ink_rect);
333  if (it == it_begin || bearing < min_bearing) {
334  min_bearing = bearing;
335  }
336  total_advance += PANGO_RBEARING(logical_rect);
337  }
338  *x_bearing = min_bearing;
339  *x_advance = total_advance;
340  g_object_unref(font);
341  return true;
342 }
343 
344 bool PangoFontInfo::CanRenderString(const char* utf8_word, int len) const {
345  std::vector<string> graphemes;
346  return CanRenderString(utf8_word, len, &graphemes);
347 }
348 
349 bool PangoFontInfo::CanRenderString(const char* utf8_word, int len,
350  std::vector<string>* graphemes) const {
351  if (graphemes) graphemes->clear();
352  // We check for font coverage of the text first, as otherwise Pango could
353  // (undesirably) fall back to another font that does have the required
354  // coverage.
355  if (!CoversUTF8Text(utf8_word, len)) {
356  return false;
357  }
358  // U+25CC dotted circle character that often (but not always) gets rendered
359  // when there is an illegal grapheme sequence.
360  const char32 kDottedCircleGlyph = 9676;
361  bool bad_glyph = false;
362  PangoFontMap* font_map = pango_cairo_font_map_get_default();
363  PangoContext* context = pango_context_new();
364  pango_context_set_font_map(context, font_map);
365  PangoLayout* layout;
366  {
367  // Pango is not relasing the cached layout.
369  layout = pango_layout_new(context);
370  }
371  if (desc_) {
372  pango_layout_set_font_description(layout, desc_);
373  } else {
374  PangoFontDescription *desc = pango_font_description_from_string(
375  DescriptionName().c_str());
376  pango_layout_set_font_description(layout, desc);
377  pango_font_description_free(desc);
378  }
379  pango_layout_set_text(layout, utf8_word, len);
380  PangoLayoutIter* run_iter = nullptr;
381  { // Fontconfig caches some information here that is not freed before exit.
383  run_iter = pango_layout_get_iter(layout);
384  }
385  do {
386  PangoLayoutRun* run = pango_layout_iter_get_run_readonly(run_iter);
387  if (!run) {
388  tlog(2, "Found end of line nullptr run marker\n");
389  continue;
390  }
391  PangoGlyph dotted_circle_glyph;
392  PangoFont* font = run->item->analysis.font;
393 
394 #ifdef _WIN32 // Fixme! Leaks memory and breaks unittests.
395  PangoGlyphString* glyphs = pango_glyph_string_new();
396  char s[] = "\xc2\xa7";
397  pango_shape(s, sizeof(s), &(run->item->analysis), glyphs);
398  dotted_circle_glyph = glyphs->glyphs[0].glyph;
399 #else
400  dotted_circle_glyph = pango_fc_font_get_glyph(
401  reinterpret_cast<PangoFcFont*>(font), kDottedCircleGlyph);
402 #endif
403 
404  if (TLOG_IS_ON(2)) {
405  PangoFontDescription* desc = pango_font_describe(font);
406  char* desc_str = pango_font_description_to_string(desc);
407  tlog(2, "Desc of font in run: %s\n", desc_str);
408  g_free(desc_str);
409  pango_font_description_free(desc);
410  }
411 
412  PangoGlyphItemIter cluster_iter;
413  gboolean have_cluster;
414  for (have_cluster = pango_glyph_item_iter_init_start(&cluster_iter,
415  run, utf8_word);
416  have_cluster && !bad_glyph;
417  have_cluster = pango_glyph_item_iter_next_cluster(&cluster_iter)) {
418  const int start_byte_index = cluster_iter.start_index;
419  const int end_byte_index = cluster_iter.end_index;
420  int start_glyph_index = cluster_iter.start_glyph;
421  int end_glyph_index = cluster_iter.end_glyph;
422  string cluster_text = string(utf8_word + start_byte_index,
423  end_byte_index - start_byte_index);
424  if (graphemes) graphemes->push_back(cluster_text);
425  if (IsUTF8Whitespace(cluster_text.c_str())) {
426  tlog(2, "Skipping whitespace\n");
427  continue;
428  }
429  if (TLOG_IS_ON(2)) {
430  printf("start_byte=%d end_byte=%d start_glyph=%d end_glyph=%d ",
431  start_byte_index, end_byte_index,
432  start_glyph_index, end_glyph_index);
433  }
434  for (int i = start_glyph_index,
435  step = (end_glyph_index > start_glyph_index) ? 1 : -1;
436  !bad_glyph && i != end_glyph_index; i+= step) {
437  const bool unknown_glyph =
438  (cluster_iter.glyph_item->glyphs->glyphs[i].glyph &
439  PANGO_GLYPH_UNKNOWN_FLAG);
440  const bool illegal_glyph =
441  (cluster_iter.glyph_item->glyphs->glyphs[i].glyph ==
442  dotted_circle_glyph);
443  bad_glyph = unknown_glyph || illegal_glyph;
444  if (TLOG_IS_ON(2)) {
445  printf("(%d=%d)", cluster_iter.glyph_item->glyphs->glyphs[i].glyph,
446  bad_glyph ? 1 : 0);
447  }
448  }
449  if (TLOG_IS_ON(2)) {
450  printf(" '%s'\n", cluster_text.c_str());
451  }
452  if (bad_glyph)
453  tlog(1, "Found illegal glyph!\n");
454  }
455  } while (!bad_glyph && pango_layout_iter_next_run(run_iter));
456 
457  pango_layout_iter_free(run_iter);
458  g_object_unref(context);
459  g_object_unref(layout);
460  if (bad_glyph && graphemes) graphemes->clear();
461  return !bad_glyph;
462 }
463 
464 
465 // ------------------------ FontUtils ------------------------------------
466 std::vector<string> FontUtils::available_fonts_; // cache list
467 
468 // Returns whether the specified font description is available in the fonts
469 // directory.
470 //
471 // The generated list of font families and faces includes "synthesized" font
472 // faces that are not truly loadable. Pango versions >=1.18 have a
473 // pango_font_face_is_synthesized method that can be used to prune the list.
474 // Until then, we are restricted to using a hack where we try to load the font
475 // from the font_map, and then check what we loaded to see if it has the
476 // description we expected. If it is not, then the font is deemed unavailable.
477 /* static */
478 bool FontUtils::IsAvailableFont(const char* input_query_desc,
479  string* best_match) {
480  string query_desc(input_query_desc);
481 #if (PANGO_VERSION <= 12005)
482  // Strip commas and any ' Medium' substring in the name.
483  query_desc.erase(std::remove(query_desc.begin(), query_desc.end(), ','),
484  query_desc.end());
485  const string kMediumStr = " Medium";
486  std::size_t found = query_desc.find(kMediumStr);
487  if (found != std::string::npos) {
488  query_desc.erase(found, kMediumStr.length());
489  }
490 #endif
491  PangoFontDescription *desc = pango_font_description_from_string(
492  query_desc.c_str());
493  PangoFont* selected_font = nullptr;
494  {
496  PangoFontMap* font_map = pango_cairo_font_map_get_default();
497  PangoContext* context = pango_context_new();
498  pango_context_set_font_map(context, font_map);
499  {
501  selected_font = pango_font_map_load_font(font_map, context, desc);
502  }
503  g_object_unref(context);
504  }
505  if (selected_font == nullptr) {
506  pango_font_description_free(desc);
507  return false;
508  }
509  PangoFontDescription* selected_desc = pango_font_describe(selected_font);
510 
511  bool equal = pango_font_description_equal(desc, selected_desc);
512  tlog(3, "query weight = %d \t selected weight =%d\n",
513  pango_font_description_get_weight(desc),
514  pango_font_description_get_weight(selected_desc));
515 
516  char* selected_desc_str = pango_font_description_to_string(selected_desc);
517  tlog(2, "query_desc: '%s' Selected: '%s'\n", query_desc.c_str(),
518  selected_desc_str);
519  if (!equal && best_match != nullptr) {
520  *best_match = selected_desc_str;
521  // Clip the ending ' 0' if there is one. It seems that, if there is no
522  // point size on the end of the fontname, then Pango always appends ' 0'.
523  int len = best_match->size();
524  if (len > 2 && best_match->at(len - 1) == '0' &&
525  best_match->at(len - 2) == ' ') {
526  *best_match = best_match->substr(0, len - 2);
527  }
528  }
529  g_free(selected_desc_str);
530  pango_font_description_free(selected_desc);
531  g_object_unref(selected_font);
532  pango_font_description_free(desc);
533  return equal;
534 }
535 
536 static bool ShouldIgnoreFontFamilyName(const char* query) {
537  static const char* kIgnoredFamilyNames[] = {"Sans", "Serif", "Monospace",
538  nullptr};
539  const char** list = kIgnoredFamilyNames;
540  for (; *list != nullptr; ++list) {
541  if (!strcmp(*list, query))
542  return true;
543  }
544  return false;
545 }
546 
547 // Outputs description names of available fonts.
548 /* static */
549 const std::vector<string>& FontUtils::ListAvailableFonts() {
550  if (!available_fonts_.empty()) {
551  return available_fonts_;
552  }
553 #ifdef GOOGLE_TESSERACT
554  if (FLAGS_use_only_legacy_fonts) {
555  // Restrict view to list of fonts in legacy_fonts.h
556  tprintf("Using list of legacy fonts only\n");
557  const int kNumFontLists = 4;
558  for (int i = 0; i < kNumFontLists; ++i) {
559  for (int j = 0; kFontlists[i][j] != nullptr; ++j) {
560  available_fonts_.push_back(kFontlists[i][j]);
561  }
562  }
563  return available_fonts_;
564  }
565 #endif
566 
567  PangoFontFamily** families = 0;
568  int n_families = 0;
569  ListFontFamilies(&families, &n_families);
570  for (int i = 0; i < n_families; ++i) {
571  const char* family_name = pango_font_family_get_name(families[i]);
572  tlog(2, "Listing family %s\n", family_name);
573  if (ShouldIgnoreFontFamilyName(family_name)) {
574  continue;
575  }
576 
577  int n_faces;
578  PangoFontFace** faces = nullptr;
579  pango_font_family_list_faces(families[i], &faces, &n_faces);
580  for (int j = 0; j < n_faces; ++j) {
581  PangoFontDescription* desc = pango_font_face_describe(faces[j]);
582  char* desc_str = pango_font_description_to_string(desc);
583  if (IsAvailableFont(desc_str)) {
584  available_fonts_.push_back(desc_str);
585  }
586  pango_font_description_free(desc);
587  g_free(desc_str);
588  }
589  g_free(faces);
590  }
591  g_free(families);
592  std::sort(available_fonts_.begin(), available_fonts_.end());
593  return available_fonts_;
594 }
595 
596 
597 static void CharCoverageMapToBitmap(PangoCoverage* coverage,
598  std::vector<bool>* unichar_bitmap) {
599  const int kMinUnicodeValue = 33;
600  const int kMaxUnicodeValue = 0x10FFFF;
601  unichar_bitmap->resize(kMaxUnicodeValue + 1, false);
602  // Mark off characters that the font can render.
603  for (int i = kMinUnicodeValue; i <= kMaxUnicodeValue; ++i) {
604  if (IsInterchangeValid(i)) {
605  (*unichar_bitmap)[i]
606  = (pango_coverage_get(coverage, i) == PANGO_COVERAGE_EXACT);
607  }
608  }
609 }
610 
611 /* static */
612 void FontUtils::GetAllRenderableCharacters(std::vector<bool>* unichar_bitmap) {
613  const std::vector<string>& all_fonts = ListAvailableFonts();
614  return GetAllRenderableCharacters(all_fonts, unichar_bitmap);
615 }
616 
617 /* static */
618 void FontUtils::GetAllRenderableCharacters(const string& font_name,
619  std::vector<bool>* unichar_bitmap) {
620  PangoFontInfo font_info(font_name);
621  PangoFont* font = font_info.ToPangoFont();
622  PangoCoverage* coverage = pango_font_get_coverage(font, nullptr);
623  CharCoverageMapToBitmap(coverage, unichar_bitmap);
624  pango_coverage_unref(coverage);
625  g_object_unref(font);
626 }
627 
628 /* static */
629 void FontUtils::GetAllRenderableCharacters(const std::vector<string>& fonts,
630  std::vector<bool>* unichar_bitmap) {
631  // Form the union of coverage maps from the fonts
632  PangoCoverage* all_coverage = pango_coverage_new();
633  tlog(1, "Processing %u fonts\n", static_cast<unsigned>(fonts.size()));
634  for (unsigned i = 0; i < fonts.size(); ++i) {
635  PangoFontInfo font_info(fonts[i]);
636  PangoFont* font = font_info.ToPangoFont();
637  PangoCoverage* coverage = pango_font_get_coverage(font, nullptr);
638  // Mark off characters that any font can render.
639  pango_coverage_max(all_coverage, coverage);
640  pango_coverage_unref(coverage);
641  g_object_unref(font);
642  }
643  CharCoverageMapToBitmap(all_coverage, unichar_bitmap);
644  pango_coverage_unref(all_coverage);
645 }
646 
647 
648 // Utilities written to be backward compatible with StringRender
649 
650 /* static */
651 int FontUtils::FontScore(const std::unordered_map<char32, inT64>& ch_map,
652  const string& fontname, int* raw_score,
653  std::vector<bool>* ch_flags) {
654  PangoFontInfo font_info;
655  if (!font_info.ParseFontDescriptionName(fontname)) {
656  tprintf("ERROR: Could not parse %s\n", fontname.c_str());
657  }
658  PangoFont* font = font_info.ToPangoFont();
659  PangoCoverage* coverage = pango_font_get_coverage(font, nullptr);
660 
661  if (ch_flags) {
662  ch_flags->clear();
663  ch_flags->reserve(ch_map.size());
664  }
665  *raw_score = 0;
666  int ok_chars = 0;
667  for (std::unordered_map<char32, inT64>::const_iterator it = ch_map.begin();
668  it != ch_map.end(); ++it) {
669  bool covered = (IsWhitespace(it->first) ||
670  (pango_coverage_get(coverage, it->first)
671  == PANGO_COVERAGE_EXACT));
672  if (covered) {
673  ++(*raw_score);
674  ok_chars += it->second;
675  }
676  if (ch_flags) {
677  ch_flags->push_back(covered);
678  }
679  }
680  pango_coverage_unref(coverage);
681  g_object_unref(font);
682  return ok_chars;
683 }
684 
685 
686 /* static */
688  const std::unordered_map<char32, inT64>& ch_map,
689  std::vector<std::pair<const char*, std::vector<bool> > >* fonts) {
690  const double kMinOKFraction = 0.99;
691  // Weighted fraction of characters that must be renderable in a font to make
692  // it OK even if the raw count is not good.
693  const double kMinWeightedFraction = 0.99995;
694 
695  fonts->clear();
696  std::vector<std::vector<bool> > font_flags;
697  std::vector<int> font_scores;
698  std::vector<int> raw_scores;
699  int most_ok_chars = 0;
700  int best_raw_score = 0;
701  const std::vector<string>& font_names = FontUtils::ListAvailableFonts();
702  for (unsigned i = 0; i < font_names.size(); ++i) {
703  std::vector<bool> ch_flags;
704  int raw_score = 0;
705  int ok_chars = FontScore(ch_map, font_names[i], &raw_score, &ch_flags);
706  most_ok_chars = MAX(ok_chars, most_ok_chars);
707  best_raw_score = MAX(raw_score, best_raw_score);
708 
709  font_flags.push_back(ch_flags);
710  font_scores.push_back(ok_chars);
711  raw_scores.push_back(raw_score);
712  }
713 
714  // Now select the fonts with a score above a threshold fraction
715  // of both the raw and weighted best scores. To prevent bogus fonts being
716  // selected for CJK, we require a high fraction (kMinOKFraction = 0.99) of
717  // BOTH weighted and raw scores.
718  // In low character-count scripts, the issue is more getting enough fonts,
719  // when only 1 or 2 might have all those rare dingbats etc in them, so we
720  // allow a font with a very high weighted (coverage) score
721  // (kMinWeightedFraction = 0.99995) to be used even if its raw score is poor.
722  int least_good_enough = static_cast<int>(most_ok_chars * kMinOKFraction);
723  int least_raw_enough = static_cast<int>(best_raw_score * kMinOKFraction);
724  int override_enough = static_cast<int>(most_ok_chars * kMinWeightedFraction);
725 
726  string font_list;
727  for (unsigned i = 0; i < font_names.size(); ++i) {
728  int score = font_scores[i];
729  int raw_score = raw_scores[i];
730  if ((score >= least_good_enough && raw_score >= least_raw_enough) ||
731  score >= override_enough) {
732  fonts->push_back(std::make_pair(font_names[i].c_str(), font_flags[i]));
733  tlog(1, "OK font %s = %.4f%%, raw = %d = %.2f%%\n",
734  font_names[i].c_str(),
735  100.0 * score / most_ok_chars,
736  raw_score, 100.0 * raw_score / best_raw_score);
737  font_list += font_names[i];
738  font_list += "\n";
739  } else if (score >= least_good_enough || raw_score >= least_raw_enough) {
740  tlog(1, "Runner-up font %s = %.4f%%, raw = %d = %.2f%%\n",
741  font_names[i].c_str(),
742  100.0 * score / most_ok_chars,
743  raw_score, 100.0 * raw_score / best_raw_score);
744  }
745  }
746  return font_list;
747 }
748 
749 /* static */
750 bool FontUtils::SelectFont(const char* utf8_word, const int utf8_len,
751  string* font_name, std::vector<string>* graphemes) {
752  return SelectFont(utf8_word, utf8_len, ListAvailableFonts(), font_name,
753  graphemes);
754 }
755 
756 /* static */
757 bool FontUtils::SelectFont(const char* utf8_word, const int utf8_len,
758  const std::vector<string>& all_fonts,
759  string* font_name, std::vector<string>* graphemes) {
760  if (font_name) font_name->clear();
761  if (graphemes) graphemes->clear();
762  for (unsigned i = 0; i < all_fonts.size(); ++i) {
763  PangoFontInfo font;
764  std::vector<string> found_graphemes;
765  ASSERT_HOST_MSG(font.ParseFontDescriptionName(all_fonts[i]),
766  "Could not parse font desc name %s\n",
767  all_fonts[i].c_str());
768  if (font.CanRenderString(utf8_word, utf8_len, &found_graphemes)) {
769  if (graphemes) graphemes->swap(found_graphemes);
770  if (font_name) *font_name = all_fonts[i];
771  return true;
772  }
773  }
774  return false;
775 }
776 
777 // PangoFontInfo is reinitialized, so clear the static list of fonts.
778 /* static */
779 void FontUtils::ReInit() { available_fonts_.clear(); }
780 
781 } // namespace tesseract
bool GetSpacingProperties(const string &utf8_char, int *x_bearing, int *x_advance) const
static const std::vector< string > & ListAvailableFonts()
#define ASSERT_HOST_MSG(x,...)
Definition: errcode.h:90
STRING_PARAM_FLAG(fontconfig_tmpdir, "/tmp", "Overrides fontconfig default temporary dir")
bool ParseFontDescriptionName(const string &name)
static string BestFonts(const std::unordered_map< char32, inT64 > &ch_map, std::vector< std::pair< const char *, std::vector< bool > > > *font_flag)
#define MAX(x, y)
Definition: ndminx.h:24
static bool DeleteMatchingFiles(const char *pattern)
Definition: fileio.cpp:111
static const_iterator begin(const char *utf8_str, const int byte_length)
Definition: unichar.cpp:202
bool IsUTF8Whitespace(const char *text)
Definition: normstrngs.cpp:229
bool CoversUTF8Text(const char *utf8_text, int byte_length) const
bool IsWhitespace(const char32 ch)
Definition: normstrngs.cpp:223
static void GetAllRenderableCharacters(std::vector< bool > *unichar_bitmap)
#define tprintf(...)
Definition: tprintf.h:31
int DropUncoveredChars(string *utf8_text) const
signed int char32
Definition: unichar.h:52
const int kDefaultResolution
#define BOOL_PARAM_FLAG(name, val, comment)
bool IsInterchangeValid(const char32 ch)
Definition: normstrngs.cpp:253
const string & family_name() const
static int FontScore(const std::unordered_map< char32, inT64 > &ch_map, const string &fontname, int *raw_score, std::vector< bool > *ch_flags)
char * utf8_str() const
Definition: unichar.cpp:127
static const_iterator end(const char *utf8_str, const int byte_length)
Definition: unichar.cpp:206
#define tlog(level,...)
Definition: tlog.h:33
static void HardInitFontConfig(const string &fonts_dir, const string &cache_dir)
static bool SelectFont(const char *utf8_word, const int utf8_len, string *font_name, std::vector< string > *graphemes)
bool CanRenderString(const char *utf8_word, int len, std::vector< string > *graphemes) const
#define DISABLE_HEAP_LEAK_CHECK
Definition: util.h:60
static string JoinPath(const string &prefix, const string &suffix)
Definition: fileio.cpp:81
#define TLOG_IS_ON(level)
Definition: tlog.h:39
static void WriteStringToFileOrDie(const string &str, const string &filename)
Definition: fileio.cpp:52
static bool IsAvailableFont(const char *font_desc)