Make FontList description-parsing public.
[chromium-blink-merge.git] / ui / gfx / pango_util.cc
blob27ecdd946c1967f5d023dffc2cfd89b4bdcfc783
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/pango_util.h"
7 #include <cairo/cairo.h>
8 #include <pango/pango.h>
9 #include <pango/pangocairo.h>
10 #include <string>
12 #include <algorithm>
13 #include <map>
15 #include "base/logging.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "ui/gfx/canvas.h"
18 #include "ui/gfx/font_list.h"
19 #include "ui/gfx/font_render_params.h"
20 #include "ui/gfx/linux_font_delegate.h"
21 #include "ui/gfx/platform_font_pango.h"
22 #include "ui/gfx/text_utils.h"
24 namespace gfx {
26 namespace {
28 // Creates and returns a PangoContext. The caller owns the context.
29 PangoContext* GetPangoContext() {
30 PangoFontMap* font_map = pango_cairo_font_map_get_default();
31 return pango_font_map_create_context(font_map);
34 // Returns the DPI that should be used by Pango.
35 double GetPangoDPI() {
36 static double dpi = -1.0;
37 if (dpi < 0.0) {
38 const gfx::LinuxFontDelegate* delegate = gfx::LinuxFontDelegate::instance();
39 if (delegate)
40 dpi = delegate->GetFontDPI();
41 if (dpi <= 0.0)
42 dpi = 96.0;
44 return dpi;
47 // Returns the number of pixels in a point.
48 // - multiply a point size by this to get pixels ("device units")
49 // - divide a pixel size by this to get points
50 double GetPixelsInPoint() {
51 static double pixels_in_point = GetPangoDPI() / 72.0; // 72 points in an inch
52 return pixels_in_point;
55 } // namespace
57 int GetPangoFontSizeInPixels(PangoFontDescription* pango_font) {
58 // If the size is absolute, then it's in Pango units rather than points. There
59 // are PANGO_SCALE Pango units in a device unit (pixel).
60 if (pango_font_description_get_size_is_absolute(pango_font))
61 return pango_font_description_get_size(pango_font) / PANGO_SCALE;
63 // Otherwise, we need to convert from points.
64 return static_cast<int>(GetPixelsInPoint() *
65 pango_font_description_get_size(pango_font) / PANGO_SCALE + 0.5);
68 PangoFontMetrics* GetPangoFontMetrics(PangoFontDescription* desc) {
69 static std::map<int, PangoFontMetrics*>* desc_to_metrics = NULL;
70 static PangoContext* context = NULL;
72 if (!context) {
73 context = GetPangoContext();
74 pango_context_set_language(context, pango_language_get_default());
77 if (!desc_to_metrics)
78 desc_to_metrics = new std::map<int, PangoFontMetrics*>();
80 const int desc_hash = pango_font_description_hash(desc);
81 std::map<int, PangoFontMetrics*>::iterator i =
82 desc_to_metrics->find(desc_hash);
84 if (i == desc_to_metrics->end()) {
85 PangoFontMetrics* metrics = pango_context_get_metrics(context, desc, NULL);
86 desc_to_metrics->insert(std::make_pair(desc_hash, metrics));
87 return metrics;
89 return i->second;
92 } // namespace gfx