Debian Codegraph @

phoenix/gtk/font.cpp

raw
1 namespace phoenix {
2
3 string pFont::serif(unsigned size, string style) {
4 if(size == 0) size = 8;
5 if(style == "") style = "Normal";
6 return {"Serif, ", size, ", ", style};
7 }
8
9 string pFont::sans(unsigned size, string style) {
10 if(size == 0) size = 8;
11 if(style == "") style = "Normal";
12 return {"Sans, ", size, ", ", style};
13 }
14
15 string pFont::monospace(unsigned size, string style) {
16 if(size == 0) size = 8;
17 return {"Liberation Mono, ", size, ", ", style};
18 }
19
20 Size pFont::size(string font, string text) {
21 PangoFontDescription* description = create(font);
22 Size size = pFont::size(description, text);
23 free(description);
24 return size;
25 }
26
27 PangoFontDescription* pFont::create(string description) {
28 lstring part;
29 part.split<2>(",", description);
30 for(auto& item : part) item.trim(" ");
31
32 string family = "Sans";
33 unsigned size = 8u;
34 bool bold = false;
35 bool italic = false;
36
37 if(part[0] != "") family = part[0];
38 if(part.size() >= 2) size = decimal(part[1]);
39 if(part.size() >= 3) bold = part[2].find("Bold");
40 if(part.size() >= 3) italic = part[2].find("Italic");
41
42 PangoFontDescription* font = pango_font_description_new();
43 pango_font_description_set_family(font, family);
44 pango_font_description_set_size(font, size * PANGO_SCALE);
45 pango_font_description_set_weight(font, !bold ? PANGO_WEIGHT_NORMAL : PANGO_WEIGHT_BOLD);
46 pango_font_description_set_style(font, !italic ? PANGO_STYLE_NORMAL : PANGO_STYLE_OBLIQUE);
47 return font;
48 }
49
50 void pFont::free(PangoFontDescription* font) {
51 pango_font_description_free(font);
52 }
53
54 Size pFont::size(PangoFontDescription* font, string text) {
55 PangoContext* context = gdk_pango_context_get_for_screen(gdk_screen_get_default());
56 PangoLayout* layout = pango_layout_new(context);
57 pango_layout_set_font_description(layout, font);
58 pango_layout_set_text(layout, text, -1);
59 int width = 0, height = 0;
60 pango_layout_get_pixel_size(layout, &width, &height);
61 g_object_unref((gpointer)layout);
62 return {width, height};
63 }
64
65 void pFont::setFont(GtkWidget* widget, string font) {
66 auto gtkFont = pFont::create(font);
67 pFont::setFont(widget, (gpointer)gtkFont);
68 pFont::free(gtkFont);
69 }
70
71 void pFont::setFont(GtkWidget* widget, gpointer font) {
72 if(font == nullptr) return;
73 gtk_widget_modify_font(widget, (PangoFontDescription*)font);
74 if(GTK_IS_CONTAINER(widget)) {
75 gtk_container_foreach(GTK_CONTAINER(widget), (GtkCallback)pFont::setFont, font);
76 }
77 }
78
79 }