Home | History | Annotate | Download | only in gfx
      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.
      4 
      5 #include "ui/gfx/platform_font_win.h"
      6 
      7 #include <windows.h>
      8 #include <math.h>
      9 
     10 #include <algorithm>
     11 #include <string>
     12 
     13 #include "base/logging.h"
     14 #include "base/strings/string_util.h"
     15 #include "base/strings/sys_string_conversions.h"
     16 #include "base/strings/utf_string_conversions.h"
     17 #include "base/win/scoped_hdc.h"
     18 #include "base/win/scoped_select_object.h"
     19 #include "base/win/win_util.h"
     20 #include "ui/base/win/scoped_set_map_mode.h"
     21 #include "ui/gfx/canvas.h"
     22 #include "ui/gfx/font.h"
     23 
     24 namespace {
     25 
     26 // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
     27 // font is bold.
     28 const int kTextMetricWeightBold = 700;
     29 
     30 // Returns the minimum font size, using the minimum size callback, if set.
     31 int GetMinimumFontSize() {
     32   int min_font_size = 0;
     33   if (gfx::PlatformFontWin::get_minimum_font_size_callback)
     34     min_font_size = gfx::PlatformFontWin::get_minimum_font_size_callback();
     35   return min_font_size;
     36 }
     37 
     38 // Returns either minimum font allowed for a current locale or
     39 // lf_height + size_delta value.
     40 int AdjustFontSize(int lf_height, int size_delta) {
     41   if (lf_height < 0) {
     42     lf_height -= size_delta;
     43   } else {
     44     lf_height += size_delta;
     45   }
     46   const int min_font_size = GetMinimumFontSize();
     47   // Make sure lf_height is not smaller than allowed min font size for current
     48   // locale.
     49   if (abs(lf_height) < min_font_size) {
     50     return lf_height < 0 ? -min_font_size : min_font_size;
     51   } else {
     52     return lf_height;
     53   }
     54 }
     55 
     56 // Sets style properties on |font_info| based on |font_style|.
     57 void SetLogFontStyle(int font_style, LOGFONT* font_info) {
     58   font_info->lfUnderline = (font_style & gfx::Font::UNDERLINE) != 0;
     59   font_info->lfItalic = (font_style & gfx::Font::ITALIC) != 0;
     60   font_info->lfWeight = (font_style & gfx::Font::BOLD) ? FW_BOLD : FW_NORMAL;
     61 }
     62 
     63 }  // namespace
     64 
     65 namespace gfx {
     66 
     67 // static
     68 PlatformFontWin::HFontRef* PlatformFontWin::base_font_ref_;
     69 
     70 // static
     71 PlatformFontWin::AdjustFontCallback
     72     PlatformFontWin::adjust_font_callback = NULL;
     73 PlatformFontWin::GetMinimumFontSizeCallback
     74     PlatformFontWin::get_minimum_font_size_callback = NULL;
     75 
     76 ////////////////////////////////////////////////////////////////////////////////
     77 // PlatformFontWin, public
     78 
     79 PlatformFontWin::PlatformFontWin() : font_ref_(GetBaseFontRef()) {
     80 }
     81 
     82 PlatformFontWin::PlatformFontWin(NativeFont native_font) {
     83   InitWithCopyOfHFONT(native_font);
     84 }
     85 
     86 PlatformFontWin::PlatformFontWin(const std::string& font_name,
     87                                  int font_size) {
     88   InitWithFontNameAndSize(font_name, font_size);
     89 }
     90 
     91 Font PlatformFontWin::DeriveFontWithHeight(int height, int style) {
     92   DCHECK_GE(height, 0);
     93   if (GetHeight() == height && GetStyle() == style)
     94     return Font(this);
     95 
     96   // CreateFontIndirect() doesn't return the largest size for the given height
     97   // when decreasing the height. Iterate to find it.
     98   if (GetHeight() > height) {
     99     const int min_font_size = GetMinimumFontSize();
    100     Font font = DeriveFont(-1, style);
    101     int font_height = font.GetHeight();
    102     int font_size = font.GetFontSize();
    103     while (font_height > height && font_size != min_font_size) {
    104       font = font.DeriveFont(-1, style);
    105       if (font_height == font.GetHeight() && font_size == font.GetFontSize())
    106         break;
    107       font_height = font.GetHeight();
    108       font_size = font.GetFontSize();
    109     }
    110     return font;
    111   }
    112 
    113   LOGFONT font_info;
    114   GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
    115   font_info.lfHeight = height;
    116   SetLogFontStyle(style, &font_info);
    117 
    118   HFONT hfont = CreateFontIndirect(&font_info);
    119   return Font(new PlatformFontWin(CreateHFontRef(hfont)));
    120 }
    121 
    122 ////////////////////////////////////////////////////////////////////////////////
    123 // PlatformFontWin, PlatformFont implementation:
    124 
    125 Font PlatformFontWin::DeriveFont(int size_delta, int style) const {
    126   LOGFONT font_info;
    127   GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
    128   const int requested_font_size = font_ref_->requested_font_size();
    129   font_info.lfHeight = AdjustFontSize(-requested_font_size, size_delta);
    130   SetLogFontStyle(style, &font_info);
    131 
    132   HFONT hfont = CreateFontIndirect(&font_info);
    133   return Font(new PlatformFontWin(CreateHFontRef(hfont)));
    134 }
    135 
    136 int PlatformFontWin::GetHeight() const {
    137   return font_ref_->height();
    138 }
    139 
    140 int PlatformFontWin::GetBaseline() const {
    141   return font_ref_->baseline();
    142 }
    143 
    144 int PlatformFontWin::GetAverageCharacterWidth() const {
    145   return font_ref_->ave_char_width();
    146 }
    147 
    148 int PlatformFontWin::GetStringWidth(const base::string16& text) const {
    149   return Canvas::GetStringWidth(text,
    150                                 Font(const_cast<PlatformFontWin*>(this)));
    151 }
    152 
    153 int PlatformFontWin::GetExpectedTextWidth(int length) const {
    154   return length * std::min(font_ref_->GetDluBaseX(),
    155                            GetAverageCharacterWidth());
    156 }
    157 
    158 int PlatformFontWin::GetStyle() const {
    159   return font_ref_->style();
    160 }
    161 
    162 std::string PlatformFontWin::GetFontName() const {
    163   return font_ref_->font_name();
    164 }
    165 
    166 std::string PlatformFontWin::GetLocalizedFontName() const {
    167   base::win::ScopedCreateDC memory_dc(CreateCompatibleDC(NULL));
    168   if (!memory_dc.Get())
    169     return GetFontName();
    170 
    171   // When a font has a localized name for a language matching the system
    172   // locale, GetTextFace() returns the localized name.
    173   base::win::ScopedSelectObject font(memory_dc, font_ref_->hfont());
    174   wchar_t localized_font_name[LF_FACESIZE];
    175   int length = GetTextFace(memory_dc, arraysize(localized_font_name),
    176                            &localized_font_name[0]);
    177   if (length <= 0)
    178     return GetFontName();
    179   return base::SysWideToUTF8(localized_font_name);
    180 }
    181 
    182 int PlatformFontWin::GetFontSize() const {
    183   return font_ref_->font_size();
    184 }
    185 
    186 NativeFont PlatformFontWin::GetNativeFont() const {
    187   return font_ref_->hfont();
    188 }
    189 
    190 ////////////////////////////////////////////////////////////////////////////////
    191 // Font, private:
    192 
    193 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont) {
    194   DCHECK(hfont);
    195   LOGFONT font_info;
    196   GetObject(hfont, sizeof(LOGFONT), &font_info);
    197   font_ref_ = CreateHFontRef(CreateFontIndirect(&font_info));
    198 }
    199 
    200 void PlatformFontWin::InitWithFontNameAndSize(const std::string& font_name,
    201                                               int font_size) {
    202   HFONT hf = ::CreateFont(-font_size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    203                           UTF8ToUTF16(font_name).c_str());
    204   font_ref_ = CreateHFontRef(hf);
    205 }
    206 
    207 // static
    208 PlatformFontWin::HFontRef* PlatformFontWin::GetBaseFontRef() {
    209   if (base_font_ref_ == NULL) {
    210     NONCLIENTMETRICS metrics;
    211     base::win::GetNonClientMetrics(&metrics);
    212 
    213     if (adjust_font_callback)
    214       adjust_font_callback(&metrics.lfMessageFont);
    215     metrics.lfMessageFont.lfHeight =
    216         AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
    217     HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
    218     DLOG_ASSERT(font);
    219     base_font_ref_ = PlatformFontWin::CreateHFontRef(font);
    220     // base_font_ref_ is global, up the ref count so it's never deleted.
    221     base_font_ref_->AddRef();
    222   }
    223   return base_font_ref_;
    224 }
    225 
    226 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRef(HFONT font) {
    227   TEXTMETRIC font_metrics;
    228 
    229   {
    230     base::win::ScopedGetDC screen_dc(NULL);
    231     base::win::ScopedSelectObject scoped_font(screen_dc, font);
    232     ui::ScopedSetMapMode mode(screen_dc, MM_TEXT);
    233     GetTextMetrics(screen_dc, &font_metrics);
    234   }
    235 
    236   const int height = std::max<int>(1, font_metrics.tmHeight);
    237   const int baseline = std::max<int>(1, font_metrics.tmAscent);
    238   const int ave_char_width = std::max<int>(1, font_metrics.tmAveCharWidth);
    239   const int font_size =
    240       std::max<int>(1, font_metrics.tmHeight - font_metrics.tmInternalLeading);
    241   int style = 0;
    242   if (font_metrics.tmItalic)
    243     style |= Font::ITALIC;
    244   if (font_metrics.tmUnderlined)
    245     style |= Font::UNDERLINE;
    246   if (font_metrics.tmWeight >= kTextMetricWeightBold)
    247     style |= Font::BOLD;
    248 
    249   return new HFontRef(font, font_size, height, baseline, ave_char_width, style);
    250 }
    251 
    252 PlatformFontWin::PlatformFontWin(HFontRef* hfont_ref) : font_ref_(hfont_ref) {
    253 }
    254 
    255 ////////////////////////////////////////////////////////////////////////////////
    256 // PlatformFontWin::HFontRef:
    257 
    258 PlatformFontWin::HFontRef::HFontRef(HFONT hfont,
    259          int font_size,
    260          int height,
    261          int baseline,
    262          int ave_char_width,
    263          int style)
    264     : hfont_(hfont),
    265       font_size_(font_size),
    266       height_(height),
    267       baseline_(baseline),
    268       ave_char_width_(ave_char_width),
    269       style_(style),
    270       dlu_base_x_(-1),
    271       requested_font_size_(font_size) {
    272   DLOG_ASSERT(hfont);
    273 
    274   LOGFONT font_info;
    275   GetObject(hfont_, sizeof(LOGFONT), &font_info);
    276   font_name_ = UTF16ToUTF8(base::string16(font_info.lfFaceName));
    277   if (font_info.lfHeight < 0)
    278     requested_font_size_ = -font_info.lfHeight;
    279 }
    280 
    281 int PlatformFontWin::HFontRef::GetDluBaseX() {
    282   if (dlu_base_x_ != -1)
    283     return dlu_base_x_;
    284 
    285   base::win::ScopedGetDC screen_dc(NULL);
    286   base::win::ScopedSelectObject font(screen_dc, hfont_);
    287   ui::ScopedSetMapMode mode(screen_dc, MM_TEXT);
    288 
    289   // Yes, this is how Microsoft recommends calculating the dialog unit
    290   // conversions. See: http://support.microsoft.com/kb/125681
    291   SIZE ave_text_size;
    292   GetTextExtentPoint32(screen_dc,
    293                        L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
    294                        52, &ave_text_size);
    295   dlu_base_x_ = (ave_text_size.cx / 26 + 1) / 2;
    296 
    297   DCHECK_NE(dlu_base_x_, -1);
    298   return dlu_base_x_;
    299 }
    300 
    301 PlatformFontWin::HFontRef::~HFontRef() {
    302   DeleteObject(hfont_);
    303 }
    304 
    305 ////////////////////////////////////////////////////////////////////////////////
    306 // PlatformFont, public:
    307 
    308 // static
    309 PlatformFont* PlatformFont::CreateDefault() {
    310   return new PlatformFontWin;
    311 }
    312 
    313 // static
    314 PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) {
    315   return new PlatformFontWin(native_font);
    316 }
    317 
    318 // static
    319 PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name,
    320                                                   int font_size) {
    321   return new PlatformFontWin(font_name, font_size);
    322 }
    323 
    324 }  // namespace gfx
    325