16#define GETTEXT_DOMAIN "wesnoth-lib"
45#define DBG_FT LOG_STREAM(debug, log_font)
52void render_image_shape(cairo_t* cr, PangoAttrShape* pShape,
int ,
void* )
55 cairo_surface_t* img =
static_cast<cairo_surface_t*
>(pShape->data);
57 cairo_rel_move_to (cr,
58 pShape->ink_rect.x/PANGO_SCALE,
59 pShape->ink_rect.y/PANGO_SCALE);
61 cairo_get_current_point (cr, &x, &y);
62 cairo_translate (cr, x, y);
65 cairo_set_source_surface(cr, img, 0, 0);
69 pShape->ink_rect.width/PANGO_SCALE,
70 pShape->ink_rect.height/PANGO_SCALE);
76 : context_(pango_font_map_create_context(pango_cairo_font_map_get_default()), g_object_unref)
77 , layout_(pango_layout_new(context_.get()), g_object_unref)
80 , markedup_text_(false)
85 , font_style_(STYLE_NORMAL)
89 , characters_per_line_(0)
92 , ellipse_mode_(PANGO_ELLIPSIZE_END)
93 , alignment_(PANGO_ALIGN_LEFT)
94 , maximum_length_(
std::string::npos)
95 , calculation_dirty_(true)
101 pango_cairo_context_set_resolution(
context_.get(), 72.0);
105 pango_layout_set_wrap(
layout_.get(), PANGO_WRAP_WORD_CHAR);
110 cairo_font_options_t *fo = cairo_font_options_create();
111 cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
112 cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
113 cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_DEFAULT);
115 pango_cairo_context_set_font_options(
context_.get(), fo);
116 cairo_font_options_destroy(fo);
118 pango_cairo_context_set_shape_renderer(
context_.get(), render_image_shape,
nullptr,
nullptr);
167 return (pango_layout_is_ellipsized(
layout_.get()) != 0);
184 std::string tmp =
text_;
193 std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>> itor(
194 pango_layout_get_iter(
layout_.get()), pango_layout_iter_free);
199 if(
static_cast<int>(line) >= pango_layout_get_line_count(
layout_.get())) {
203 for(std::size_t
i = 0;
i < line; ++
i) {
204 pango_layout_iter_next_line(itor.get());
209 for(std::size_t
i = 0;
i < offset; ++
i) {
210 if(!pango_layout_iter_next_char(itor.get())) {
214 if(
i + 1 == offset) {
223 return pango_layout_iter_get_index(itor.get());
236 pango_layout_get_cursor_pos(
layout_.get(), offset, &
rect,
nullptr);
247 const std::string_view
text = pango_layout_get_text(
layout_.get());
251 const auto prev_char = [&
text](
int index) {
254 }
while(index > 0 && (
static_cast<unsigned char>(
text[index]) & 0xC0) == 0x80);
258 std::vector<std::pair<point, int>> res;
260 using layout_iterator = std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>>;
261 layout_iterator
i{pango_layout_get_iter(
layout_.get()), pango_layout_iter_free};
264 const PangoLayoutLine* ll = pango_layout_iter_get_line_readonly(
i.get());
265 const int span_start = std::max(start_index, ll->start_index);
266 int span_end = std::min(end_index, ll->start_index + ll->length);
270 while(span_end > span_start && std::isspace(
static_cast<unsigned char>(
text[span_end - 1]))) {
274 if(span_end > span_start) {
277 PangoRectangle last_rect;
278 pango_layout_index_to_pos(
layout_.get(), prev_char(span_end), &last_rect);
282 }
while(pango_layout_iter_next_line(
i.get()));
295 const auto [index,
_, inside_bounds] =
xy_to_index(position);
296 std::string txt = pango_layout_get_text(
layout_.get());
298 if (!inside_bounds || index < 0 || (
static_cast<std::size_t
>(index) >= txt.size()) || delim.find(txt.at(index)) != std::string::npos) {
302 std::size_t l = index;
303 while (l > 0 && (delim.find(txt.at(l-1)) == std::string::npos)) {
307 std::size_t r = index + 1;
308 while (r < txt.size() && (delim.find(txt.at(r)) == std::string::npos)) {
312 return txt.substr(l,r-l);
328 const auto [index, trailing,
_] =
xy_to_index(position);
332 const PangoLayoutLine* ll = pango_layout_get_line_readonly(
layout_.get(), line);
349 const std::string_view
text = pango_layout_get_text(
layout_.get());
350 const std::string_view line_text =
text.substr(ll->start_index, ll->length);
352 const std::size_t char_start = std::max(index, ll->start_index) - ll->start_index;
353 const std::size_t
cursor = char_start +
utf8::index(line_text.substr(std::min(char_start, line_text.size())), trailing);
355 return point(
static_cast<int>(
utf8::size(line_text.substr(0, std::min(
cursor, line_text.size())))), line);
365 int res = pango_layout_xy_to_index(
layout_.get(),
368 return { index, trailing, res != 0 };
373 pango_layout_set_attributes(
layout_.get(),
nullptr);
378 if(PangoAttrList* current_attrs = pango_layout_get_attributes(
layout_.get())) {
388 const std::u32string wide = unicode_cast<std::u32string>(
text);
389 std::string narrow = unicode_cast<std::string>(wide);
392 <<
"pango_text::" << __func__
394 <<
"' contains invalid utf-8, trimmed the invalid parts.";
398 pango_layout_set_text(
layout_.get(), narrow.c_str(), narrow.size());
402 text_ = std::move(narrow);
499 pango_layout_set_ellipsize(
layout_.get(), ellipse_mode);
510 pango_layout_set_alignment(
layout_.get(), alignment);
522 std::string tmp =
text_;
564 PangoFont*
f = pango_font_map_load_font(
565 pango_cairo_font_map_get_default(),
569 PangoFontMetrics* m = pango_font_get_metrics(
f,
nullptr);
571 auto ascent = pango_font_metrics_get_ascent(m);
572 auto descent = pango_font_metrics_get_descent(m);
574 pango_font_metrics_unref(m);
577 return ceil(pango_units_to_double(ascent + descent) /
pixel_scale_);
616 pango_layout_set_font_description(&layout,
font.get());
618 int maximum_width = 0;
620 PangoFont*
f = pango_font_map_load_font(
621 pango_cairo_font_map_get_default(),
625 PangoFontMetrics* m = pango_font_get_metrics(
f,
nullptr);
627 int w = pango_font_metrics_get_approximate_char_width(m);
630 maximum_width = ceil(pango_units_to_double(
w));
632 pango_font_metrics_unref(m);
635 maximum_width = maximum_width_scaled;
638 if(maximum_width_scaled != -1) {
639 maximum_width = std::min(maximum_width, maximum_width_scaled);
650 ? maximum_height * PANGO_SCALE
653 pango_layout_set_width(&layout, maximum_width == -1
655 : maximum_width * PANGO_SCALE);
656 pango_layout_get_pixel_extents(&layout,
nullptr, &size);
660 <<
"' maximum_width " << maximum_width
661 <<
" width " << size.x + size.width
666 <<
"' font_size " << font_size
668 <<
" font_style " << std::hex <<
font_style_ << std::dec
669 <<
" maximum_width " << maximum_width
670 <<
" maximum_height " << maximum_height
671 <<
" result " << size
674 if(maximum_width != -1 && size.x + size.width > maximum_width) {
677 <<
" ' width " << size.x + size.width
678 <<
" greater as the wanted maximum of " << maximum_width
683 if(maximum_height != -1 && size.y + size.height > maximum_height) {
686 <<
" ' height " << size.y + size.height
687 <<
" greater as the wanted maximum of " << maximum_height
689 size.height = maximum_height - std::max(0, size.y);
707 for (
int i = 1;
i < 256; ++
i) {
722 unsigned temp = (
value * div) / 256u;
730 value = std::min(255u, temp);
739 uint8_t a = (
c >> 24) & 0xff;
740 uint8_t r = (
c >> 16) & 0xff;
741 uint8_t
g = (
c >> 8) & 0xff;
742 uint8_t
b =
c & 0xff;
749 c = (
static_cast<uint32_t
>(a) << 24) | (
static_cast<uint32_t
>(r) << 16) | (
static_cast<uint32_t
>(
g) << 8) |
static_cast<uint32_t
>(
b);
758 cairo_t* cr = cairo_context.get();
760 if(cairo_status(cr) == CAIRO_STATUS_INVALID_SIZE) {
761 throw std::length_error(
"Text is too long to render");
765 cairo_move_to(cr, -viewport.x, -viewport.y);
778 pango_cairo_layout_path(cr, &layout);
781 cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 1.0);
783 cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
784 cairo_set_line_width(cr, 3.0);
791 cairo_set_source_rgba(cr,
800 list.
insert(pango_attr_underline_new(PANGO_UNDERLINE_SINGLE));
804 pango_cairo_show_layout(cr, &layout);
816 cairo_format_t format = CAIRO_FORMAT_ARGB32;
817 const int stride = cairo_format_stride_for_width(format, viewport.w);
821 if(stride <= 0 || viewport.h <= 0) {
826 DBG_FT <<
"creating new text surface";
831 if(viewport.h > std::numeric_limits<int>::max() / stride) {
832 throw std::length_error(
"Text is too long to render");
846 for(
int y = 0; y < viewport.h; ++y) {
847 uint32_t* pixels =
reinterpret_cast<uint32_t*
>(&
surface_buffer_[y * stride]);
848 for(
int x = 0; x < viewport.w; ++x) {
853 return SDL_CreateSurfaceFrom(viewport.w, viewport.h, SDL_PIXELFORMAT_ARGB8888, &
surface_buffer_[0], stride);
859 std::string semi_escaped;
861 if(!semi_escaped.empty()) {
868 pango_layout_set_markup(&layout, formatted_text.c_str(), formatted_text.size());
870 pango_layout_set_markup(&layout,
text.data(),
text.size());
883 static const std::string delim =
" \n\r\t";
884 std::ostringstream result;
886 std::size_t tok_start = 0;
887 for(std::size_t pos = 0; pos <
text.length(); ++pos) {
888 if(delim.find(
text[pos]) == std::string::npos) {
892 if(
const auto tok_length = pos - tok_start) {
894 auto token =
text.substr(tok_start, tok_length);
907 if(tok_start <
text.length()) {
921 if(pango_parse_markup(
text.data(),
text.size(),
922 0,
nullptr, raw_text,
nullptr,
nullptr)) {
941 if(
text.size() == semi_escaped.size()
942 || !pango_parse_markup(semi_escaped.c_str(), semi_escaped.size()
943 , 0,
nullptr, raw_text,
nullptr,
nullptr)) {
952 <<
"' has unescaped ampersands '&', escaped them.";
961 PangoLayout*
const layout =
layout_.get();
962 std::vector<std::string> res;
963 int count = pango_layout_get_line_count(layout);
969 using layout_iterator = std::unique_ptr<PangoLayoutIter, std::function<void(PangoLayoutIter*)>>;
970 layout_iterator
i{pango_layout_get_iter(layout), pango_layout_iter_free};
975 PangoLayoutLine* ll = pango_layout_iter_get_line_readonly(
i.get());
976 const char* begin = &pango_layout_get_text(layout)[ll->start_index];
977 res.emplace_back(begin, ll->length);
978 }
while(pango_layout_iter_next_line(
i.get()));
985 return pango_layout_get_line_readonly(
layout_.get(), index);
990 int line_num = 0, x_pos = 0;
991 pango_layout_index_to_line_x(
layout_.get(), offset, trailing, &line_num, &x_pos);
992 return { line_num, x_pos };
998 return text_renderer;
Helper class to encapsulate the management of a PangoAttrList.
void splice_into(PangoAttrList *target) const
void apply_to(PangoLayout *layout) const
void insert(PangoAttribute *attr)
Small helper class to make sure the pango font object is destroyed properly.
const std::string & text() const
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.
bool multiline_
Whether the maximum height is also passed to the layout.
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)
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.
unsigned insert_text(const unsigned offset, const std::string &text, const bool use_markup=false)
Inserts UTF-8 text.
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.
texture render_texture(const rect &viewport)
Wrapper around render_surface which sets texture::w() and texture::h() in the same way that render_an...
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 get_byte_index(const unsigned offset, const unsigned line=0) const
Given a character index and optionally the starting line, returns the corresponding byte index.
std::string get_token(const point &position, std::string_view delimiters=" \n\r\t") const
Gets the largest collection of characters, including the token at position, and not including any cha...
PangoLayoutLine * get_line(int index)
Get a specific line from the pango layout.
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)
void update_pixel_scale() const
Update pixel scale, if necessary.
font::family_class font_class_
The font family class used.
void apply_attributes(const font::attribute_list &attrs)
std::vector< std::string > get_lines() const
Retrieves a list of strings with contents for each rendered line.
std::tuple< int, int, bool > xy_to_index(const point &position) const
Wrapper function around pango_layout_xy_to_index.
unsigned font_size_
The font size to draw, in draw-space (before pixel scaling).
std::vector< uint8_t > surface_buffer_
Buffer to store the image on.
pango_text & set_add_outline(bool do_add)
point get_cursor_position(const unsigned offset, const unsigned line=0) const
Gets the location for the cursor, in drawing coordinates.
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).
std::pair< int, int > index_to_line_x(const unsigned offset, const bool trailing=0) const
Given a byte index, find out at which line the corresponding character is located.
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)
void render(PangoLayout &layout, const rect &viewport)
This is part of create_surface(viewport).
FONT_STYLE font_style_
The style of the font, this is an orred mask of the font flags.
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.
surface render_surface(const rect &viewport)
Returns the rendered text.
std::size_t maximum_length_
The maximum length of the text.
point get_cursor_pos_from_index(const unsigned offset) const
Gets the location for the cursor, in drawing coordinates.
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.
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.
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...
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.
int font_scaled(int size)
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.
context_ptr create_context(const surface_ptr &surf)
surface_ptr create_surface(uint8_t *buffer, const point &size)
pango_text & get_text_renderer()
Returns a reference to a static pango_text object.
constexpr float get_line_spacing_factor()
bool looks_like_url(std::string_view str)
const t_string & get_font_families(family_class fclass)
Returns the currently defined fonts.
int get_max_height(unsigned size, font::family_class fclass, pango_text::FONT_STYLE style)
Returns the maximum glyph height of a font, in pixels.
std::string semi_escape_text(std::string_view text)
std::string format_as_link(const std::string &link, color_t color)
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.
static constexpr inverse_table inverse_table_
std::string_view debug_truncate(std::string_view text)
Returns a truncated version of the text.
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(std::string_view 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.
std::size_t index(std::string_view str, const std::size_t index)
Codepoint index corresponding to the nth character in a UTF-8 string.
int get_pixel_scale()
Get the current active pixel scale multiplier.
std::unique_ptr< MIX_Audio, decltype(&MIX_DestroyAudio)> value
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.
contains the current text being parsed as well as the token_type of what's being parsed.
static lg::log_domain log_font("font")