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/gfx/canvas.h"
     21 #include "ui/gfx/font.h"
     22 #include "ui/gfx/win/scoped_set_map_mode.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.Derive(-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::GetCapHeight() const {
    145   return font_ref_->cap_height();
    146 }
    147 
    148 int PlatformFontWin::GetExpectedTextWidth(int length) const {
    149   return length * std::min(font_ref_->GetDluBaseX(),
    150                            font_ref_->ave_char_width());
    151 }
    152 
    153 int PlatformFontWin::GetStyle() const {
    154   return font_ref_->style();
    155 }
    156 
    157 std::string PlatformFontWin::GetFontName() const {
    158   return font_ref_->font_name();
    159 }
    160 
    161 std::string PlatformFontWin::GetActualFontNameForTesting() const {
    162   // With the current implementation on Windows, HFontRef::font_name() returns
    163   // the font name taken from the HFONT handle, but it's not the name that comes
    164   // from the font's metadata.  See http://crbug.com/327287
    165   return font_ref_->font_name();
    166 }
    167 
    168 std::string PlatformFontWin::GetLocalizedFontName() const {
    169   base::win::ScopedCreateDC memory_dc(CreateCompatibleDC(NULL));
    170   if (!memory_dc.Get())
    171     return GetFontName();
    172 
    173   // When a font has a localized name for a language matching the system
    174   // locale, GetTextFace() returns the localized name.
    175   base::win::ScopedSelectObject font(memory_dc, font_ref_->hfont());
    176   wchar_t localized_font_name[LF_FACESIZE];
    177   int length = GetTextFace(memory_dc, arraysize(localized_font_name),
    178                            &localized_font_name[0]);
    179   if (length <= 0)
    180     return GetFontName();
    181   return base::SysWideToUTF8(localized_font_name);
    182 }
    183 
    184 int PlatformFontWin::GetFontSize() const {
    185   return font_ref_->font_size();
    186 }
    187 
    188 NativeFont PlatformFontWin::GetNativeFont() const {
    189   return font_ref_->hfont();
    190 }
    191 
    192 ////////////////////////////////////////////////////////////////////////////////
    193 // Font, private:
    194 
    195 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont) {
    196   DCHECK(hfont);
    197   LOGFONT font_info;
    198   GetObject(hfont, sizeof(LOGFONT), &font_info);
    199   font_ref_ = CreateHFontRef(CreateFontIndirect(&font_info));
    200 }
    201 
    202 void PlatformFontWin::InitWithFontNameAndSize(const std::string& font_name,
    203                                               int font_size) {
    204   HFONT hf = ::CreateFont(-font_size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    205                           base::UTF8ToUTF16(font_name).c_str());
    206   font_ref_ = CreateHFontRef(hf);
    207 }
    208 
    209 // static
    210 PlatformFontWin::HFontRef* PlatformFontWin::GetBaseFontRef() {
    211   if (base_font_ref_ == NULL) {
    212     NONCLIENTMETRICS metrics;
    213     base::win::GetNonClientMetrics(&metrics);
    214 
    215     if (adjust_font_callback)
    216       adjust_font_callback(&metrics.lfMessageFont);
    217     metrics.lfMessageFont.lfHeight =
    218         AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
    219     HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
    220     DLOG_ASSERT(font);
    221     base_font_ref_ = PlatformFontWin::CreateHFontRef(font);
    222     // base_font_ref_ is global, up the ref count so it's never deleted.
    223     base_font_ref_->AddRef();
    224   }
    225   return base_font_ref_;
    226 }
    227 
    228 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRef(HFONT font) {
    229   TEXTMETRIC font_metrics;
    230 
    231   {
    232     base::win::ScopedGetDC screen_dc(NULL);
    233     base::win::ScopedSelectObject scoped_font(screen_dc, font);
    234     gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
    235     GetTextMetrics(screen_dc, &font_metrics);
    236   }
    237 
    238   const int height = std::max<int>(1, font_metrics.tmHeight);
    239   const int baseline = std::max<int>(1, font_metrics.tmAscent);
    240   const int cap_height =
    241       std::max<int>(1, font_metrics.tmAscent - font_metrics.tmInternalLeading);
    242   const int ave_char_width = std::max<int>(1, font_metrics.tmAveCharWidth);
    243   const int font_size =
    244       std::max<int>(1, font_metrics.tmHeight - font_metrics.tmInternalLeading);
    245   int style = 0;
    246   if (font_metrics.tmItalic)
    247     style |= Font::ITALIC;
    248   if (font_metrics.tmUnderlined)
    249     style |= Font::UNDERLINE;
    250   if (font_metrics.tmWeight >= kTextMetricWeightBold)
    251     style |= Font::BOLD;
    252 
    253   return new HFontRef(font, font_size, height, baseline, cap_height,
    254                       ave_char_width, style);
    255 }
    256 
    257 PlatformFontWin::PlatformFontWin(HFontRef* hfont_ref) : font_ref_(hfont_ref) {
    258 }
    259 
    260 ////////////////////////////////////////////////////////////////////////////////
    261 // PlatformFontWin::HFontRef:
    262 
    263 PlatformFontWin::HFontRef::HFontRef(HFONT hfont,
    264                                     int font_size,
    265                                     int height,
    266                                     int baseline,
    267                                     int cap_height,
    268                                     int ave_char_width,
    269                                     int style)
    270     : hfont_(hfont),
    271       font_size_(font_size),
    272       height_(height),
    273       baseline_(baseline),
    274       cap_height_(cap_height),
    275       ave_char_width_(ave_char_width),
    276       style_(style),
    277       dlu_base_x_(-1),
    278       requested_font_size_(font_size) {
    279   DLOG_ASSERT(hfont);
    280 
    281   LOGFONT font_info;
    282   GetObject(hfont_, sizeof(LOGFONT), &font_info);
    283   font_name_ = base::UTF16ToUTF8(base::string16(font_info.lfFaceName));
    284   if (font_info.lfHeight < 0)
    285     requested_font_size_ = -font_info.lfHeight;
    286 }
    287 
    288 int PlatformFontWin::HFontRef::GetDluBaseX() {
    289   if (dlu_base_x_ != -1)
    290     return dlu_base_x_;
    291 
    292   base::win::ScopedGetDC screen_dc(NULL);
    293   base::win::ScopedSelectObject font(screen_dc, hfont_);
    294   gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
    295 
    296   // Yes, this is how Microsoft recommends calculating the dialog unit
    297   // conversions. See: http://support.microsoft.com/kb/125681
    298   SIZE ave_text_size;
    299   GetTextExtentPoint32(screen_dc,
    300                        L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
    301                        52, &ave_text_size);
    302   dlu_base_x_ = (ave_text_size.cx / 26 + 1) / 2;
    303 
    304   DCHECK_NE(dlu_base_x_, -1);
    305   return dlu_base_x_;
    306 }
    307 
    308 PlatformFontWin::HFontRef::~HFontRef() {
    309   DeleteObject(hfont_);
    310 }
    311 
    312 ////////////////////////////////////////////////////////////////////////////////
    313 // PlatformFont, public:
    314 
    315 // static
    316 PlatformFont* PlatformFont::CreateDefault() {
    317   return new PlatformFontWin;
    318 }
    319 
    320 // static
    321 PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) {
    322   return new PlatformFontWin(native_font);
    323 }
    324 
    325 // static
    326 PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name,
    327                                                   int font_size) {
    328   return new PlatformFontWin(font_name, font_size);
    329 }
    330 
    331 }  // namespace gfx
    332