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),
103 pen_color_{0.0, 0.0, 0.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),
113 drop_uncovered_chars_(
true),
114 strip_unrenderable_words_(
false),
115 add_ligatures_(
false),
116 output_word_boxes_(
false),
128 set_resolution(kDefaultOutputResolution);
167 PangoContext* context = pango_layout_get_context(
layout_);
168 pango_context_set_base_gravity(context, PANGO_GRAVITY_EAST);
170 pango_context_set_gravity_hint(context, PANGO_GRAVITY_HINT_STRONG);
172 pango_layout_context_changed(
layout_);
181 PangoFontDescription *desc =
182 pango_font_description_from_string(font_desc.c_str());
184 pango_layout_set_font_description(
layout_, desc);
185 pango_font_description_free(desc);
186 pango_cairo_context_set_resolution(pango_layout_get_context(
layout_),
191 tlog(3,
"max_width = %d, max_height = %d\n", max_width, max_height);
193 swap(max_width, max_height);
195 pango_layout_set_width(
layout_, max_width * PANGO_SCALE);
196 pango_layout_set_wrap(
layout_, PANGO_WRAP_WORD);
199 PangoAttrList* attr_list = pango_attr_list_new();
201 PangoAttribute* spacing_attr = pango_attr_letter_spacing_new(
203 spacing_attr->start_index = 0;
204 spacing_attr->end_index =
static_cast<guint
>(-1);
205 pango_attr_list_change(attr_list, spacing_attr);
207 #if (PANGO_VERSION_MAJOR == 1 && PANGO_VERSION_MINOR >= 38) 210 PangoAttribute* feature_attr = pango_attr_font_features_new(
features_);
211 pango_attr_list_change(attr_list, feature_attr);
214 pango_layout_set_attributes(
layout_, attr_list);
215 pango_attr_list_unref(attr_list);
239 PangoAttrList* attr_list = pango_layout_get_attributes(
layout_);
241 const char* text = page_text.c_str();
244 bool started_underline =
false;
245 PangoAttribute* und_attr = NULL;
247 while (offset < page_text.length()) {
249 if (offset == page_text.length())
break;
251 int word_start = offset;
254 if (started_underline) {
258 und_attr->end_index = word_start + word_len;
262 pango_attr_list_insert(attr_list, und_attr);
263 started_underline =
false;
270 und_attr->start_index = word_start;
271 und_attr->end_index = word_start + word_len;
272 started_underline =
true;
276 if (started_underline) {
277 und_attr->end_index = page_text.length();
278 pango_attr_list_insert(attr_list, und_attr);
285 if (!text_length)
return 0;
288 const int max_layout_height =
vertical_text_ ? max_width : max_height;
292 const int kMaxUnicodeBufLength = 15000;
293 for (
int i = 0; i < kMaxUnicodeBufLength && it != it_end; ++it, ++i);
295 tlog(1,
"len = %d buf_len = %d\n", text_length, buf_length);
296 pango_layout_set_text(
layout_, text, buf_length);
298 PangoLayoutIter* line_iter = NULL;
301 line_iter = pango_layout_get_iter(
layout_);
303 bool first_page =
true;
305 int offset = buf_length;
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);
313 page_top = line_ink_rect.y;
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);
322 }
while (pango_layout_iter_next_line(line_iter));
323 pango_layout_iter_free(line_iter);
342 for (
int i = 0; i <
boxchars_.size(); ++i)
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_);
364 PangoLayoutRun* run = pango_layout_iter_get_run_readonly(run_iter);
367 tlog(2,
"Found end of line marker\n");
370 PangoGlyphItemIter cluster_iter;
371 gboolean have_cluster;
372 for (have_cluster = pango_glyph_item_iter_init_start(&cluster_iter,
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);
381 tlog(2,
"Found whitespace\n");
384 tlog(2,
"start_byte=%d end_byte=%d : '%s'\n", start_byte_index,
385 end_byte_index, text.c_str());
391 start_byte_to_text[start_byte_index] = text;
393 }
while (pango_layout_iter_next_run(run_iter));
394 pango_layout_iter_free(run_iter);
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);
401 return !cluster_text->empty();
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;
429 result.push_back(boxchars->at(i));
430 boxchars->at(i) = NULL;
432 BoxChar* last_boxchar = result.back();
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);
443 if (right - left > last_box->w + 5 * box->w) {
444 tlog(1,
"Found line break after '%s'", last_boxchar->ch().c_str());
447 result.push_back(
new BoxChar(
" ", 1));
448 result.push_back(boxchars->at(i));
449 boxchars->at(i) = NULL;
453 last_boxchar->mutable_ch()->append(boxchars->at(i)->ch());
455 last_box->w = right - left;
457 last_box->h = bottom - top;
458 delete boxchars->at(i);
459 boxchars->at(i) = NULL;
462 boxchars->swap(result);
467 const char* text = pango_layout_get_text(
layout_);
468 PangoLayoutIter* cluster_iter = pango_layout_get_iter(
layout_);
471 vector<int> cluster_start_indices;
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());
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];
489 cluster_iter = pango_layout_get_iter(
layout_);
491 map<int, BoxChar*> start_byte_to_box;
493 PangoRectangle cluster_rect;
494 pango_layout_iter_get_cluster_extents(cluster_iter, &cluster_rect,
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");
505 if (!cluster_rect.width || !cluster_rect.height ||
507 tlog(2,
"Skipping whitespace with boxdim (%d,%d) '%s'\n",
508 cluster_rect.width, cluster_rect.height, cluster_text.c_str());
510 boxchar->set_page(
page_);
511 start_byte_to_box[start_byte_index] = boxchar;
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());
521 "cluster_text:%s start_byte_index:%d\n",
522 cluster_text.c_str(), start_byte_index);
524 "cluster_text:%s start_byte_index:%d\n",
525 cluster_text.c_str(), start_byte_index);
537 BoxChar* boxchar =
new BoxChar(cluster_text.c_str(), cluster_text.size());
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);
551 vector<string> cluster_text;
553 ASSERT_HOST(cluster_text.size() == start_byte_to_box.size());
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]);
562 vector<BoxChar*> page_boxchars;
563 page_boxchars.reserve(start_byte_to_box.size());
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) {
571 page_boxchars.push_back(it->second);
577 for (map<int, BoxChar*>::iterator it = start_byte_to_box.begin();
578 it != start_byte_to_box.end(); ++it) {
581 it->second->mutable_ch()->swap(half);
587 MergeBoxCharsToWords(&page_boxchars);
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);
601 if (all_boxes != NULL) {
602 boxaGetExtent(all_boxes, NULL, NULL, &page_box);
603 boxaDestroy(&all_boxes);
612 const double rotation = - pango_gravity_to_rotation(
613 pango_context_get_base_gravity(pango_layout_get_context(
layout_)));
616 0, boxchars->size(), boxchars);
624 const char* text = utf8_text->c_str();
627 while (offset < utf8_text->length()) {
629 output_text.append(text + offset, space_len);
631 if (offset == utf8_text->length())
break;
635 output_text.append(text + offset, word_len);
641 utf8_text->swap(output_text);
643 if (num_dropped > 0) {
644 tprintf(
"Stripped %d unrenderable words\n", num_dropped);
651 Pix *orig_pix = NULL;
654 *pix = pixConvertTo8(orig_pix,
false);
655 pixDestroy(&orig_pix);
661 int threshold, Pix** pix) {
662 Pix *orig_pix = NULL;
665 Pix* gray_pix = pixConvertTo8(orig_pix,
false);
666 pixDestroy(&orig_pix);
667 *pix = pixThresholdToBinary(gray_pix, threshold);
668 pixDestroy(&gray_pix);
683 it != it_end; ++it) {
685 out_str.append(it.utf8_data(), it.utf8_len());
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;
706 it != it_end; ++it) {
711 char32 full_char = *it + 0xFEE0;
712 full_str.append(EncodeAsUTF8(full_char));
714 full_str.append(it.utf8_data(), it.utf8_len());
725 it != it_end; ++it) {
730 isprint(half_char) && !isspace(half_char)) {
731 half_str.append(EncodeAsUTF8(half_char));
733 half_str.append(it.utf8_data(), it.utf8_len());
742 if (pix && *pix) pixDestroy(pix);
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);
770 string page_text(text, page_offset);
782 tprintf(
"WARNING: Dropped %d uncovered characters\n", num_dropped);
793 pango_layout_set_text(
layout_, page_text.c_str(), page_text.length());
797 cairo_set_source_rgb(
cr_, 1.0, 1.0, 1.0);
841 const char* text,
int text_length,
842 string* font_used, Pix** image) {
845 const char kTitleTemplate[] =
"%s : %d hits = %.2f%%, raw = %d = %.2f%%";
848 &title_font, NULL)) {
849 tprintf(
"WARNING: Could not find a font to render image title with!\n");
850 title_font =
"Arial";
853 tlog(1,
"Selected title font: %s\n", title_font.c_str());
854 if (font_used) font_used->clear();
868 for (
int i =
font_index_; i < all_fonts.size(); ++i) {
873 if (ok_chars > 0 && ok_chars >=
total_chars_ * min_coverage) {
877 const int kMaxTitleLength = 1024;
878 char title[kMaxTitleLength];
879 snprintf(title, kMaxTitleLength, kTitleTemplate,
880 all_fonts[i].c_str(), ok_chars,
888 if (font_used) *font_used = all_fonts[i];
893 Pix* title_image = NULL;
895 pixOr(*image, *image, title_image);
896 pixDestroy(&title_image);
903 tprintf(
"Font %s failed with %d hits = %.2f%%\n",
904 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)