16 #define GETTEXT_DOMAIN "wesnoth-lib"
37 #include <boost/algorithm/string/replace.hpp>
38 #include <boost/functional/hash_fwd.hpp>
45 #define DBG_FT LOG_STREAM(debug, log_font)
62 std::map<std::size_t, texture> rendered_cache{};
67 rendered_cache.clear();
71 : context_(pango_font_map_create_context(pango_cairo_font_map_get_default()), g_object_unref)
72 , layout_(pango_layout_new(context_.
get()), g_object_unref)
75 , markedup_text_(false)
80 , font_style_(STYLE_NORMAL)
84 , characters_per_line_(0)
86 , ellipse_mode_(PANGO_ELLIPSIZE_END)
87 , alignment_(PANGO_ALIGN_LEFT)
88 , maximum_length_(std::string::npos)
89 , calculation_dirty_(true)
95 pango_cairo_context_set_resolution(
context_.get(), 72.0);
99 pango_layout_set_wrap(
layout_.get(), PANGO_WRAP_WORD_CHAR);
100 pango_layout_set_line_spacing(
layout_.get(), 1.3f);
102 cairo_font_options_t *fo = cairo_font_options_create();
103 cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
104 cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
105 cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_DEFAULT);
107 pango_cairo_context_set_font_options(
context_.get(), fo);
108 cairo_font_options_destroy(fo);
121 const std::size_t hash = std::hash<pango_text>{}(*this);
123 if(
const auto iter = rendered_cache.find(hash); iter != rendered_cache.end()) {
128 const auto& [new_iter, added] = rendered_cache.try_emplace(hash, std::move(text_surf));
173 return (pango_layout_is_ellipsized(
layout_.get()) != 0);
190 std::string tmp =
text_;
202 std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>> itor(
203 pango_layout_get_iter(
layout_.get()), pango_layout_iter_free);
207 if(pango_layout_get_line_count(
layout_.get()) >=
static_cast<int>(
line)) {
211 for(std::size_t
i = 0;
i <
line; ++
i) {
212 pango_layout_iter_next_line(itor.get());
217 for(std::size_t
i = 0;
i < column; ++
i) {
218 if(!pango_layout_iter_next_char(itor.get())) {
222 if(
i + 1 == column) {
231 const int offset = pango_layout_iter_get_index(itor.get());
235 pango_layout_get_cursor_pos(
layout_.get(), offset, &
rect,
nullptr);
251 if (!pango_layout_xy_to_index(
layout_.get(), position.x * PANGO_SCALE,
252 position.y * PANGO_SCALE, &
index, &trailing)) {
256 std::string txt = pango_layout_get_text(
layout_.get());
258 std::string
d(delim);
260 if (
index < 0 || (
static_cast<std::size_t
>(
index) >= txt.size()) ||
d.find(txt.at(
index)) != std::string::npos) {
264 std::size_t l =
index;
265 while (l > 0 && (
d.find(txt.at(l-1)) == std::string::npos)) {
269 std::size_t r =
index + 1;
270 while (r < txt.size() && (
d.find(txt.at(r)) == std::string::npos)) {
274 return txt.substr(l,r-l);
283 std::string tok = this->
get_token(position,
" \n\r\t");
298 pango_layout_xy_to_index(
layout_.get(), position.x * PANGO_SCALE,
299 position.y * PANGO_SCALE, &
index, &trailing);
303 pango_layout_index_to_line_x(
layout_.get(),
index, trailing, &
line, &offset);
304 offset = PANGO_PIXELS(offset);
317 for(std::size_t
i = 0; ; ++
i) {
333 const std::u32string wide = unicode_cast<std::u32string>(
text);
334 const std::string narrow = unicode_cast<std::string>(wide);
338 <<
"' contains invalid utf-8, trimmed the invalid parts.";
350 pango_layout_set_attributes(
layout_.get(),
nullptr);
351 pango_layout_set_text(
layout_.get(), narrow.c_str(), narrow.size());
447 pango_layout_set_height(
layout_.get(), !multiline ? -1 : height * PANGO_SCALE);
460 pango_layout_set_ellipsize(
layout_.get(), ellipse_mode);
469 pango_layout_set_height(
layout_.get(), -1);
478 pango_layout_set_alignment(
layout_.get(), alignment);
490 std::string tmp =
text_;
531 PangoFont*
f = pango_font_map_load_font(
532 pango_cairo_font_map_get_default(),
536 PangoFontMetrics* m = pango_font_get_metrics(
f,
nullptr);
538 auto ascent = pango_font_metrics_get_ascent(m);
539 auto descent = pango_font_metrics_get_descent(m);
541 pango_font_metrics_unref(m);
544 return ceil(pango_units_to_double(ascent + descent) /
pixel_scale_);
587 pango_layout_set_font_description(&
layout,
font.get());
590 PangoAttrList *attribute_list = pango_attr_list_new();
591 pango_attr_list_insert(attribute_list
592 , pango_attr_underline_new(PANGO_UNDERLINE_SINGLE));
594 pango_layout_set_attributes(&
layout, attribute_list);
595 pango_attr_list_unref(attribute_list);
598 int maximum_width = 0;
600 PangoFont*
f = pango_font_map_load_font(
601 pango_cairo_font_map_get_default(),
605 PangoFontMetrics* m = pango_font_get_metrics(
f,
nullptr);
607 int w = pango_font_metrics_get_approximate_char_width(m);
610 maximum_width = ceil(pango_units_to_double(
w));
612 pango_font_metrics_unref(m);
622 pango_layout_set_width(&
layout, maximum_width == -1
624 : maximum_width * PANGO_SCALE);
625 pango_layout_get_pixel_extents(&
layout,
nullptr, &
size);
629 <<
"' maximum_width " << maximum_width
637 <<
" font_style " << std::hex <<
font_style_ << std::dec
638 <<
" maximum_width " << maximum_width
640 <<
" result " <<
size
643 if(maximum_width != -1 &&
size.x +
size.width > maximum_width) {
646 <<
" ' width " <<
size.x +
size.width
647 <<
" greater as the wanted maximum of " << maximum_width
655 <<
" ' height " <<
size.y +
size.height
676 for (
int i = 1;
i < 256; ++
i) {
691 unsigned temp = (value * div) / 256u;
699 value = std::min(255u, temp);
708 uint8_t
a = (
c >> 24) & 0xff;
709 uint8_t r = (
c >> 16) & 0xff;
710 uint8_t
g = (
c >> 8) & 0xff;
711 uint8_t
b =
c & 0xff;
718 c = (
static_cast<uint32_t
>(
a) << 24) | (
static_cast<uint32_t
>(r) << 16) | (
static_cast<uint32_t
>(
g) << 8) |
static_cast<uint32_t
>(
b);
723 cairo_format_t
format = CAIRO_FORMAT_ARGB32;
727 std::unique_ptr<cairo_surface_t, std::function<void(cairo_surface_t*)>> cairo_surface(
728 cairo_image_surface_create_for_data(buffer,
format, viewport.w, viewport.h, stride), cairo_surface_destroy);
729 std::unique_ptr<cairo_t, std::function<void(cairo_t*)>> cr(cairo_create(cairo_surface.get()), cairo_destroy);
731 if(cairo_status(cr.get()) == CAIRO_STATUS_INVALID_SIZE) {
732 throw std::length_error(
"Text is too long to render");
736 cairo_move_to(cr.get(), -viewport.x, -viewport.y);
749 pango_cairo_layout_path(cr.get(), &
layout);
752 cairo_set_source_rgba(cr.get(), 0.0, 0.0, 0.0, 1.0);
754 cairo_set_line_join(cr.get(), CAIRO_LINE_JOIN_ROUND);
755 cairo_set_line_width(cr.get(), 3.0);
758 cairo_stroke(cr.get());
762 cairo_set_source_rgba(cr.get(),
769 pango_cairo_show_layout(cr.get(), &
layout);
781 cairo_format_t
format = CAIRO_FORMAT_ARGB32;
782 const int stride = cairo_format_stride_for_width(
format, viewport.w);
786 if(stride <= 0 || viewport.h <= 0) {
791 DBG_FT <<
"creating new text surface";
796 if(viewport.h > std::numeric_limits<int>::max() / stride) {
797 throw std::length_error(
"Text is too long to render");
811 for(
int y = 0; y < viewport.h; ++y) {
812 uint32_t* pixels =
reinterpret_cast<uint32_t*
>(&
surface_buffer_[y * stride]);
813 for(
int x = 0; x < viewport.w; ++x) {
818 return SDL_CreateRGBSurfaceWithFormatFrom(
819 &
surface_buffer_[0], viewport.w, viewport.h, 32, stride, SDL_PIXELFORMAT_ARGB8888);
825 std::string semi_escaped;
827 if(semi_escaped !=
"") {
834 pango_layout_set_markup(&
layout, formatted_text.c_str(), formatted_text.size());
841 <<
"' has broken markup, set to normal text.";
842 set_text(
_(
"The text contains invalid Pango markup: ") + std::string(
text),
false);
854 static const std::string delim =
" \n\r\t";
855 std::ostringstream result;
857 std::size_t tok_start = 0;
858 for(std::size_t pos = 0; pos <
text.length(); ++pos) {
859 if(delim.find(
text[pos]) == std::string::npos) {
863 if(
const auto tok_length = pos - tok_start) {
865 auto token =
text.substr(tok_start, tok_length);
878 if(tok_start <
text.length()) {
892 if(pango_parse_markup(
text.data(),
text.size(),
893 0,
nullptr, raw_text,
nullptr,
nullptr)) {
912 if(
text.size() == semi_escaped.size()
913 || !pango_parse_markup(semi_escaped.c_str(), semi_escaped.size()
914 , 0,
nullptr, raw_text,
nullptr,
nullptr)) {
923 <<
"' has unescaped ampersands '&', escaped them.";
930 pango_layout_set_alignment(&dst, pango_layout_get_alignment(&src));
931 pango_layout_set_height(&dst, pango_layout_get_height(&src));
932 pango_layout_set_ellipsize(&dst, pango_layout_get_ellipsize(&src));
940 std::vector<std::string> res;
941 int count = pango_layout_get_line_count(
layout);
947 using layout_iterator = std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>>;
948 layout_iterator
i{pango_layout_get_iter(
layout), pango_layout_iter_free};
953 PangoLayoutLine* ll = pango_layout_iter_get_line_readonly(
i.get());
954 const char* begin = &pango_layout_get_text(
layout)[ll->start_index];
955 res.emplace_back(begin, ll->length);
956 }
while(pango_layout_iter_next_line(
i.get()));
964 return text_renderer;
983 std::size_t hash = 0;
985 boost::hash_combine(hash,
t.text_);
986 boost::hash_combine(hash,
t.font_class_);
987 boost::hash_combine(hash,
t.font_size_);
988 boost::hash_combine(hash,
t.font_style_);
989 boost::hash_combine(hash,
t.foreground_color_.to_rgba_bytes());
990 boost::hash_combine(hash,
t.rect_.width);
991 boost::hash_combine(hash,
t.rect_.height);
992 boost::hash_combine(hash,
t.maximum_width_);
993 boost::hash_combine(hash,
t.maximum_height_);
994 boost::hash_combine(hash,
t.alignment_);
995 boost::hash_combine(hash,
t.ellipse_mode_);
996 boost::hash_combine(hash,
t.add_outline_);
Small helper class to make sure the pango font object is destroyed properly.
int pixel_scale_
The pixel scale, used to render high-DPI text.
pango_text & set_font_style(const FONT_STYLE font_style)
PangoEllipsizeMode ellipse_mode_
The way too long text is shown depends on this mode.
static void copy_layout_properties(PangoLayout &src, PangoLayout &dst)
bool add_outline_
Whether to add an outline effect.
bool validate_markup(std::string_view text, char **raw_text, std::string &semi_escaped) const
bool set_markup(std::string_view text, PangoLayout &layout)
Sets the markup'ed text.
pango_text & set_maximum_length(const std::size_t maximum_length)
void render(PangoLayout &layout, const SDL_Rect &viewport, const unsigned stride)
This is part of create_surface(viewport).
unsigned insert_text(const unsigned offset, const std::string &text)
Inserts UTF-8 text.
surface create_surface()
Equivalent to create_surface(viewport), where the viewport's top-left is at (0,0) and the area is lar...
PangoAlignment alignment_
The alignment of the text.
int maximum_height_
The maximum height of the text.
point get_size()
Returns the size of the text, in drawing coordinates.
pango_text & set_characters_per_line(const unsigned characters_per_line)
color_t link_color_
The color to render links in.
void recalculate() const
Recalculates the text layout.
color_t foreground_color_
The foreground color.
point get_column_line(const point &position) const
Gets the column of line of the character at the position.
std::unique_ptr< PangoContext, std::function< void(void *)> > context_
bool link_aware_
Are hyperlinks in the text marked-up, and will get_link return them.
pango_text & set_foreground_color(const color_t &color)
int to_draw_scale(int s) const
Scale the given render-space size to draw-space, rounding up.
std::string format_links(std::string_view text) const
Replaces all instances of URLs in a given string with formatted links and returns the result.
unsigned characters_per_line_
The number of characters per line.
bool markedup_text_
Does the text contain pango markup? If different render routines must be used.
pango_text & set_family_class(font::family_class fclass)
font::family_class font_class_
The font family class used.
std::vector< std::string > get_lines() const
Retrieves a list of strings with contents for each rendered line.
void update_pixel_scale()
Update pixel scale, if necessary.
unsigned font_size_
The font size to draw.
texture render_texture(const SDL_Rect &viewport)
Wrapper around render_surface which sets texture::w() and texture::h() in the same way that render_an...
surface render_surface(const SDL_Rect &viewport)
Returns the rendered text.
std::vector< uint8_t > surface_buffer_
Buffer to store the image on.
pango_text & set_add_outline(bool do_add)
pango_text & set_ellipse_mode(const PangoEllipsizeMode ellipse_mode)
PangoRectangle calculate_size(PangoLayout &layout) const
Calculates surface size.
pango_text & set_alignment(const PangoAlignment alignment)
std::string text_
The text to draw (stored as UTF-8).
point get_cursor_position(const unsigned column, const unsigned line=0) const
Gets the location for the cursor, in drawing coordinates.
bool calculation_dirty_
The text has two dirty states:
std::unique_ptr< PangoLayout, std::function< void(void *)> > layout_
pango_text & set_font_size(unsigned font_size)
pango_text & set_link_aware(bool b)
FONT_STYLE font_style_
The style of the font, this is an orred mask of the font flags.
std::string get_token(const point &position, const char *delimiters=" \n\r\t") const
Gets the largest collection of characters, including the token at position, and not including any cha...
bool set_text(const std::string &text, const bool markedup)
Sets the text to render.
bool is_truncated() const
Has the text been truncated? This happens if it exceeds max width or height.
texture with_draw_scale(const texture &t) const
Adjust a texture's draw-width and height according to pixel scale.
std::size_t maximum_length_
The maximum length of the text.
pango_text & set_maximum_height(int height, bool multiline)
pango_text & set_maximum_width(int width)
std::size_t get_maximum_length() const
Get maximum length.
texture render_and_get_texture()
Returns the cached texture, or creates a new one otherwise.
pango_text & set_link_color(const color_t &color)
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...
const std::string & text() const
std::size_t length_
Length of the text.
int get_max_glyph_height() const
Returns the maximum glyph height of a font, in drawing coordinates.
int maximum_width_
The maximum width of the text.
Wrapper class to encapsulate creation and management of an SDL_Texture.
void set_draw_size(int w, int h)
Set the intended size of the texture, in draw-space.
static std::string _(const char *str)
Define the common log macros for the gui toolkit.
void point(int x, int y)
Draw a single point.
void rect(const SDL_Rect &rect)
Draw a rectangle.
void line(int from_x, int from_y, int to_x, int to_y)
Draw a line.
Collection of helper functions relating to Pango formatting.
family_class
Font classes for get_font_families().
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.
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
bool looks_like_url(std::string_view str)
std::string format_as_link(const std::string &link, color_t color)
std::string semi_escape_text(const std::string &text)
const t_string & get_font_families(family_class fclass)
Returns the currently defined fonts.
static void unpremultiply(uint8_t &value, const unsigned div)
static void from_cairo_format(uint32_t &c)
Converts from cairo-format ARGB32 premultiplied alpha to plain alpha.
void flush_texture_cache()
Flush the rendered text cache.
static constexpr inverse_table inverse_table_
std::string_view debug_truncate(std::string_view text)
Returns a truncated version of the text.
int font_scaled(int size)
std::size_t index(const std::string &str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
std::string & insert(std::string &str, const std::size_t pos, const std::string &insert)
Insert a UTF-8 string at the specified position.
std::size_t size(const std::string &str)
Length in characters of a UTF-8 string.
std::string & truncate(std::string &str, const std::size_t size)
Truncates a UTF-8 string to the specified number of characters.
int get_pixel_scale()
Get the current active pixel scale multiplier.
The basic class for representing 8-bit RGB or RGBA colour values.
constexpr inverse_table()
unsigned operator[](uint8_t i) const
An abstract description of a rectangle with integer coordinates.
std::size_t operator()(const font::pango_text &) const
static lg::log_domain log_font("font")