libwtk-sdl2  0.0.1
font_word_cache.hpp
1 #ifndef LIBWTK_SDL2_FONT_WORD_CACHE_HPP
2 #define LIBWTK_SDL2_FONT_WORD_CACHE_HPP
3 
4 #include <memory>
5 #include <stdexcept>
6 #include <tuple>
7 #include <unordered_map>
8 #include <vector>
9 
10 #include <SDL2/SDL_ttf.h>
11 
12 #include "copy_command.hpp"
13 #include "font.hpp"
14 #include "geometry.hpp"
15 #include "sdl_util.hpp"
16 
17 struct font_not_found : std::runtime_error
18 {
19  font_not_found(std::string);
20 };
21 
22 struct font_render_error : std::runtime_error
23 {
24  font_render_error(std::string);
25 };
26 
28 {
29  std::string word;
30  std::size_t extra_spaces;
31 };
32 
34 {
35  font_word_cache(SDL_Renderer * renderer, font f);
36  ~font_word_cache();
37 
38  font_word_cache(font_word_cache const &) = delete;
40 
41  // Renders words onto textures with a cache. A proper layout is then created
42  // to fit the textures on the given line width.
43  //
44  // The result is the required space and the commands necessary to copy it to
45  // a render target. Note that it is not guaranteed that the textures are
46  // still valid after another call only in between calls.
47  //
48  // TODO add offset parameter
49  std::tuple<vec, std::vector<copy_command>> text(std::string t, int max_line_width = -1);
50 
51  vec text_size(std::string t, int max_line_width = -1);
52  int text_minimum_width(std::string t);
53 
54  unsigned int font_height() const;
55 
56  int font_line_skip() const;
57 
58  void clear();
59 
60  private:
61 
62  template <typename BackInsertIt>
63  vec compute_text_layout(std::string t, int max_line_width, BackInsertIt it);
64 
65  int get_word_left_kerning(std::string const & word);
66  int get_word_right_kerning(std::string const & word);
67 
68  // Correctly handles dimension for a nullptr.
69  vec texture_dim_nullptr(SDL_Texture * texture) const;
70 
71  // May return nullptr for zero-length text.
72  SDL_Texture * word(std::string);
73 
74  SDL_Renderer * _renderer;
75  std::unordered_map<std::string, SDL_Texture *> _prerendered;
76  TTF_Font * _font;
77  int _space_advance;
78  int _space_minx;
79 
80 };
81 
82 #endif
83 
Definition: font_word_cache.hpp:27
Definition: font.hpp:6
Definition: geometry.hpp:12
Definition: font_word_cache.hpp:33
Definition: font_word_cache.hpp:17
Definition: font_word_cache.hpp:22