enough with umpteen "i18n.h" files. Consolidate on pbd/i18n.h
[ardour.git] / libs / gtkmm2ext / emscale.cc
1 /*
2     Copyright (C) 2014 Paul Davis, Robin Gareus
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <algorithm>
20 #include <gdk/gdk.h>
21 #include <pangomm/layout.h>
22
23 #include "gtkmm2ext/emscale.h"
24
25 #include "pbd/i18n.h"
26
27 using namespace Gtkmm2ext;
28
29 std::map<std::string,EmScale> EmScale::_emscales;
30
31 EmScale::EmScale (const Pango::FontDescription& fd)
32         : _font (fd)
33         , _char_pixel_width (-1)
34         , _char_pixel_height (-1)
35         , _char_avg_pixel_width (-1)
36 {
37 }
38
39 void
40 EmScale::recalc_char_pixel_geometry ()
41 {
42         if (_char_pixel_height > 0 && _char_pixel_width > 0) {
43                 return;
44         }
45
46         Glib::RefPtr<Pango::Context> pc = Glib::wrap (gdk_pango_context_get_for_screen (gdk_screen_get_default()));
47         Glib::RefPtr<Pango::Layout> layout = Pango::Layout::create (pc);
48
49         layout->set_font_description (_font);
50
51         int w, h;
52         std::string x = _("ABCDEFGHIJLKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
53         layout->set_text (x);
54         layout->get_pixel_size (w, h);
55         _char_pixel_height = std::max(4, h);
56         // number of actual chars in the string (not bytes)
57         // Glib to the rescue.
58         Glib::ustring gx(x);
59         _char_avg_pixel_width = w / (float)gx.size();
60         _char_pixel_width = std::max(4, (int) ceil (_char_avg_pixel_width));
61 }
62
63 EmScale&
64 EmScale::by_font (const Pango::FontDescription& fd)
65 {
66         std::map<std::string,EmScale>::iterator i = _emscales.find (fd.to_string());
67
68         if (i == _emscales.end()) {
69                 i = _emscales.insert (std::make_pair (fd.to_string(), EmScale (fd))).first;
70         }
71
72         return i->second;
73 }