The Battle for Wesnoth  1.15.0-dev
text.hpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2008 - 2018 by Mark de Wever <koraq@xs4all.nl>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #pragma once
16 
17 #include "font/font_options.hpp"
18 #include "color.hpp"
19 #include "sdl/surface.hpp"
21 
22 #include <pango/pango.h>
23 #include <pango/pangocairo.h>
24 
25 #include <functional>
26 #include <memory>
27 #include <string>
28 #include <vector>
29 
30 /***
31  * Note: This is the cairo-pango code path, not the SDL_TTF code path.
32  */
33 
34 struct language_def;
35 struct point;
36 
37 namespace font {
38 
39 // add background color and also font markup.
40 
41 /**
42  * Text class.
43  *
44  * This class represents text which is rendered using Pango.
45  *
46  * It takes text, as a utf-8 std::string, plus formatting options including
47  * font and color. It provides a surface object which holds the rendered text.
48  *
49  * Besides this, it can do some additional calculations using the font layout.
50  *
51  * It can take an index into the text, and convert it to pixel coordinates,
52  * so that if we want to draw a cursor in an editbox, we know where to draw it.
53  *
54  * It can also take a pixel coordinate with respect to the text layout, and
55  * translate it back to an index into the original text. This is useful if the
56  * user clicks on the text, and we want to know where to move the cursor.
57  *
58  * The get_token method takes a pixel coordinate, which we assume represents a
59  * click position, and gets the corresponding "token" from the string. The default
60  * token delimiters are whitespace " \n\r\t". So, this returns the "word" that the
61  * user clicked on.
62  *
63  * Finally, the get_link method represents special support for hyperlinks in text.
64  * A token "looks like a link" if it begins "http://" or "https://".
65  * If a text has link_aware enabled, then any such token is rendered with an
66  * underline and in a special color, see `link_color`.
67  * The get_link method calls get_token and further checks if the clicked token
68  * looks like a link.
69  *
70  * This class stores the text to draw and uses pango with the cairo backend to
71  * render the text. See http://pango.org for more info.
72  *
73  */
75 {
76 public:
77 
78  pango_text();
79 
80  pango_text(const pango_text &) = delete;
81  pango_text & operator = (const pango_text &) = delete;
82 
83  /**
84  * Returns the rendered text.
85  *
86  * Before rendering it tests whether a redraw is needed and if so it first
87  * redraws the surface before returning it.
88  */
89  surface& render();
90 
91  /** Returns the width needed for the text. */
92  int get_width() const;
93 
94  /** Returns the height needed for the text. */
95  int get_height() const;
96 
97  /** Returns the pixel size needed for the text. */
98  point get_size() const;
99 
100  /** Has the text been truncated? This happens if it exceeds max width or height. */
101  bool is_truncated() const;
102 
103  /**
104  * Inserts UTF-8 text.
105  *
106  * @param offset The position to insert the text.
107  * @param text The UTF-8 text to insert.
108  *
109  * @returns The number of characters inserted.
110  */
111  unsigned insert_text(const unsigned offset, const std::string& text);
112 
113  /**
114  * Inserts a unicode char.
115  *
116  * @param offset The position to insert the char.
117  * @param unicode The character to insert.
118  *
119  * @returns True upon success, false otherwise.
120  */
121  bool insert_unicode(const unsigned offset, char32_t unicode);
122 
123  /**
124  * Inserts unicode text.
125  *
126  * @param offset The position to insert the text.
127  * @param unicode Vector with characters to insert.
128  *
129  * @returns The number of characters inserted.
130  */
131  unsigned insert_unicode(
132  const unsigned offset, const std::u32string& unicode);
133 
134  /***** ***** ***** ***** Font flags ***** ***** ***** *****/
135 
136  // NOTE: these values must be powers of 2 in order to be bit-unique
137  enum FONT_STYLE {
142  };
143 
144  /***** ***** ***** ***** Query details ***** ***** ***** *****/
145 
146  /**
147  * Gets the location for the cursor.
148  *
149  * @param column The column offset of the cursor.
150  * @param line The line offset of the cursor.
151  *
152  * @returns The position of the top of the cursor. It the
153  * requested location is out of range 0,0 is
154  * returned.
155  */
157  const unsigned column, const unsigned line = 0) const;
158 
159  /**
160  * Get maximum length.
161  *
162  * @returns The maximum length of the text. The length of text
163  * should not exceed this value.
164  */
165  std::size_t get_maximum_length() const;
166 
167  /**
168  * Gets the largest collection of characters, including the token at position,
169  * and not including any characters from the delimiters set.
170  *
171  * @param position The pixel position in the text area.
172  *
173  * @returns The token containing position, and none of the
174  * delimiter characters. If position is out of bounds,
175  * it returns the empty string.
176  */
177  std::string get_token(const point & position, const char * delimiters = " \n\r\t") const;
178 
179  /**
180  * Checks if position points to a character in a link in the text, returns it
181  * if so, empty string otherwise. Link-awareness must be enabled to get results.
182  * @param position The pixel position in the text area.
183  *
184  * @returns The link if one is found, the empty string otherwise.
185  */
186  std::string get_link(const point & position) const;
187 
188  /**
189  * Gets the column of line of the character at the position.
190  *
191  * @param position The pixel position in the text area.
192  *
193  * @returns A point with the x value the column and the y
194  * value the line of the character found (or last
195  * character if not found.
196  */
197  point get_column_line(const point& position) const;
198 
199  /**
200  * Gets the length of the text in bytes.
201  *
202  * The text set is UTF-8 so the length of the string might not be the length
203  * of the text.
204  */
205  std::size_t get_length() const { return length_; }
206 
207  /**
208  * Sets the text to render.
209  *
210  * @param text The text to render.
211  * @param markedup Should the text be rendered with pango
212  * markup. If the markup is invalid it's
213  * rendered as text without markup.
214  *
215  * @returns The status, if rendered as markup and the
216  * markup contains errors, false is returned
217  * else true.
218  */
219  bool set_text(const std::string& text, const bool markedup);
220 
221  /***** ***** ***** ***** Setters / getters ***** ***** ***** *****/
222 
223  const std::string& text() const { return text_; }
224 
226 
227  pango_text& set_font_size(const unsigned font_size);
228 
229  pango_text& set_font_style(const FONT_STYLE font_style);
230 
231  pango_text& set_foreground_color(const color_t& color);
232 
233  pango_text& set_maximum_width(int width);
234 
235  pango_text& set_characters_per_line(const unsigned characters_per_line);
236 
237  pango_text& set_maximum_height(int height, bool multiline);
238 
239  pango_text& set_ellipse_mode(const PangoEllipsizeMode ellipse_mode);
240 
241  pango_text& set_alignment(const PangoAlignment alignment);
242 
243  pango_text& set_maximum_length(const std::size_t maximum_length);
244 
245  bool link_aware() const { return link_aware_; }
246 
247  pango_text& set_link_aware(bool b);
248 
249  pango_text& set_link_color(const color_t& color);
250 
251  pango_text& set_add_outline(bool do_add);
252 
253 private:
254 
255  /***** ***** ***** ***** Pango variables ***** ***** ***** *****/
256  std::unique_ptr<PangoContext, std::function<void(void*)>> context_;
257  std::unique_ptr<PangoLayout, std::function<void(void*)>> layout_;
258  mutable PangoRectangle rect_;
259 
260  // Used if the text is too long to fit into a single Cairo surface.
261  std::vector<std::unique_ptr<PangoLayout, std::function<void(void*)>>> sublayouts_;
262 
263  /** The SDL surface to render upon used as a cache. */
264  mutable surface surface_;
265 
266 
267  /** The text to draw (stored as UTF-8). */
268  std::string text_;
269 
270  /** Does the text contain pango markup? If different render routines must be used. */
272 
273  /** Are hyperlinks in the text marked-up, and will get_link return them. */
275 
276  /**
277  * The color to render links in.
278  *
279  * Links are formatted using pango &lt;span> as follows:
280  *
281  * &lt;span underline="single" color=" + link_color_ + ">
282  */
284 
285  /** The font family class used. */
287 
288  /** The font size to draw. */
289  unsigned font_size_;
290 
291  /** The style of the font, this is an orred mask of the font flags. */
293 
294  /** The foreground color. */
296 
297  /** Whether to add an outline effect. */
299 
300  /**
301  * The maximum width of the text.
302  *
303  * Values less or equal to 0 mean no maximum and are internally stored as
304  * -1, since that's the value pango uses for it.
305  *
306  * See @ref characters_per_line_.
307  */
309 
310  /**
311  * The number of characters per line.
312  *
313  * This can be used as an alternative of @ref maximum_width_. The user can
314  * select a number of characters on a line for wrapping. When the value is
315  * non-zero it determines the maximum width based on the average character
316  * width.
317  *
318  * If both @ref maximum_width_ and @ref characters_per_line_ are set the
319  * minimum of the two will be the maximum.
320  *
321  * @note Long lines are often harder to read, setting this value can
322  * automatically wrap on a number of characters regardless of the font
323  * size. Often 66 characters is considered the optimal value for a one
324  * column text.
325  */
327 
328  /**
329  * The maximum height of the text.
330  *
331  * Values less or equal to 0 mean no maximum and are internally stored as
332  * -1, since that's the value pango uses for it.
333  */
335 
336  /** The way too long text is shown depends on this mode. */
337  PangoEllipsizeMode ellipse_mode_;
338 
339  /** The alignment of the text. */
340  PangoAlignment alignment_;
341 
342  /** The maximum length of the text. */
343  std::size_t maximum_length_;
344 
345  /**
346  * The text has two dirty states:
347  * - The setting of the state and the size calculations.
348  * - The rendering of the surface.
349  */
350 
351  /** The dirty state of the calculations. */
352  mutable bool calculation_dirty_;
353 
354  /** Length of the text. */
355  mutable std::size_t length_;
356 
357  /**
358  * Recalculates the text layout.
359  *
360  * When the text is recalculated the surface is dirtied.
361  *
362  * @param force Recalculate even if not dirty?
363  */
364  void recalculate(const bool force = false) const;
365 
366  /** Calculates surface size. */
367  PangoRectangle calculate_size(PangoLayout& layout) const;
368 
369  /** The dirty state of the surface. */
370  mutable bool surface_dirty_;
371 
372  /**
373  * Renders the text.
374  *
375  * It will do a recalculation first so no need to call both.
376  *
377  * @param force Render even if not dirty? This parameter is
378  * also send to recalculate().
379  */
380  void rerender(const bool force = false);
381 
382  void render(PangoLayout& layout, const PangoRectangle& rect,
383  const std::size_t surface_buffer_offset, const unsigned stride);
384 
385  /**
386  * Buffer to store the image on.
387  *
388  * We use a cairo surface to draw on this buffer and then use the buffer as
389  * data source for the SDL_Surface. This means the buffer needs to be stored
390  * in the object, since SDL_Surface doesn't own its buffer.
391  */
392  mutable std::vector<uint8_t> surface_buffer_;
393 
394  /**
395  * Creates a new buffer.
396  *
397  * If needed frees the other surface and then creates a new buffer and
398  * initializes the entire buffer with values 0.
399  *
400  * NOTE even though we're clearly modifying function we don't change the
401  * state of the object. The const is needed so other functions can also be
402  * marked const (those also don't change the state of the object.
403  *
404  * @param size The required size of the buffer.
405  */
406  void create_surface_buffer(const std::size_t size) const;
407 
408  /**
409  * Sets the markup'ed text.
410  *
411  * It tries to set the text as markup. If the markup is invalid it will try
412  * a bit harder to recover from the errors and still set the markup.
413  *
414  * @param text The text to set as markup.
415  *
416  * @returns Whether the markup was set or an
417  * unrecoverable error occurred and the text is
418  * set as plain text with an error message.
419  */
420  bool set_markup(utils::string_view text, PangoLayout& layout);
421 
422  bool validate_markup(utils::string_view text, char** raw_text, std::string& semi_escaped) const;
423 
424  /** Splits the text to two Cairo surfaces.
425  *
426  * The implementation isn't recursive: the function only splits the text once.
427  * As a result, it only doubles the maximum surface height to 64,000 pixels
428  * or so.
429  * The reason for this is that a recursive implementation would be more complex
430  * and it's unnecessary for now, as the longest surface in the game
431  * (end credits) is only about 40,000 pixels high with the default_large widget
432  * definition.
433  * If we need even larger surfaces in the future, the implementation can be made
434  * recursive.
435  */
436  void split_surface();
437 
438  bool is_surface_split() const
439  {
440  return sublayouts_.size() > 0;
441  }
442 
443  static void copy_layout_properties(PangoLayout& src, PangoLayout& dst);
444 
445  std::vector<std::string> find_links(utils::string_view text) const;
446  void format_links(std::string& text, const std::vector<std::string>& links) const;
447 };
448 
449 /**
450  * Returns a reference to a static pango_text object.
451  *
452  * Since the class is essentially a render pipeline, there's no need for individual
453  * areas of the game to own their own renderers. Not to mention it isn't a trivial
454  * class; constructing one is likely to be expensive.
455  */
457 
458 } // namespace font
unsigned font_size_
The font size to draw.
Definition: text.hpp:289
void format_links(std::string &text, const std::vector< std::string > &links) const
Definition: text.cpp:792
family_class
Font classes for get_font_families().
std::size_t get_length() const
Gets the length of the text in bytes.
Definition: text.hpp:205
bool set_text(const std::string &text, const bool markedup)
Sets the text to render.
Definition: text.cpp:284
Note: Specific to sdl_ttf.
int get_width() const
Returns the width needed for the text.
Definition: text.cpp:98
int maximum_height_
The maximum height of the text.
Definition: text.hpp:334
unsigned characters_per_line_
The number of characters per line.
Definition: text.hpp:326
std::size_t length_
Length of the text.
Definition: text.hpp:355
pango_text & set_link_aware(bool b)
Definition: text.cpp:450
bool link_aware() const
Definition: text.hpp:245
std::size_t maximum_length_
The maximum length of the text.
Definition: text.hpp:343
void recalculate(const bool force=false) const
Recalculates the text layout.
Definition: text.cpp:482
std::size_t get_maximum_length() const
Get maximum length.
Definition: text.cpp:198
font::family_class font_class_
The font family class used.
Definition: text.hpp:286
pango_text & set_font_style(const FONT_STYLE font_style)
Definition: text.cpp:345
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
Definition: text.cpp:865
pango_text & set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
Definition: text.cpp:412
pango_text & set_maximum_length(const std::size_t maximum_length)
Definition: text.cpp:437
std::vector< uint8_t > surface_buffer_
Buffer to store the image on.
Definition: text.hpp:392
bool is_surface_split() const
Definition: text.hpp:438
pango_text & set_alignment(const PangoAlignment alignment)
Definition: text.cpp:426
bool set_markup(utils::string_view text, PangoLayout &layout)
Sets the markup&#39;ed text.
Definition: text.cpp:740
#define b
point get_cursor_position(const unsigned column, const unsigned line=0) const
Gets the location for the cursor.
Definition: text.cpp:153
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
Definition: unicode.cpp:86
std::string get_token(const point &position, const char *delimiters=" \\) const
Gets the largest collection of characters, including the token at position, and not including any cha...
Definition: text.cpp:203
point get_size() const
Returns the pixel size needed for the text.
Definition: text.cpp:108
std::unique_ptr< PangoLayout, std::function< void(void *)> > layout_
Definition: text.hpp:257
bool is_truncated() const
Has the text been truncated? This happens if it exceeds max width or height.
Definition: text.cpp:115
int maximum_width_
The maximum width of the text.
Definition: text.hpp:308
void rerender(const bool force=false)
Renders the text.
Definition: text.cpp:685
color_t foreground_color_
The foreground color.
Definition: text.hpp:295
std::string get_link(const point &position) const
Checks if position points to a character in a link in the text, returns it if so, empty string otherw...
Definition: text.cpp:235
pango_text & set_font_size(const unsigned font_size)
Definition: text.cpp:333
bool validate_markup(utils::string_view text, char **raw_text, std::string &semi_escaped) const
Definition: text.cpp:799
PangoEllipsizeMode ellipse_mode_
The way too long text is shown depends on this mode.
Definition: text.hpp:337
pango_text & set_characters_per_line(const unsigned characters_per_line)
Definition: text.cpp:381
bool markedup_text_
Does the text contain pango markup? If different render routines must be used.
Definition: text.hpp:271
PangoRectangle calculate_size(PangoLayout &layout) const
Calculates surface size.
Definition: text.cpp:494
bool surface_dirty_
The dirty state of the surface.
Definition: text.hpp:370
PangoRectangle rect_
Definition: text.hpp:258
bool calculation_dirty_
The text has two dirty states:
Definition: text.hpp:352
unsigned insert_text(const unsigned offset, const std::string &text)
Inserts UTF-8 text.
Definition: text.cpp:122
pango_text & set_family_class(font::family_class fclass)
Definition: text.cpp:322
bool insert_unicode(const unsigned offset, char32_t unicode)
Inserts a unicode char.
Definition: text.cpp:142
std::unique_ptr< PangoContext, std::function< void(void *)> > context_
Definition: text.hpp:256
bool link_aware_
Are hyperlinks in the text marked-up, and will get_link return them.
Definition: text.hpp:274
void create_surface_buffer(const std::size_t size) const
Creates a new buffer.
Definition: text.cpp:731
point get_column_line(const point &position) const
Gets the column of line of the character at the position.
Definition: text.cpp:250
FONT_STYLE font_style_
The style of the font, this is an orred mask of the font flags.
Definition: text.hpp:292
bool add_outline_
Whether to add an outline effect.
Definition: text.hpp:298
Holds a 2D point.
Definition: point.hpp:23
pango_text & set_link_color(const color_t &color)
Definition: text.cpp:460
int get_height() const
Returns the height needed for the text.
Definition: text.cpp:103
std::vector< std::string > find_links(utils::string_view text) const
Definition: text.cpp:767
const std::string & text() const
Definition: text.hpp:223
color_t link_color_
The color to render links in.
Definition: text.hpp:283
Text class.
Definition: text.hpp:74
pango_text & set_maximum_width(int width)
Definition: text.cpp:366
surface surface_
The SDL surface to render upon used as a cache.
Definition: text.hpp:264
std::vector< std::unique_ptr< PangoLayout, std::function< void(void *)> > > sublayouts_
Definition: text.hpp:261
surface & render()
Returns the rendered text.
Definition: text.cpp:91
pango_text & set_maximum_height(int height, bool multiline)
Definition: text.cpp:393
void split_surface()
Splits the text to two Cairo surfaces.
Definition: text.cpp:837
std::string text_
The text to draw (stored as UTF-8).
Definition: text.hpp:268
pango_text & set_foreground_color(const color_t &color)
Definition: text.cpp:356
const int font_size
Definition: button.cpp:40
PangoAlignment alignment_
The alignment of the text.
Definition: text.hpp:340
pango_text & set_add_outline(bool do_add)
Definition: text.cpp:471
static void copy_layout_properties(PangoLayout &src, PangoLayout &dst)
Definition: text.cpp:858
pango_text & operator=(const pango_text &)=delete