The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
text.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2008 - 2025
3 by Mark de Wever <koraq@xs4all.nl>
4 Part of the Battle for Wesnoth Project https://www.wesnoth.org/
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY.
12
13 See the COPYING file for more details.
14*/
15
16#define GETTEXT_DOMAIN "wesnoth-lib"
17
18#include "font/text.hpp"
19
20#include "font/attributes.hpp"
21#include "font/cairo.hpp"
22#include "font/font_config.hpp"
23
24#include "font/pango/escape.hpp"
25#include "font/pango/font.hpp"
28
29#include "gettext.hpp"
31#include "gui/core/log.hpp"
32#include "sdl/point.hpp"
35#include "video.hpp"
36
37#include <algorithm>
38#include <cassert>
39#include <cctype>
40#include <cstring>
41#include <stdexcept>
42#include <string_view>
43
44static lg::log_domain log_font("font");
45#define DBG_FT LOG_STREAM(debug, log_font)
46
47namespace font
48{
49
50namespace
51{
52void render_image_shape(cairo_t* cr, PangoAttrShape* pShape, int /* do_path */, void* /* data */)
53{
54 // NOTE: this data is owned by the underlying SDL_Surface. See add_attribute_image_shape
55 cairo_surface_t* img = static_cast<cairo_surface_t*>(pShape->data);
56
57 cairo_rel_move_to (cr,
58 pShape->ink_rect.x/PANGO_SCALE,
59 pShape->ink_rect.y/PANGO_SCALE);
60 double x, y;
61 cairo_get_current_point (cr, &x, &y);
62 cairo_translate (cr, x, y);
64
65 cairo_set_source_surface(cr, img, 0, 0);
66 cairo_rectangle(cr,
67 0,
68 0,
69 pShape->ink_rect.width/PANGO_SCALE,
70 pShape->ink_rect.height/PANGO_SCALE);
71 cairo_fill(cr);
72}
73}
74
76 : context_(pango_font_map_create_context(pango_cairo_font_map_get_default()), g_object_unref)
77 , layout_(pango_layout_new(context_.get()), g_object_unref)
78 , rect_()
79 , text_()
80 , markedup_text_(false)
81 , link_aware_(false)
82 , link_color_()
83 , font_class_(font::family_class::sans_serif)
84 , font_size_(14)
85 , font_style_(STYLE_NORMAL)
86 , foreground_color_() // solid white
87 , add_outline_(false)
88 , maximum_width_(-1)
89 , characters_per_line_(0)
90 , maximum_height_(-1)
91 , multiline_(false)
92 , ellipse_mode_(PANGO_ELLIPSIZE_END)
93 , alignment_(PANGO_ALIGN_LEFT)
94 , maximum_length_(std::string::npos)
95 , calculation_dirty_(true)
96 , length_(0)
97 , pixel_scale_(1)
98 , surface_buffer_()
99{
100 // With 72 dpi the sizes are the same as with SDL_TTF so hardcoded.
101 pango_cairo_context_set_resolution(context_.get(), 72.0);
102
103 pango_layout_set_ellipsize(layout_.get(), ellipse_mode_);
104 pango_layout_set_alignment(layout_.get(), alignment_);
105 pango_layout_set_wrap(layout_.get(), PANGO_WRAP_WORD_CHAR);
106
107 // TODO: phase this out in favor of a global line height attribute.
108 pango_layout_set_line_spacing(layout_.get(), get_line_spacing_factor());
109
110 cairo_font_options_t *fo = cairo_font_options_create();
111 cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
112 cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
113 cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_DEFAULT);
114
115 pango_cairo_context_set_font_options(context_.get(), fo);
116 cairo_font_options_destroy(fo);
117
118 pango_cairo_context_set_shape_renderer(context_.get(), render_image_shape, nullptr, nullptr);
119}
120
122{
123 return with_draw_scale(texture(render_surface(viewport)));
124}
125
131
133{
134 recalculate();
135 return create_surface(viewport);
136}
137
139{
140 texture res(t);
141 res.set_draw_size(to_draw_scale(t.get_raw_size()));
142 return res;
143}
144
146{
147 return (i + pixel_scale_ - 1) / pixel_scale_;
148}
149
151{
152 // Round up, rather than truncating.
153 return {to_draw_scale(p.x), to_draw_scale(p.y)};
154}
155
157{
158 recalculate();
159
160 return to_draw_scale({rect_.width, rect_.height});
161}
162
164{
165 recalculate();
166
167 return (pango_layout_is_ellipsized(layout_.get()) != 0);
168}
169
170unsigned pango_text::insert_text(const unsigned offset, const std::string& text, const bool use_markup)
171{
172 if (text.empty() || length_ == maximum_length_) {
173 return 0;
174 }
175
176 // do we really need that assert? utf8::insert will just append in this case, which seems fine
177 assert(offset <= length_);
178
179 unsigned len = utf8::size(text);
180 if (length_ + len > maximum_length_) {
181 len = maximum_length_ - length_;
182 }
183 const std::string insert = text.substr(0, utf8::index(text, len));
184 std::string tmp = text_;
185 set_text(utf8::insert(tmp, offset, insert), use_markup);
186 // report back how many characters were actually inserted (e.g. to move the cursor selection)
187 return len;
188}
189
190unsigned pango_text::get_byte_index(const unsigned offset, const unsigned line) const
191{
192 // Determing byte offset
193 std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>> itor(
194 pango_layout_get_iter(layout_.get()), pango_layout_iter_free);
195
196 // Go the wanted line.
197 if(line != 0) {
198
199 if(static_cast<int>(line) >= pango_layout_get_line_count(layout_.get())) {
200 return 0;
201 }
202
203 for(std::size_t i = 0; i < line; ++i) {
204 pango_layout_iter_next_line(itor.get());
205 }
206 }
207
208 // Go the wanted column.
209 for(std::size_t i = 0; i < offset; ++i) {
210 if(!pango_layout_iter_next_char(itor.get())) {
211 // It seems that the documentation is wrong and causes and off by
212 // one error... the result should be false if already at the end of
213 // the data when started.
214 if(i + 1 == offset) {
215 break;
216 }
217 // Beyond data.
218 return 0;
219 }
220 }
221
222 // Get the byte offset
223 return pango_layout_iter_get_index(itor.get());
224}
225
226point pango_text::get_cursor_position(const unsigned offset, const unsigned line) const
227{
228 recalculate();
229 return get_cursor_pos_from_index(get_byte_index(offset, line));
230}
231
233{
234 // Convert the byte offset to a position.
235 PangoRectangle rect;
236 pango_layout_get_cursor_pos(layout_.get(), offset, &rect, nullptr);
237
238 return to_draw_scale({PANGO_PIXELS(rect.x), PANGO_PIXELS(rect.y)});
239}
240
241std::vector<std::pair<point, int>> pango_text::get_line_spans(const unsigned start, const unsigned end) const
242{
243 recalculate();
244
245 const int start_index = get_byte_index(start);
246 const int end_index = get_byte_index(end);
247 const std::string_view text = pango_layout_get_text(layout_.get());
248
249 // Byte index of the UTF-8 character before index. Continuation bytes have
250 // the form 10xxxxxx, ie (byte & 0xC0) == 0x80.
251 const auto prev_char = [&text](int index) {
252 do {
253 --index;
254 } while(index > 0 && (static_cast<unsigned char>(text[index]) & 0xC0) == 0x80);
255 return index;
256 };
257
258 std::vector<std::pair<point, int>> res;
259
260 using layout_iterator = std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>>;
261 layout_iterator i{pango_layout_get_iter(layout_.get()), pango_layout_iter_free};
262
263 do {
264 const PangoLayoutLine* ll = pango_layout_iter_get_line_readonly(i.get());
265 const int span_start = std::max(start_index, ll->start_index);
266 int span_end = std::min(end_index, ll->start_index + ll->length);
267
268 // Leave out the whitespace where the line wraps. Only ASCII whitespace is checked;
269 // the last byte of a multi-byte character is never ASCII.
270 while(span_end > span_start && std::isspace(static_cast<unsigned char>(text[span_end - 1]))) {
271 --span_end;
272 }
273
274 if(span_end > span_start) {
275 // The cursor position after the last character may be on the next line,
276 // so use the trailing edge of that character instead
277 PangoRectangle last_rect;
278 pango_layout_index_to_pos(layout_.get(), prev_char(span_end), &last_rect);
279
280 res.emplace_back(get_cursor_pos_from_index(span_start), to_draw_scale(PANGO_PIXELS(last_rect.x + last_rect.width)));
281 }
282 } while(pango_layout_iter_next_line(i.get()));
283
284 return res;
285}
286
288{
289 return maximum_length_;
290}
291
292std::string pango_text::get_token(const point& position, const std::string_view delim) const
293{
294 // Get the index of the character.
295 const auto [index, _, inside_bounds] = xy_to_index(position);
296 std::string txt = pango_layout_get_text(layout_.get());
297
298 if (!inside_bounds || index < 0 || (static_cast<std::size_t>(index) >= txt.size()) || delim.find(txt.at(index)) != std::string::npos) {
299 return ""; // if the index is out of bounds, or the index character is a delimiter, return nothing
300 }
301
302 std::size_t l = index;
303 while (l > 0 && (delim.find(txt.at(l-1)) == std::string::npos)) {
304 --l;
305 }
306
307 std::size_t r = index + 1;
308 while (r < txt.size() && (delim.find(txt.at(r)) == std::string::npos)) {
309 ++r;
310 }
311
312 return txt.substr(l,r-l);
313}
314
315std::string pango_text::get_link(const point& position) const
316{
317 if (!link_aware_) {
318 return "";
319 }
320
321 std::string tok = get_token(position);
322 return looks_like_url(tok) ? tok : "";
323}
324
326{
327 // Get the index of the character.
328 const auto [index, trailing, _] = xy_to_index(position);
329
330 // Find the line containing it.
331 const int line = index_to_line_x(index, trailing).first;
332 const PangoLayoutLine* ll = pango_layout_get_line_readonly(layout_.get(), line);
333 if(!ll) {
334 return point(0, 0);
335 }
336
337 /**
338 * @todo There's still a bug left. When you select a text which is in the
339 * ellipses on the right side the text gets reformatted with ellipses on
340 * the left and the selected character is not the one under the cursor.
341 * Other widget toolkits don't show ellipses and have no indication more
342 * text is available. Haven't found what the best thing to do would be.
343 * Until that time leave it as is.
344 */
345
346 // Convert the byte index to a column by counting the characters from the
347 // start of the line. A non-zero trailing means the position is on the
348 // trailing edge of the character, so the cursor goes after it.
349 const std::string_view text = pango_layout_get_text(layout_.get());
350 const std::string_view line_text = text.substr(ll->start_index, ll->length);
351
352 const std::size_t char_start = std::max(index, ll->start_index) - ll->start_index;
353 const std::size_t cursor = char_start + utf8::index(line_text.substr(std::min(char_start, line_text.size())), trailing);
354
355 return point(static_cast<int>(utf8::size(line_text.substr(0, std::min(cursor, line_text.size())))), line);
356}
357
358std::tuple<int, int, bool> pango_text::xy_to_index(const point& position) const
359{
360 recalculate();
361
362 // Get the index of the character.
363 int index, trailing;
364 // The layout is in render-space, position is in draw-space.
365 int res = pango_layout_xy_to_index(layout_.get(),
366 position.x * pixel_scale_ * PANGO_SCALE, position.y * pixel_scale_ * PANGO_SCALE, &index, &trailing);
367 // res is gboolean
368 return { index, trailing, res != 0 };
369}
370
372{
373 pango_layout_set_attributes(layout_.get(), nullptr);
374}
375
377{
378 if(PangoAttrList* current_attrs = pango_layout_get_attributes(layout_.get())) {
379 attrs.splice_into(current_attrs);
380 } else {
381 attrs.apply_to(layout_.get());
382 }
383}
384
385bool pango_text::set_text(const std::string& text, const bool markedup)
386{
387 if(markedup != markedup_text_ || text != text_) {
388 const std::u32string wide = unicode_cast<std::u32string>(text);
389 std::string narrow = unicode_cast<std::string>(wide);
390 if(text != narrow) {
392 << "pango_text::" << __func__
393 << " text '" << text
394 << "' contains invalid utf-8, trimmed the invalid parts.";
395 }
396
397 if(!markedup || !set_markup(narrow, *layout_)) {
398 pango_layout_set_text(layout_.get(), narrow.c_str(), narrow.size());
400 }
401
402 text_ = std::move(narrow);
403 length_ = wide.size();
404 markedup_text_ = markedup;
405 calculation_dirty_ = true;
406 }
407
408 return true;
409}
410
412{
413 if(fclass != font_class_) {
414 font_class_ = fclass;
415 calculation_dirty_ = true;
416 }
417
418 return *this;
419}
420
422{
423 font_size = prefs::get().font_scaled(font_size);
424
425 if(font_size != font_size_) {
426 font_size_ = font_size;
427 calculation_dirty_ = true;
428 }
429
430 return *this;
431}
432
434{
435 if(font_style != font_style_) {
436 font_style_ = font_style;
437 calculation_dirty_ = true;
438 }
439
440 return *this;
441}
442
444{
445 if(color != foreground_color_) {
446 foreground_color_ = color;
447 }
448
449 return *this;
450}
451
453{
454 if(width <= 0) {
455 width = -1;
456 }
457
458 if(width != maximum_width_) {
459 maximum_width_ = width;
460 calculation_dirty_ = true;
461 }
462
463 return *this;
464}
465
466pango_text& pango_text::set_characters_per_line(const unsigned characters_per_line)
467{
468 if(characters_per_line != characters_per_line_) {
469 characters_per_line_ = characters_per_line;
470
471 calculation_dirty_ = true;
472 }
473
474 return *this;
475}
476
477pango_text& pango_text::set_maximum_height(int height, bool multiline)
478{
479 if(height <= 0) {
480 height = -1;
481 multiline = false;
482 }
483
484 if(height != maximum_height_ || multiline != multiline_) {
485 // The maximum height is handled in this class' calculate_size() method.
486 maximum_height_ = height;
487 multiline_ = multiline;
488 calculation_dirty_ = true;
489 }
490
491 return *this;
492}
493
494pango_text& pango_text::set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
495{
496 if(ellipse_mode != ellipse_mode_) {
497 // assert(context_);
498
499 pango_layout_set_ellipsize(layout_.get(), ellipse_mode);
500 ellipse_mode_ = ellipse_mode;
501 calculation_dirty_ = true;
502 }
503
504 return *this;
505}
506
507pango_text &pango_text::set_alignment(const PangoAlignment alignment)
508{
509 if (alignment != alignment_) {
510 pango_layout_set_alignment(layout_.get(), alignment);
511 alignment_ = alignment;
512 }
513
514 return *this;
515}
516
517pango_text& pango_text::set_maximum_length(const std::size_t maximum_length)
518{
519 if(maximum_length != maximum_length_) {
520 maximum_length_ = maximum_length;
522 std::string tmp = text_;
524 }
525 }
526
527 return *this;
528}
529
531{
532 if (link_aware_ != b) {
533 calculation_dirty_ = true;
534 link_aware_ = b;
535 }
536 return *this;
537}
538
540{
541 if(color != link_color_) {
542 link_color_ = color;
543 calculation_dirty_ = true;
544 }
545
546 return *this;
547}
548
550{
551 if(do_add != add_outline_) {
552 add_outline_ = do_add;
553 //calculation_dirty_ = true;
554 }
555
556 return *this;
557}
558
560{
563
564 PangoFont* f = pango_font_map_load_font(
565 pango_cairo_font_map_get_default(),
566 context_.get(),
567 font.get());
568
569 PangoFontMetrics* m = pango_font_get_metrics(f, nullptr);
570
571 auto ascent = pango_font_metrics_get_ascent(m);
572 auto descent = pango_font_metrics_get_descent(m);
573
574 pango_font_metrics_unref(m);
575 g_object_unref(f);
576
577 return ceil(pango_units_to_double(ascent + descent) / pixel_scale_);
578}
579
581{
582 const int ps = video::get_pixel_scale();
583 if(ps != pixel_scale_) {
584 pixel_scale_ = ps;
585 calculation_dirty_ = true;
586 }
587}
588
590{
591 // TODO: clean up this "const everything then mutable everything" mess.
592
593 // The size calculation scales the font size and maximum width and height
594 // by the pixel scale, so make sure it's current first.
596
598 assert(layout_ != nullptr);
599
600 calculation_dirty_ = false;
602 }
603}
604
605PangoRectangle pango_text::calculate_size(PangoLayout& layout) const
606{
607 PangoRectangle size;
608
609 // The font size and maximum width and height are stored in draw-space,
610 // but the layout is in render-space.
611 const unsigned font_size = font_size_ * pixel_scale_;
612 const int maximum_width_scaled = maximum_width_ == -1 ? -1 : maximum_width_ * pixel_scale_;
613 const int maximum_height = maximum_height_ == -1 ? -1 : maximum_height_ * pixel_scale_;
614
616 pango_layout_set_font_description(&layout, font.get());
617
618 int maximum_width = 0;
619 if(characters_per_line_ != 0) {
620 PangoFont* f = pango_font_map_load_font(
621 pango_cairo_font_map_get_default(),
622 context_.get(),
623 font.get());
624
625 PangoFontMetrics* m = pango_font_get_metrics(f, nullptr);
626
627 int w = pango_font_metrics_get_approximate_char_width(m);
629
630 maximum_width = ceil(pango_units_to_double(w));
631
632 pango_font_metrics_unref(m);
633 g_object_unref(f);
634 } else {
635 maximum_width = maximum_width_scaled;
636 }
637
638 if(maximum_width_scaled != -1) {
639 maximum_width = std::min(maximum_width, maximum_width_scaled);
640 }
641
642 // The maximum height is mostly handled below, rather than by Pango. Although
643 // we also pass it to the layout for multi-line text, the documentation of
644 // pango_layout_set_height possibly suggests that we should avoid that
645 // function completely. For example, "at least one line is included in each
646 // paragraph regardless" and "may be changed in future, file a bug if you
647 // rely on the current behavior". It also says the behaviour is undefined if
648 // a height other than -1 is combined with PANGO_ELLIPSIZE_NONE.
649 pango_layout_set_height(&layout, multiline_ && ellipse_mode_ != PANGO_ELLIPSIZE_NONE
650 ? maximum_height * PANGO_SCALE
651 : -1);
652
653 pango_layout_set_width(&layout, maximum_width == -1
654 ? -1
655 : maximum_width * PANGO_SCALE);
656 pango_layout_get_pixel_extents(&layout, nullptr, &size);
657
658 DBG_GUI_L << "pango_text::" << __func__
659 << " text '" << gui2::debug_truncate(text_)
660 << "' maximum_width " << maximum_width
661 << " width " << size.x + size.width
662 << ".";
663
664 DBG_GUI_L << "pango_text::" << __func__
665 << " text '" << gui2::debug_truncate(text_)
666 << "' font_size " << font_size
667 << " markedup_text " << markedup_text_
668 << " font_style " << std::hex << font_style_ << std::dec
669 << " maximum_width " << maximum_width
670 << " maximum_height " << maximum_height
671 << " result " << size
672 << ".";
673
674 if(maximum_width != -1 && size.x + size.width > maximum_width) {
675 DBG_GUI_L << "pango_text::" << __func__
676 << " text '" << gui2::debug_truncate(text_)
677 << " ' width " << size.x + size.width
678 << " greater as the wanted maximum of " << maximum_width
679 << ".";
680 }
681
682 // The maximum height is handled here instead of using the library - see the comments above
683 if(maximum_height != -1 && size.y + size.height > maximum_height) {
684 DBG_GUI_L << "pango_text::" << __func__
685 << " text '" << gui2::debug_truncate(text_)
686 << " ' height " << size.y + size.height
687 << " greater as the wanted maximum of " << maximum_height
688 << ".";
689 size.height = maximum_height - std::max(0, size.y);
690 }
691
692 return size;
693}
694
695/***
696 * Inverse table
697 *
698 * Holds a high-precision inverse for each number i, that is, a number x such that x * i / 256 is close to 255.
699 */
701{
702 unsigned values[256] {};
703
704 constexpr inverse_table()
705 {
706 values[0] = 0;
707 for (int i = 1; i < 256; ++i) {
708 values[i] = (255 * 256) / i;
709 }
710 }
711
712 unsigned operator[](uint8_t i) const { return values[i]; }
713};
714
716
717/***
718 * Helper function for un-premultiplying alpha
719 * Div should be the high-precision inverse for the alpha value.
720 */
721static void unpremultiply(uint8_t & value, const unsigned div) {
722 unsigned temp = (value * div) / 256u;
723 // Note: It's always the case that alpha * div < 256 if div is the inverse
724 // for alpha, so if cairo is computing premultiplied alpha by rounding down,
725 // this min is not necessary. However, if cairo generates illegal output,
726 // the min may be selected.
727 // It's probably not worth removing the min, since branch prediction will
728 // make it essentially free if one of the branches is never actually
729 // selected.
730 value = std::min(255u, temp);
731}
732
733/**
734 * Converts from cairo-format ARGB32 premultiplied alpha to plain alpha.
735 * @param c a uint32 representing the color
736 */
737static void from_cairo_format(uint32_t & c)
738{
739 uint8_t a = (c >> 24) & 0xff;
740 uint8_t r = (c >> 16) & 0xff;
741 uint8_t g = (c >> 8) & 0xff;
742 uint8_t b = c & 0xff;
743
744 const unsigned div = inverse_table_[a];
745 unpremultiply(r, div);
746 unpremultiply(g, div);
747 unpremultiply(b, div);
748
749 c = (static_cast<uint32_t>(a) << 24) | (static_cast<uint32_t>(r) << 16) | (static_cast<uint32_t>(g) << 8) | static_cast<uint32_t>(b);
750}
751
752void pango_text::render(PangoLayout& layout, const rect& viewport)
753{
754 auto cairo_surface = cairo::create_surface(&surface_buffer_[0], point{ viewport.w, viewport.h }); // TODO: use rect::size
755 auto cairo_context = cairo::create_context(cairo_surface);
756
757 // Convenience pointer
758 cairo_t* cr = cairo_context.get();
759
760 if(cairo_status(cr) == CAIRO_STATUS_INVALID_SIZE) {
761 throw std::length_error("Text is too long to render");
762 }
763
764 // The top-left of the text, which can be outside the area to be rendered
765 cairo_move_to(cr, -viewport.x, -viewport.y);
766
767 //
768 // TODO: the outline may be slightly cut off around certain text if it renders too
769 // close to the surface's edge. That causes the outline to extend just slightly
770 // outside the surface's borders. I'm not sure how best to deal with this. Obviously,
771 // we want to increase the surface size, but we also don't want to invalidate all
772 // the placement and size calculations. Thankfully, it's not very noticeable.
773 //
774 // -- vultraz, 2018-03-07
775 //
776 if(add_outline_) {
777 // Add a path to the cairo context tracing the current text.
778 pango_cairo_layout_path(cr, &layout);
779
780 // Set color for background outline (black).
781 cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 1.0);
782
783 cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
784 cairo_set_line_width(cr, 3.0); // Adjust as necessary
785
786 // Stroke path to draw outline.
787 cairo_stroke(cr);
788 }
789
790 // Set main text color.
791 cairo_set_source_rgba(cr,
792 foreground_color_.r / 255.0,
793 foreground_color_.g / 255.0,
794 foreground_color_.b / 255.0,
795 foreground_color_.a / 255.0
796 );
797
800 list.insert(pango_attr_underline_new(PANGO_UNDERLINE_SINGLE));
801 apply_attributes(list);
802 }
803
804 pango_cairo_show_layout(cr, &layout);
805}
806
808{
809 return create_surface({0, 0, rect_.x + rect_.width, rect_.y + rect_.height});
810}
811
813{
814 assert(layout_.get());
815
816 cairo_format_t format = CAIRO_FORMAT_ARGB32;
817 const int stride = cairo_format_stride_for_width(format, viewport.w);
818
819 // The width and stride can be zero if the text is empty or the stride can be negative to indicate an error from
820 // Cairo. Width isn't tested here because it's implied by stride.
821 if(stride <= 0 || viewport.h <= 0) {
822 surface_buffer_.clear();
823 return nullptr;
824 }
825
826 DBG_FT << "creating new text surface";
827
828 // Check to prevent arithmetic overflow when calculating (stride * height).
829 // The size of the viewport should already provide a far lower limit on the
830 // maximum size, but this is left in as a sanity check.
831 if(viewport.h > std::numeric_limits<int>::max() / stride) {
832 throw std::length_error("Text is too long to render");
833 }
834
835 // Resize buffer appropriately and set all pixel values to 0.
836 surface_buffer_.assign(viewport.h * stride, 0);
837
838 // Try rendering the whole text in one go. If this throws a length_error
839 // then leave it to the caller to handle; one reason it may throw is that
840 // cairo surfaces are limited to approximately 2**15 pixels in height.
841 render(*layout_, viewport);
842
843 // The cairo surface is in CAIRO_FORMAT_ARGB32 which uses
844 // pre-multiplied alpha. SDL doesn't use that so the pixels need to be
845 // decoded again.
846 for(int y = 0; y < viewport.h; ++y) {
847 uint32_t* pixels = reinterpret_cast<uint32_t*>(&surface_buffer_[y * stride]);
848 for(int x = 0; x < viewport.w; ++x) {
849 from_cairo_format(pixels[x]);
850 }
851 }
852
853 return SDL_CreateSurfaceFrom(viewport.w, viewport.h, SDL_PIXELFORMAT_ARGB8888, &surface_buffer_[0], stride);
854}
855
856bool pango_text::set_markup(std::string_view text, PangoLayout& layout)
857{
858 char* raw_text;
859 std::string semi_escaped;
860 bool valid = validate_markup(text, &raw_text, semi_escaped);
861 if(!semi_escaped.empty()) {
862 text = semi_escaped;
863 }
864
865 if(valid) {
866 if(link_aware_) {
867 std::string formatted_text = format_links(text);
868 pango_layout_set_markup(&layout, formatted_text.c_str(), formatted_text.size());
869 } else {
870 pango_layout_set_markup(&layout, text.data(), text.size());
871 }
872 }
873
874 return valid;
875}
876
877/**
878 * Replaces all instances of URLs in a given string with formatted links
879 * and returns the result.
880 */
881std::string pango_text::format_links(std::string_view text) const
882{
883 static const std::string delim = " \n\r\t";
884 std::ostringstream result;
885
886 std::size_t tok_start = 0;
887 for(std::size_t pos = 0; pos < text.length(); ++pos) {
888 if(delim.find(text[pos]) == std::string::npos) {
889 continue;
890 }
891
892 if(const auto tok_length = pos - tok_start) {
893 // Token starts from after the last delimiter up to (but not including) this delimiter
894 auto token = text.substr(tok_start, tok_length);
895 if(looks_like_url(token)) {
896 result << format_as_link(std::string{token}, link_color_);
897 } else {
898 result << token;
899 }
900 }
901
902 result << text[pos];
903 tok_start = pos + 1;
904 }
905
906 // Deal with the remainder token
907 if(tok_start < text.length()) {
908 auto token = text.substr(tok_start);
909 if(looks_like_url(token)) {
910 result << format_as_link(std::string{token}, link_color_);
911 } else {
912 result << token;
913 }
914 }
915
916 return result.str();
917}
918
919bool pango_text::validate_markup(std::string_view text, char** raw_text, std::string& semi_escaped) const
920{
921 if(pango_parse_markup(text.data(), text.size(),
922 0, nullptr, raw_text, nullptr, nullptr)) {
923 return true;
924 }
925
926 /*
927 * The markup is invalid. Try to recover.
928 *
929 * The pango engine tested seems to accept stray single quotes »'« and
930 * double quotes »"«. Stray ampersands »&« seem to give troubles.
931 * So only try to recover from broken ampersands, by simply replacing them
932 * with the escaped version.
933 */
934 semi_escaped = semi_escape_text(text);
935
936 /*
937 * If at least one ampersand is replaced the semi-escaped string
938 * is longer than the original. If this isn't the case then the
939 * markup wasn't (only) broken by ampersands in the first place.
940 */
941 if(text.size() == semi_escaped.size()
942 || !pango_parse_markup(semi_escaped.c_str(), semi_escaped.size()
943 , 0, nullptr, raw_text, nullptr, nullptr)) {
944
945 /* Fixing the ampersands didn't work. */
946 return false;
947 }
948
949 /* Replacement worked, still warn the user about the error. */
950 WRN_GUI_L << "pango_text::" << __func__
951 << " text '" << text
952 << "' has unescaped ampersands '&', escaped them.";
953
954 return true;
955}
956
957std::vector<std::string> pango_text::get_lines() const
958{
959 recalculate();
960
961 PangoLayout* const layout = layout_.get();
962 std::vector<std::string> res;
963 int count = pango_layout_get_line_count(layout);
964
965 if(count < 1) {
966 return res;
967 }
968
969 using layout_iterator = std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>>;
970 layout_iterator i{pango_layout_get_iter(layout), pango_layout_iter_free};
971
972 res.reserve(count);
973
974 do {
975 PangoLayoutLine* ll = pango_layout_iter_get_line_readonly(i.get());
976 const char* begin = &pango_layout_get_text(layout)[ll->start_index];
977 res.emplace_back(begin, ll->length);
978 } while(pango_layout_iter_next_line(i.get()));
979
980 return res;
981}
982
983PangoLayoutLine* pango_text::get_line(int index)
984{
985 return pango_layout_get_line_readonly(layout_.get(), index);
986}
987
988std::pair<int, int> pango_text::index_to_line_x(const unsigned offset, const bool trailing) const
989{
990 int line_num = 0, x_pos = 0;
991 pango_layout_index_to_line_x(layout_.get(), offset, trailing, &line_num, &x_pos);
992 return { line_num, x_pos };
993}
994
996{
997 static pango_text text_renderer;
998 return text_renderer;
999}
1000
1002{
1003 // Reset metrics to defaults
1004 return get_text_renderer()
1005 .set_family_class(fclass)
1006 .set_font_style(style)
1007 .set_font_size(size)
1009}
1010
1011} // namespace font
double t
Helper class to encapsulate the management of a PangoAttrList.
void splice_into(PangoAttrList *target) const
void apply_to(PangoLayout *layout) const
void insert(PangoAttribute *attr)
Small helper class to make sure the pango font object is destroyed properly.
Definition font.hpp:25
Text class.
Definition text.hpp:78
const std::string & text() const
Definition text.hpp:336
int pixel_scale_
The pixel scale, used to render high-DPI text.
Definition text.hpp:488
pango_text & set_font_style(const FONT_STYLE font_style)
Definition text.cpp:433
PangoEllipsizeMode ellipse_mode_
The way too long text is shown depends on this mode.
Definition text.hpp:467
bool multiline_
Whether the maximum height is also passed to the layout.
Definition text.hpp:464
bool add_outline_
Whether to add an outline effect.
Definition text.hpp:421
void clear_attributes()
Definition text.cpp:371
bool validate_markup(std::string_view text, char **raw_text, std::string &semi_escaped) const
Definition text.cpp:919
bool set_markup(std::string_view text, PangoLayout &layout)
Sets the markup'ed text.
Definition text.cpp:856
pango_text & set_maximum_length(const std::size_t maximum_length)
Definition text.cpp:517
surface create_surface()
Equivalent to create_surface(viewport), where the viewport's top-left is at (0,0) and the area is lar...
Definition text.cpp:807
PangoAlignment alignment_
The alignment of the text.
Definition text.hpp:470
PangoRectangle rect_
Definition text.hpp:388
int maximum_height_
The maximum height of the text.
Definition text.hpp:461
point get_size()
Returns the size of the text, in drawing coordinates.
Definition text.cpp:156
pango_text & set_characters_per_line(const unsigned characters_per_line)
Definition text.cpp:466
color_t link_color_
The color to render links in.
Definition text.hpp:406
unsigned insert_text(const unsigned offset, const std::string &text, const bool use_markup=false)
Inserts UTF-8 text.
Definition text.cpp:170
void recalculate() const
Recalculates the text layout.
Definition text.cpp:589
color_t foreground_color_
The foreground color.
Definition text.hpp:418
point get_column_line(const point &position) const
Gets the column of line of the character at the position.
Definition text.cpp:325
std::unique_ptr< PangoContext, std::function< void(void *)> > context_
Definition text.hpp:386
bool link_aware_
Are hyperlinks in the text marked-up, and will get_link return them.
Definition text.hpp:397
pango_text & set_foreground_color(const color_t &color)
Definition text.cpp:443
int to_draw_scale(int s) const
Scale the given render-space size to draw-space, rounding up.
Definition text.cpp:145
texture render_texture(const rect &viewport)
Wrapper around render_surface which sets texture::w() and texture::h() in the same way that render_an...
Definition text.cpp:121
std::string format_links(std::string_view text) const
Replaces all instances of URLs in a given string with formatted links and returns the result.
Definition text.cpp:881
unsigned get_byte_index(const unsigned offset, const unsigned line=0) const
Given a character index and optionally the starting line, returns the corresponding byte index.
Definition text.cpp:190
std::string get_token(const point &position, std::string_view delimiters=" \n\r\t") const
Gets the largest collection of characters, including the token at position, and not including any cha...
Definition text.cpp:292
PangoLayoutLine * get_line(int index)
Get a specific line from the pango layout.
Definition text.cpp:983
unsigned characters_per_line_
The number of characters per line.
Definition text.hpp:451
bool markedup_text_
Does the text contain pango markup? If different render routines must be used.
Definition text.hpp:394
pango_text & set_family_class(font::family_class fclass)
Definition text.cpp:411
void update_pixel_scale() const
Update pixel scale, if necessary.
Definition text.cpp:580
font::family_class font_class_
The font family class used.
Definition text.hpp:409
void apply_attributes(const font::attribute_list &attrs)
Definition text.cpp:376
std::vector< std::string > get_lines() const
Retrieves a list of strings with contents for each rendered line.
Definition text.cpp:957
std::tuple< int, int, bool > xy_to_index(const point &position) const
Wrapper function around pango_layout_xy_to_index.
Definition text.cpp:358
unsigned font_size_
The font size to draw, in draw-space (before pixel scaling).
Definition text.hpp:412
std::vector< uint8_t > surface_buffer_
Buffer to store the image on.
Definition text.hpp:533
pango_text & set_add_outline(bool do_add)
Definition text.cpp:549
point get_cursor_position(const unsigned offset, const unsigned line=0) const
Gets the location for the cursor, in drawing coordinates.
Definition text.cpp:226
pango_text & set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
Definition text.cpp:494
PangoRectangle calculate_size(PangoLayout &layout) const
Calculates surface size.
Definition text.cpp:605
pango_text & set_alignment(const PangoAlignment alignment)
Definition text.cpp:507
std::string text_
The text to draw (stored as UTF-8).
Definition text.hpp:391
std::pair< int, int > index_to_line_x(const unsigned offset, const bool trailing=0) const
Given a byte index, find out at which line the corresponding character is located.
Definition text.cpp:988
bool calculation_dirty_
The text has two dirty states:
Definition text.hpp:482
std::unique_ptr< PangoLayout, std::function< void(void *)> > layout_
Definition text.hpp:387
pango_text & set_font_size(unsigned font_size)
Definition text.cpp:421
pango_text & set_link_aware(bool b)
Definition text.cpp:530
void render(PangoLayout &layout, const rect &viewport)
This is part of create_surface(viewport).
Definition text.cpp:752
FONT_STYLE font_style_
The style of the font, this is an orred mask of the font flags.
Definition text.hpp:415
bool set_text(const std::string &text, const bool markedup)
Sets the text to render.
Definition text.cpp:385
bool is_truncated() const
Has the text been truncated? This happens if it exceeds max width or height.
Definition text.cpp:163
texture with_draw_scale(const texture &t) const
Adjust a texture's draw-width and height according to pixel scale.
Definition text.cpp:138
surface render_surface(const rect &viewport)
Returns the rendered text.
Definition text.cpp:132
std::size_t maximum_length_
The maximum length of the text.
Definition text.hpp:473
point get_cursor_pos_from_index(const unsigned offset) const
Gets the location for the cursor, in drawing coordinates.
Definition text.cpp:232
pango_text & set_maximum_height(int height, bool multiline)
Definition text.cpp:477
pango_text & set_maximum_width(int width)
Definition text.cpp:452
std::size_t get_maximum_length() const
Get maximum length.
Definition text.cpp:287
texture render_and_get_texture()
Returns the cached texture, or creates a new one otherwise.
Definition text.cpp:126
std::vector< std::pair< point, int > > get_line_spans(const unsigned start, const unsigned end) const
Gets where a range of characters lies on each line it spans.
Definition text.cpp:241
pango_text & set_link_color(const color_t &color)
Definition text.cpp:539
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:315
std::size_t length_
Length of the text.
Definition text.hpp:485
int get_max_glyph_height() const
Returns the maximum glyph height of a font, in drawing coordinates.
Definition text.cpp:559
int maximum_width_
The maximum width of the text.
Definition text.hpp:433
static prefs & get()
int font_scaled(int size)
Wrapper class to encapsulate creation and management of an SDL_Texture.
Definition texture.hpp:33
void set_draw_size(int w, int h)
Set the intended size of the texture, in draw-space.
Definition texture.hpp:129
#define DBG_FT
static std::string _(const char *str)
Definition gettext.hpp:100
Define the common log macros for the gui toolkit.
#define DBG_GUI_L
Definition log.hpp:55
#define ERR_GUI_L
Definition log.hpp:58
#define WRN_GUI_L
Definition log.hpp:57
context_ptr create_context(const surface_ptr &surf)
Definition cairo.hpp:41
surface_ptr create_surface(uint8_t *buffer, const point &size)
Definition cairo.hpp:30
Graphical text output.
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
Definition text.cpp:995
constexpr float get_line_spacing_factor()
Definition text.hpp:597
bool looks_like_url(std::string_view str)
Definition hyperlink.hpp:28
const t_string & get_font_families(family_class fclass)
Returns the currently defined fonts.
int get_max_height(unsigned size, font::family_class fclass, pango_text::FONT_STYLE style)
Returns the maximum glyph height of a font, in pixels.
Definition text.cpp:1001
std::string semi_escape_text(std::string_view text)
Definition escape.hpp:52
std::string format_as_link(const std::string &link, color_t color)
Definition hyperlink.hpp:33
static void unpremultiply(uint8_t &value, const unsigned div)
Definition text.cpp:721
static void from_cairo_format(uint32_t &c)
Converts from cairo-format ARGB32 premultiplied alpha to plain alpha.
Definition text.cpp:737
static constexpr inverse_table inverse_table_
Definition text.cpp:715
std::string_view debug_truncate(std::string_view text)
Returns a truncated version of the text.
Definition helper.cpp:172
STL namespace.
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:100
std::size_t size(std::string_view str)
Length in characters of a UTF-8 string.
Definition unicode.cpp:81
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:118
std::size_t index(std::string_view str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
Definition unicode.cpp:70
int get_pixel_scale()
Get the current active pixel scale multiplier.
Definition video.cpp:480
int w
Definition pathfind.cpp:188
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
Definition sound.cpp:139
The basic class for representing 8-bit RGB or RGBA colour values.
Definition color.hpp:51
unsigned values[256]
Definition text.cpp:702
constexpr inverse_table()
Definition text.cpp:704
unsigned operator[](uint8_t i) const
Definition text.cpp:712
Holds a 2D point.
Definition point.hpp:25
An abstract description of a rectangle with integer coordinates.
Definition rect.hpp:49
contains the current text being parsed as well as the token_type of what's being parsed.
Definition tokenizer.hpp:41
mock_party p
static lg::log_domain log_font("font")
#define i
#define g
#define f
#define c
#define b