30 #include "allheaders.h" 34 #include "pango/pango-font.h" 35 #include "pango/pango-glyph-item.h" 38 #include "unicode/uchar.h" 41 #ifdef USE_STD_NAMESPACE 50 static const int kDefaultOutputResolution = 300;
55 static const char* kWordJoinerUTF8 =
"\xE2\x81\xA0";
56 static const char32 kWordJoiner = 0x2060;
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));
65 static string EncodeAsUTF8(
const char32 ch32) {
67 return string(uni_ch.utf8(), uni_ch.utf8_len());
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;
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));
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);
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));
99 : page_width_(page_width),
100 page_height_(page_height),
105 vertical_text_(false),
106 gravity_hint_strong_(false),
107 render_fullwidth_latin_(false),
108 underline_start_prob_(0),
109 underline_continuation_prob_(0),
110 underline_style_(PANGO_UNDERLINE_SINGLE),
112 drop_uncovered_chars_(true),
113 strip_unrenderable_words_(false),
114 add_ligatures_(false),
115 output_word_boxes_(false),
169 PangoContext* context = pango_layout_get_context(
layout_);
170 pango_context_set_base_gravity(context, PANGO_GRAVITY_EAST);
172 pango_context_set_gravity_hint(context, PANGO_GRAVITY_HINT_STRONG);
174 pango_layout_context_changed(
layout_);
183 PangoFontDescription *desc =
184 pango_font_description_from_string(font_desc.c_str());
186 pango_layout_set_font_description(
layout_, desc);
187 pango_font_description_free(desc);
188 pango_cairo_context_set_resolution(pango_layout_get_context(
layout_),
193 tlog(3,
"max_width = %d, max_height = %d\n", max_width, max_height);
195 swap(max_width, max_height);
197 pango_layout_set_width(
layout_, max_width * PANGO_SCALE);
198 pango_layout_set_wrap(
layout_, PANGO_WRAP_WORD);
201 PangoAttrList* attr_list = pango_attr_list_new();
203 PangoAttribute* spacing_attr = pango_attr_letter_spacing_new(
205 spacing_attr->start_index = 0;
206 spacing_attr->end_index =
static_cast<guint
>(-1);
207 pango_attr_list_change(attr_list, spacing_attr);
209 #if (PANGO_VERSION_MAJOR == 1 && PANGO_VERSION_MINOR >= 38) 212 PangoAttribute* feature_attr = pango_attr_font_features_new(
features_);
213 pango_attr_list_change(attr_list, feature_attr);
216 pango_layout_set_attributes(
layout_, attr_list);
217 pango_attr_list_unref(attr_list);
241 PangoAttrList* attr_list = pango_layout_get_attributes(
layout_);
243 const char* text = page_text.c_str();
246 bool started_underline =
false;
247 PangoAttribute* und_attr = NULL;
249 while (offset < page_text.length()) {
251 if (offset == page_text.length())
break;
253 int word_start = offset;
256 if (started_underline) {
260 und_attr->end_index = word_start + word_len;
264 pango_attr_list_insert(attr_list, und_attr);
265 started_underline =
false;
272 und_attr->start_index = word_start;
273 und_attr->end_index = word_start + word_len;
274 started_underline =
true;
278 if (started_underline) {
279 und_attr->end_index = page_text.length();
280 pango_attr_list_insert(attr_list, und_attr);
287 if (!text_length)
return 0;
290 const int max_layout_height =
vertical_text_ ? max_width : max_height;
294 const int kMaxUnicodeBufLength = 15000;
295 for (
int i = 0; i < kMaxUnicodeBufLength && it != it_end; ++it, ++i);
297 tlog(1,
"len = %d buf_len = %d\n", text_length, buf_length);
298 pango_layout_set_text(
layout_, text, buf_length);
300 PangoLayoutIter* line_iter = NULL;
303 line_iter = pango_layout_get_iter(
layout_);
305 bool first_page =
true;
307 int offset = buf_length;
310 PangoRectangle line_ink_rect;
311 pango_layout_iter_get_line_extents(line_iter, &line_ink_rect, NULL);
312 pango_extents_to_pixels(&line_ink_rect, NULL);
313 PangoLayoutLine* line = pango_layout_iter_get_line_readonly(line_iter);
315 page_top = line_ink_rect.y;
318 int line_bottom = line_ink_rect.y + line_ink_rect.height;
319 if (line_bottom - page_top > max_layout_height) {
320 offset = line->start_index;
321 tlog(1,
"Found offset = %d\n", offset);
324 }
while (pango_layout_iter_next_line(line_iter));
325 pango_layout_iter_free(line_iter);
344 for (
int i = 0; i <
boxchars_.size(); ++i)
362 map<int, string> start_byte_to_text;
363 PangoLayoutIter* run_iter = pango_layout_get_iter(
layout_);
364 const char* full_text = pango_layout_get_text(
layout_);
366 PangoLayoutRun* run = pango_layout_iter_get_run_readonly(run_iter);
369 tlog(2,
"Found end of line marker\n");
372 PangoGlyphItemIter cluster_iter;
373 gboolean have_cluster;
374 for (have_cluster = pango_glyph_item_iter_init_start(&cluster_iter,
377 have_cluster = pango_glyph_item_iter_next_cluster(&cluster_iter)) {
378 const int start_byte_index = cluster_iter.start_index;
379 const int end_byte_index = cluster_iter.end_index;
380 string text = string(full_text + start_byte_index,
381 end_byte_index - start_byte_index);
383 tlog(2,
"Found whitespace\n");
386 tlog(2,
"start_byte=%d end_byte=%d : '%s'\n", start_byte_index,
387 end_byte_index, text.c_str());
393 start_byte_to_text[start_byte_index] = text;
395 }
while (pango_layout_iter_next_run(run_iter));
396 pango_layout_iter_free(run_iter);
398 cluster_text->clear();
399 for (map<int, string>::const_iterator it = start_byte_to_text.begin();
400 it != start_byte_to_text.end(); ++it) {
401 cluster_text->push_back(it->second);
403 return !cluster_text->empty();
416 static void MergeBoxCharsToWords(vector<BoxChar*>* boxchars) {
417 vector<BoxChar*> result;
418 bool started_word =
false;
419 for (
int i = 0; i < boxchars->size(); ++i) {
420 if (boxchars->at(i)->ch() ==
" " ||
421 boxchars->at(i)->box() == NULL) {
422 result.push_back(boxchars->at(i));
423 boxchars->at(i) = NULL;
424 started_word =
false;
431 result.push_back(boxchars->at(i));
432 boxchars->at(i) = NULL;
434 BoxChar* last_boxchar = result.back();
436 const Box* box = boxchars->at(i)->box();
437 Box* last_box = last_boxchar->mutable_box();
438 int left = min(last_box->x, box->x);
439 int right = max(last_box->x + last_box->w, box->x + box->w);
440 int top = min(last_box->y, box->y);
441 int bottom = max(last_box->y + last_box->h, box->y + box->h);
445 if (right - left > last_box->w + 5 * box->w) {
446 tlog(1,
"Found line break after '%s'", last_boxchar->ch().c_str());
449 result.push_back(
new BoxChar(
" ", 1));
450 result.push_back(boxchars->at(i));
451 boxchars->at(i) = NULL;
455 last_boxchar->mutable_ch()->append(boxchars->at(i)->ch());
457 last_box->w = right - left;
459 last_box->h = bottom - top;
460 delete boxchars->at(i);
461 boxchars->at(i) = NULL;
464 boxchars->swap(result);
469 const char* text = pango_layout_get_text(
layout_);
470 PangoLayoutIter* cluster_iter = pango_layout_get_iter(
layout_);
473 vector<int> cluster_start_indices;
475 cluster_start_indices.push_back(pango_layout_iter_get_index(cluster_iter));
476 tlog(3,
"Added %d\n", cluster_start_indices.back());
477 }
while (pango_layout_iter_next_cluster(cluster_iter));
478 pango_layout_iter_free(cluster_iter);
479 cluster_start_indices.push_back(strlen(text));
480 tlog(3,
"Added last index %d\n", cluster_start_indices.back());
482 sort(cluster_start_indices.begin(), cluster_start_indices.end());
483 map<int, int> cluster_start_to_end_index;
484 for (
int i = 0; i < cluster_start_indices.size() - 1; ++i) {
485 cluster_start_to_end_index[cluster_start_indices[i]]
486 = cluster_start_indices[i + 1];
491 cluster_iter = pango_layout_get_iter(
layout_);
493 map<int, BoxChar*> start_byte_to_box;
495 PangoRectangle cluster_rect;
496 pango_layout_iter_get_cluster_extents(cluster_iter, &cluster_rect,
498 pango_extents_to_pixels(&cluster_rect, NULL);
499 const int start_byte_index = pango_layout_iter_get_index(cluster_iter);
500 const int end_byte_index = cluster_start_to_end_index[start_byte_index];
501 string cluster_text = string(text + start_byte_index,
502 end_byte_index - start_byte_index);
503 if (!cluster_text.empty() && cluster_text[0] ==
'\n') {
504 tlog(2,
"Skipping newlines at start of text.\n");
507 if (!cluster_rect.width || !cluster_rect.height ||
509 tlog(2,
"Skipping whitespace with boxdim (%d,%d) '%s'\n",
510 cluster_rect.width, cluster_rect.height, cluster_text.c_str());
512 boxchar->set_page(
page_);
513 start_byte_to_box[start_byte_index] = boxchar;
517 tlog(2,
"[%d %d], %d, %d : start_byte=%d end_byte=%d : '%s'\n",
518 cluster_rect.x, cluster_rect.y,
519 cluster_rect.width, cluster_rect.height,
520 start_byte_index, end_byte_index,
521 cluster_text.c_str());
523 "cluster_text:%s start_byte_index:%d\n",
524 cluster_text.c_str(), start_byte_index);
526 "cluster_text:%s start_byte_index:%d\n",
527 cluster_text.c_str(), start_byte_index);
539 BoxChar* boxchar =
new BoxChar(cluster_text.c_str(), cluster_text.size());
541 boxchar->
AddBox(cluster_rect.x, cluster_rect.y,
542 cluster_rect.width, cluster_rect.height);
543 start_byte_to_box[start_byte_index] = boxchar;
544 }
while (pango_layout_iter_next_cluster(cluster_iter));
545 pango_layout_iter_free(cluster_iter);
553 vector<string> cluster_text;
555 ASSERT_HOST(cluster_text.size() == start_byte_to_box.size());
557 for (map<int, BoxChar*>::iterator it = start_byte_to_box.begin();
558 it != start_byte_to_box.end(); ++it, ++ind) {
559 it->second->mutable_ch()->swap(cluster_text[ind]);
564 vector<BoxChar*> page_boxchars;
565 page_boxchars.reserve(start_byte_to_box.size());
567 for (map<int, BoxChar*>::const_iterator it = start_byte_to_box.begin();
568 it != start_byte_to_box.end(); ++it) {
569 if (it->second->ch() == kWordJoinerUTF8) {
573 page_boxchars.push_back(it->second);
579 for (map<int, BoxChar*>::iterator it = start_byte_to_box.begin();
580 it != start_byte_to_box.end(); ++it) {
583 it->second->mutable_ch()->swap(half);
589 MergeBoxCharsToWords(&page_boxchars);
595 Box* page_box = NULL;
596 Boxa* all_boxes = NULL;
597 for (
int i = 0; i < page_boxchars.size(); ++i) {
598 if (page_boxchars[i]->box() == NULL)
continue;
599 if (all_boxes == NULL)
600 all_boxes = boxaCreate(0);
601 boxaAddBox(all_boxes, page_boxchars[i]->mutable_box(), L_CLONE);
603 if (all_boxes != NULL) {
604 boxaGetExtent(all_boxes, NULL, NULL, &page_box);
605 boxaDestroy(&all_boxes);
614 const double rotation = - pango_gravity_to_rotation(
615 pango_context_get_base_gravity(pango_layout_get_context(
layout_)));
618 0, boxchars->size(), boxchars);
626 const char* text = utf8_text->c_str();
629 while (offset < utf8_text->length()) {
631 output_text.append(text + offset, space_len);
633 if (offset == utf8_text->length())
break;
637 output_text.append(text + offset, word_len);
643 utf8_text->swap(output_text);
645 if (num_dropped > 0) {
646 tprintf(
"Stripped %d unrenderable words\n", num_dropped);
653 Pix *orig_pix = NULL;
656 *pix = pixConvertTo8(orig_pix,
false);
657 pixDestroy(&orig_pix);
663 int threshold, Pix** pix) {
664 Pix *orig_pix = NULL;
667 Pix* gray_pix = pixConvertTo8(orig_pix,
false);
668 pixDestroy(&orig_pix);
669 *pix = pixThresholdToBinary(gray_pix, threshold);
670 pixDestroy(&gray_pix);
685 it != it_end; ++it) {
687 out_str.append(it.utf8_data(), it.utf8_len());
691 bool next_char_is_boundary = (next_it == it_end || *next_it ==
' ');
692 bool next_char_is_combiner = (next_it == it_end) ?
693 false : IsCombiner(*next_it);
694 if (*it !=
' ' && *it !=
'\n' && !next_char_is_boundary &&
695 !next_char_is_combiner) {
696 out_str += kWordJoinerUTF8;
708 it != it_end; ++it) {
713 char32 full_char = *it + 0xFEE0;
714 full_str.append(EncodeAsUTF8(full_char));
716 full_str.append(it.utf8_data(), it.utf8_len());
727 it != it_end; ++it) {
732 isprint(half_char) && !isspace(half_char)) {
733 half_str.append(EncodeAsUTF8(half_char));
735 half_str.append(it.utf8_data(), it.utf8_len());
744 if (pix && *pix) pixDestroy(pix);
766 double rotation = - pango_gravity_to_rotation(
767 pango_context_get_base_gravity(pango_layout_get_context(
layout_)));
768 tlog(2,
"Rotating by %f radians\n", rotation);
769 cairo_rotate(
cr_, rotation);
772 string page_text(text, page_offset);
784 tprintf(
"WARNING: Dropped %d uncovered characters\n", num_dropped);
795 pango_layout_set_text(
layout_, page_text.c_str(), page_text.length());
799 cairo_set_source_rgb(
cr_, 1.0, 1.0, 1.0);
843 const char* text,
int text_length,
844 string* font_used, Pix** image) {
847 const char kTitleTemplate[] =
"%s : %d hits = %.2f%%, raw = %d = %.2f%%";
850 &title_font, NULL)) {
851 tprintf(
"WARNING: Could not find a font to render image title with!\n");
852 title_font =
"Arial";
855 tlog(1,
"Selected title font: %s\n", title_font.c_str());
856 if (font_used) font_used->clear();
870 for (
int i =
font_index_; i < all_fonts.size(); ++i) {
875 if (ok_chars > 0 && ok_chars >=
total_chars_ * min_coverage) {
879 const int kMaxTitleLength = 1024;
880 char title[kMaxTitleLength];
881 snprintf(title, kMaxTitleLength, kTitleTemplate,
882 all_fonts[i].c_str(), ok_chars,
890 if (font_used) *font_used = all_fonts[i];
895 Pix* title_image = NULL;
897 pixOr(*image, *image, title_image);
898 pixDestroy(&title_image);
905 tprintf(
"Font %s failed with %d hits = %.2f%%\n",
906 all_fonts[i].c_str(), ok_chars, 100.0 * ok_chars /
total_chars_);
static string ConvertBasicLatinToFullwidthLatin(const string &text)
double underline_continuation_prob_
void SetLayoutProperties()
static void TranslateBoxes(int xshift, int yshift, vector< BoxChar *> *boxes)
bool strip_unrenderable_words_
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
std::vector< BoxChar * > boxchars_
bool gravity_hint_strong_
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)
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)
int SpanUTF8NotWhitespace(const char *text)
bool render_fullwidth_latin_
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)
bool IsInterchangeValid7BitAscii(const char32 ch)
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)
int RenderToImage(const char *text, int text_length, Pix **pix)
double underline_start_prob_
#define ASSERT_HOST_MSG(x,...)
static const_iterator begin(const char *utf8_str, const int byte_length)
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)
static void PrepareToWrite(vector< BoxChar *> *boxes)
const std::vector< BoxChar * > & GetBoxes() const
Boxa * GetPageBoxes() const
cairo_surface_t * surface_
void RotatePageBoxes(float rotation)
static void WriteTesseractBoxFile(const string &name, int height, const vector< BoxChar *> &boxes)
void CorrectBoxPositionsToLayout(std::vector< BoxChar *> *boxchars)
bool drop_uncovered_chars_
bool GetClusterStrings(std::vector< string > *cluster_text)
PangoUnderline underline_style_
char32 FullwidthToHalfwidth(const char32 ch)
void set_underline_start_prob(const double frac)
string DescriptionName() const
void set_features(const char *features)
static void RotateBoxes(float rotation, int xcenter, int ycenter, int start_box, int end_box, vector< BoxChar *> *boxes)
void ComputeClusterBoxes()
void WriteAllBoxes(const string &filename)
bool set_font(const string &desc)
Pix * CairoARGB32ToPixFormat(cairo_surface_t *surface)
void set_resolution(const int resolution)
static LigatureTable * Get()
static const std::vector< string > & ListAvailableFonts()
#define DISABLE_HEAP_LEAK_CHECK
void SetWordUnderlineAttributes(const string &page_text)