tesseract  3.05.02
stringrenderer.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: stringrenderer.cpp
3  * Description: Class for rendering UTF-8 text to an image, and retrieving
4  * bounding boxes around each grapheme cluster.
5  * Author: Ranjith Unnikrishnan
6  * Created: Mon Nov 18 2013
7  *
8  * (C) Copyright 2013, Google Inc.
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  **********************************************************************/
20 
21 #include "stringrenderer.h"
22 
23 #include <stdio.h>
24 #include <string.h>
25 #include <algorithm>
26 #include <map>
27 #include <utility>
28 #include <vector>
29 
30 #include "allheaders.h" // from leptonica
31 #include "boxchar.h"
32 #include "ligature_table.h"
33 #include "normstrngs.h"
34 #include "pango/pango-font.h"
35 #include "pango/pango-glyph-item.h"
36 #include "tlog.h"
37 #include "unichar.h"
38 #include "unicode/uchar.h" // from libicu
39 #include "util.h"
40 
41 #ifdef USE_STD_NAMESPACE
42 using std::map;
43 using std::max;
44 using std::min;
45 using std::swap;
46 #endif
47 
48 namespace tesseract {
49 
50 static const int kDefaultOutputResolution = 300;
51 
52 // Word joiner (U+2060) inserted after letters in ngram mode, as per
53 // recommendation in http://unicode.org/reports/tr14/ to avoid line-breaks at
54 // hyphens and other non-alpha characters.
55 static const char* kWordJoinerUTF8 = "\xE2\x81\xA0"; // u8"\u2060";
56 static const char32 kWordJoiner = 0x2060;
57 
58 static bool IsCombiner(int ch) {
59  const int char_type = u_charType(ch);
60  return ((char_type == U_NON_SPACING_MARK) ||
61  (char_type == U_ENCLOSING_MARK) ||
62  (char_type == U_COMBINING_SPACING_MARK));
63 }
64 
65 static string EncodeAsUTF8(const char32 ch32) {
66  UNICHAR uni_ch(ch32);
67  return string(uni_ch.utf8(), uni_ch.utf8_len());
68 }
69 
70 // Returns true with probability 'prob'.
71 static bool RandBool(const double prob, TRand* rand) {
72  if (prob == 1.0) return true;
73  if (prob == 0.0) return false;
74  return rand->UnsignedRand(1.0) < prob;
75 }
76 
77 /* static */
78 Pix* CairoARGB32ToPixFormat(cairo_surface_t *surface) {
79  if (cairo_image_surface_get_format(surface) != CAIRO_FORMAT_ARGB32) {
80  printf("Unexpected surface format %d\n",
81  cairo_image_surface_get_format(surface));
82  return NULL;
83  }
84  const int width = cairo_image_surface_get_width(surface);
85  const int height = cairo_image_surface_get_height(surface);
86  Pix* pix = pixCreate(width, height, 32);
87  int byte_stride = cairo_image_surface_get_stride(surface);
88 
89  for (int i = 0; i < height; ++i) {
90  memcpy(reinterpret_cast<unsigned char*>(pix->data + i * pix->wpl) + 1,
91  cairo_image_surface_get_data(surface) + i * byte_stride,
92  byte_stride - ((i == height - 1) ? 1 : 0));
93  }
94  return pix;
95 }
96 
97 StringRenderer::StringRenderer(const string& font_desc, int page_width,
98  int page_height)
99  : page_width_(page_width),
100  page_height_(page_height),
101  h_margin_(50),
102  v_margin_(50),
103  pen_color_{0.0, 0.0, 0.0},
104  char_spacing_(0),
105  leading_(0),
106  vertical_text_(false),
107  gravity_hint_strong_(false),
108  render_fullwidth_latin_(false),
109  underline_start_prob_(0),
110  underline_continuation_prob_(0),
111  underline_style_(PANGO_UNDERLINE_SINGLE),
112  features_(NULL),
113  drop_uncovered_chars_(true),
114  strip_unrenderable_words_(false),
115  add_ligatures_(false),
116  output_word_boxes_(false),
117  surface_(NULL),
118  cr_(NULL),
119  layout_(NULL),
120  start_box_(0),
121  page_(0),
122  box_padding_(0),
123  page_boxes_(NULL),
124  total_chars_(0),
125  font_index_(0),
126  last_offset_(0) {
127  set_font(font_desc);
128  set_resolution(kDefaultOutputResolution);
129 }
130 
131 bool StringRenderer::set_font(const string& desc) {
132  bool success = font_.ParseFontDescriptionName(desc);
134  return success;
135 }
136 
137 void StringRenderer::set_resolution(const int resolution) {
138  resolution_ = resolution;
139  font_.set_resolution(resolution);
140 }
141 
143  underline_start_prob_ = min(max(frac, 0.0), 1.0);
144 }
145 
147  underline_continuation_prob_ = min(max(frac, 0.0), 1.0);
148 }
149 
151  free(features_);
152  ClearBoxes();
153  FreePangoCairo();
154 }
155 
157  FreePangoCairo();
158  surface_ = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, page_width_,
159  page_height_);
160  cr_ = cairo_create(surface_);
161  {
163  layout_ = pango_cairo_create_layout(cr_);
164  }
165 
166  if (vertical_text_) {
167  PangoContext* context = pango_layout_get_context(layout_);
168  pango_context_set_base_gravity(context, PANGO_GRAVITY_EAST);
169  if (gravity_hint_strong_) {
170  pango_context_set_gravity_hint(context, PANGO_GRAVITY_HINT_STRONG);
171  }
172  pango_layout_context_changed(layout_);
173  }
174 
176 }
177 
179  string font_desc = font_.DescriptionName();
180  // Specify the font via a description name
181  PangoFontDescription *desc =
182  pango_font_description_from_string(font_desc.c_str());
183  // Assign the font description to the layout
184  pango_layout_set_font_description(layout_, desc);
185  pango_font_description_free(desc); // free the description
186  pango_cairo_context_set_resolution(pango_layout_get_context(layout_),
187  resolution_);
188 
189  int max_width = page_width_ - 2 * h_margin_;
190  int max_height = page_height_ - 2 * v_margin_;
191  tlog(3, "max_width = %d, max_height = %d\n", max_width, max_height);
192  if (vertical_text_) {
193  swap(max_width, max_height);
194  }
195  pango_layout_set_width(layout_, max_width * PANGO_SCALE);
196  pango_layout_set_wrap(layout_, PANGO_WRAP_WORD);
197 
198  // Adjust character spacing
199  PangoAttrList* attr_list = pango_attr_list_new();
200  if (char_spacing_) {
201  PangoAttribute* spacing_attr = pango_attr_letter_spacing_new(
202  static_cast<int>(char_spacing_ * PANGO_SCALE + 0.5));
203  spacing_attr->start_index = 0;
204  spacing_attr->end_index = static_cast<guint>(-1);
205  pango_attr_list_change(attr_list, spacing_attr);
206  }
207 #if (PANGO_VERSION_MAJOR == 1 && PANGO_VERSION_MINOR >= 38)
208  if (add_ligatures_) {
209  set_features("liga, clig, dlig, hlig");
210  PangoAttribute* feature_attr = pango_attr_font_features_new(features_);
211  pango_attr_list_change(attr_list, feature_attr);
212  }
213 #endif
214  pango_layout_set_attributes(layout_, attr_list);
215  pango_attr_list_unref(attr_list);
216  // Adjust line spacing
217  if (leading_) {
218  pango_layout_set_spacing(layout_, leading_ * PANGO_SCALE);
219  }
220 }
221 
223  if (layout_) {
224  g_object_unref(layout_);
225  layout_ = NULL;
226  }
227  if (cr_) {
228  cairo_destroy(cr_);
229  cr_ = NULL;
230  }
231  if (surface_) {
232  cairo_surface_destroy(surface_);
233  surface_ = NULL;
234  }
235 }
236 
237 void StringRenderer::SetWordUnderlineAttributes(const string& page_text) {
238  if (underline_start_prob_ == 0) return;
239  PangoAttrList* attr_list = pango_layout_get_attributes(layout_);
240 
241  const char* text = page_text.c_str();
242  int offset = 0;
243  TRand rand;
244  bool started_underline = false;
245  PangoAttribute* und_attr = NULL;
246 
247  while (offset < page_text.length()) {
248  offset += SpanUTF8Whitespace(text + offset);
249  if (offset == page_text.length()) break;
250 
251  int word_start = offset;
252  int word_len = SpanUTF8NotWhitespace(text + offset);
253  offset += word_len;
254  if (started_underline) {
255  // Should we continue the underline to the next word?
256  if (RandBool(underline_continuation_prob_, &rand)) {
257  // Continue the current underline to this word.
258  und_attr->end_index = word_start + word_len;
259  } else {
260  // Otherwise end the current underline attribute at the end of the
261  // previous word.
262  pango_attr_list_insert(attr_list, und_attr);
263  started_underline = false;
264  und_attr = NULL;
265  }
266  }
267  if (!started_underline && RandBool(underline_start_prob_, &rand)) {
268  // Start a new underline attribute
269  und_attr = pango_attr_underline_new(underline_style_);
270  und_attr->start_index = word_start;
271  und_attr->end_index = word_start + word_len;
272  started_underline = true;
273  }
274  }
275  // Finish the current underline attribute at the end of the page.
276  if (started_underline) {
277  und_attr->end_index = page_text.length();
278  pango_attr_list_insert(attr_list, und_attr);
279  }
280 }
281 
282 // Returns offset in utf8 bytes to first page.
284  int text_length) {
285  if (!text_length) return 0;
286  const int max_height = (page_height_ - 2 * v_margin_);
287  const int max_width = (page_width_ - 2 * h_margin_);
288  const int max_layout_height = vertical_text_ ? max_width : max_height;
289 
290  UNICHAR::const_iterator it = UNICHAR::begin(text, text_length);
291  const UNICHAR::const_iterator it_end = UNICHAR::end(text, text_length);
292  const int kMaxUnicodeBufLength = 15000;
293  for (int i = 0; i < kMaxUnicodeBufLength && it != it_end; ++it, ++i);
294  int buf_length = it.utf8_data() - text;
295  tlog(1, "len = %d buf_len = %d\n", text_length, buf_length);
296  pango_layout_set_text(layout_, text, buf_length);
297 
298  PangoLayoutIter* line_iter = NULL;
299  { // Fontconfig caches some info here that is not freed before exit.
301  line_iter = pango_layout_get_iter(layout_);
302  }
303  bool first_page = true;
304  int page_top = 0;
305  int offset = buf_length;
306  do {
307  // Get bounding box of the current line
308  PangoRectangle line_ink_rect;
309  pango_layout_iter_get_line_extents(line_iter, &line_ink_rect, NULL);
310  pango_extents_to_pixels(&line_ink_rect, NULL);
311  PangoLayoutLine* line = pango_layout_iter_get_line_readonly(line_iter);
312  if (first_page) {
313  page_top = line_ink_rect.y;
314  first_page = false;
315  }
316  int line_bottom = line_ink_rect.y + line_ink_rect.height;
317  if (line_bottom - page_top > max_layout_height) {
318  offset = line->start_index;
319  tlog(1, "Found offset = %d\n", offset);
320  break;
321  }
322  } while (pango_layout_iter_next_line(line_iter));
323  pango_layout_iter_free(line_iter);
324  return offset;
325 }
326 
327 const vector<BoxChar*>& StringRenderer::GetBoxes() const {
328  return boxchars_;
329 }
330 
332  return page_boxes_;
333 }
334 
335 void StringRenderer::RotatePageBoxes(float rotation) {
336  BoxChar::RotateBoxes(rotation, page_width_ / 2, page_height_ / 2,
337  start_box_, boxchars_.size(), &boxchars_);
338 }
339 
340 
342  for (int i = 0; i < boxchars_.size(); ++i)
343  delete boxchars_[i];
344  boxchars_.clear();
345  boxaDestroy(&page_boxes_);
346 }
347 
351 }
352 
356 }
357 
358 // Returns cluster strings in logical order.
359 bool StringRenderer::GetClusterStrings(vector<string>* cluster_text) {
360  map<int, string> start_byte_to_text;
361  PangoLayoutIter* run_iter = pango_layout_get_iter(layout_);
362  const char* full_text = pango_layout_get_text(layout_);
363  do {
364  PangoLayoutRun* run = pango_layout_iter_get_run_readonly(run_iter);
365  if (!run) {
366  // End of line NULL run marker
367  tlog(2, "Found end of line marker\n");
368  continue;
369  }
370  PangoGlyphItemIter cluster_iter;
371  gboolean have_cluster;
372  for (have_cluster = pango_glyph_item_iter_init_start(&cluster_iter,
373  run, full_text);
374  have_cluster;
375  have_cluster = pango_glyph_item_iter_next_cluster(&cluster_iter)) {
376  const int start_byte_index = cluster_iter.start_index;
377  const int end_byte_index = cluster_iter.end_index;
378  string text = string(full_text + start_byte_index,
379  end_byte_index - start_byte_index);
380  if (IsUTF8Whitespace(text.c_str())) {
381  tlog(2, "Found whitespace\n");
382  text = " ";
383  }
384  tlog(2, "start_byte=%d end_byte=%d : '%s'\n", start_byte_index,
385  end_byte_index, text.c_str());
386  if (add_ligatures_) {
387  // Make sure the output box files have ligatured text in case the font
388  // decided to use an unmapped glyph.
389  text = LigatureTable::Get()->AddLigatures(text, NULL);
390  }
391  start_byte_to_text[start_byte_index] = text;
392  }
393  } while (pango_layout_iter_next_run(run_iter));
394  pango_layout_iter_free(run_iter);
395 
396  cluster_text->clear();
397  for (map<int, string>::const_iterator it = start_byte_to_text.begin();
398  it != start_byte_to_text.end(); ++it) {
399  cluster_text->push_back(it->second);
400  }
401  return !cluster_text->empty();
402 }
403 
404 // Merges an array of BoxChars into words based on the identification of
405 // BoxChars containing the space character as inter-word separators.
406 //
407 // Sometime two adjacent characters in the sequence may be detected as lying on
408 // different lines based on their spatial positions. This may be the result of a
409 // newline character at end of the last word on a line in the source text, or of
410 // a discretionary line-break created by Pango at intra-word locations like
411 // hyphens. When this is detected the word is split at that location into
412 // multiple BoxChars. Otherwise, each resulting BoxChar will contain a word and
413 // its bounding box.
414 static void MergeBoxCharsToWords(vector<BoxChar*>* boxchars) {
415  vector<BoxChar*> result;
416  bool started_word = false;
417  for (int i = 0; i < boxchars->size(); ++i) {
418  if (boxchars->at(i)->ch() == " " ||
419  boxchars->at(i)->box() == NULL) {
420  result.push_back(boxchars->at(i));
421  boxchars->at(i) = NULL;
422  started_word = false;
423  continue;
424  }
425 
426  if (!started_word) {
427  // Begin new word
428  started_word = true;
429  result.push_back(boxchars->at(i));
430  boxchars->at(i) = NULL;
431  } else {
432  BoxChar* last_boxchar = result.back();
433  // Compute bounding box union
434  const Box* box = boxchars->at(i)->box();
435  Box* last_box = last_boxchar->mutable_box();
436  int left = min(last_box->x, box->x);
437  int right = max(last_box->x + last_box->w, box->x + box->w);
438  int top = min(last_box->y, box->y);
439  int bottom = max(last_box->y + last_box->h, box->y + box->h);
440  // Conclude that the word was broken to span multiple lines based on the
441  // size of the merged bounding box in relation to those of the individual
442  // characters seen so far.
443  if (right - left > last_box->w + 5 * box->w) {
444  tlog(1, "Found line break after '%s'", last_boxchar->ch().c_str());
445  // Insert a fake interword space and start a new word with the current
446  // boxchar.
447  result.push_back(new BoxChar(" ", 1));
448  result.push_back(boxchars->at(i));
449  boxchars->at(i) = NULL;
450  continue;
451  }
452  // Append to last word
453  last_boxchar->mutable_ch()->append(boxchars->at(i)->ch());
454  last_box->x = left;
455  last_box->w = right - left;
456  last_box->y = top;
457  last_box->h = bottom - top;
458  delete boxchars->at(i);
459  boxchars->at(i) = NULL;
460  }
461  }
462  boxchars->swap(result);
463 }
464 
465 
467  const char* text = pango_layout_get_text(layout_);
468  PangoLayoutIter* cluster_iter = pango_layout_get_iter(layout_);
469 
470  // Do a first pass to store cluster start indexes.
471  vector<int> cluster_start_indices;
472  do {
473  cluster_start_indices.push_back(pango_layout_iter_get_index(cluster_iter));
474  tlog(3, "Added %d\n", cluster_start_indices.back());
475  } while (pango_layout_iter_next_cluster(cluster_iter));
476  pango_layout_iter_free(cluster_iter);
477  cluster_start_indices.push_back(strlen(text));
478  tlog(3, "Added last index %d\n", cluster_start_indices.back());
479  // Sort the indices and create a map from start to end indices.
480  sort(cluster_start_indices.begin(), cluster_start_indices.end());
481  map<int, int> cluster_start_to_end_index;
482  for (int i = 0; i < cluster_start_indices.size() - 1; ++i) {
483  cluster_start_to_end_index[cluster_start_indices[i]]
484  = cluster_start_indices[i + 1];
485  }
486 
487  // Iterate again to compute cluster boxes and their text with the obtained
488  // cluster extent information.
489  cluster_iter = pango_layout_get_iter(layout_);
490  // Store BoxChars* sorted by their byte start positions
491  map<int, BoxChar*> start_byte_to_box;
492  do {
493  PangoRectangle cluster_rect;
494  pango_layout_iter_get_cluster_extents(cluster_iter, &cluster_rect,
495  NULL);
496  pango_extents_to_pixels(&cluster_rect, NULL);
497  const int start_byte_index = pango_layout_iter_get_index(cluster_iter);
498  const int end_byte_index = cluster_start_to_end_index[start_byte_index];
499  string cluster_text = string(text + start_byte_index,
500  end_byte_index - start_byte_index);
501  if (!cluster_text.empty() && cluster_text[0] == '\n') {
502  tlog(2, "Skipping newlines at start of text.\n");
503  continue;
504  }
505  if (!cluster_rect.width || !cluster_rect.height ||
506  IsUTF8Whitespace(cluster_text.c_str())) {
507  tlog(2, "Skipping whitespace with boxdim (%d,%d) '%s'\n",
508  cluster_rect.width, cluster_rect.height, cluster_text.c_str());
509  BoxChar* boxchar = new BoxChar(" ", 1);
510  boxchar->set_page(page_);
511  start_byte_to_box[start_byte_index] = boxchar;
512  continue;
513  }
514  // Prepare a boxchar for addition at this byte position.
515  tlog(2, "[%d %d], %d, %d : start_byte=%d end_byte=%d : '%s'\n",
516  cluster_rect.x, cluster_rect.y,
517  cluster_rect.width, cluster_rect.height,
518  start_byte_index, end_byte_index,
519  cluster_text.c_str());
520  ASSERT_HOST_MSG(cluster_rect.width,
521  "cluster_text:%s start_byte_index:%d\n",
522  cluster_text.c_str(), start_byte_index);
523  ASSERT_HOST_MSG(cluster_rect.height,
524  "cluster_text:%s start_byte_index:%d\n",
525  cluster_text.c_str(), start_byte_index);
526  if (box_padding_) {
527  cluster_rect.x = max(0, cluster_rect.x - box_padding_);
528  cluster_rect.width += 2 * box_padding_;
529  cluster_rect.y = max(0, cluster_rect.y - box_padding_);
530  cluster_rect.height += 2 * box_padding_;
531  }
532  if (add_ligatures_) {
533  // Make sure the output box files have ligatured text in case the font
534  // decided to use an unmapped glyph.
535  cluster_text = LigatureTable::Get()->AddLigatures(cluster_text, NULL);
536  }
537  BoxChar* boxchar = new BoxChar(cluster_text.c_str(), cluster_text.size());
538  boxchar->set_page(page_);
539  boxchar->AddBox(cluster_rect.x, cluster_rect.y,
540  cluster_rect.width, cluster_rect.height);
541  start_byte_to_box[start_byte_index] = boxchar;
542  } while (pango_layout_iter_next_cluster(cluster_iter));
543  pango_layout_iter_free(cluster_iter);
544 
545  // There is a subtle bug in the cluster text reported by the PangoLayoutIter
546  // on ligatured characters (eg. The word "Lam-Aliph" in arabic). To work
547  // around this, we use text reported using the PangoGlyphIter which is
548  // accurate.
549  // TODO(ranjith): Revisit whether this is still needed in newer versions of
550  // pango.
551  vector<string> cluster_text;
552  if (GetClusterStrings(&cluster_text)) {
553  ASSERT_HOST(cluster_text.size() == start_byte_to_box.size());
554  int ind = 0;
555  for (map<int, BoxChar*>::iterator it = start_byte_to_box.begin();
556  it != start_byte_to_box.end(); ++it, ++ind) {
557  it->second->mutable_ch()->swap(cluster_text[ind]);
558  }
559  }
560 
561  // Append to the boxchars list in byte order.
562  vector<BoxChar*> page_boxchars;
563  page_boxchars.reserve(start_byte_to_box.size());
564  string last_ch;
565  for (map<int, BoxChar*>::const_iterator it = start_byte_to_box.begin();
566  it != start_byte_to_box.end(); ++it) {
567  if (it->second->ch() == kWordJoinerUTF8) {
568  // Skip zero-width joiner characters (ZWJs) here.
569  delete it->second;
570  } else {
571  page_boxchars.push_back(it->second);
572  }
573  }
574  CorrectBoxPositionsToLayout(&page_boxchars);
575 
577  for (map<int, BoxChar*>::iterator it = start_byte_to_box.begin();
578  it != start_byte_to_box.end(); ++it) {
579  // Convert fullwidth Latin characters to their halfwidth forms.
580  string half(ConvertFullwidthLatinToBasicLatin(it->second->ch()));
581  it->second->mutable_ch()->swap(half);
582  }
583  }
584 
585  // Merge the character boxes into word boxes if we are rendering n-grams.
586  if (output_word_boxes_) {
587  MergeBoxCharsToWords(&page_boxchars);
588  }
589 
590  boxchars_.insert(boxchars_.end(), page_boxchars.begin(), page_boxchars.end());
591 
592  // Compute the page bounding box
593  Box* page_box = NULL;
594  Boxa* all_boxes = NULL;
595  for (int i = 0; i < page_boxchars.size(); ++i) {
596  if (page_boxchars[i]->box() == NULL) continue;
597  if (all_boxes == NULL)
598  all_boxes = boxaCreate(0);
599  boxaAddBox(all_boxes, page_boxchars[i]->mutable_box(), L_CLONE);
600  }
601  if (all_boxes != NULL) {
602  boxaGetExtent(all_boxes, NULL, NULL, &page_box);
603  boxaDestroy(&all_boxes);
604  if (page_boxes_ == NULL) page_boxes_ = boxaCreate(0);
605  boxaAddBox(page_boxes_, page_box, L_INSERT);
606  }
607 }
608 
609 
610 void StringRenderer::CorrectBoxPositionsToLayout(vector<BoxChar*>* boxchars) {
611  if (vertical_text_) {
612  const double rotation = - pango_gravity_to_rotation(
613  pango_context_get_base_gravity(pango_layout_get_context(layout_)));
616  0, boxchars->size(), boxchars);
617  } else {
619  }
620 }
621 
622 int StringRenderer::StripUnrenderableWords(string* utf8_text) const {
623  string output_text;
624  const char* text = utf8_text->c_str();
625  int offset = 0;
626  int num_dropped = 0;
627  while (offset < utf8_text->length()) {
628  int space_len = SpanUTF8Whitespace(text + offset);
629  output_text.append(text + offset, space_len);
630  offset += space_len;
631  if (offset == utf8_text->length()) break;
632 
633  int word_len = SpanUTF8NotWhitespace(text + offset);
634  if (font_.CanRenderString(text + offset, word_len)) {
635  output_text.append(text + offset, word_len);
636  } else {
637  ++num_dropped;
638  }
639  offset += word_len;
640  }
641  utf8_text->swap(output_text);
642 
643  if (num_dropped > 0) {
644  tprintf("Stripped %d unrenderable words\n", num_dropped);
645  }
646  return num_dropped;
647 }
648 
649 int StringRenderer::RenderToGrayscaleImage(const char* text, int text_length,
650  Pix** pix) {
651  Pix *orig_pix = NULL;
652  int offset = RenderToImage(text, text_length, &orig_pix);
653  if (orig_pix) {
654  *pix = pixConvertTo8(orig_pix, false);
655  pixDestroy(&orig_pix);
656  }
657  return offset;
658 }
659 
660 int StringRenderer::RenderToBinaryImage(const char* text, int text_length,
661  int threshold, Pix** pix) {
662  Pix *orig_pix = NULL;
663  int offset = RenderToImage(text, text_length, &orig_pix);
664  if (orig_pix) {
665  Pix* gray_pix = pixConvertTo8(orig_pix, false);
666  pixDestroy(&orig_pix);
667  *pix = pixThresholdToBinary(gray_pix, threshold);
668  pixDestroy(&gray_pix);
669  } else {
670  *pix = orig_pix;
671  }
672  return offset;
673 }
674 
675 // Add word joiner (WJ) characters between adjacent non-space characters except
676 // immediately before a combiner.
677 /* static */
678 string StringRenderer::InsertWordJoiners(const string& text) {
679  string out_str;
680  const UNICHAR::const_iterator it_end = UNICHAR::end(text.c_str(),
681  text.length());
682  for (UNICHAR::const_iterator it = UNICHAR::begin(text.c_str(), text.length());
683  it != it_end; ++it) {
684  // Add the symbol to the output string.
685  out_str.append(it.utf8_data(), it.utf8_len());
686  // Check the next symbol.
687  UNICHAR::const_iterator next_it = it;
688  ++next_it;
689  bool next_char_is_boundary = (next_it == it_end || *next_it == ' ');
690  bool next_char_is_combiner = (next_it == it_end) ?
691  false : IsCombiner(*next_it);
692  if (*it != ' ' && *it != '\n' && !next_char_is_boundary &&
693  !next_char_is_combiner) {
694  out_str += kWordJoinerUTF8;
695  }
696  }
697  return out_str;
698 }
699 
700 // Convert halfwidth Basic Latin characters to their fullwidth forms.
702  string full_str;
703  const UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(),
704  str.length());
705  for (UNICHAR::const_iterator it = UNICHAR::begin(str.c_str(), str.length());
706  it != it_end; ++it) {
707  // Convert printable and non-space 7-bit ASCII characters to
708  // their fullwidth forms.
709  if (IsInterchangeValid7BitAscii(*it) && isprint(*it) && !isspace(*it)) {
710  // Convert by adding 0xFEE0 to the codepoint of 7-bit ASCII.
711  char32 full_char = *it + 0xFEE0;
712  full_str.append(EncodeAsUTF8(full_char));
713  } else {
714  full_str.append(it.utf8_data(), it.utf8_len());
715  }
716  }
717  return full_str;
718 }
719 
720 // Convert fullwidth Latin characters to their halfwidth forms.
722  string half_str;
723  UNICHAR::const_iterator it_end = UNICHAR::end(str.c_str(), str.length());
724  for (UNICHAR::const_iterator it = UNICHAR::begin(str.c_str(), str.length());
725  it != it_end; ++it) {
726  char32 half_char = FullwidthToHalfwidth(*it);
727  // Convert fullwidth Latin characters to their halfwidth forms
728  // only if halfwidth forms are printable and non-space 7-bit ASCII.
729  if (IsInterchangeValid7BitAscii(half_char) &&
730  isprint(half_char) && !isspace(half_char)) {
731  half_str.append(EncodeAsUTF8(half_char));
732  } else {
733  half_str.append(it.utf8_data(), it.utf8_len());
734  }
735  }
736  return half_str;
737 }
738 
739 // Returns offset to end of text substring rendered in this method.
740 int StringRenderer::RenderToImage(const char* text, int text_length,
741  Pix** pix) {
742  if (pix && *pix) pixDestroy(pix);
743  InitPangoCairo();
744 
745  const int page_offset = FindFirstPageBreakOffset(text, text_length);
746  if (!page_offset) {
747  return 0;
748  }
749  start_box_ = boxchars_.size();
750 
751  if (!vertical_text_) {
752  // Translate by the specified margin
753  cairo_translate(cr_, h_margin_, v_margin_);
754  } else {
755  // Vertical text rendering is achieved by a two-step process of first
756  // performing regular horizontal layout with character orientation set to
757  // EAST, and then translating and rotating the layout before rendering onto
758  // the desired image surface. The settings required for the former step are
759  // done within InitPangoCairo().
760  //
761  // Translate to the top-right margin of page
762  cairo_translate(cr_, page_width_ - h_margin_, v_margin_);
763  // Rotate the layout
764  double rotation = - pango_gravity_to_rotation(
765  pango_context_get_base_gravity(pango_layout_get_context(layout_)));
766  tlog(2, "Rotating by %f radians\n", rotation);
767  cairo_rotate(cr_, rotation);
768  pango_cairo_update_layout(cr_, layout_);
769  }
770  string page_text(text, page_offset);
772  // Convert Basic Latin to their fullwidth forms.
773  page_text = ConvertBasicLatinToFullwidthLatin(page_text);
774  }
776  StripUnrenderableWords(&page_text);
777  }
778  if (drop_uncovered_chars_ &&
779  !font_.CoversUTF8Text(page_text.c_str(), page_text.length())) {
780  int num_dropped = font_.DropUncoveredChars(&page_text);
781  if (num_dropped) {
782  tprintf("WARNING: Dropped %d uncovered characters\n", num_dropped);
783  }
784  }
785  if (add_ligatures_) {
786  // Add ligatures wherever possible, including custom ligatures.
787  page_text = LigatureTable::Get()->AddLigatures(page_text, &font_);
788  }
789  if (underline_start_prob_ > 0) {
790  SetWordUnderlineAttributes(page_text);
791  }
792 
793  pango_layout_set_text(layout_, page_text.c_str(), page_text.length());
794 
795  if (pix) {
796  // Set a white background for the target image surface.
797  cairo_set_source_rgb(cr_, 1.0, 1.0, 1.0); // sets drawing colour to white
798  // Fill the surface with the active colour (if you don't do this, you will
799  // be given a surface with a transparent background to draw on)
800  cairo_paint(cr_);
801  // Set the ink color to black
802  cairo_set_source_rgb(cr_, pen_color_[0], pen_color_[1], pen_color_[2]);
803  // If the target surface or transformation properties of the cairo instance
804  // have changed, update the pango layout to reflect this
805  pango_cairo_update_layout(cr_, layout_);
806  {
807  DISABLE_HEAP_LEAK_CHECK; // for Fontconfig
808  // Draw the pango layout onto the cairo surface
809  pango_cairo_show_layout(cr_, layout_);
810  }
812  }
814  FreePangoCairo();
815  // Update internal state variables.
816  ++page_;
817  return page_offset;
818 }
819 
820 // Render a string to an image, returning it as an 8 bit pix. Behaves as
821 // RenderString, except that it ignores the font set at construction and works
822 // through all the fonts, returning 0 until they are exhausted, at which point
823 // it returns the value it should have returned all along, but no pix this time.
824 // Fonts that don't contain a given proportion of the characters in the string
825 // get skipped.
826 // Fonts that work each get rendered and the font name gets added
827 // to the image.
828 // NOTE that no boxes are produced by this function.
829 //
830 // Example usage: To render a null terminated char-array "txt"
831 //
832 // int offset = 0;
833 // do {
834 // Pix *pix;
835 // offset += renderer.RenderAllFontsToImage(min_proportion, txt + offset,
836 // strlen(txt + offset), NULL, &pix);
837 // ...
838 // } while (offset < strlen(text));
839 //
841  const char* text, int text_length,
842  string* font_used, Pix** image) {
843  *image = NULL;
844  // Select a suitable font to render the title with.
845  const char kTitleTemplate[] = "%s : %d hits = %.2f%%, raw = %d = %.2f%%";
846  string title_font;
847  if (!FontUtils::SelectFont(kTitleTemplate, strlen(kTitleTemplate),
848  &title_font, NULL)) {
849  tprintf("WARNING: Could not find a font to render image title with!\n");
850  title_font = "Arial";
851  }
852  title_font += " 8";
853  tlog(1, "Selected title font: %s\n", title_font.c_str());
854  if (font_used) font_used->clear();
855 
856  string orig_font = font_.DescriptionName();
857  if (char_map_.empty()) {
858  total_chars_ = 0;
859  // Fill the hash table and use that for computing which fonts to use.
860  for (UNICHAR::const_iterator it = UNICHAR::begin(text, text_length);
861  it != UNICHAR::end(text, text_length); ++it) {
862  ++total_chars_;
863  ++char_map_[*it];
864  }
865  tprintf("Total chars = %d\n", total_chars_);
866  }
867  const vector<string>& all_fonts = FontUtils::ListAvailableFonts();
868  for (int i = font_index_; i < all_fonts.size(); ++i) {
869  ++font_index_;
870  int raw_score = 0;
871  int ok_chars = FontUtils::FontScore(char_map_, all_fonts[i], &raw_score,
872  NULL);
873  if (ok_chars > 0 && ok_chars >= total_chars_ * min_coverage) {
874  set_font(all_fonts[i]);
875  int offset = RenderToBinaryImage(text, text_length, 128, image);
876  ClearBoxes(); // Get rid of them as they are garbage.
877  const int kMaxTitleLength = 1024;
878  char title[kMaxTitleLength];
879  snprintf(title, kMaxTitleLength, kTitleTemplate,
880  all_fonts[i].c_str(), ok_chars,
881  100.0 * ok_chars / total_chars_, raw_score,
882  100.0 * raw_score / char_map_.size());
883  tprintf("%s\n", title);
884  // This is a good font! Store the offset to return once we've tried all
885  // the fonts.
886  if (offset) {
887  last_offset_ = offset;
888  if (font_used) *font_used = all_fonts[i];
889  }
890  // Add the font to the image.
891  set_font(title_font);
892  v_margin_ /= 8;
893  Pix* title_image = NULL;
894  RenderToBinaryImage(title, strlen(title), 128, &title_image);
895  pixOr(*image, *image, title_image);
896  pixDestroy(&title_image);
897 
898  v_margin_ *= 8;
899  set_font(orig_font);
900  // We return the real offset only after cycling through the list of fonts.
901  return 0;
902  } else {
903  tprintf("Font %s failed with %d hits = %.2f%%\n",
904  all_fonts[i].c_str(), ok_chars, 100.0 * ok_chars / total_chars_);
905  }
906  }
907  font_index_ = 0;
908  char_map_.clear();
909  return last_offset_ == 0 ? -1 : last_offset_;
910 }
911 
912 } // namespace tesseract
static string ConvertBasicLatinToFullwidthLatin(const string &text)
static void TranslateBoxes(int xshift, int yshift, vector< BoxChar *> *boxes)
Definition: boxchar.cpp:52
bool CanRenderString(const char *utf8_word, int len, std::vector< string > *graphemes) const
bool ParseFontDescriptionName(const string &name)
TessHashMap< char32, inT64 > char_map_
const char * utf8_data() const
Definition: unichar.h:130
std::vector< BoxChar * > boxchars_
#define tlog(level,...)
Definition: tlog.h:33
int RenderToBinaryImage(const char *text, int text_length, int threshold, Pix **pix)
void set_underline_continuation_prob(const double frac)
void AddBox(int x, int y, int width, int height)
Definition: boxchar.cpp:47
int StripUnrenderableWords(string *utf8_text) const
bool CoversUTF8Text(const char *utf8_text, int byte_length) const
void set_resolution(const int resolution)
bool IsUTF8Whitespace(const char *text)
Definition: normstrngs.cpp:182
int SpanUTF8NotWhitespace(const char *text)
Definition: normstrngs.cpp:197
static int FontScore(const TessHashMap< char32, inT64 > &ch_map, const string &fontname, int *raw_score, std::vector< bool > *ch_flags)
StringRenderer(const string &font_desc, int page_width, int page_height)
int RenderToGrayscaleImage(const char *text, int text_length, Pix **pix)
static const_iterator end(const char *utf8_str, const int byte_length)
Definition: unichar.cpp:204
bool IsInterchangeValid7BitAscii(const char32 ch)
Definition: normstrngs.cpp:232
int RenderAllFontsToImage(double min_coverage, const char *text, int text_length, string *font_used, Pix **pix)
string AddLigatures(const string &str, const PangoFontInfo *font) const
int DropUncoveredChars(string *utf8_text) const
static string GetTesseractBoxStr(int height, const vector< BoxChar *> &boxes)
Definition: boxchar.cpp:300
int RenderToImage(const char *text, int text_length, Pix **pix)
#define ASSERT_HOST_MSG(x,...)
Definition: errcode.h:90
static const_iterator begin(const char *utf8_str, const int byte_length)
Definition: unichar.cpp:200
int FindFirstPageBreakOffset(const char *text, int text_length)
static bool SelectFont(const char *utf8_word, const int utf8_len, string *font_name, std::vector< string > *graphemes)
static string InsertWordJoiners(const string &text)
static string ConvertFullwidthLatinToBasicLatin(const string &text)
int SpanUTF8Whitespace(const char *text)
Definition: normstrngs.cpp:186
static void PrepareToWrite(vector< BoxChar *> *boxes)
Definition: boxchar.cpp:66
const std::vector< BoxChar * > & GetBoxes() const
#define tprintf(...)
Definition: tprintf.h:31
cairo_surface_t * surface_
void RotatePageBoxes(float rotation)
static void WriteTesseractBoxFile(const string &name, int height, const vector< BoxChar *> &boxes)
Definition: boxchar.cpp:293
void CorrectBoxPositionsToLayout(std::vector< BoxChar *> *boxchars)
bool GetClusterStrings(std::vector< string > *cluster_text)
PangoUnderline underline_style_
char32 FullwidthToHalfwidth(const char32 ch)
Definition: normstrngs.cpp:239
void set_underline_start_prob(const double frac)
void set_features(const char *features)
static void RotateBoxes(float rotation, int xcenter, int ycenter, int start_box, int end_box, vector< BoxChar *> *boxes)
Definition: boxchar.cpp:272
void WriteAllBoxes(const string &filename)
bool set_font(const string &desc)
void set_page(int page)
Definition: boxchar.h:55
Pix * CairoARGB32ToPixFormat(cairo_surface_t *surface)
void set_resolution(const int resolution)
static LigatureTable * Get()
#define ASSERT_HOST(x)
Definition: errcode.h:84
signed int char32
Definition: normstrngs.h:27
static const std::vector< string > & ListAvailableFonts()
#define DISABLE_HEAP_LEAK_CHECK
Definition: util.h:63
void SetWordUnderlineAttributes(const string &page_text)