README: explain further musl-specific tweaks
[rofl0r-df-libgraphics.git] / g_src / ttf_manager.hpp
blob8316c5a6d48694cb6dd8b0f9e4459329d77e688a
1 #ifndef TTF_MANAGER_HPP
2 #define TTF_MANAGER_HPP
4 #include "init.h"
5 #include "enabler.h"
6 #ifdef __APPLE__
7 #include <SDL_ttf/SDL_ttf.h>
8 #else
9 #include <SDL/SDL_ttf.h>
10 #endif
11 #include <unordered_map>
12 #include <list>
14 using std::unordered_map;
15 using std::list;
17 struct handleid {
18 list<ttf_id> text;
19 justification just;
21 bool operator< (const handleid &other) const {
22 if (text != other.text) return text < other.text;
23 return just < other.just;
26 bool operator== (const handleid &other) const {
27 return just == other.just && text == other.text;
31 namespace std {
32 template<> struct hash<struct handleid> {
33 size_t operator()(handleid val) const {
34 size_t h = 0;
35 auto end = val.text.cend();
36 for (auto it = val.text.cbegin(); it != end; ++it) {
37 h += hash<ttf_id>()(*it);
39 return h + val.just;
44 struct ttf_details {
45 int handle;
46 int offset;
47 int width;
50 class ttf_managerst {
51 TTF_Font *font;
52 int max_handle;
53 int tile_width, ceiling;
54 double tab_width;
55 int em_width;
56 unordered_map<handleid, ttf_details> handles;
57 unordered_map<int, SDL_Surface*> textures;
58 struct todum {
59 int handle;
60 list<ttf_id> text;
61 int height;
62 int pixel_offset, pixel_width;
63 todum(int handle, const list<ttf_id> &t, int h, int po, int pw) :
64 handle(handle), text(t), height(h), pixel_offset(po), pixel_width(pw) {}
66 list<todum> todo;
67 public:
68 ttf_managerst() {
69 font = NULL;
70 max_handle = 1;
71 tab_width = 2;
72 em_width = 8;
74 ~ttf_managerst() {
75 for (auto it = textures.cbegin(); it != textures.cend(); ++it)
76 SDL_FreeSurface(it->second);
77 if (font) TTF_CloseFont(font);
79 bool init(int ceiling, int tile_width);
80 bool was_init() const { return font != NULL; }
81 // Return the expected size of a bit of text, in tiles.
82 int size_text(const string &text);
83 ttf_details get_handle(const list<ttf_id> &text, justification just);
84 // Returns rendered text. Renders too, if necessary.
85 // The returned SDL_Surface is owned by the ttf_managerst.
86 SDL_Surface *get_texture(int handle);
87 // Garbage-collect ttf surfaces
88 void gc();
89 // Set tab-stop width (in ems, i.e. tile widths)
90 void set_tab_width(double width) { tab_width = width; }
91 // Check if TTF is currently active
92 bool ttf_active() const {
93 return was_init() &&
94 (::init.font.use_ttf == ttf_on ||
95 (::init.font.use_ttf == ttf_auto && ::init.font.ttf_limit <= ceiling));
99 extern ttf_managerst ttf_manager;
101 #endif