The Battle for Wesnoth 1.21.0-dev
 
Loading...
Searching...
No Matches
rich_label.cpp
Go to the documentation of this file.
1/*
2 Copyright (C) 2024 - 2025
3 by Subhraman Sarkar (babaissarkar) <sbmskmm@protonmail.com>
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
19
20#include "gui/core/log.hpp"
24
25#include "cursor.hpp"
26#include "picture.hpp"
27#include "font/constants.hpp"
29#include "log.hpp"
33#include "sound.hpp"
34#include "wml_exception.hpp"
35
36#include <boost/format.hpp>
37#include <boost/multi_array.hpp>
38#include <functional>
39#include <numeric>
40#include <string>
41#include <utility>
42
43static lg::log_domain log_rich_label("gui/widget/rich_label");
44#define DBG_GUI_RL LOG_STREAM(debug, log_rich_label)
45
46// Enable this to draw borders around links.
47// Useful for debugging misplaced links.
48#define LINK_DEBUG_BORDER false
49
50namespace gui2
51{
52namespace
53{
54using namespace std::string_literals;
55
56/** Possible formatting tags, must be the same as those in gui2::text_shape::draw */
57const std::array format_tags{ "bold"s, "b"s, "italic"s, "i"s, "underline"s, "u"s };
58}
59
60// ------------ WIDGET -----------{
61
62REGISTER_WIDGET(rich_label)
63
64rich_label::rich_label(const implementation::builder_rich_label& builder)
65 : styled_widget(builder, type())
66 , state_(ENABLED)
67 , can_wrap_(true)
68 , link_aware_(builder.link_aware)
69 , link_color_(font::YELLOW_COLOR)
70 , predef_colors_()
71 , font_size_(font::SIZE_NORMAL)
72 , can_shrink_(true)
73 , text_alpha_(ALPHA_OPAQUE)
74 , init_w_(0)
75 , size_(0, 0)
76 , padding_(builder.padding)
77{
78 const auto conf = cast_config_to<rich_label_definition>();
79 assert(conf);
80 text_color_enabled_ = conf->text_color_enabled;
81 text_color_disabled_ = conf->text_color_disabled;
82 font_family_ = conf->font_family;
83 font_size_ = conf->font_size;
84 font_style_ = conf->font_style;
85 link_color_ = conf->link_color;
86 predef_colors_.insert(conf->colors.begin(), conf->colors.end());
87 set_text_alignment(builder.text_alignment);
88 set_label(builder.label_string);
89}
90
91color_t rich_label::get_color(const std::string& color)
92{
93 const auto iter = predef_colors_.find(color);
94 return (iter != predef_colors_.end()) ? iter->second : font::string_to_color(color);
95}
96
98{
99 // Set up fake render to calculate text position
101 variables.add("text", wfl::variant(tshape.get_text()));
102 variables.add("width", wfl::variant(width));
103 variables.add("text_wrap_mode", wfl::variant(PANGO_ELLIPSIZE_NONE));
104 variables.add("fake_draw", wfl::variant(true));
105 tshape.draw(variables);
106 return variables;
107}
108
109point rich_label::get_text_size(text_shape& tshape, unsigned width) const
110{
111 wfl::map_formula_callable variables = setup_text_renderer(tshape, width);
112 return {
113 variables.query_value("text_width").as_int(),
114 variables.query_value("text_height").as_int()
115 };
116}
117
118point rich_label::get_image_size(const std::string& path) const
119{
120 return ::image::get_size(::image::locator{path});
121}
122
123std::pair<std::size_t, std::size_t> rich_label::add_text_with_attribute(
124 text_shape& tshape,
125 const t_string& text,
126 const std::string& attr_name,
127 const std::string& extra_data)
128{
129 const auto [start, end] = tshape.add_text(text);
130 tshape.add_attribute(attr_name, extra_data, start, end);
131 return { start, end };
132}
133
134std::pair<unsigned, unsigned> rich_label::add_link(
135 text_shape& tshape,
136 const std::string& name,
137 const std::string& dest,
138 const point& origin,
139 int img_width)
140{
141 DBG_GUI_RL << "add_link: " << name << "->" << dest;
142
143 const unsigned start = utf8::size(tshape.get_text());
144 std::string link_text = name.empty() ? dest : name;
145 add_text_with_attribute(tshape, link_text, "color", link_color_.to_hex_string());
146 const unsigned end = utf8::size(tshape.get_text());
147
148 add_link_area(tshape, dest, start, end, origin, img_width);
149 return { start, end };
150}
151
153 text_shape& tshape,
154 const std::string& dest,
155 const unsigned start,
156 const unsigned end,
157 const point& origin,
158 int img_width)
159{
160 // TODO algorithm needs to be text_alignment independent
161
162 DBG_GUI_RL << "add_link_area: " << dest << " [" << start << "," << end << ")";
163 DBG_GUI_RL << "origin: " << origin;
164 DBG_GUI_RL << "width: " << img_width;
165
166 // Measure with the link text added, so a link that wraps as a whole starts on the next line.
167 setup_text_renderer(tshape, init_w_ - origin.x - img_width);
168
169 // TODO link after right aligned images
170
171 // Add a rect for each line of the link text, ending at that line's last character.
172 // Pango's lines are used rather than comparing x positions, since a link starting at
173 // the left edge (eg in a table cell) can wrap and still end to the right of where it started.
174 // GitHub #11718
175 const int text_height = font::get_max_height(font_size_);
176 for(const auto& [line_start, line_end_x] : font::get_text_renderer().get_line_spans(start, end)) {
177 rect link_rect{ origin + line_start, point{ line_end_x - line_start.x, text_height } };
178 links_.emplace_back(link_rect, dest);
179 DBG_GUI_RL << "added link at rect: " << link_rect;
180 }
181}
182
183std::size_t rich_label::get_split_location(std::string_view text, const point& pos)
184{
185 const auto [offset, trailing] = get_offset_from_xy(pos);
186 if(offset <= 0) {
187 return 0;
188 }
189
190 std::size_t len = static_cast<size_t>(offset);
191
192 // Past the end of a paragraph's last line, Pango gives the last character with
193 // trailing set, so move after it. Otherwise the word boundary search below would
194 // move that line's last word below the floating image.
195 if(trailing > 0 && len < text.size()) {
196 // Step over the whole UTF-8 character: its continuation bytes have the
197 // form 10xxxxxx, ie (byte & 0xC0) == 0x80.
198 do {
199 len++;
200 } while(len < text.size() && (static_cast<unsigned char>(text[len]) & 0xC0) == 0x80);
201 }
202
203 if (len >= text.size() - 1) {
204 return text.size() - 1;
205 }
206
207 // break only at word boundary
208 while(!utils::portable_isspace(text[len])) {
209 len--;
210 if(len == 0) {
211 break;
212 }
213 }
214
215 return len;
216}
217
219{
220 dom_ = dom;
221 auto [shapes, size] = get_parsed_text(dom, point(0,0), init_w_, true);
222 // FIXME: because of move semantics, we can set shapes to only one canvas
223 // However, this means one of the state will have an empty canvas.
224 // Also `get_parsed_text()` is heavy, so we don't want to run it multiple times
225 // unless really needed.
226 get_canvas(0).set_shapes(std::move(shapes), true);
227 size_ = size;
229 queue_redraw();
230}
231
233{
235}
236
237void rich_label::request_reduce_width(const unsigned maximum_width)
238{
239 if(maximum_width != static_cast<unsigned>(size_.x)) {
240 init_w_ = maximum_width;
241 set_dom(dom_);
242 }
244}
245
247{
248 return size_;
249}
250
251void rich_label::place(const point& origin, const point& size)
252{
253 if(size.x != size_.x) {
254 init_w_ = size.x;
255 set_dom(dom_);
256 }
257 styled_widget::place(origin, size);
258}
259
260std::pair<std::vector<rich_label::shape_ptr>, point> rich_label::get_parsed_text(
261 const config& parsed_text,
262 const point& origin,
263 const unsigned init_width,
264 const bool finalize)
265{
266 // Initial width
267 DBG_GUI_RL << "Initial width: " << init_width;
268
269 // Initialization
270 unsigned x = 0;
271 unsigned prev_blk_height = origin.y;
272 unsigned text_height = 0;
273 unsigned h = 0;
274 unsigned w = 0;
275
276 if(finalize) {
277 links_.clear();
278 }
279
280 std::vector<shape_ptr> shapes;
281 std::unique_ptr<gui2::text_shape> curr_item = nullptr;
282
283 // Links in curr_item, so their click areas can be moved if its text is split
284 // around a floating image: destination, character range and range in links_.
285 struct item_link
286 {
287 std::string dest;
288 unsigned start, end;
289 std::size_t first_area, last_area;
290 };
291 std::vector<item_link> item_links;
292
293 bool is_text = false;
294 bool is_image = false;
295 bool wrap_mode = false;
296 bool new_text_block = false;
297
298 point pos(origin);
299 point float_pos, float_size;
300 point img_size;
301
302 DBG_GUI_RL << parsed_text.debug();
303
304 auto children = parsed_text.all_children_view();
305 for(auto it = children.begin(); it != children.end(); ++it) {
306 const auto [orig_key, child] = *it;
307
308 const std::string key = (orig_key == "img" && !child["float"].to_bool(false)) ? "inline_image" : orig_key;
309
310 DBG_GUI_RL << "\n Trying to layout tag: " << key;
311
312 if(key == "img") {
313 prev_blk_height += text_height;
314 text_height = 0;
315
316 const std::string& align = child["align"].str("left");
317 const point& curr_img_size = get_image_size(child["src"]);
318
319 if (align == "right") {
320 float_pos.x = init_width - curr_img_size.x;
321 } else if (align == "middle" || align == "center") {
322 // works for single image only
323 float_pos.x = float_size.x + (init_width - curr_img_size.x)/2;
324 }
325
326 if (is_image) {
327 float_pos.y += float_size.y;
328 }
329
330 shapes.emplace_back(std::make_unique<image_shape>(point{float_pos.x, pos.y + float_pos.y}, child["src"]));
331
332 float_size.x = curr_img_size.x + padding_;
333 float_size.y += curr_img_size.y + padding_;
334
335 x = ((align == "left") ? float_size.x : 0);
336 pos.x += ((align == "left") ? float_size.x : 0);
337
338 wrap_mode = true;
339
340 w = std::max(w, x);
341
342 is_image = true;
343 is_text = false;
344 new_text_block = true;
345
346 DBG_GUI_RL << key << ": src=" << child["src"] << ", size=" << img_size;
347 DBG_GUI_RL << "wrap turned on.";
348 } else if(key == "clear") {
349 // Moves the text below the preceding floating image and turns off wrapping
350 wrap_mode = false;
351 prev_blk_height += float_size.y;
352 pos.y += float_size.y;
353 float_size = point(0, 0);
354 pos.x = origin.x;
355
356 DBG_GUI_RL << key;
357 DBG_GUI_RL << "wrap turned off";
358 } else if(key == "table") {
359 if(curr_item == nullptr) {
360 curr_item = new_text_shape(pos, init_width);
361 new_text_block = false;
362 }
363
364 // table doesn't support floating images alongside
365 img_size = point(0,0);
366 float_size = point(0,0);
367 x = origin.x;
368 prev_blk_height += text_height + padding_;
369 text_height = 0;
370 pos = point(origin.x, prev_blk_height + padding_);
371
372 // init table vars
373 unsigned col_idx = 0, row_idx = 0;
374 unsigned rows = child.child_count("row");
375 unsigned columns = 1;
376 if(rows > 0) {
377 columns = child.mandatory_child("row").child_count("col");
378 }
379 columns = (columns == 0) ? 1 : columns;
380 int init_cell_width;
381 if(child["width"] == "fill") {
382 init_cell_width = init_width/columns;
383 } else {
384 init_cell_width = child["width"].to_int(init_width)/columns;
385 }
386 std::vector<int> col_widths(columns, 0);
387 std::vector<int> row_heights(rows, 0);
388
389 is_text = false;
390 new_text_block = true;
391 is_image = false;
392
393 DBG_GUI_RL << "start table: " << "row=" << rows << " col=" << columns
394 << " width=" << init_cell_width*columns;
395
396 const auto get_padding = [this](const config::attribute_value& val) {
397 if(val.blank()) {
398 return std::array{ padding_, padding_ };
399 } else {
400 auto paddings = utils::split(val.str(), ' ');
401 if(paddings.size() == 1) {
402 return std::array{ std::stoi(paddings[0]), std::stoi(paddings[0]) };
403 } else {
404 return std::array{ std::stoi(paddings[0]), std::stoi(paddings[1]) };
405 }
406 }
407 };
408
409 std::array<int, 2> row_paddings;
410 boost::multi_array<point, 2> cell_sizes(boost::extents[rows][columns]);
411
412 // optimal col width calculation
413 for(const config& row : child.child_range("row")) {
414 pos.x = origin.x;
415 col_idx = 0;
416
417 // order: top padding|bottom padding
418 row_paddings = get_padding(row["padding"]);
419
420 pos.y += row_paddings[0];
421 for(const config& col : row.child_range("col")) {
422 DBG_GUI_RL << "table cell origin (pre-layout): " << pos.x << ", " << pos.y;
423 config col_cfg;
424 col_cfg.append_children(col);
425 config& col_txt_cfg = col_cfg.add_child("text");
426 col_txt_cfg.append_attributes(col);
427
428 // order: left padding|right padding
429 std::array<int, 2> col_paddings = get_padding(col["padding"]);
430 int cell_width = init_cell_width - col_paddings[0] - col_paddings[1];
431
432 pos.x += col_paddings[0];
433 // attach data
434 auto links = links_;
435 cell_sizes[row_idx][col_idx] = get_parsed_text(col_cfg, pos, init_cell_width).second;
436 links_ = links;
437
438 // column post-processing
439 row_heights[row_idx] = std::max(row_heights[row_idx], cell_sizes[row_idx][col_idx].y);
440 if(!child["width"].empty()) {
441 col_widths[col_idx] = cell_width;
442 }
443 col_widths[col_idx] = std::max(col_widths[col_idx], cell_sizes[row_idx][col_idx].x);
444 if(child["width"].empty()) {
445 col_widths[col_idx] = std::min(col_widths[col_idx], cell_width);
446 }
447
448 DBG_GUI_RL << "table row " << row_idx << " height: " << row_heights[row_idx]
449 << "col " << col_idx << " width: " << col_widths[col_idx];
450
451 pos.x += cell_width;
452 pos.x += col_paddings[1];
453 col_idx++;
454 }
455
456 pos.y += row_heights[row_idx] + row_paddings[1];
457 row_idx++;
458 }
459
460 // table layouting
461 row_idx = 0;
462 pos = point(origin.x, prev_blk_height);
463 for(const config& row : child.child_range("row")) {
464 pos.x = origin.x;
465 col_idx = 0;
466
467 if(!row["bgcolor"].blank()) {
468 unsigned width = std::accumulate(col_widths.begin(), col_widths.end(), 0) + 2*(row_paddings[0] + row_paddings[1])*columns;
469 unsigned height = row_paddings[0] + row_heights[row_idx] + row_paddings[1];
470 shapes.emplace_back(std::make_unique<rectangle_shape>(
471 rect{origin.x, pos.y, static_cast<int>(width), static_cast<int>(height)},
472 get_color(row["bgcolor"].str())));
473 }
474
475 row_paddings = get_padding(row["padding"]);
476 pos.y += row_paddings[0];
477
478 for(const config& col : row.child_range("col")) {
479 DBG_GUI_RL << "table row " << row_idx << " height: " << row_heights[row_idx]
480 << "col " << col_idx << " width: " << col_widths[col_idx];
481 DBG_GUI_RL << "cell origin: " << pos;
482
483 config col_cfg;
484 col_cfg.append_children(col);
485 config& col_txt_cfg = col_cfg.add_child("text");
486 col_txt_cfg.append_attributes(col);
487
488 // order: left padding|right padding
489 std::array<int, 2> col_paddings = get_padding(col["padding"]);
490
491 pos.x += col_paddings[0];
492
493 const std::string& valign = row["valign"].str("center");
494 const std::string& halign = col["halign"].str("left");
495
496 // set position according to alignment keys
497 point text_pos(pos);
498 if (valign == "center" || valign == "middle") {
499 text_pos.y += (row_heights[row_idx] - cell_sizes[row_idx][col_idx].y)/2;
500 } else if (valign == "bottom") {
501 text_pos.y += row_heights[row_idx] - cell_sizes[row_idx][col_idx].y;
502 }
503 if (halign == "center" || halign == "middle") {
504 text_pos.x += (col_widths[col_idx] - cell_sizes[row_idx][col_idx].x)/2;
505 } else if (halign == "right") {
506 text_pos.x += col_widths[col_idx] - cell_sizes[row_idx][col_idx].x;
507 }
508
509 // append child shapes to toplevel shape list
510 std::vector<shape_ptr> table_shapes = get_parsed_text(col_cfg, text_pos, col_widths[col_idx]).first;
511 std::move(table_shapes.begin(), table_shapes.end(), std::back_inserter(shapes));
512 pos.x += col_widths[col_idx];
513 pos.x += col_paddings[1];
514
515 if(!shapes.empty()) {
516 if(auto* tshape = dynamic_cast<text_shape*>(shapes.back().get())) {
517 tshape->set_wrap_width(col_widths[col_idx]);
518 }
519 }
520
521 DBG_GUI_RL << "jump to next column";
522
523 if(!is_image) {
524 new_text_block = true;
525 }
526 is_image = false;
527 col_idx++;
528 }
529
530 pos.y += row_heights[row_idx];
531 pos.y += row_paddings[1];
532 DBG_GUI_RL << "row height: " << row_heights[row_idx];
533 row_idx++;
534 }
535
536 w = std::max(w, static_cast<unsigned>(pos.x));
537 prev_blk_height = pos.y;
538 text_height = 0;
539 pos.x = origin.x;
540
541 is_image = false;
542 is_text = false;
543
544 x = origin.x;
545
546 } else {
547 std::string line = child["text"];
548
549 if(!finalize && (line.empty() && key == "text")) {
550 continue;
551 }
552
553 if(curr_item == nullptr || new_text_block) {
554 if (new_text_block && curr_item != nullptr) {
555 shapes.emplace_back(std::move(curr_item));
556 }
557
558 curr_item = new_text_shape(pos, init_width - (pos.x - origin.x) - float_size.x);
559 item_links.clear();
560 new_text_block = false;
561 }
562
563 // }---------- TEXT TAGS -----------{
564 int tmp_h = get_text_size(*curr_item, init_width - (x == 0 ? float_size.x : x)).y;
565
566 if(is_text && key == "text") {
567 add_text_with_attribute(*curr_item, "\n\n");
568 }
569
570 is_text = false;
571 is_image = false;
572
573 if(key == "inline_image") {
574
575 // Inline image is rendered as a custom text glyph (pango shape attribute)
576 // FIXME: If linebreak (\n) is followed by an inline image
577 // the text size is calculated wrongly as being decreased.
578 // Workaround: append a zero width space always in front of the image.
579 curr_item->add_text("\u200b");
580 add_text_with_attribute(*curr_item, "\ufffc", "image", child["src"]);
581
582 DBG_GUI_RL << key << ": src=" << child["src"];
583
584 } else if(key == "ref") {
585
586 const std::size_t first_area = links_.size();
587 const auto [start, end] = add_link(*curr_item, line, child["dst"], point(x + origin.x, prev_blk_height), float_size.x);
588 item_links.push_back({ child["dst"].str(), start, end, first_area, links_.size() });
589
590 DBG_GUI_RL << key << ": dst=" << child["dst"];
591
592 } else if(utils::contains(format_tags, key)) {
593 // TODO only the formatting tags here support nesting
594
595 add_text_with_attribute(*curr_item, line, key);
596
597 // Calculate the location of the nested children
598 setup_text_renderer(*curr_item, init_w_ - origin.x - float_size.x);
599 point child_origin = origin + get_xy_from_offset(utf8::size(curr_item->get_text()));
600 child_origin.y += prev_blk_height;
601
602 auto [child_shapes, _] = get_parsed_text(child, child_origin, init_width);
603 for(auto&& shape : child_shapes) {
604 if(auto* tshape = dynamic_cast<text_shape*>(shape.get())) {
605 const auto [start, end] = curr_item->add_text(tshape->get_text());
606 curr_item->add_attributes_from(*tshape, start);
607 curr_item->add_attribute(key, "", start, end);
608 } else {
609 shapes.emplace_back(std::move(shape));
610 }
611 }
612
613 DBG_GUI_RL << key << ": text=" << gui2::debug_truncate(line);
614
615 } else if(key == "header" || key == "h") {
616
617 const auto [start, end] = curr_item->add_text(line);
618 curr_item->add_attribute("weight", "heavy", start, end);
619 curr_item->add_attribute("color", "white", start, end);
620 curr_item->add_attribute("size", std::to_string(font::SIZE_TITLE - 2), start, end);
621
622 DBG_GUI_RL << key << ": text=" << line;
623
624 } else if(key == "character_entity") {
625
626 line = "&" + child["name"].str() + ";";
627
628 const auto [start, end] = curr_item->add_text(line);
629 curr_item->add_attribute("face", "monospace", start, end);
630 curr_item->add_attribute("color", "red", start, end);
631
632 DBG_GUI_RL << key << ": text=" << line;
633
634 } else if(key == "span" || key == "format") {
635
636 const auto [start, end] = curr_item->add_text(line);
637 DBG_GUI_RL << "span/format: text=" << line;
638 DBG_GUI_RL << "attributes:";
639
640 for (const auto& [key, value] : child.attribute_range()) {
641 if (key != "text") {
642 curr_item->add_attribute(key, value, start, end);
643 DBG_GUI_RL << key << "=" << value;
644 }
645 }
646
647 } else if (key == "text") {
648
649 DBG_GUI_RL << "text: text=" << gui2::debug_truncate(line) << "...";
650
651 curr_item->add_text(line);
652
653 point text_size = get_text_size(*curr_item, init_width - (x == 0 ? float_size.x : x));
654
655 is_text = true;
656
657 // Text wrapping around floating images
658 // Only split once the last line is complete. Mark-up that follows this text
659 // (eg the italic note after a bullet) is appended to that line, so splitting
660 // before then would push the rest of the line on to a new line. GitHub #11717
661 // The line is also complete if no more text will be appended to it, ie this is
662 // the last tag or the next one starts a new block.
663 const std::string full_text = curr_item->get_text();
664 const auto next = std::next(it);
665 const auto starts_new_block = [](const auto& tag) {
666 const auto [tag_key, tag_child] = tag;
667 return tag_key == "table" || tag_key == "clear"
668 || (tag_key == "img" && tag_child["float"].to_bool(false));
669 };
670 const bool block_ends = next == children.end() || starts_new_block(*next);
671 const bool line_complete = block_ends || (!full_text.empty() && full_text.back() == '\n');
672
673 if(wrap_mode && line_complete && (float_size.y > 0) && (text_size.y > float_size.y)) {
674 DBG_GUI_RL << "wrap start";
675
676 std::size_t len = get_split_location(full_text, point(init_width - float_size.x, float_size.y));
677
678 DBG_GUI_RL << "wrap around area: " << float_size;
679
680 // Where the links in the first part of the text were positioned
681 const point first_origin(x + origin.x, prev_blk_height);
682 const int first_img_width = float_size.x;
683
684 if(len > 0) {
685 // first part of the text
686 curr_item->set_text(full_text.substr(0, len));
687 }
688
689 curr_item->set_wrap_width(init_width - float_size.x);
690 float_size = point(0,0);
691
692 // Height update
693 // The split can fall within text added by an earlier tag (eg a formatting tag),
694 // so the first part may be shorter than tmp_h. text_height already counts tmp_h,
695 // so it must shrink in that case rather than count the first part again.
696 // GitHub #11715
697 int ah = get_text_size(*curr_item, init_width - float_size.x).y;
698 text_height = std::max(0, static_cast<int>(text_height) + ah - tmp_h);
699 prev_blk_height += text_height;
700 pos = point(origin.x, prev_blk_height);
701
702 DBG_GUI_RL << "wrap: " << prev_blk_height << "," << text_height;
703 text_height = 0;
704
705 // New text block
706 x = origin.x;
707 wrap_mode = false;
708
709 if (len > 0) {
710 // layout rest of the text
711 text_shape& first_item = *curr_item;
712 shapes.emplace_back(std::move(curr_item));
713 curr_item = new_text_shape(pos, init_width - pos.x);
714 tmp_h = get_text_size(*curr_item, init_width).y;
715 // get_split_location always splits at word bounds,
716 // so substr(len) will include a space. we skip that.
717 const std::size_t start = curr_item->add_text(full_text.substr(len+1)).first;
718 // carry over formatting (italic, links etc.) for the rest of the text
719 curr_item->add_attributes_from(first_item, start, len+1);
720
721 // The click areas of links that continue past the split were positioned
722 // for the unsplit text, so replace them. Remove them last to first, so the
723 // ranges in links_ of those not yet removed stay valid.
724 const unsigned first_end = utf8::size(std::string_view(full_text).substr(0, len));
725 const unsigned rest_start = first_end + 1;
726 for(auto link = item_links.rbegin(); link != item_links.rend(); ++link) {
727 if(link->end > first_end) {
728 links_.erase(links_.begin() + link->first_area, links_.begin() + link->last_area);
729 }
730 }
731
732 std::vector<item_link> rest_links;
733 for(const item_link& link : item_links) {
734 if(link.end <= first_end) {
735 continue;
736 }
737
738 if(link.start < first_end) {
739 add_link_area(first_item, link.dest, link.start, first_end, first_origin, first_img_width);
740 }
741
742 if(link.end > rest_start) {
743 const unsigned link_start = std::max(link.start, rest_start) - rest_start;
744 const unsigned link_end = link.end - rest_start;
745 const std::size_t first_area = links_.size();
746 add_link_area(*curr_item, link.dest, link_start, link_end, pos, 0);
747 rest_links.push_back({ link.dest, link_start, link_end, first_area, links_.size() });
748 }
749 }
750 item_links = std::move(rest_links);
751 }
752 } else if((float_size.y > 0) && (text_size.y < float_size.y)) {
753 //TODO padding?
754 // text height less than floating image's height, don't split
755 DBG_GUI_RL << "no wrap";
756 pos.y += text_size.y;
757 }
758
759 if(!wrap_mode) {
760 float_size = point(0,0);
761 }
762 }
763
764 point size = get_text_size(*curr_item, init_width - (x == 0 ? float_size.x : x));
765 // update text size and widget height
766 if(tmp_h > size.y) {
767 tmp_h = 0;
768 }
769 w = std::max(w, x + static_cast<unsigned>(size.x));
770
771 text_height += size.y - tmp_h;
772 pos.y += size.y - tmp_h;
773 }
774
775 if(!is_image && !wrap_mode && img_size.y > 0) {
776 img_size = point(0,0);
777 }
778
779 DBG_GUI_RL << "X: " << x;
780 DBG_GUI_RL << "Prev block height: " << prev_blk_height << " Current text block height: " << text_height;
781 DBG_GUI_RL << "Height: " << h;
782 h = text_height + prev_blk_height;
783 DBG_GUI_RL << "-----------";
784 } // for loop ends
785
786 // DEBUG: draw boxes around links
787 #if LINK_DEBUG_BORDER
788 if(finalize) {
789 for(const auto& entry : links_) {
790 shapes.emplace_back(std::make_unique<rectangle_shape>(
791 rect{ entry.first.x, entry.first.y, entry.first.w, entry.first.h },
792 color_t(255, 180, 0, 255)));
793 }
794 }
795 #endif
796
797 if(curr_item != nullptr) {
798 shapes.emplace_back(std::move(curr_item));
799 }
800
801 if(w == 0) {
802 w = init_width;
803 }
804 // TODO float and a mix of floats and images and tables
805 h = std::max(static_cast<unsigned>(img_size.y), h);
806
807 DBG_GUI_RL << "Width: " << w << " Height: " << h << " Origin: " << origin;
808 return { std::move(shapes), point(w, h - origin.y) };
809} // function ends
810
811std::unique_ptr<gui2::text_shape> rich_label::new_text_shape(
812 const point& origin,
813 const int max_width)
814{
815 auto tshape = std::make_unique<gui2::text_shape>(
816 origin,
821 max_width
822 );
823
824 tshape->add_attribute("line_height", std::to_string(font::get_line_spacing_factor()));
825 return tshape;
826}
827
829{
830 for(canvas& tmp : get_canvases()) {
831 tmp.set_variable("width", wfl::variant(init_w_));
832 tmp.set_variable("padding", wfl::variant(padding_));
833 // Disable ellipsization so that text wrapping can work
834 tmp.set_variable("text_wrap_mode", wfl::variant(PANGO_ELLIPSIZE_NONE));
835 tmp.set_variable("text_alpha", wfl::variant(text_alpha_));
836 }
837}
838
839void rich_label::set_text_alpha(unsigned short alpha)
840{
841 if(alpha != text_alpha_) {
842 text_alpha_ = alpha;
844 queue_redraw();
845 }
846}
847
848void rich_label::set_active(const bool /*active*/)
849{
850 set_state(ENABLED); // Always enabled
851}
852
853void rich_label::set_link_aware(bool link_aware)
854{
855 if(link_aware != link_aware_) {
856 link_aware_ = link_aware;
858 queue_redraw();
859 }
860}
861
863{
864 if(color != link_color_) {
865 link_color_ = color;
867 queue_redraw();
868 }
869}
870
872{
873 if(state != state_) {
874 state_ = state;
875 queue_redraw();
876 }
877}
878
879void rich_label::register_link_callback(std::function<void(std::string)> link_handler)
880{
881 if(!link_aware_) {
882 return;
883 }
884
885 connect_signal<event::LEFT_BUTTON_CLICK>(
886 std::bind(&rich_label::signal_handler_left_button_click, this, std::placeholders::_3));
887 connect_signal<event::MOUSE_MOTION>(
888 std::bind(&rich_label::signal_handler_mouse_motion, this, std::placeholders::_3, std::placeholders::_5));
889 connect_signal<event::MOUSE_LEAVE>(
890 std::bind(&rich_label::signal_handler_mouse_leave, this, std::placeholders::_3));
891 link_handler_ = std::move(link_handler);
892}
893
894
896{
897 DBG_GUI_E << "rich_label click";
898
899 if(!get_link_aware()) {
900 return; // without marking event as "handled"
901 }
902
903 point mouse = get_mouse_position() - get_origin();
904
905 DBG_GUI_RL << "(mouse) " << mouse;
906 DBG_GUI_RL << "link count :" << links_.size();
907
908 utils::optional<std::string> click_target;
909 for(const auto& entry : links_) {
910 DBG_GUI_RL << "link " << entry.second;
911
912 if(entry.first.contains(mouse)) {
913 click_target = entry.second;
914 break;
915 }
916 }
917
918 if (click_target) {
919 DBG_GUI_RL << "Clicked link! dst = " << *click_target;
921 if(link_handler_) {
922 link_handler_(*click_target);
923 } else {
924 DBG_GUI_RL << "No registered link handler found";
925 }
926 }
927
928 handled = true;
929}
930
931void rich_label::signal_handler_mouse_motion(bool& handled, const point& coordinate)
932{
933 DBG_GUI_E << "rich_label mouse motion";
934
935 if(!get_link_aware()) {
936 return; // without marking event as "handled"
937 }
938
939 point mouse = coordinate - get_origin();
940
941 for(const auto& entry : links_) {
942 if(entry.first.contains(mouse)) {
944 handled = true;
945 return;
946 }
947 }
948
949 update_mouse_cursor(false);
950}
951
953{
954 DBG_GUI_E << "rich_label mouse leave";
955
956 if(!get_link_aware()) {
957 return; // without marking event as "handled"
958 }
959
960 // We left the widget, so just unconditionally reset the cursor
961 update_mouse_cursor(false);
962
963 handled = true;
964}
965
967{
968 // Someone else may set the mouse cursor for us to something unusual (e.g.
969 // the WAIT cursor) so we ought to mess with that only if it's set to
970 // NORMAL or HYPERLINK.
971
972 if(enable && cursor::get() == cursor::NORMAL) {
974 } else if(!enable && cursor::get() == cursor::HYPERLINK) {
976 }
977}
978
979// }---------- DEFINITION ---------{
980
983{
984 DBG_GUI_P << "Parsing rich_label " << id;
985
986 load_resolutions<resolution>(cfg);
987}
988
991 , text_color_enabled(color_t::from_rgba_string(cfg["text_font_color_enabled"].str()))
992 , text_color_disabled(color_t::from_rgba_string(cfg["text_font_color_disabled"].str()))
993 , link_color(cfg["link_color"].empty() ? font::YELLOW_COLOR : color_t::from_rgba_string(cfg["link_color"].str()))
994 , font_family(cfg["text_font_family"].str())
995 , font_size(cfg["text_font_size"].to_int(font::SIZE_NORMAL))
996 , font_style(cfg["text_font_style"].str("normal"))
997 , colors()
998{
999 if(auto colors_cfg = cfg.optional_child("colors")) {
1000 for(const auto& [name, value] : colors_cfg->attribute_range()) {
1001 colors.try_emplace(name, color_t::from_rgba_string(value.str()));
1002 }
1003 }
1004
1005 // Note the order should be the same as the enum state_t is rich_label.hpp.
1006 state.emplace_back(VALIDATE_WML_CHILD(cfg, "state_enabled", missing_mandatory_wml_tag("rich_label_definition][resolution", "state_enabled")));
1007}
1008
1009// }---------- BUILDER -----------{
1010
1011namespace implementation
1012{
1013
1014builder_rich_label::builder_rich_label(const config& cfg)
1016 , text_alignment(decode_text_alignment(cfg["text_alignment"]))
1017 , link_aware(cfg["link_aware"].to_bool(true))
1018 , padding(cfg["padding"].to_int(5))
1019{
1020}
1021
1022std::unique_ptr<widget> builder_rich_label::build() const
1023{
1024 DBG_GUI_G << "Window builder: placed rich_label '" << id << "' with definition '"
1025 << definition << "'.";
1026
1027 return std::make_unique<rich_label>(*this);
1028}
1029
1030} // namespace implementation
1031
1032// }------------ END --------------
1033
1034} // namespace gui2
Variant for storing WML attributes.
A config object defines a single node in a WML file, with access to child nodes.
Definition config.hpp:157
config & add_child(std::string_view key)
Definition config.cpp:428
optional_config_impl< config > optional_child(std::string_view key, int n=0)
Equivalent to mandatory_child, but returns an empty optional if the nth child was not found.
Definition config.cpp:372
auto all_children_view() const
In-order iteration over all children.
Definition config.hpp:795
void append_attributes(const config &cfg)
Adds attributes from cfg.
Definition config.cpp:166
std::string debug() const
Definition config.cpp:1206
void append_children(const config &cfg)
Adds children from cfg.
Definition config.cpp:159
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:261
A simple canvas which can be drawn upon.
Definition canvas.hpp:45
void set_shapes(const config &cfg, const bool force=false)
Sets the config.
Definition canvas.hpp:126
A rich_label takes marked up text and shows it correctly formatted and wrapped but no scrollbars are ...
point calculate_best_size() const override
See widget::calculate_best_size.
void signal_handler_mouse_motion(bool &handled, const point &coordinate)
Mouse motion signal handler: checks if the cursor is on a hyperlink.
std::pair< int, int > get_offset_from_xy(const point &position) const
Returns the byte offset of the character at position, and whether the position is in its trailing hal...
state_t state_
Current state of the widget.
virtual void set_active(const bool) override
Sets the styled_widget's state.
void set_state(const state_t state)
void add_link_area(text_shape &tshape, const std::string &dest, const unsigned start, const unsigned end, const point &origin, int img_width)
Adds the clickable area of a link covering characters [start, end) of tshape's text.
std::function< void(std::string)> link_handler_
virtual void update_canvas() override
Updates the canvas(ses).
std::pair< std::vector< shape_ptr >, point > get_parsed_text(const config &parsed_text, const point &origin, const unsigned init_width, const bool finalize=false)
int padding_
Padding.
void signal_handler_mouse_leave(bool &handled)
Mouse leave signal handler: checks if the cursor left a hyperlink.
std::vector< std::pair< rect, std::string > > links_
link variables and functions
void place(const point &origin, const point &size) override
See widget::place.
int font_size_
Base font size.
unsigned short text_alpha_
std::unique_ptr< gui2::text_shape > new_text_shape(const point &origin, const int max_width)
Create template for text config that can be shown in canvas.
std::string font_family_
Base font family.
unsigned init_w_
Width and height of the canvas.
void set_dom(const config &dom)
point get_xy_from_offset(const unsigned offset) const
color_t get_color(const std::string &color)
If color is a predefined color set in resolution, return it, otherwise decode using font::string_to_c...
wfl::map_formula_callable setup_text_renderer(text_shape &tshape, unsigned width) const
size calculation functions
void request_reduce_width(const unsigned maximum_width) override
See widget::request_reduce_width.
std::string font_style_
Base font style.
state_t
Possible states of the widget.
void register_link_callback(std::function< void(std::string)> link_handler)
void signal_handler_left_button_click(bool &handled)
Left click signal handler: checks if we clicked on a hyperlink.
point get_image_size(const std::string &path) const
bool link_aware_
Whether the rich_label is link aware, rendering links with special formatting and handling click even...
void set_link_color(const color_t &color)
std::map< std::string, color_t > predef_colors_
Color variables that can be used in place of colors strings, like <row bgcolor=color1>
void set_link_aware(bool l)
virtual bool get_link_aware() const override
Returns whether the label should be link_aware, in in rendering and in searching for links with get_l...
std::pair< unsigned, unsigned > add_link(text_shape &tshape, const std::string &name, const std::string &dest, const point &origin, int img_width)
Adds a link to tshape.
void set_text_alpha(unsigned short alpha)
color_t link_color_
What color links will be rendered in.
void set_label(const t_string &text) override
point get_text_size(text_shape &tshape, unsigned width) const
void update_mouse_cursor(bool enable)
Implementation detail for (re)setting the hyperlink cursor.
std::pair< std::size_t, std::size_t > add_text_with_attribute(text_shape &tshape, const t_string &text, const std::string &attr_name="", const std::string &extra_data="")
std::size_t get_split_location(std::string_view text, const point &pos)
PangoAlignment get_text_alignment() const
canvas & get_canvas(const unsigned index)
virtual void request_reduce_width(const unsigned maximum_width) override
See widget::request_reduce_width.
std::vector< canvas > & get_canvases()
virtual void place(const point &origin, const point &size) override
See widget::place.
t_string get_text() const
Definition canvas.cpp:545
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition canvas.cpp:620
std::pair< std::size_t, std::size_t > add_text(const t_string &text)
Definition canvas.cpp:553
void add_attribute(const std::string &attr_name, const std::string &extra_data="", std::size_t start=PANGO_ATTR_INDEX_FROM_TEXT_BEGINNING, std::size_t end=PANGO_ATTR_INDEX_TO_TEXT_END)
Definition canvas.cpp:566
void queue_redraw()
Indicates that this widget should be redrawn.
Definition widget.cpp:464
point get_origin() const
Returns the screen origin of the widget.
Definition widget.cpp:311
Generic locator abstracting the location of an image.
Definition picture.hpp:59
variant query_value(const std::string &key) const
Definition callable.hpp:50
map_formula_callable & add(const std::string &key, const variant &value)
Definition callable.hpp:249
int as_int(int fallback=0) const
Returns the variant's value as an integer.
Definition variant.cpp:336
constexpr uint8_t ALPHA_OPAQUE
Definition color.hpp:37
const config * cfg
static std::string _(const char *str)
Definition gettext.hpp:100
Define the common log macros for the gui toolkit.
#define DBG_GUI_G
Definition log.hpp:41
#define DBG_GUI_P
Definition log.hpp:66
#define DBG_GUI_E
Definition log.hpp:35
Standard logging facilities (interface).
CURSOR_TYPE get()
Definition cursor.cpp:195
@ NORMAL
Definition cursor.hpp:28
@ HYPERLINK
Definition cursor.hpp:28
void set(CURSOR_TYPE type)
Use the default parameter to reset cursors.
Definition cursor.cpp:161
Graphical text output.
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
Definition text.cpp:1071
constexpr float get_line_spacing_factor()
Definition text.hpp:613
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:1077
const int SIZE_TITLE
Definition constants.cpp:31
family_class decode_family_class(const std::string &str)
color_t string_to_color(const std::string &color_str)
Return the color the string represents.
std::string sound_button_click
Definition settings.cpp:50
Generic file dialog.
point get_mouse_position()
Returns the current mouse position.
Definition helper.cpp:167
std::string_view debug_truncate(std::string_view text)
Returns a truncated version of the text.
Definition helper.cpp:172
font::pango_text::FONT_STYLE decode_font_style(const std::string &style)
Converts a font style string to a font style.
Definition helper.cpp:31
PangoAlignment decode_text_alignment(const std::string &alignment)
Converts a text alignment string to a text alignment.
Definition helper.cpp:84
std::string encode_text_alignment(const PangoAlignment alignment)
Converts a PangoAlignment to its string representation.
Definition helper.cpp:130
Contains the implementation details for lexical_cast and shouldn't be used directly.
config parse_text(const std::string &text)
Parse a xml style marked up text string.
Definition markup.cpp:448
void play_UI_sound(const std::string &files)
Definition sound.cpp:1009
std::size_t size(std::string_view str)
Length in characters of a UTF-8 string.
Definition unicode.cpp:81
bool contains(const Container &container, const Value &value)
Returns true iff value is found in container.
Definition general.hpp:88
constexpr bool portable_isspace(int c)
std::vector< std::string > split(const config_attribute_value &val)
int w
Definition pathfind.cpp:188
std::size_t size_
Definition picture.cpp:310
#define REGISTER_WIDGET(id)
Wrapper for REGISTER_WIDGET3.
static lg::log_domain log_rich_label("gui/widget/rich_label")
#define DBG_GUI_RL
Transitional API for porting SDL_ttf-based code to Pango.
This file contains the settings handling of the widget library.
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
std::string to_hex_string() const
Returns the stored color in rrggbb hex format.
Definition color.cpp:88
static color_t from_rgba_string(std::string_view c)
Creates a new color_t object from a string variable in "R,G,B,A" format.
Definition color.cpp:23
virtual std::unique_ptr< widget > build() const override
std::string definition
Parameters for the styled_widget.
std::vector< state_definition > state
std::map< std::string, color_t > colors
rich_label_definition(const config &cfg)
Holds a 2D point.
Definition point.hpp:25
An abstract description of a rectangle with integer coordinates.
Definition rect.hpp:49
static map_location::direction s
std::string missing_mandatory_wml_tag(const std::string &section, const std::string &tag)
Returns a standard message for a missing wml child (tag).
Add a special kind of assert to validate whether the input from WML doesn't contain any problems that...
#define VALIDATE_WML_CHILD(cfg, key, message)
#define h