The Battle for Wesnoth  1.15.0-dev
text.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2008 - 2018 by Mark de Wever <koraq@xs4all.nl>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #define GETTEXT_DOMAIN "wesnoth-lib"
16 
17 #include "font/text.hpp"
18 
19 #include "font/font_config.hpp"
20 
21 #include "font/pango/escape.hpp"
22 #include "font/pango/font.hpp"
23 #include "font/pango/hyperlink.hpp"
25 
26 #include "gettext.hpp"
27 #include "gui/widgets/helper.hpp"
28 #include "gui/core/log.hpp"
29 #include "sdl/point.hpp"
30 #include "sdl/utils.hpp"
33 #include "preferences/general.hpp"
34 
35 #include <boost/algorithm/string/replace.hpp>
36 
37 #include <cassert>
38 #include <cstring>
39 #include <stdexcept>
40 
41 namespace font {
42 
44  : context_(pango_font_map_create_context(pango_cairo_font_map_get_default()), g_object_unref)
45  , layout_(pango_layout_new(context_.get()), g_object_unref)
46  , rect_()
47  , sublayouts_()
48  , surface_()
49  , text_()
50  , markedup_text_(false)
51  , link_aware_(false)
52  , link_color_()
53  , font_class_(font::FONT_SANS_SERIF)
54  , font_size_(14)
55  , font_style_(STYLE_NORMAL)
56  , foreground_color_() // solid white
57  , add_outline_(false)
58  , maximum_width_(-1)
59  , characters_per_line_(0)
60  , maximum_height_(-1)
61  , ellipse_mode_(PANGO_ELLIPSIZE_END)
62  , alignment_(PANGO_ALIGN_LEFT)
63  , maximum_length_(std::string::npos)
64  , calculation_dirty_(true)
65  , length_(0)
66  , surface_dirty_(true)
67  , surface_buffer_()
68 {
69  // With 72 dpi the sizes are the same as with SDL_TTF so hardcoded.
70  pango_cairo_context_set_resolution(context_.get(), 72.0);
71 
72  pango_layout_set_ellipsize(layout_.get(), ellipse_mode_);
73  pango_layout_set_alignment(layout_.get(), alignment_);
74  pango_layout_set_wrap(layout_.get(), PANGO_WRAP_WORD_CHAR);
75 
76  /*
77  * Set the pango spacing a bit bigger since the default is deemed to small
78  * https://www.wesnoth.org/forum/viewtopic.php?p=358832#p358832
79  */
80  pango_layout_set_spacing(layout_.get(), 4 * PANGO_SCALE);
81 
82  cairo_font_options_t *fo = cairo_font_options_create();
83  cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
84  cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
85  cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_DEFAULT);
86 
87  pango_cairo_context_set_font_options(context_.get(), fo);
88  cairo_font_options_destroy(fo);
89 }
90 
92 {
93  this->rerender();
94  return surface_;
95 }
96 
97 
99 {
100  return this->get_size().x;
101 }
102 
104 {
105  return this->get_size().y;
106 }
107 
109 {
110  this->recalculate();
111 
112  return point(rect_.width, rect_.height);
113 }
114 
116 {
117  this->recalculate();
118 
119  return (pango_layout_is_ellipsized(layout_.get()) != 0);
120 }
121 
122 unsigned pango_text::insert_text(const unsigned offset, const std::string& text)
123 {
124  if (text.empty() || length_ == maximum_length_) {
125  return 0;
126  }
127 
128  // do we really need that assert? utf8::insert will just append in this case, which seems fine
129  assert(offset <= length_);
130 
131  unsigned len = utf8::size(text);
132  if (length_ + len > maximum_length_) {
133  len = maximum_length_ - length_;
134  }
135  const std::string insert = text.substr(0, utf8::index(text, len));
136  std::string tmp = text_;
137  this->set_text(utf8::insert(tmp, offset, insert), false);
138  // report back how many characters were actually inserted (e.g. to move the cursor selection)
139  return len;
140 }
141 
142 bool pango_text::insert_unicode(const unsigned offset, char32_t unicode)
143 {
144  return this->insert_unicode(offset, std::u32string(1, unicode)) == 1;
145 }
146 
147 unsigned pango_text::insert_unicode(const unsigned offset, const std::u32string& unicode)
148 {
149  const std::string insert = unicode_cast<std::string>(unicode);
150  return this->insert_text(offset, insert);
151 }
152 
154  const unsigned column, const unsigned line) const
155 {
156  this->recalculate();
157 
158  // First we need to determine the byte offset, if more routines need it it
159  // would be a good idea to make it a separate function.
160  std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>> itor(
161  pango_layout_get_iter(layout_.get()), pango_layout_iter_free);
162 
163  // Go the wanted line.
164  if(line != 0) {
165  if(pango_layout_get_line_count(layout_.get()) >= static_cast<int>(line)) {
166  return point(0, 0);
167  }
168 
169  for(std::size_t i = 0; i < line; ++i) {
170  pango_layout_iter_next_line(itor.get());
171  }
172  }
173 
174  // Go the wanted column.
175  for(std::size_t i = 0; i < column; ++i) {
176  if(!pango_layout_iter_next_char(itor.get())) {
177  // It seems that the documentation is wrong and causes and off by
178  // one error... the result should be false if already at the end of
179  // the data when started.
180  if(i + 1 == column) {
181  break;
182  }
183  // We are beyond data.
184  return point(0, 0);
185  }
186  }
187 
188  // Get the byte offset
189  const int offset = pango_layout_iter_get_index(itor.get());
190 
191  // Convert the byte offset in a position.
192  PangoRectangle rect;
193  pango_layout_get_cursor_pos(layout_.get(), offset, &rect, nullptr);
194 
195  return point(PANGO_PIXELS(rect.x), PANGO_PIXELS(rect.y));
196 }
197 
199 {
200  return maximum_length_;
201 }
202 
203 std::string pango_text::get_token(const point & position, const char * delim) const
204 {
205  this->recalculate();
206 
207  // Get the index of the character.
208  int index, trailing;
209  if (!pango_layout_xy_to_index(layout_.get(), position.x * PANGO_SCALE,
210  position.y * PANGO_SCALE, &index, &trailing)) {
211  return "";
212  }
213 
214  std::string txt = pango_layout_get_text(layout_.get());
215 
216  std::string d(delim);
217 
218  if (index < 0 || (static_cast<std::size_t>(index) >= txt.size()) || d.find(txt.at(index)) != std::string::npos) {
219  return ""; // if the index is out of bounds, or the index character is a delimiter, return nothing
220  }
221 
222  std::size_t l = index;
223  while (l > 0 && (d.find(txt.at(l-1)) == std::string::npos)) {
224  --l;
225  }
226 
227  std::size_t r = index + 1;
228  while (r < txt.size() && (d.find(txt.at(r)) == std::string::npos)) {
229  ++r;
230  }
231 
232  return txt.substr(l,r-l);
233 }
234 
235 std::string pango_text::get_link(const point & position) const
236 {
237  if (!link_aware_) {
238  return "";
239  }
240 
241  std::string tok = this->get_token(position, " \n\r\t");
242 
243  if (looks_like_url(tok)) {
244  return tok;
245  } else {
246  return "";
247  }
248 }
249 
251 {
252  this->recalculate();
253 
254  // Get the index of the character.
255  int index, trailing;
256  pango_layout_xy_to_index(layout_.get(), position.x * PANGO_SCALE,
257  position.y * PANGO_SCALE, &index, &trailing);
258 
259  // Extract the line and the offset in pixels in that line.
260  int line, offset;
261  pango_layout_index_to_line_x(layout_.get(), index, trailing, &line, &offset);
262  offset = PANGO_PIXELS(offset);
263 
264  // Now convert this offset to a column, this way is a bit hacky but haven't
265  // found a better solution yet.
266 
267  /**
268  * @todo There's still a bug left. When you select a text which is in the
269  * ellipses on the right side the text gets reformatted with ellipses on
270  * the left and the selected character is not the one under the cursor.
271  * Other widget toolkits don't show ellipses and have no indication more
272  * text is available. Haven't found what the best thing to do would be.
273  * Until that time leave it as is.
274  */
275  for(std::size_t i = 0; ; ++i) {
276  const int pos = this->get_cursor_position(i, line).x;
277 
278  if(pos == offset) {
279  return point(i, line);
280  }
281  }
282 }
283 
284 bool pango_text::set_text(const std::string& text, const bool markedup)
285 {
286  if(markedup != markedup_text_ || text != text_) {
287  sublayouts_.clear();
288  if(layout_ == nullptr) {
289  layout_.reset(pango_layout_new(context_.get()));
290  }
291 
292  const std::u32string wide = unicode_cast<std::u32string>(text);
293  const std::string narrow = unicode_cast<std::string>(wide);
294  if(text != narrow) {
295  ERR_GUI_L << "pango_text::" << __func__
296  << " text '" << text
297  << "' contains invalid utf-8, trimmed the invalid parts.\n";
298  }
299  if(markedup) {
300  if(!this->set_markup(narrow, *layout_)) {
301  return false;
302  }
303  } else {
304  /*
305  * pango_layout_set_text after pango_layout_set_markup might
306  * leave the layout in an undefined state regarding markup so
307  * clear it unconditionally.
308  */
309  pango_layout_set_attributes(layout_.get(), nullptr);
310  pango_layout_set_text(layout_.get(), narrow.c_str(), narrow.size());
311  }
312  text_ = narrow;
313  length_ = wide.size();
314  markedup_text_ = markedup;
315  calculation_dirty_ = true;
316  surface_dirty_ = true;
317  }
318 
319  return true;
320 }
321 
323 {
324  if(fclass != font_class_) {
325  font_class_ = fclass;
326  calculation_dirty_ = true;
327  surface_dirty_ = true;
328  }
329 
330  return *this;
331 }
332 
334 {
335  unsigned int actual_size = preferences::font_scaled(font_size);
336  if(actual_size != font_size_) {
337  font_size_ = actual_size;
338  calculation_dirty_ = true;
339  surface_dirty_ = true;
340  }
341 
342  return *this;
343 }
344 
346 {
347  if(font_style != font_style_) {
348  font_style_ = font_style;
349  calculation_dirty_ = true;
350  surface_dirty_ = true;
351  }
352 
353  return *this;
354 }
355 
357 {
358  if(color != foreground_color_) {
359  foreground_color_ = color;
360  surface_dirty_ = true;
361  }
362 
363  return *this;
364 }
365 
367 {
368  if(width <= 0) {
369  width = -1;
370  }
371 
372  if(width != maximum_width_) {
373  maximum_width_ = width;
374  calculation_dirty_ = true;
375  surface_dirty_ = true;
376  }
377 
378  return *this;
379 }
380 
381 pango_text& pango_text::set_characters_per_line(const unsigned characters_per_line)
382 {
383  if(characters_per_line != characters_per_line_) {
384  characters_per_line_ = characters_per_line;
385 
386  calculation_dirty_ = true;
387  surface_dirty_ = true;
388  }
389 
390  return *this;
391 }
392 
393 pango_text& pango_text::set_maximum_height(int height, bool multiline)
394 {
395  if(height <= 0) {
396  height = -1;
397  multiline = false;
398  }
399 
400  if(height != maximum_height_) {
401  // assert(context_);
402 
403  pango_layout_set_height(layout_.get(), !multiline ? -1 : height * PANGO_SCALE);
404  maximum_height_ = height;
405  calculation_dirty_ = true;
406  surface_dirty_ = true;
407  }
408 
409  return *this;
410 }
411 
412 pango_text& pango_text::set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
413 {
414  if(ellipse_mode != ellipse_mode_) {
415  // assert(context_);
416 
417  pango_layout_set_ellipsize(layout_.get(), ellipse_mode);
418  ellipse_mode_ = ellipse_mode;
419  calculation_dirty_ = true;
420  surface_dirty_ = true;
421  }
422 
423  return *this;
424 }
425 
426 pango_text &pango_text::set_alignment(const PangoAlignment alignment)
427 {
428  if (alignment != alignment_) {
429  pango_layout_set_alignment(layout_.get(), alignment);
430  alignment_ = alignment;
431  surface_dirty_ = true;
432  }
433 
434  return *this;
435 }
436 
437 pango_text& pango_text::set_maximum_length(const std::size_t maximum_length)
438 {
439  if(maximum_length != maximum_length_) {
440  maximum_length_ = maximum_length;
441  if(length_ > maximum_length_) {
442  std::string tmp = text_;
443  this->set_text(utf8::truncate(tmp, maximum_length_), false);
444  }
445  }
446 
447  return *this;
448 }
449 
451 {
452  if (link_aware_ != b) {
453  calculation_dirty_ = true;
454  surface_dirty_ = true;
455  link_aware_ = b;
456  }
457  return *this;
458 }
459 
461 {
462  if(color != link_color_) {
463  link_color_ = color;
464  calculation_dirty_ = true;
465  surface_dirty_ = true;
466  }
467 
468  return *this;
469 }
470 
472 {
473  if(do_add != add_outline_) {
474  add_outline_ = do_add;
475  //calculation_dirty_ = true;
476  surface_dirty_ = true;
477  }
478 
479  return *this;
480 }
481 
482 void pango_text::recalculate(const bool force) const
483 {
484  if(calculation_dirty_ || force) {
485  assert(layout_ != nullptr);
486 
487  calculation_dirty_ = false;
488  surface_dirty_ = true;
489 
491  }
492 }
493 
494 PangoRectangle pango_text::calculate_size(PangoLayout& layout) const
495 {
496  PangoRectangle size;
497 
499  pango_layout_set_font_description(&layout, font.get());
500 
501  if(font_style_ & pango_text::STYLE_UNDERLINE) {
502  PangoAttrList *attribute_list = pango_attr_list_new();
503  pango_attr_list_insert(attribute_list
504  , pango_attr_underline_new(PANGO_UNDERLINE_SINGLE));
505 
506  pango_layout_set_attributes(&layout, attribute_list);
507  pango_attr_list_unref(attribute_list);
508  }
509 
510  int maximum_width = 0;
511  if(characters_per_line_ != 0) {
512  PangoFont* f = pango_font_map_load_font(
513  pango_cairo_font_map_get_default(),
514  context_.get(),
515  font.get());
516 
517  PangoFontMetrics* m = pango_font_get_metrics(f, nullptr);
518 
519  int w = pango_font_metrics_get_approximate_char_width(m);
521 
522  maximum_width = ceil(pango_units_to_double(w));
523  } else {
524  maximum_width = maximum_width_;
525  }
526 
527  if(maximum_width_ != -1) {
528  maximum_width = std::min(maximum_width, maximum_width_);
529  }
530 
531  pango_layout_set_width(&layout, maximum_width == -1
532  ? -1
533  : maximum_width * PANGO_SCALE);
534  pango_layout_get_pixel_extents(&layout, nullptr, &size);
535 
536  DBG_GUI_L << "pango_text::" << __func__
537  << " text '" << gui2::debug_truncate(text_)
538  << "' maximum_width " << maximum_width
539  << " width " << size.x + size.width
540  << ".\n";
541 
542  DBG_GUI_L << "pango_text::" << __func__
543  << " text '" << gui2::debug_truncate(text_)
544  << "' font_size " << font_size_
545  << " markedup_text " << markedup_text_
546  << " font_style " << std::hex << font_style_ << std::dec
547  << " maximum_width " << maximum_width
548  << " maximum_height " << maximum_height_
549  << " result " << size
550  << ".\n";
551  if(maximum_width != -1 && size.x + size.width > maximum_width) {
552  DBG_GUI_L << "pango_text::" << __func__
553  << " text '" << gui2::debug_truncate(text_)
554  << " ' width " << size.x + size.width
555  << " greater as the wanted maximum of " << maximum_width
556  << ".\n";
557  }
558 
559  return size;
560 }
561 
562 /***
563  * Inverse table
564  *
565  * Holds a high-precision inverse for each number i, that is, a number x such that x * i / 256 is close to 255.
566  */
568 {
569  unsigned values[256];
570 
572  {
573  values[0] = 0;
574  for (int i = 1; i < 256; ++i) {
575  values[i] = (255 * 256) / i;
576  }
577  }
578 
579  unsigned operator[](uint8_t i) const { return values[i]; }
580 };
581 
583 
584 /***
585  * Helper function for un-premultiplying alpha
586  * Div should be the high-precision inverse for the alpha value.
587  */
588 static void unpremultiply(uint8_t & value, const unsigned div) {
589  unsigned temp = (value * div) / 256u;
590  // Note: It's always the case that alpha * div < 256 if div is the inverse
591  // for alpha, so if cairo is computing premultiplied alpha by rounding down,
592  // this min is not necessary. However, if cairo generates illegal output,
593  // the min may be selected.
594  // It's probably not worth removing the min, since branch prediction will
595  // make it essentially free if one of the branches is never actually
596  // selected.
597  value = std::min(255u, temp);
598 }
599 
600 /**
601  * Converts from cairo-format ARGB32 premultiplied alpha to plain alpha.
602  * @param c a uint32 representing the color
603  */
604 static void from_cairo_format(uint32_t & c)
605 {
606  uint8_t a = (c >> 24) & 0xff;
607  uint8_t r = (c >> 16) & 0xff;
608  uint8_t g = (c >> 8) & 0xff;
609  uint8_t b = c & 0xff;
610 
611  const unsigned div = inverse_table_[a];
612  unpremultiply(r, div);
613  unpremultiply(g, div);
614  unpremultiply(b, div);
615 
616  c = (static_cast<uint32_t>(a) << 24) | (static_cast<uint32_t>(r) << 16) | (static_cast<uint32_t>(g) << 8) | static_cast<uint32_t>(b);
617 }
618 
619 void pango_text::render(PangoLayout& layout, const PangoRectangle& rect, const std::size_t surface_buffer_offset, const unsigned stride)
620 {
621  int width = rect.x + rect.width;
622  int height = rect.y + rect.height;
623  if(maximum_width_ > 0) { width = std::min(width, maximum_width_); }
624  if(maximum_height_ > 0) { height = std::min(height, maximum_height_); }
625 
626  cairo_format_t format = CAIRO_FORMAT_ARGB32;
627 
628  uint8_t* buffer = &surface_buffer_[surface_buffer_offset];
629 
630  std::unique_ptr<cairo_surface_t, std::function<void(cairo_surface_t*)>> cairo_surface(
631  cairo_image_surface_create_for_data(buffer, format, width, height, stride), cairo_surface_destroy);
632  std::unique_ptr<cairo_t, std::function<void(cairo_t*)>> cr(cairo_create(cairo_surface.get()), cairo_destroy);
633 
634  if(cairo_status(cr.get()) == CAIRO_STATUS_INVALID_SIZE) {
635  if(!is_surface_split()) {
636  split_surface();
637 
638  PangoRectangle upper_rect = calculate_size(*sublayouts_[0]);
639  PangoRectangle lower_rect = calculate_size(*sublayouts_[1]);
640 
641  render(*sublayouts_[0], upper_rect, 0u, stride);
642  render(*sublayouts_[1], lower_rect, upper_rect.height * stride, stride);
643 
644  return;
645  } else {
646  // If this occurs in practice, it can be fixed by implementing recursive splitting.
647  throw std::length_error("Text is too long to render");
648  }
649  }
650 
651  //
652  // TODO: the outline may be slightly cut off around certain text if it renders too
653  // close to the surface's edge. That causes the outline to extend just slightly
654  // outside the surface's borders. I'm not sure how best to deal with this. Obviously,
655  // we want to increase the surface size, but we also don't want to invalidate all
656  // the placement and size calculations. Thankfully, it's not very noticeable.
657  //
658  // -- vultraz, 2018-03-07
659  //
660  if(add_outline_) {
661  // Add a path to the cairo context tracing the current text.
662  pango_cairo_layout_path(cr.get(), &layout);
663 
664  // Set color for background outline (black).
665  cairo_set_source_rgba(cr.get(), 0.0, 0.0, 0.0, 1.0);
666 
667  cairo_set_line_join(cr.get(), CAIRO_LINE_JOIN_ROUND);
668  cairo_set_line_width(cr.get(), 3.0); // Adjust as necessary
669 
670  // Stroke path to draw outline.
671  cairo_stroke(cr.get());
672  }
673 
674  // Set main text color.
675  cairo_set_source_rgba(cr.get(),
676  foreground_color_.r / 255.0,
677  foreground_color_.g / 255.0,
678  foreground_color_.b / 255.0,
679  foreground_color_.a / 255.0
680  );
681 
682  pango_cairo_show_layout(cr.get(), &layout);
683 }
684 
685 void pango_text::rerender(const bool force)
686 {
687  if(surface_dirty_ || force) {
688  assert(layout_.get());
689 
690  this->recalculate(force);
691  surface_dirty_ = false;
692 
693  int width = rect_.x + rect_.width;
694  int height = rect_.y + rect_.height;
695  if(maximum_width_ > 0) { width = std::min(width, maximum_width_); }
696  if(maximum_height_ > 0) { height = std::min(height, maximum_height_); }
697 
698  cairo_format_t format = CAIRO_FORMAT_ARGB32;
699  const unsigned stride = cairo_format_stride_for_width(format, width);
700 
701  this->create_surface_buffer(stride * height);
702 
703  if (surface_buffer_.empty()) {
705  return;
706  }
707 
708  render(*layout_, rect_, 0u, stride);
709 
710  // The cairo surface is in CAIRO_FORMAT_ARGB32 which uses
711  // pre-multiplied alpha. SDL doesn't use that so the pixels need to be
712  // decoded again.
713  uint32_t * pixels = reinterpret_cast<uint32_t *>(&surface_buffer_[0]);
714 
715  for(int y = 0; y < height; ++y) {
716  for(int x = 0; x < width; ++x) {
717  from_cairo_format(pixels[y * width + x]);
718  }
719  }
720 
721 #if SDL_VERSION_ATLEAST(2, 0, 6)
722  surface_.assign(SDL_CreateRGBSurfaceWithFormatFrom(
723  &surface_buffer_[0], width, height, 32, stride, SDL_PIXELFORMAT_ARGB8888));
724 #else
725  surface_.assign(SDL_CreateRGBSurfaceFrom(
726  &surface_buffer_[0], width, height, 32, stride, 0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000));
727 #endif
728  }
729 }
730 
731 void pango_text::create_surface_buffer(const std::size_t size) const
732 {
733  // Clear surface.
734  surface_.assign(nullptr);
735 
736  // Resize buffer appropriately and clear all existing data (essentially sets all pixel values to 0).
737  surface_buffer_.assign(size, 0);
738 }
739 
740 bool pango_text::set_markup(utils::string_view text, PangoLayout& layout) {
741  char* raw_text;
742  std::string semi_escaped;
743  bool valid = validate_markup(text, &raw_text, semi_escaped);
744  if(semi_escaped != "") {
745  text = semi_escaped;
746  }
747 
748  if(valid) {
749  if(link_aware_) {
750  std::vector<std::string> links = find_links(raw_text);
751  std::string final_text = text.to_string();
752  format_links(final_text, links);
753  pango_layout_set_markup(&layout, final_text.c_str(), final_text.size());
754  } else {
755  pango_layout_set_markup(&layout, text.data(), text.size());
756  }
757  } else {
758  ERR_GUI_L << "pango_text::" << __func__
759  << " text '" << text
760  << "' has broken markup, set to normal text.\n";
761  set_text(_("The text contains invalid Pango markup: ") + text.to_string(), false);
762  }
763 
764  return valid;
765 }
766 
767 std::vector<std::string> pango_text::find_links(utils::string_view text) const {
768  const std::string delim = " \n\r\t";
769  std::vector<std::string> links;
770 
771  int last_delim = -1;
772  for (std::size_t index = 0; index < text.size(); ++index) {
773  if (delim.find(text[index]) != std::string::npos) {
774  // want to include chars from range since last token, don't want to include any delimiters
775  utils::string_view token = text.substr(last_delim + 1, index - last_delim - 1);
776  if(looks_like_url(token)) {
777  links.push_back(token.to_string());
778  }
779  last_delim = index;
780  }
781  }
782  if (last_delim < static_cast<int>(text.size()) - 1) {
783  utils::string_view token = text.substr(last_delim + 1, text.size() - last_delim - 1);
784  if(looks_like_url(token)) {
785  links.push_back(token.to_string());
786  }
787  }
788 
789  return links;
790 }
791 
792 void pango_text::format_links(std::string& text, const std::vector<std::string>& links) const
793 {
794  for(const std::string& link : links) {
795  boost::algorithm::replace_first(text, link, format_as_link(link, link_color_));
796  }
797 }
798 
799 bool pango_text::validate_markup(utils::string_view text, char** raw_text, std::string& semi_escaped) const
800 {
801  if(pango_parse_markup(text.data(), text.size(),
802  0, nullptr, raw_text, nullptr, nullptr)) {
803  return true;
804  }
805 
806  /*
807  * The markup is invalid. Try to recover.
808  *
809  * The pango engine tested seems to accept stray single quotes »'« and
810  * double quotes »"«. Stray ampersands »&« seem to give troubles.
811  * So only try to recover from broken ampersands, by simply replacing them
812  * with the escaped version.
813  */
814  semi_escaped = semi_escape_text(text.to_string());
815 
816  /*
817  * If at least one ampersand is replaced the semi-escaped string
818  * is longer than the original. If this isn't the case then the
819  * markup wasn't (only) broken by ampersands in the first place.
820  */
821  if(text.size() == semi_escaped.size()
822  || !pango_parse_markup(semi_escaped.c_str(), semi_escaped.size()
823  , 0, nullptr, raw_text, nullptr, nullptr)) {
824 
825  /* Fixing the ampersands didn't work. */
826  return false;
827  }
828 
829  /* Replacement worked, still warn the user about the error. */
830  WRN_GUI_L << "pango_text::" << __func__
831  << " text '" << text
832  << "' has unescaped ampersands '&', escaped them.\n";
833 
834  return true;
835 }
836 
838 {
839  auto text_parts = utils::vertical_split(text_);
840 
841  PangoLayout* upper_layout = pango_layout_new(context_.get());
842  PangoLayout* lower_layout = pango_layout_new(context_.get());
843 
844  set_markup(text_parts.first, *upper_layout);
845  set_markup(text_parts.second, *lower_layout);
846 
847  copy_layout_properties(*layout_, *upper_layout);
848  copy_layout_properties(*layout_, *lower_layout);
849 
850  sublayouts_.emplace_back(upper_layout, g_object_unref);
851  sublayouts_.emplace_back(lower_layout, g_object_unref);
852 
853  // Freeing the old layout causes all text to use
854  // default line spacing in the future.
855  // layout_.reset(nullptr);
856 }
857 
858 void pango_text::copy_layout_properties(PangoLayout& src, PangoLayout& dst)
859 {
860  pango_layout_set_alignment(&dst, pango_layout_get_alignment(&src));
861  pango_layout_set_height(&dst, pango_layout_get_height(&src));
862  pango_layout_set_ellipsize(&dst, pango_layout_get_ellipsize(&src));
863 }
864 
866 {
867  static pango_text text_renderer;
868  return text_renderer;
869 }
870 
871 } // namespace font
Define the common log macros for the gui toolkit.
surface create_neutral_surface(int w, int h)
Definition: utils.cpp:84
unsigned font_size_
The font size to draw.
Definition: text.hpp:289
bool looks_like_url(utils::string_view str)
Definition: hyperlink.hpp:26
void format_links(std::string &text, const std::vector< std::string > &links) const
Definition: text.cpp:792
#define DBG_GUI_L
Definition: log.hpp:57
family_class
Font classes for get_font_families().
bool set_text(const std::string &text, const bool markedup)
Sets the text to render.
Definition: text.cpp:284
Note: Specific to sdl_ttf.
static void unpremultiply(uint8_t &value, const unsigned div)
Definition: text.cpp:588
int get_width() const
Returns the width needed for the text.
Definition: text.cpp:98
std::pair< string_view, string_view > vertical_split(const std::string &val)
Splits a string into two parts as evenly as possible based on lines.
static void from_cairo_format(uint32_t &c)
Converts from cairo-format ARGB32 premultiplied alpha to plain alpha.
Definition: text.cpp:604
int maximum_height_
The maximum height of the text.
Definition: text.hpp:334
#define a
unsigned characters_per_line_
The number of characters per line.
Definition: text.hpp:326
ucs4_convert_impl::enableif< TD, typename TS::value_type >::type unicode_cast(const TS &source)
std::size_t length_
Length of the text.
Definition: text.hpp:355
#define WRN_GUI_L
Definition: log.hpp:59
pango_text & set_link_aware(bool b)
Definition: text.cpp:450
BOOST_CXX14_CONSTEXPR basic_string_view substr(size_type pos, size_type n=npos) const
STL namespace.
std::size_t maximum_length_
The maximum length of the text.
Definition: text.hpp:343
void recalculate(const bool force=false) const
Recalculates the text layout.
Definition: text.cpp:482
#define d
std::size_t get_maximum_length() const
Get maximum length.
Definition: text.cpp:198
font::family_class font_class_
The font family class used.
Definition: text.hpp:286
pango_text & set_font_style(const FONT_STYLE font_style)
Definition: text.cpp:345
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
Definition: text.cpp:865
pango_text & set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
Definition: text.cpp:412
pango_text & set_maximum_length(const std::size_t maximum_length)
Definition: text.cpp:437
std::vector< uint8_t > surface_buffer_
Buffer to store the image on.
Definition: text.hpp:392
Small helper class to make sure the pango font object is destroyed properly.
Definition: font.hpp:23
bool is_surface_split() const
Definition: text.hpp:438
int x
x coordinate.
Definition: point.hpp:44
pango_text & set_alignment(const PangoAlignment alignment)
Definition: text.cpp:426
bool set_markup(utils::string_view text, PangoLayout &layout)
Sets the markup&#39;ed text.
Definition: text.cpp:740
#define b
std::basic_string< charT, traits, Allocator > to_string(const Allocator &a=Allocator()) const
BOOST_CONSTEXPR const_pointer data() const BOOST_NOEXCEPT
#define ERR_GUI_L
Definition: log.hpp:60
const t_string & get_font_families(family_class fclass)
Returns the currently defined fonts.
static UNUSEDNOWARN std::string _(const char *str)
Definition: gettext.hpp:89
point get_cursor_position(const unsigned column, const unsigned line=0) const
Gets the location for the cursor.
Definition: text.cpp:153
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
std::string get_token(const point &position, const char *delimiters=" \\) const
Gets the largest collection of characters, including the token at position, and not including any cha...
Definition: text.cpp:203
point get_size() const
Returns the pixel size needed for the text.
Definition: text.cpp:108
std::unique_ptr< PangoLayout, std::function< void(void *)> > layout_
Definition: text.hpp:257
bool is_truncated() const
Has the text been truncated? This happens if it exceeds max width or height.
Definition: text.cpp:115
int maximum_width_
The maximum width of the text.
Definition: text.hpp:308
std::string semi_escape_text(const std::string &text)
Definition: escape.hpp:51
void rerender(const bool force=false)
Renders the text.
Definition: text.cpp:685
color_t foreground_color_
The foreground color.
Definition: text.hpp:295
std::string get_link(const point &position) const
Checks if position points to a character in a link in the text, returns it if so, empty string otherw...
Definition: text.cpp:235
pango_text & set_font_size(const unsigned font_size)
Definition: text.cpp:333
int font_scaled(int size)
Definition: general.cpp:450
static const inverse_table inverse_table_
Definition: text.cpp:582
bool validate_markup(utils::string_view text, char **raw_text, std::string &semi_escaped) const
Definition: text.cpp:799
PangoEllipsizeMode ellipse_mode_
The way too long text is shown depends on this mode.
Definition: text.hpp:337
unsigned operator[](uint8_t i) const
Definition: text.cpp:579
pango_text & set_characters_per_line(const unsigned characters_per_line)
Definition: text.cpp:381
std::string & truncate(std::string &str, const std::size_t size)
Truncates a UTF-8 string to the specified number of characters.
Definition: unicode.cpp:117
uint8_t r
Red value.
Definition: color.hpp:177
uint8_t a
Alpha value.
Definition: color.hpp:186
bool markedup_text_
Does the text contain pango markup? If different render routines must be used.
Definition: text.hpp:271
PangoRectangle calculate_size(PangoLayout &layout) const
Calculates surface size.
Definition: text.cpp:494
bool surface_dirty_
The dirty state of the surface.
Definition: text.hpp:370
PangoRectangle rect_
Definition: text.hpp:258
bool calculation_dirty_
The text has two dirty states:
Definition: text.hpp:352
unsigned insert_text(const unsigned offset, const std::string &text)
Inserts UTF-8 text.
Definition: text.cpp:122
pango_text & set_family_class(font::family_class fclass)
Definition: text.cpp:322
BOOST_CONSTEXPR size_type size() const BOOST_NOEXCEPT
bool insert_unicode(const unsigned offset, char32_t unicode)
Inserts a unicode char.
Definition: text.cpp:142
std::unique_ptr< PangoContext, std::function< void(void *)> > context_
Definition: text.hpp:256
bool link_aware_
Are hyperlinks in the text marked-up, and will get_link return them.
Definition: text.hpp:274
std::size_t i
Definition: function.cpp:933
void create_surface_buffer(const std::size_t size) const
Creates a new buffer.
Definition: text.cpp:731
point get_column_line(const point &position) const
Gets the column of line of the character at the position.
Definition: text.cpp:250
std::string debug_truncate(const std::string &text)
Returns a truncated version of the text.
Definition: helper.cpp:124
double g
Definition: astarsearch.cpp:64
CURSOR_TYPE get()
Definition: cursor.cpp:213
FONT_STYLE font_style_
The style of the font, this is an orred mask of the font flags.
Definition: text.hpp:292
bool add_outline_
Whether to add an outline effect.
Definition: text.hpp:298
Holds a 2D point.
Definition: point.hpp:23
pango_text & set_link_color(const color_t &color)
Definition: text.cpp:460
int get_height() const
Returns the height needed for the text.
Definition: text.cpp:103
std::string & insert(std::string &str, const std::size_t pos, const std::string &insert)
Insert a UTF-8 string at the specified position.
Definition: unicode.cpp:99
int w
std::vector< std::string > find_links(utils::string_view text) const
Definition: text.cpp:767
std::size_t index(const std::string &str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
Definition: unicode.cpp:71
const std::string & text() const
Definition: text.hpp:223
color_t link_color_
The color to render links in.
Definition: text.hpp:283
Text class.
Definition: text.hpp:74
std::string format_as_link(const std::string &link, color_t color)
Definition: hyperlink.hpp:31
pango_text & set_maximum_width(int width)
Definition: text.cpp:366
void assign(SDL_Surface *surf)
Definition: surface.hpp:46
#define f
std::vector< std::unique_ptr< PangoLayout, std::function< void(void *)> > > sublayouts_
Definition: text.hpp:261
surface surface_
The SDL surface to render upon used as a cache.
Definition: text.hpp:264
surface & render()
Returns the rendered text.
Definition: text.cpp:91
pango_text & set_maximum_height(int height, bool multiline)
Definition: text.cpp:393
void split_surface()
Splits the text to two Cairo surfaces.
Definition: text.cpp:837
uint8_t g
Green value.
Definition: color.hpp:180
uint8_t b
Blue value.
Definition: color.hpp:183
mock_char c
std::string text_
The text to draw (stored as UTF-8).
Definition: text.hpp:268
pango_text & set_foreground_color(const color_t &color)
Definition: text.cpp:356
const int font_size
Definition: button.cpp:40
int y
y coordinate.
Definition: point.hpp:47
PangoAlignment alignment_
The alignment of the text.
Definition: text.hpp:340
pango_text & set_add_outline(bool do_add)
Definition: text.cpp:471
static void copy_layout_properties(PangoLayout &src, PangoLayout &dst)
Definition: text.cpp:858