The Battle for Wesnoth  1.19.21+dev
canvas.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2007 - 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 /**
17  * @file
18  * Implementation of canvas.hpp.
19  */
20 
21 #define GETTEXT_DOMAIN "wesnoth-lib"
22 
23 #include "gui/core/canvas.hpp"
25 
26 #include "draw.hpp"
27 #include "draw_manager.hpp"
28 #include "font/text.hpp"
29 #include "font/attributes.hpp"
30 #include "font/font_options.hpp"
31 #include "formatter.hpp"
32 #include "gettext.hpp"
34 #include "gui/core/log.hpp"
35 #include "gui/widgets/helper.hpp"
36 #include "font/font_config.hpp"
37 #include "font/standard_colors.hpp"
38 #include "picture.hpp"
39 #include "sdl/point.hpp"
40 #include "sdl/rect.hpp"
41 #include "sdl/surface.hpp"
42 #include "sdl/texture.hpp"
43 #include "sdl/utils.hpp" // blur_surface
44 #include "video.hpp" // read_pixels_low_res, only used for blurring
45 #include "wml_exception.hpp"
46 
47 namespace gui2
48 {
49 
50 /***** ***** ***** ***** ***** LINE ***** ***** ***** ***** *****/
51 
53  : shape(cfg)
54  , x1_(cfg["x1"])
55  , y1_(cfg["y1"])
56  , x2_(cfg["x2"])
57  , y2_(cfg["y2"])
58  , color_(cfg["color"])
59  , thickness_(cfg["thickness"].to_unsigned())
60 {
61  const std::string& debug = (cfg["debug"]);
62  if(!debug.empty()) {
63  DBG_GUI_P << "Line: found debug message '" << debug << "'.";
64  }
65 }
66 
68 {
69  /**
70  * @todo formulas are now recalculated every draw cycle which is a bit silly
71  * unless there has been a resize. So to optimize we should use an extra
72  * flag or do the calculation in a separate routine.
73  */
74 
75  const unsigned x1 = x1_(variables);
76  const unsigned y1 = y1_(variables);
77  const unsigned x2 = x2_(variables);
78  const unsigned y2 = y2_(variables);
79 
80  DBG_GUI_D << "Line: draw from " << x1 << ',' << y1 << " to " << x2 << ',' << y2 << ".";
81 
82  // @todo FIXME respect the thickness.
83 
84  draw::line(x1, y1, x2, y2, color_(variables));
85 }
86 
87 /***** ***** ***** ***** ***** Rectangle ***** ***** ***** ***** *****/
88 
91  , border_thickness_(cfg["border_thickness"].to_int())
92  , border_color_(cfg["border_color"], color_t::null_color())
93  , fill_color_(cfg["fill_color"], color_t::null_color())
94 {
95  // Check if a raw color string evaluates to a null color.
96  if(!border_color_.has_formula() && border_color_().null()) {
98  }
99 
100  const std::string& debug = (cfg["debug"]);
101  if(!debug.empty()) {
102  DBG_GUI_P << "Rectangle: found debug message '" << debug << "'.";
103  }
104 }
105 
107  const rect& bounds,
108  const color_t& border_color,
109  const unsigned thickness,
110  const color_t& fill_color)
111  : rect_bounded_shape(bounds)
112  , border_thickness_(thickness)
113  , border_color_(border_color)
114  , fill_color_(fill_color)
115 {
116 }
117 
119 {
120  const rect area {
121  x_(variables),
122  y_(variables),
123  w_(variables),
124  h_(variables)
125  };
126 
127  const color_t fill_color = fill_color_(variables);
128 
129  // Fill the background, if applicable
130  if(!fill_color.null()) {
131  DBG_GUI_D << "fill " << fill_color;
132  draw::set_color(fill_color);
133  draw::fill(area.padded_by(-border_thickness_));
134  }
135 
136  const color_t border_color = border_color_(variables);
137 
138  // Draw the border
139  draw::set_color(border_color);
140  DBG_GUI_D << "border thickness " << border_thickness_ << ", colour " << border_color;
141  for(int i = 0; i < border_thickness_; ++i) {
142  draw::rect(area.padded_by(-i));
143  }
144 }
145 
146 /***** ***** ***** ***** ***** Rounded Rectangle ***** ***** ***** ***** *****/
147 
150  , r_(cfg["corner_radius"])
151  , border_thickness_(cfg["border_thickness"].to_int())
152  , border_color_(cfg["border_color"], color_t::null_color())
153  , fill_color_(cfg["fill_color"], color_t::null_color())
154 {
155  // Check if a raw color string evaluates to a null color.
156  if(!border_color_.has_formula() && border_color_().null()) {
157  border_thickness_ = 0;
158  }
159 
160  const std::string& debug = (cfg["debug"]);
161  if(!debug.empty()) {
162  DBG_GUI_P << "Rounded Rectangle: found debug message '" << debug << "'.";
163  }
164 }
165 
167 {
168  const int x = x_(variables);
169  const int y = y_(variables);
170  const int w = w_(variables);
171  const int h = h_(variables);
172  const int r = r_(variables);
173 
174  DBG_GUI_D << "Rounded Rectangle: draw from " << x << ',' << y << " width " << w << " height " << h << ".";
175 
176  const color_t fill_color = fill_color_(variables);
177 
178  // Fill the background, if applicable
179  if(!fill_color.null() && w && h) {
180  draw::set_color(fill_color);
181 
182  draw::fill(rect{x + r, y + border_thickness_, w - r * 2, r - border_thickness_ + 1});
183  draw::fill(rect{x + border_thickness_, y + r + 1, w - border_thickness_ * 2, h - r * 2});
184  draw::fill(rect{x + r, y - r + h + 1, w - r * 2, r - border_thickness_});
185 
186  draw::disc(x + r, y + r, r, 0xc0);
187  draw::disc(x + w - r, y + r, r, 0x03);
188  draw::disc(x + r, y + h - r, r, 0x30);
189  draw::disc(x + w - r, y + h - r, r, 0x0c);
190  }
191 
192  const color_t border_color = border_color_(variables);
193 
194  // Draw the border
195  draw::set_color(border_color);
196 
197  for(int i = 0; i < border_thickness_; ++i) {
198  draw::line(x + r, y + i, x + w - r, y + i);
199  draw::line(x + r, y + h - i, x + w - r, y + h - i);
200 
201  draw::line(x + i, y + r, x + i, y + h - r);
202  draw::line(x + w - i, y + r, x + w - i, y + h - r);
203 
204  draw::circle(x + r, y + r, r - i, 0xc0);
205  draw::circle(x + w - r, y + r, r - i, 0x03);
206  draw::circle(x + r, y + h - r, r - i, 0x30);
207  draw::circle(x + w - r, y + h - r, r - i, 0x0c);
208  }
209 }
210 
211 /***** ***** ***** ***** ***** CIRCLE ***** ***** ***** ***** *****/
212 
214  : shape(cfg)
215  , x_(cfg["x"])
216  , y_(cfg["y"])
217  , radius_(cfg["radius"])
218  , border_color_(cfg["border_color"])
219  , fill_color_(cfg["fill_color"])
220  , border_thickness_(cfg["border_thickness"].to_int(1))
221 {
222  const std::string& debug = (cfg["debug"]);
223  if(!debug.empty()) {
224  DBG_GUI_P << "Circle: found debug message '" << debug << "'.";
225  }
226 }
227 
229 {
230  /**
231  * @todo formulas are now recalculated every draw cycle which is a bit
232  * silly unless there has been a resize. So to optimize we should use an
233  * extra flag or do the calculation in a separate routine.
234  */
235  const int x = x_(variables);
236  const int y = y_(variables);
237  const unsigned radius = radius_(variables);
238  const color_t fill_color = fill_color_(variables);
239  if (!fill_color.null()) {
240  draw::cairo_disc(x, y, radius, fill_color);
241  }
242 
243  const color_t border_color = border_color_(variables);
244  draw::cairo_circle(x, y, radius, border_color, border_thickness_);
245 
246  DBG_GUI_D << "Circle: drawn at " << x << ',' << y << " radius " << radius << ".";
247 }
248 
249 /***** ***** ***** ***** ***** IMAGE ***** ***** ***** ***** *****/
250 
252  : shape(cfg)
253  , x_(cfg["x"])
254  , y_(cfg["y"])
255  , w_(cfg["w"])
256  , h_(cfg["h"])
257  , image_name_(cfg["name"], "") // avoid ambiguous ctor error
258  , resize_mode_(get_resize_mode(cfg["resize_mode"]))
259  , mirror_(cfg.get_old_attribute("mirror", "vertical_mirror", "image"))
260  , actions_formula_(cfg["actions"], &functions)
261  , failure_logged_(false)
262 {
263  const std::string& debug = (cfg["debug"]);
264  if(!debug.empty()) {
265  DBG_GUI_P << "Image: found debug message '" << debug << "'.";
266  }
267 }
268 
270  const point& origin,
271  const std::string& img_path)
272  : shape()
273  , x_(origin.x)
274  , y_(origin.y)
275  , w_("(image_width)")
276  , h_("(image_height)")
277  , image_name_(img_path, img_path) // avoid ambiguous ctor error
278  , resize_mode_(get_resize_mode("scale_sharp"))
279  , mirror_(false)
280  , actions_formula_("")
281 {
282 }
283 
284 void image_shape::dimension_validation(unsigned value, const std::string& name, const std::string& key)
285 {
286  const int as_int = static_cast<int>(value);
287 
288  VALIDATE_WITH_DEV_MESSAGE(as_int >= 0, _("Image doesn’t fit on canvas."),
289  formatter() << "Image '" << name << "', " << key << " = " << as_int << "."
290  );
291 }
292 
294 {
295  DBG_GUI_D << "Image: draw.";
296 
297  // The name will be passed to the texture loading code on each draw, any caching is left to the
298  // image loading code itself. A name can point to a different image file due to i18n support,
299  // even when the image_name_ isn't a formula.
300  const std::string& name = image_name_(variables);
301 
302  if(name.empty()) {
303  if(!failure_logged_) {
304  DBG_GUI_D << "Image: name is empty or contains invalid formula, will not be drawn.";
305  failure_logged_ = true;
306  }
307  return;
308  }
309 
310  // Texture filtering mode must be set on texture creation,
311  // so check whether we need smooth scaling or not here.
315  {
317  }
319 
320  if(!tex) {
321  if(!failure_logged_) {
322  ERR_GUI_D << "Image: '" << name << "' not found and won't be drawn.";
323  failure_logged_ = true;
324  }
325  return;
326  }
327 
328  wfl::map_formula_callable local_variables(variables);
329  local_variables.add("image_original_width", wfl::variant(tex.w()));
330  local_variables.add("image_original_height", wfl::variant(tex.h()));
331 
332  int w = w_(local_variables);
333  dimension_validation(w, name, "w");
334 
335  int h = h_(local_variables);
336  dimension_validation(h, name, "h");
337 
338  local_variables.add("image_width", wfl::variant(w ? w : tex.w()));
339  local_variables.add("image_height", wfl::variant(h ? h : tex.h()));
340 
341  const int x = x_(local_variables);
342  const int y = y_(local_variables);
343 
344  // used in gui/dialogs/story_viewer.cpp
345  local_variables.add("clip_x", wfl::variant(x));
346  local_variables.add("clip_y", wfl::variant(y));
347 
348  if (variables.has_key("fake_draw") && variables.query_value("fake_draw").as_bool()) {
349  variables.add("image_original_width", wfl::variant(tex.w()));
350  variables.add("image_original_height", wfl::variant(tex.h()));
351  variables.add("image_width", wfl::variant(w ? w : tex.w()));
352  variables.add("image_height", wfl::variant(h ? h : tex.h()));
353  return;
354  }
355 
356  // Execute the provided actions for this context.
357  wfl::variant(variables.fake_ptr()).execute_variant(actions_formula_.evaluate(local_variables));
358 
359  // If w or h is 0, assume it means the whole image.
360  if (!w) { w = tex.w(); }
361  if (!h) { h = tex.h(); }
362 
363  const rect dst_rect { x, y, w, h };
364 
365  // What to do with the image depends on whether we need to tile it or not.
366  switch(resize_mode_) {
367  case resize_mode::tile:
368  draw::tiled(tex, dst_rect, false, mirror_(variables));
369  break;
371  draw::tiled(tex, dst_rect, true, mirror_(variables));
372  break;
374  draw::tiled_highres(tex, dst_rect, false, mirror_(variables));
375  break;
377  // Stretching is identical to scaling in terms of handling.
378  // Is this intended? That's what previous code was doing.
379  case resize_mode::scale:
380  // Filtering mode is set on texture creation above.
381  // Handling is otherwise identical to sharp scaling.
383  if(mirror_(variables)) {
384  draw::flipped(tex, dst_rect);
385  } else {
386  draw::blit(tex, dst_rect);
387  }
388  break;
389  default:
390  ERR_GUI_D << "Image: unrecognized resize mode.";
391  break;
392  }
393 }
394 
396 {
397  if(resize_mode == "tile") {
398  return resize_mode::tile;
399  } else if(resize_mode == "tile_center") {
401  } else if(resize_mode == "tile_highres") {
403  } else if(resize_mode == "stretch") {
404  return resize_mode::stretch;
405  } else if(resize_mode == "scale_sharp") {
407  } else if(resize_mode == "scale") {
408  return resize_mode::scale;
409  } else {
410  if(!resize_mode.empty()) {
411  ERR_GUI_E << "Invalid resize mode '" << resize_mode << "' falling back to 'scale'.";
412  }
413 
414  // Linear scaling just looks horrible as a default, especially on HDPI screens, and even
415  // for some non-pixel art (the logo, for example). Nearest-neighbor isn't perfect for those
416  // usecases, but it's definitely better, in my opinion.
417  //
418  // -- vultraz, 2022-08-20
420  }
421 }
422 
423 /***** ***** ***** ***** ***** TEXT ***** ***** ***** ***** *****/
424 
425 namespace
426 {
427 /** Populates the attribute list from the given config child range. */
428 auto parse_attributes(const config::const_child_itors& range)
429 {
430  // TODO: most of the time this will be empty, unless you're using rich_label.
431  // It's a lot of memory allocations to always have a valid object here...
432  // Do we need store it as an optional?
433  font::attribute_list text_attributes;
434 
435  for(const config& attr : range) {
436  const std::string name = attr["name"];
437 
438  if(name.empty()) {
439  continue;
440  }
441 
442  const unsigned start = attr["start"].to_int(PANGO_ATTR_INDEX_FROM_TEXT_BEGINNING);
443  const unsigned end = attr["end"].to_int(PANGO_ATTR_INDEX_TO_TEXT_END);
444 
445  // Attributes with start == end set won't do anything, so skip
446  if (start == end) {
447  WRN_GUI_D << "attribute " << name << " has equal start and end indices, will not be added.";
448  continue;
449  }
450 
451  if (name == "color" || name == "fgcolor" || name == "foreground") {
452  add_attribute_fg_color(text_attributes, start, end, attr["value"].empty() ? font::NORMAL_COLOR : font::string_to_color(attr["value"]));
453  } else if (name == "bgcolor" || name == "background") {
454  add_attribute_bg_color(text_attributes, start, end, attr["value"].empty() ? font::GOOD_COLOR : font::string_to_color(attr["value"]));
455  } else if (name == "font_size" || name == "size") {
456  add_attribute_size(text_attributes, start, end, attr["value"].to_int(font::SIZE_NORMAL));
457  } else if (name == "font_family" || name == "face") {
458  add_attribute_font_family(text_attributes, start, end, font::decode_family_class(attr["value"]));
459  } else if (name == "weight") {
460  add_attribute_weight(text_attributes, start, end, decode_text_weight(attr["value"]));
461  } else if (name == "style") {
462  add_attribute_style(text_attributes, start, end, decode_text_style(attr["value"]));
463  } else if (name == "bold" || name == "b") {
464  add_attribute_weight(text_attributes, start, end, PANGO_WEIGHT_BOLD);
465  } else if (name == "italic" || name == "i") {
466  add_attribute_style(text_attributes, start, end, PANGO_STYLE_ITALIC);
467  } else if (name == "underline" || name == "u") {
468  add_attribute_underline(text_attributes, start, end, PANGO_UNDERLINE_SINGLE);
469  } else if (name == "line_height") {
470  add_attribute_line_height(text_attributes, start, end, attr["value"].to_double());
471  } else if (name == "image") { // An inline image that behave as a custom text glyph
472  add_attribute_image_shape(text_attributes, start, end, attr["value"]);
473  } else {
474  // Unsupported formatting or normal text
475  add_attribute_weight(text_attributes, start, end, PANGO_WEIGHT_NORMAL);
476  add_attribute_style(text_attributes, start, end, PANGO_STYLE_NORMAL);
477  }
478  }
479 
480  return text_attributes;
481 }
482 
483 } // anon namespace
484 
487  , font_family_(font::decode_family_class(cfg["font_family"]))
488  , font_size_(cfg["font_size"], font::SIZE_NORMAL)
489  , font_style_(decode_font_style(cfg["font_style"]))
490  , text_alignment_(cfg["text_alignment"])
491  , color_(cfg["color"], font::NORMAL_COLOR)
492  , text_(cfg["text"])
493  , parse_text_as_formula_(cfg["parse_text_as_formula"].to_bool(true))
494  , text_markup_(cfg["text_markup"], false)
495  , link_aware_(cfg["text_link_aware"], false)
496  , link_color_(cfg["text_link_color"], font::YELLOW_COLOR)
497  , maximum_width_(cfg["maximum_width"], -1)
498  , characters_per_line_(cfg["text_characters_per_line"].to_unsigned())
499  , maximum_height_(cfg["maximum_height"], -1)
500  , highlight_start_(cfg["highlight_start"])
501  , highlight_end_(cfg["highlight_end"])
502  , highlight_color_(cfg["highlight_color"], color_t::from_hex_string("215380"))
503  , line_spacing_(cfg["line_spacing"].to_double(font::get_line_spacing_factor()))
504  , outline_(cfg["outline"], false)
505  , actions_formula_(cfg["actions"], &functions)
506  , text_attributes_(parse_attributes(cfg.child_range("attribute")))
507 {
508  const std::string& debug = (cfg["debug"]);
509  if(!debug.empty()) {
510  DBG_GUI_P << "Text: found debug message '" << debug << "'.";
511  }
512 }
513 
515  const point& origin,
516  font::family_class family,
517  const unsigned size,
519  const std::string& align,
520  const unsigned width)
521  : rect_bounded_shape(origin, "(text_width)", "(text_height)")
522  , font_family_(family)
523  , font_size_(size)
524  , font_style_(style)
525  , text_alignment_(align)
526  , color_(font::NORMAL_COLOR)
527  , parse_text_as_formula_(false)
528  , text_markup_(false)
529  , link_aware_(false)
530  , link_color_(font::YELLOW_COLOR)
531  , maximum_width_(width)
532  , characters_per_line_(0)
533  , maximum_height_(-1)
534  , highlight_start_("")
535  , highlight_end_("")
536  , highlight_color_(color_t::from_hex_string("215380"))
537  , line_spacing_(0)
538  , outline_(false)
539  , actions_formula_("")
540  , text_attributes_()
541 {
542 }
543 
545  return text_.t_str();
546 }
547 
548 void text_shape::set_text(const t_string& text) {
549  text_ = text;
550 }
551 
552 std::pair<std::size_t, std::size_t> text_shape::add_text(const t_string& text)
553 {
554  t_string old_text = get_text();
555  std::size_t start = old_text.size();
556  set_text(old_text + text);
557  std::size_t end = start + text.size();
558  return { start, end };
559 }
560 
561 void text_shape::set_wrap_width(const unsigned wrap_width) {
562  maximum_width_.set_value(wrap_width);
563 }
564 
566  const std::string& name,
567  const std::string& extra_data,
568  std::size_t start,
569  std::size_t end)
570 {
571  if(name.empty()) {
572  return;
573  }
574 
575  // Attributes with start == end set won't do anything, so skip
576  if (start == end) {
577  WRN_GUI_D << "attribute " << name << " has equal start and end indices, will not be added.";
578  return;
579  }
580 
581  if (name == "color" || name == "fgcolor" || name == "foreground") {
582  add_attribute_fg_color(text_attributes_, start, end, extra_data.empty() ? font::NORMAL_COLOR : font::string_to_color(extra_data));
583  } else if (name == "bgcolor" || name == "background") {
584  add_attribute_bg_color(text_attributes_, start, end, extra_data.empty() ? font::GOOD_COLOR : font::string_to_color(extra_data));
585  } else if (name == "font_size" || name == "size") {
587  } else if (name == "font_family" || name == "face") {
589  } else if (name == "weight") {
591  } else if (name == "style") {
593  } else if (name == "bold" || name == "b") {
594  add_attribute_weight(text_attributes_, start, end, PANGO_WEIGHT_BOLD);
595  } else if (name == "italic" || name == "i") {
596  add_attribute_style(text_attributes_, start, end, PANGO_STYLE_ITALIC);
597  } else if (name == "underline" || name == "u") {
598  add_attribute_underline(text_attributes_, start, end, PANGO_UNDERLINE_SINGLE);
599  } else if (name == "line_height") {
601  } else if (name == "image") { // An inline image that behave as a custom text glyph
603  } else {
604  // Unsupported formatting or normal text
605  add_attribute_weight(text_attributes_, start, end, PANGO_WEIGHT_NORMAL);
606  add_attribute_style(text_attributes_, start, end, PANGO_STYLE_NORMAL);
607  }
608 }
609 
610 void text_shape::add_attributes_from(text_shape& tshape2, const unsigned attr_start)
611 {
612  text_attributes_.splice_into(tshape2.text_attributes_, attr_start);
613 }
614 
616 {
617  assert(variables.has_key("text"));
618 
619  // We first need to determine the size of the text which need the rendered
620  // text. So resolve and render the text first and then start to resolve
621  // the other formulas.
622  const auto text = parse_text_as_formula_
623  ? typed_formula<t_string>{text_}(variables)
624  : text_.t_str();
625 
626  if(text.empty()) {
627  DBG_GUI_D << "Text: no text to render, leave.";
628  return;
629  }
630 
631  //
632  // Highlight
633  //
634  const int highlight_start = highlight_start_(variables);
635  const int highlight_end = highlight_end_(variables);
636 
637  if(highlight_start != highlight_end) {
638  add_attribute_bg_color(text_attributes_, highlight_start, highlight_end, highlight_color_(variables));
639  }
640 
641  font::pango_text& text_renderer = font::get_text_renderer();
642  text_renderer.clear_attributes();
643 
644  text_renderer
645  .set_link_aware(link_aware_(variables))
646  .set_link_color(link_color_(variables))
647  .set_text(text, text_markup_(variables));
648 
649  text_renderer
651  .set_font_size(font_size_(variables))
653  .set_alignment(text_alignment_(variables))
654  .set_foreground_color(color_(variables))
655  .set_maximum_width(maximum_width_(variables))
656  .set_maximum_height(maximum_height_(variables), true)
657  .set_ellipse_mode(variables.has_key("text_wrap_mode")
658  ? static_cast<PangoEllipsizeMode>(variables.query_value("text_wrap_mode").as_int())
659  : PANGO_ELLIPSIZE_END)
661  .set_add_outline(outline_(variables))
663 
664  // Do this last so it can merge with attributes from markup
665  text_renderer.apply_attributes(text_attributes_);
666 
667  wfl::map_formula_callable local_variables(variables);
668  const auto [tw, th] = text_renderer.get_size();
669 
670  // Translate text width and height back to draw-space, rounding up.
671  local_variables.add("text_width", wfl::variant(tw));
672  local_variables.add("text_height", wfl::variant(th));
673 
674  if (variables.has_key("fake_draw") && variables.query_value("fake_draw").as_bool()) {
675  variables.add("text_width", wfl::variant(tw));
676  variables.add("text_height", wfl::variant(th));
677  return;
678  }
679 
680  const int x = x_(local_variables);
681  const int y = y_(local_variables);
682  const int w = w_(local_variables);
683  const int h = h_(local_variables);
684  rect dst_rect{x, y, w, h};
685 
686  // Execute the provided actions for this context.
687  wfl::variant(variables.fake_ptr()).execute_variant(actions_formula_.evaluate(local_variables));
688 
689  texture tex = text_renderer.render_and_get_texture();
690  if(!tex) {
691  DBG_GUI_D << "Text: Rendering '" << text << "' resulted in an empty canvas, leave.";
692  return;
693  }
694 
695  dst_rect.w = std::min(dst_rect.w, tex.w());
696  dst_rect.h = std::min(dst_rect.h, tex.h());
697 
698  draw::blit(tex, dst_rect);
699 }
700 
701 /***** ***** ***** ***** ***** CANVAS ***** ***** ***** ***** *****/
702 
704  : shapes_()
705  , blur_depth_(0)
706  , blur_region_()
707  , deferred_(false)
708  , w_(0)
709  , h_(0)
710  , variables_()
711  , functions_()
712 {
713  parse_cfg(cfg);
714 }
715 
716 // It would be better if the blur effect was managed at a higher level.
717 // But for now this works and should be both general and robust.
718 bool canvas::update_blur(const rect& screen_region, bool force)
719 {
720  if(!blur_depth_) {
721  // No blurring needed.
722  return true;
723  }
724 
725  if(screen_region != blur_region_) {
726  DBG_GUI_D << "blur region changed from " << blur_region_
727  << " to " << screen_region;
728  // something has changed. regenerate the texture.
730  blur_region_ = screen_region;
731  }
732 
733  if(blur_texture_ && !force) {
734  // We already made the blur. It's expensive, so don't do it again.
735  return true;
736  }
737 
738  // To blur what is underneath us, it must already be rendered somewhere.
739  // This is okay for sub-elements of an opaque window (panels on the main
740  // title screen for example) as the window will already have rendered
741  // its background to the render buffer before we get here.
742  // If however we are blurring elements behind the window, such as if
743  // the window itself is translucent (objectives popup), or it is
744  // transparent with a translucent element (character dialogue),
745  // then we need to render what will be behind it before capturing that
746  // and rendering a blur.
747  // We could use the previous render frame, but there could well have been
748  // another element there last frame such as a popup window which we
749  // don't want to be part of the blur.
750  // The stable solution is to render in multiple passes,
751  // so that is what we shall do.
752 
753  // For the first pass, this element and its children are not rendered.
754  if(!deferred_) {
755  DBG_GUI_D << "Deferring blur at " << screen_region;
756  deferred_ = true;
758  return false;
759  }
760 
761  // For the second pass we read the result of the first pass at
762  // this widget's location, and blur it.
763  DBG_GUI_D << "Blurring " << screen_region << " depth " << blur_depth_;
764  rect read_region = screen_region;
765  auto setter = draw::set_render_target({});
766  surface s = video::read_pixels_low_res(&read_region);
767  blur_surface(s, {0, 0, s->w, s->h}, blur_depth_);
769  deferred_ = false;
770  return true;
771 }
772 
774 {
776 }
777 
779 {
780  // This early-return has to come before the `validate(rect.w <= w_)` check, as during the boost_unit_tests execution
781  // the debug_clock widget will have no shapes, 0x0 size, yet be given a larger rect to draw.
782  if(shapes_.empty()) {
783  DBG_GUI_D << "Canvas: empty (no shapes to draw).";
784  return;
785  }
786 
787  if(deferred_) {
788  // We will draw next frame.
789  return;
790  }
791 
792  // Draw blurred background.
793  // TODO: hwaccel - this should be able to be removed at some point with shaders
794  if(blur_depth_ && blur_texture_) {
795  DBG_GUI_D << "blitting blur size " << blur_texture_.draw_size();
797  }
798 
799  // Draw items
800  for(auto& shape : shapes_) {
801  assert(shape);
802  const lg::scope_logger inner_scope_logging_object__{log_gui_draw, "Canvas: draw shape."};
804  }
805 }
806 
808 {
809  log_scope2(log_gui_parse, "Canvas: parsing config.");
810 
811  for(const auto [type, data] : cfg.all_children_view())
812  {
813  DBG_GUI_P << "Canvas: found shape of the type " << type << ".";
814 
815  if(type == "line") {
816  shapes_.emplace_back(std::make_unique<line_shape>(data));
817  } else if(type == "rectangle") {
818  shapes_.emplace_back(std::make_unique<rectangle_shape>(data));
819  } else if(type == "round_rectangle") {
820  shapes_.emplace_back(std::make_unique<round_rectangle_shape>(data));
821  } else if(type == "circle") {
822  shapes_.emplace_back(std::make_unique<circle_shape>(data));
823  } else if(type == "image") {
824  shapes_.emplace_back(std::make_unique<image_shape>(data, functions_));
825  } else if(type == "text") {
826  shapes_.emplace_back(std::make_unique<text_shape>(data, functions_));
827  } else if(type == "pre_commit") {
828 
829  /* note this should get split if more preprocessing is used. */
830  for(const auto [func_key, func_cfg] : data.all_children_view())
831  {
832  if(func_key == "blur") {
833  blur_depth_ = func_cfg["depth"].to_unsigned();
834  } else {
835  ERR_GUI_P << "Canvas: found a pre commit function"
836  << " of an invalid type " << type << ".";
837  }
838  }
839 
840  } else {
841  ERR_GUI_P << "Canvas: found a shape of an invalid type " << type
842  << ".";
843  }
844  }
845 }
846 
848 {
850  variables_.add("width", wfl::variant(w_));
851  variables_.add("height", wfl::variant(h_));
852 }
853 
855 {
856  w_ = size.x;
857  h_ = size.y;
859 }
860 
861 void canvas::clear_shapes(const bool force)
862 {
863  if(force) {
864  shapes_.clear();
865  } else {
866  utils::erase_if(shapes_, [](const std::unique_ptr<shape>& s) { return !s->immutable(); });
867  }
868 }
869 
870 /***** ***** ***** ***** ***** SHAPE ***** ***** ***** ***** *****/
871 
872 } // namespace gui2
std::size_t w_
#define debug(x)
This file contains the canvas object which is the part where the widgets draw (temporally) images on.
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:157
auto all_children_view() const
In-order iteration over all children.
Definition: config.hpp:795
boost::iterator_range< const_child_iterator > const_child_itors
Definition: config.hpp:281
Helper class to encapsulate the management of a PangoAttrList.
Definition: attributes.hpp:28
void splice_into(PangoAttrList *target) const
Definition: attributes.hpp:71
Text class.
Definition: text.hpp:78
pango_text & set_font_style(const FONT_STYLE font_style)
Definition: text.cpp:381
void clear_attributes()
Definition: text.cpp:319
point get_size()
Returns the size of the text, in drawing coordinates.
Definition: text.cpp:154
pango_text & set_characters_per_line(const unsigned characters_per_line)
Definition: text.cpp:416
pango_text & set_foreground_color(const color_t &color)
Definition: text.cpp:391
pango_text & set_line_spacing(float line_spacing)
Definition: text.hpp:352
pango_text & set_family_class(font::family_class fclass)
Definition: text.cpp:359
void apply_attributes(const font::attribute_list &attrs)
Definition: text.cpp:324
pango_text & set_add_outline(bool do_add)
Definition: text.cpp:514
pango_text & set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
Definition: text.cpp:452
pango_text & set_alignment(const PangoAlignment alignment)
Definition: text.cpp:472
pango_text & set_font_size(unsigned font_size)
Definition: text.cpp:369
pango_text & set_link_aware(bool b)
Definition: text.cpp:495
bool set_text(const std::string &text, const bool markedup)
Sets the text to render.
Definition: text.cpp:333
pango_text & set_maximum_height(int height, bool multiline)
Definition: text.cpp:427
pango_text & set_maximum_width(int width)
Definition: text.cpp:400
texture render_and_get_texture()
Returns the cached texture, or creates a new one otherwise.
Definition: text.cpp:122
pango_text & set_link_color(const color_t &color)
Definition: text.cpp:504
std::ostringstream wrapper.
Definition: formatter.hpp:40
Abstract base class for all other shapes.
Definition: canvas.hpp:54
virtual void draw(wfl::map_formula_callable &variables)=0
Draws the canvas.
texture blur_texture_
Blurred background texture.
Definition: canvas.hpp:190
bool deferred_
Whether we have deferred rendering so we can capture for blur.
Definition: canvas.hpp:196
wfl::action_function_symbol_table functions_
Action function definitions for the canvas.
Definition: canvas.hpp:208
void clear_shapes(const bool force)
Definition: canvas.cpp:861
unsigned blur_depth_
The depth of the blur to use in the pre committing.
Definition: canvas.hpp:187
wfl::map_formula_callable variables_
The variables of the canvas.
Definition: canvas.hpp:205
bool update_blur(const rect &screen_region, const bool force=false)
Update the background blur texture, if relevant and necessary.
Definition: canvas.cpp:718
rect blur_region_
The region of the screen we have blurred (if any).
Definition: canvas.hpp:193
void parse_cfg(const config &cfg)
Parses a config object.
Definition: canvas.cpp:807
void queue_reblur()
Clear the cached blur texture, forcing it to regenerate.
Definition: canvas.cpp:773
canvas(const config &cfg)
Definition: canvas.cpp:703
std::vector< std::unique_ptr< shape > > shapes_
Vector with the shapes to draw.
Definition: canvas.hpp:177
unsigned w_
The full width of the canvas.
Definition: canvas.hpp:199
void update_size_variables()
Update WFL size variables.
Definition: canvas.cpp:847
unsigned h_
The full height of the canvas.
Definition: canvas.hpp:202
void draw()
Draw the canvas' shapes onto the screen.
Definition: canvas.cpp:778
void set_size(const point &size)
Definition: canvas.cpp:854
typed_formula< color_t > border_color_
The border color of the circle.
typed_formula< unsigned > x_
The center x coordinate of the circle.
typed_formula< unsigned > radius_
The radius of the circle.
unsigned int border_thickness_
The border thickness of the circle.
circle_shape(const config &cfg)
Constructor.
Definition: canvas.cpp:213
typed_formula< color_t > fill_color_
The fill color of the circle.
typed_formula< unsigned > y_
The center y coordinate of the circle.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:228
typed_formula< std::string > image_name_
Image path from which the image will be loaded.
resize_mode
Determines the way an image will be resized.
bool failure_logged_
Prevents duplicate error logs when an image can't be loaded.
typed_formula< unsigned > w_
The width of the image.
resize_mode get_resize_mode(const std::string &resize_mode)
Converts a string to a resize mode.
Definition: canvas.cpp:395
typed_formula< unsigned > x_
The x coordinate of the image.
static void dimension_validation(unsigned value, const std::string &name, const std::string &key)
Definition: canvas.cpp:284
typed_formula< unsigned > y_
The y coordinate of the image.
typed_formula< unsigned > h_
The height of the image.
resize_mode resize_mode_
The resize mode for an image.
wfl::formula actions_formula_
typed_formula< bool > mirror_
Mirror the image over the vertical axis.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:293
image_shape(const config &cfg, wfl::action_function_symbol_table &functions)
Constructor.
Definition: canvas.cpp:251
typed_formula< color_t > color_
The color of the line.
typed_formula< unsigned > x1_
The start x coordinate of the line.
typed_formula< unsigned > y1_
The start y coordinate of the line.
typed_formula< unsigned > x2_
The end x coordinate of the line.
line_shape(const config &cfg)
Constructor.
Definition: canvas.cpp:52
typed_formula< unsigned > y2_
The end y coordinate of the line.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:67
typed_formula< int > x_
The x coordinate of the rectangle.
typed_formula< int > w_
The width of the rectangle.
typed_formula< int > y_
The y coordinate of the rectangle.
typed_formula< int > h_
The height of the rectangle.
rectangle_shape(const config &cfg)
Constructor.
Definition: canvas.cpp:89
int border_thickness_
Border thickness.
typed_formula< color_t > fill_color_
The border color of the rectangle.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:118
typed_formula< color_t > border_color_
The border color of the rectangle.
typed_formula< color_t > border_color_
The border color of the rounded rectangle.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:166
typed_formula< int > r_
The radius of the corners.
round_rectangle_shape(const config &cfg)
Constructor.
Definition: canvas.cpp:148
int border_thickness_
Border thickness.
typed_formula< color_t > fill_color_
The border color of the rounded rectangle.
font::pango_text::FONT_STYLE font_style_
The style of the text.
typed_formula< bool > outline_
Whether to apply a text outline.
typed_formula< color_t > color_
The color of the text.
typed_formula< int > maximum_height_
The maximum height for the text.
bool parse_text_as_formula_
Whether to parse text_ as WFL formula.
t_string get_text() const
Definition: canvas.cpp:544
typed_formula< bool > link_aware_
The link aware switch of the text.
typed_formula< PangoAlignment > text_alignment_
The alignment of the text.
void set_text(const t_string &text)
Definition: canvas.cpp:548
void add_attributes_from(text_shape &tshape2, const unsigned attr_start)
Definition: canvas.cpp:610
typed_formula< color_t > highlight_color_
The color to be used for highlighting.
font::family_class font_family_
The text font family.
typed_formula< color_t > link_color_
The link color of the text.
typed_formula< int > maximum_width_
The maximum width for the text.
void draw(wfl::map_formula_callable &variables) override
Draws the canvas.
Definition: canvas.cpp:615
text_shape(const config &cfg, wfl::action_function_symbol_table &functions)
Constructor.
Definition: canvas.cpp:485
std::pair< std::size_t, std::size_t > add_text(const t_string &text)
Definition: canvas.cpp:552
config::attribute_value text_
The text to draw.
typed_formula< int > highlight_end_
End offset for highlight.
void set_wrap_width(const unsigned wrap_width)
Definition: canvas.cpp:561
float line_spacing_
Spacing between lines.
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:565
typed_formula< int > highlight_start_
Start offset for highlight.
typed_formula< unsigned > font_size_
The font size of the text.
unsigned characters_per_line_
The number of characters per line.
wfl::formula actions_formula_
Any extra WFL actions to execute.
font::attribute_list text_attributes_
Any custom Pango text attributes.
typed_formula< bool > text_markup_
The text markup switch of the text.
Template class can hold a value or a formula to calculate the value.
bool has_formula() const
Determine whether the class contains a formula.
void set_value(T value)
Set the value for this object.
Generic locator abstracting the location of an image.
Definition: picture.hpp:59
std::string::size_type size() const
Definition: tstring.hpp:201
Wrapper class to encapsulate creation and management of an SDL_Texture.
Definition: texture.hpp:33
int w() const
The draw-space width of the texture, in pixels.
Definition: texture.hpp:103
void reset()
Releases ownership of the managed texture and resets the ptr to null.
Definition: texture.cpp:184
point draw_size() const
The size of the texture in draw-space.
Definition: texture.hpp:120
int h() const
The draw-space height of the texture, in pixels.
Definition: texture.hpp:112
formula_callable_ptr fake_ptr()
Definition: callable.hpp:42
variant query_value(const std::string &key) const
Definition: callable.hpp:50
bool has_key(const std::string &key) const
Definition: callable.hpp:82
static variant evaluate(const const_formula_ptr &f, const formula_callable &variables, formula_debugger *fdb=nullptr, variant default_res=variant(0))
Definition: formula.hpp:48
map_formula_callable & add(const std::string &key, const variant &value)
Definition: callable.hpp:253
variant execute_variant(const variant &to_exec)
Definition: variant.cpp:691
int as_int(int fallback=0) const
Returns the variant's value as an integer.
Definition: variant.cpp:300
bool as_bool() const
Returns a boolean state of the variant value.
Definition: variant.cpp:322
Drawing functions, for drawing things on the screen.
const config * cfg
std::size_t i
Definition: function.cpp:1031
static std::string _(const char *str)
Definition: gettext.hpp:97
Define the common log macros for the gui toolkit.
#define ERR_GUI_P
Definition: log.hpp:69
#define DBG_GUI_P
Definition: log.hpp:66
#define ERR_GUI_D
Definition: log.hpp:32
#define ERR_GUI_E
Definition: log.hpp:38
#define DBG_GUI_D
Definition: log.hpp:29
#define WRN_GUI_D
Definition: log.hpp:31
#define log_scope2(domain, description)
Definition: log.hpp:276
void request_extra_render_pass()
Request an extra render pass.
void tiled_highres(const texture &tex, const ::rect &dst, bool centered=false, bool mirrored=false)
Tile a texture to fill a region.
Definition: draw.cpp:481
render_target_setter set_render_target(const texture &t)
Set the given texture as the active render target.
Definition: draw.cpp:748
void circle(int x, int y, int r, const color_t &c, uint8_t octants=0xff)
Draw a circle of the given colour.
Definition: draw.cpp:220
void tiled(const texture &tex, const ::rect &dst, bool centered=false, bool mirrored=false)
Tile a texture to fill a region.
Definition: draw.cpp:453
void rect(const ::rect &rect)
Draw a rectangle.
Definition: draw.cpp:159
void cairo_disc(int cx, int cy, int r, const color_t &c)
Draw filled circle using Cairo.
Definition: draw.cpp:358
void flipped(const texture &tex, const ::rect &dst, bool flip_h=true, bool flip_v=false)
Draws a texture, or part of a texture, at the given location, also mirroring/flipping the texture hor...
Definition: draw.cpp:424
void cairo_circle(int cx, int cy, int r, const color_t &c, int thickness)
Draw outline of circle using Cairo.
Definition: draw.cpp:320
void disc(int x, int y, int r, const color_t &c, uint8_t octants=0xff)
Draw a solid disc of the given colour.
Definition: draw.cpp:262
void set_color(uint8_t r, uint8_t g, uint8_t b, uint8_t a)
Set the drawing colour.
Definition: draw.cpp:109
void fill(const ::rect &rect, uint8_t r, uint8_t g, uint8_t b, uint8_t a)
Fill an area with the given colour.
Definition: draw.cpp:52
void blit(const texture &tex, const ::rect &dst)
Draws a texture, or part of a texture, at the given location.
Definition: draw.cpp:394
void line(int from_x, int from_y, int to_x, int to_y)
Draw a line.
Definition: draw.cpp:189
EXIT_STATUS start(bool clear_id, const std::string &filename, bool take_screenshot, const std::string &screenshot_filename)
Main interface for launching the editor from the title screen.
Graphical text output.
const color_t YELLOW_COLOR
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
Definition: text.cpp:960
void add_attribute_image_shape(attribute_list &list, unsigned offset_start, unsigned offset_end, const std::string &image_path)
Add Pango shape attribute to a specific portion of text.
Definition: attributes.cpp:180
constexpr float get_line_spacing_factor()
Definition: text.hpp:570
const color_t GOOD_COLOR
void add_attribute_size(attribute_list &list, unsigned offset_start, unsigned offset_end, int size)
Add Pango font size attribute to a specific portion of text.
Definition: attributes.cpp:64
void add_attribute_bg_color(attribute_list &list, unsigned offset_start, unsigned offset_end, const color_t &color)
Mark a specific portion of text for highlighting.
Definition: attributes.cpp:135
void add_attribute_weight(attribute_list &list, unsigned offset_start, unsigned offset_end, PangoWeight weight)
Add Pango font weight attribute to a specific portion of text.
Definition: attributes.cpp:80
void add_attribute_line_height(attribute_list &list, unsigned offset_start, unsigned offset_end, const double factor)
Add Pango line height attribute to a specific portion of text.
Definition: attributes.cpp:166
void add_attribute_underline(attribute_list &list, unsigned offset_start, unsigned offset_end, PangoUnderline underline)
Add Pango underline attribute to a specific portion of text.
Definition: attributes.cpp:106
family_class decode_family_class(const std::string &str)
void add_attribute_font_family(attribute_list &list, unsigned offset_start, unsigned offset_end, font::family_class family)
Add Pango font family attribute to a specific portion of text.
Definition: attributes.cpp:150
void add_attribute_style(attribute_list &list, unsigned offset_start, unsigned offset_end, PangoStyle style)
Add Pango font style attribute to a specific portion of text, used to set italic/oblique text.
Definition: attributes.cpp:93
const int SIZE_NORMAL
Definition: constants.cpp:20
const color_t NORMAL_COLOR
color_t string_to_color(const std::string &color_str)
Return the color the string represents.
void add_attribute_fg_color(attribute_list &list, unsigned offset_start, unsigned offset_end, const color_t &color)
Add Pango fg color attribute to a specific portion of text.
Definition: attributes.cpp:119
Generic file dialog.
void get_screen_size_variables(wfl::map_formula_callable &variable)
Gets a formula object with the screen size.
Definition: helper.cpp:151
lg::log_domain log_gui_draw("gui/draw")
Definition: log.hpp:28
PangoWeight decode_text_weight(const std::string &weight)
Converts a text weight string to a PangoWeight.
Definition: helper.cpp:48
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
lg::log_domain log_gui_parse("gui/parse")
Definition: log.hpp:65
PangoStyle decode_text_style(const std::string &style)
Converts a text style string to a PangoStyle.
Definition: helper.cpp:69
texture get_texture(const image::locator &i_locator, TYPE type, bool skip_cache)
Returns an image texture suitable for hardware-accelerated rendering.
Definition: picture.cpp:953
scale_quality
Definition: picture.hpp:181
std::size_t size(std::string_view str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:81
int stoi(std::string_view str)
Same interface as std::stoi and meant as a drop in replacement, except:
Definition: charconv.hpp:156
void erase_if(Container &container, const Predicate &predicate)
Convenience wrapper for using std::remove_if on a container.
Definition: general.hpp:107
double stod(std::string_view str)
Same interface as std::stod and meant as a drop in replacement, except:
Definition: charconv.hpp:142
surface read_pixels_low_res(rect *r)
The same as read_pixels, but returns a low-resolution surface suitable for use with the old drawing s...
Definition: video.cpp:657
int w
Definition: pathfind.cpp:188
std::string_view data
Definition: picture.cpp:188
int x2_
Definition: pump.cpp:132
int y1_
Definition: pump.cpp:132
int x1_
Definition: pump.cpp:132
int y2_
Definition: pump.cpp:132
Contains the SDL_Rect helper code.
The basic class for representing 8-bit RGB or RGBA colour values.
Definition: color.hpp:51
constexpr bool null() const
Definition: color.hpp:180
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
void blur_surface(surface &surf, rect rect, int depth)
Cross-fades a surface in place.
Definition: utils.cpp:842
Add a special kind of assert to validate whether the input from WML doesn't contain any problems that...
#define VALIDATE_WITH_DEV_MESSAGE(cond, message, dev_message)
#define h