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