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