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/platform_font_win.h"
12 #include "base/debug/alias.h"
13 #include "base/logging.h"
14 #include "base/macros.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/sys_string_conversions.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/win/scoped_comptr.h"
19 #include "base/win/scoped_gdi_object.h"
20 #include "base/win/scoped_hdc.h"
21 #include "base/win/scoped_select_object.h"
22 #include "base/win/win_util.h"
23 #include "third_party/skia/include/core/SkTypeface.h"
24 #include "ui/gfx/canvas.h"
25 #include "ui/gfx/font.h"
26 #include "ui/gfx/font_render_params.h"
27 #include "ui/gfx/win/scoped_set_map_mode.h"
31 // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
33 const int kTextMetricWeightBold
= 700;
35 // Returns the minimum font size, using the minimum size callback, if set.
36 int GetMinimumFontSize() {
37 int min_font_size
= 0;
38 if (gfx::PlatformFontWin::get_minimum_font_size_callback
)
39 min_font_size
= gfx::PlatformFontWin::get_minimum_font_size_callback();
43 // Returns either minimum font allowed for a current locale or
44 // lf_height + size_delta value.
45 int AdjustFontSize(int lf_height
, int size_delta
) {
47 lf_height
-= size_delta
;
49 lf_height
+= size_delta
;
51 const int min_font_size
= GetMinimumFontSize();
52 // Make sure lf_height is not smaller than allowed min font size for current
54 if (abs(lf_height
) < min_font_size
) {
55 return lf_height
< 0 ? -min_font_size
: min_font_size
;
61 // Sets style properties on |font_info| based on |font_style|.
62 void SetLogFontStyle(int font_style
, LOGFONT
* font_info
) {
63 font_info
->lfUnderline
= (font_style
& gfx::Font::UNDERLINE
) != 0;
64 font_info
->lfItalic
= (font_style
& gfx::Font::ITALIC
) != 0;
65 font_info
->lfWeight
= (font_style
& gfx::Font::BOLD
) ? FW_BOLD
: FW_NORMAL
;
68 void GetTextMetricsForFont(HDC hdc
, HFONT font
, TEXTMETRIC
* text_metrics
) {
69 base::win::ScopedSelectObject
scoped_font(hdc
, font
);
70 GetTextMetrics(hdc
, text_metrics
);
73 // Returns a matching IDWriteFont for the |font_info| passed in. If we fail
74 // to find a matching font, then we return the IDWriteFont corresponding to
75 // the default font on the system.
76 // Returns S_OK on success.
77 HRESULT
GetMatchingDirectWriteFont(const LOGFONT
& font_info
,
79 IDWriteFactory
* factory
,
80 IDWriteFont
** dwrite_font
) {
81 // First try the GDI compat route to convert the LOGFONT to a IDWriteFont
82 // If that succeeds then we are good. If that fails then try and find a
83 // match from the DirectWrite font collection.
84 base::win::ScopedComPtr
<IDWriteGdiInterop
> gdi_interop
;
85 HRESULT hr
= factory
->GetGdiInterop(gdi_interop
.Receive());
91 hr
= gdi_interop
->CreateFontFromLOGFONT(&font_info
, dwrite_font
);
95 // Get the matching font from the system font collection exposed by
97 base::win::ScopedComPtr
<IDWriteFontCollection
> font_collection
;
98 hr
= factory
->GetSystemFontCollection(font_collection
.Receive());
105 // This mirrors skia.
106 // 1. Attempt to find a DirectWrite font family based on the face name in the
107 // font. That may not work at all times, as the face name could be random
108 // GDI has its own font system where in it creates a font matching the
109 // characteristics in the LOGFONT structure passed into
110 // CreateFontIndirect. DirectWrite does not do that. If this succeeds then
111 // return the matching IDWriteFont from the family.
112 // 2. If step 1 fails then repeat with the default system font. This has the
113 // same limitations with the face name as mentioned above.
114 // 3. If step 2 fails then return the first family from the collection and
116 base::win::ScopedComPtr
<IDWriteFontFamily
> font_family
;
119 hr
= font_collection
->FindFamilyName(font_info
.lfFaceName
, &index
, &exists
);
120 // If we fail to find a match then try fallback to the default font on the
121 // system. This is what skia does as well.
122 if (FAILED(hr
) || (index
== UINT_MAX
) || !exists
) {
123 NONCLIENTMETRICS metrics
= {0};
124 metrics
.cbSize
= sizeof(metrics
);
125 if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS
,
132 hr
= font_collection
->FindFamilyName(metrics
.lfMessageFont
.lfFaceName
,
137 if (index
!= UINT_MAX
&& exists
) {
138 hr
= font_collection
->GetFontFamily(index
, font_family
.Receive());
140 // If we fail to find a matching font, then fallback to the first font in
141 // the list. This is what skia does as well.
142 hr
= font_collection
->GetFontFamily(0, font_family
.Receive());
150 DWRITE_FONT_WEIGHT weight
= (font_style
& SkTypeface::kBold
)
151 ? DWRITE_FONT_WEIGHT_BOLD
152 : DWRITE_FONT_WEIGHT_NORMAL
;
153 DWRITE_FONT_STRETCH stretch
= DWRITE_FONT_STRETCH_NORMAL
;
154 DWRITE_FONT_STYLE italic
= (font_style
& SkTypeface::kItalic
)
155 ? DWRITE_FONT_STYLE_ITALIC
156 : DWRITE_FONT_STYLE_NORMAL
;
158 // The IDWriteFontFamily::GetFirstMatchingFont call fails on certain machines
159 // for fonts like MS UI Gothic, Segoe UI, etc. It is not clear why these
160 // fonts could be accessible to GDI and not to DirectWrite.
161 // The code below adds some debug fields to help track down these failures.
162 // 1. We get the matching font list for the font attributes passed in.
163 // 2. We get the font count in the family with a debug alias variable.
164 // 3. If GetFirstMatchingFont fails then we CHECK as before.
165 // Next step would be to remove the CHECKs in this function and fallback to
167 // http://crbug.com/434425
169 // Remove the GetMatchingFonts and related code here once we get to a stable
171 base::win::ScopedComPtr
<IDWriteFontList
> matching_font_list
;
172 hr
= font_family
->GetMatchingFonts(weight
, stretch
, italic
,
173 matching_font_list
.Receive());
174 uint32 matching_font_count
= 0;
176 matching_font_count
= matching_font_list
->GetFontCount();
178 hr
= font_family
->GetFirstMatchingFont(weight
, stretch
, italic
,
181 base::debug::Alias(&matching_font_count
);
192 PlatformFontWin::HFontRef
* PlatformFontWin::base_font_ref_
;
195 PlatformFontWin::AdjustFontCallback
196 PlatformFontWin::adjust_font_callback
= nullptr;
197 PlatformFontWin::GetMinimumFontSizeCallback
198 PlatformFontWin::get_minimum_font_size_callback
= NULL
;
200 IDWriteFactory
* PlatformFontWin::direct_write_factory_
= nullptr;
202 ////////////////////////////////////////////////////////////////////////////////
203 // PlatformFontWin, public
205 PlatformFontWin::PlatformFontWin() : font_ref_(GetBaseFontRef()) {
208 PlatformFontWin::PlatformFontWin(NativeFont native_font
) {
209 InitWithCopyOfHFONT(native_font
);
212 PlatformFontWin::PlatformFontWin(const std::string
& font_name
,
214 InitWithFontNameAndSize(font_name
, font_size
);
217 Font
PlatformFontWin::DeriveFontWithHeight(int height
, int style
) {
218 DCHECK_GE(height
, 0);
219 if (GetHeight() == height
&& GetStyle() == style
)
222 // CreateFontIndirect() doesn't return the largest size for the given height
223 // when decreasing the height. Iterate to find it.
224 if (GetHeight() > height
) {
225 const int min_font_size
= GetMinimumFontSize();
226 Font font
= DeriveFont(-1, style
);
227 int font_height
= font
.GetHeight();
228 int font_size
= font
.GetFontSize();
229 while (font_height
> height
&& font_size
!= min_font_size
) {
230 font
= font
.Derive(-1, style
);
231 if (font_height
== font
.GetHeight() && font_size
== font
.GetFontSize())
233 font_height
= font
.GetHeight();
234 font_size
= font
.GetFontSize();
240 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
241 font_info
.lfHeight
= height
;
242 SetLogFontStyle(style
, &font_info
);
244 HFONT hfont
= CreateFontIndirect(&font_info
);
245 return DeriveWithCorrectedSize(hfont
);
248 ////////////////////////////////////////////////////////////////////////////////
249 // PlatformFontWin, PlatformFont implementation:
251 Font
PlatformFontWin::DeriveFont(int size_delta
, int style
) const {
253 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
254 const int requested_font_size
= font_ref_
->requested_font_size();
255 font_info
.lfHeight
= AdjustFontSize(-requested_font_size
, size_delta
);
256 SetLogFontStyle(style
, &font_info
);
258 HFONT hfont
= CreateFontIndirect(&font_info
);
259 return Font(new PlatformFontWin(CreateHFontRef(hfont
)));
262 int PlatformFontWin::GetHeight() const {
263 return font_ref_
->height();
266 int PlatformFontWin::GetBaseline() const {
267 return font_ref_
->baseline();
270 int PlatformFontWin::GetCapHeight() const {
271 return font_ref_
->cap_height();
274 int PlatformFontWin::GetExpectedTextWidth(int length
) const {
275 return length
* std::min(font_ref_
->GetDluBaseX(),
276 font_ref_
->ave_char_width());
279 int PlatformFontWin::GetStyle() const {
280 return font_ref_
->style();
283 std::string
PlatformFontWin::GetFontName() const {
284 return font_ref_
->font_name();
287 std::string
PlatformFontWin::GetActualFontNameForTesting() const {
288 // With the current implementation on Windows, HFontRef::font_name() returns
289 // the font name taken from the HFONT handle, but it's not the name that comes
290 // from the font's metadata. See http://crbug.com/327287
291 return font_ref_
->font_name();
294 std::string
PlatformFontWin::GetLocalizedFontName() const {
295 base::win::ScopedCreateDC
memory_dc(CreateCompatibleDC(NULL
));
296 if (!memory_dc
.Get())
297 return GetFontName();
299 // When a font has a localized name for a language matching the system
300 // locale, GetTextFace() returns the localized name.
301 base::win::ScopedSelectObject
font(memory_dc
.Get(), font_ref_
->hfont());
302 wchar_t localized_font_name
[LF_FACESIZE
];
303 int length
= GetTextFace(memory_dc
.Get(), arraysize(localized_font_name
),
304 &localized_font_name
[0]);
306 return GetFontName();
307 return base::SysWideToUTF8(localized_font_name
);
310 int PlatformFontWin::GetFontSize() const {
311 return font_ref_
->font_size();
314 const FontRenderParams
& PlatformFontWin::GetFontRenderParams() const {
315 CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams
, params
,
316 (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(false), NULL
)));
320 NativeFont
PlatformFontWin::GetNativeFont() const {
321 return font_ref_
->hfont();
324 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory
* factory
) {
325 // We grab a reference on the DirectWrite factory. This reference is
326 // leaked, which is ok because skia leaks it as well.
328 direct_write_factory_
= factory
;
331 ////////////////////////////////////////////////////////////////////////////////
334 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont
) {
337 GetObject(hfont
, sizeof(LOGFONT
), &font_info
);
338 font_ref_
= CreateHFontRef(CreateFontIndirect(&font_info
));
341 void PlatformFontWin::InitWithFontNameAndSize(const std::string
& font_name
,
343 HFONT hf
= ::CreateFont(-font_size
, 0, 0, 0, FW_DONTCARE
, FALSE
, FALSE
, FALSE
,
348 DEFAULT_PITCH
| FF_DONTCARE
,
349 base::UTF8ToUTF16(font_name
).c_str());
350 font_ref_
= CreateHFontRef(hf
);
354 PlatformFontWin::HFontRef
* PlatformFontWin::GetBaseFontRef() {
355 if (base_font_ref_
== NULL
) {
356 NONCLIENTMETRICS_XP metrics
;
357 base::win::GetNonClientMetrics(&metrics
);
359 if (adjust_font_callback
)
360 adjust_font_callback(&metrics
.lfMessageFont
);
361 metrics
.lfMessageFont
.lfHeight
=
362 AdjustFontSize(metrics
.lfMessageFont
.lfHeight
, 0);
363 HFONT font
= CreateFontIndirect(&metrics
.lfMessageFont
);
365 base_font_ref_
= PlatformFontWin::CreateHFontRef(font
);
366 // base_font_ref_ is global, up the ref count so it's never deleted.
367 base_font_ref_
->AddRef();
369 return base_font_ref_
;
372 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRef(HFONT font
) {
373 if (direct_write_factory_
)
374 return CreateHFontRefFromSkia(font
);
376 TEXTMETRIC font_metrics
;
379 base::win::ScopedGetDC
screen_dc(NULL
);
380 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
381 GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
384 return CreateHFontRef(font
, font_metrics
);
387 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRef(
389 const TEXTMETRIC
& font_metrics
) {
390 const int height
= std::max
<int>(1, font_metrics
.tmHeight
);
391 const int baseline
= std::max
<int>(1, font_metrics
.tmAscent
);
392 const int cap_height
=
393 std::max
<int>(1, font_metrics
.tmAscent
- font_metrics
.tmInternalLeading
);
394 const int ave_char_width
= std::max
<int>(1, font_metrics
.tmAveCharWidth
);
395 const int font_size
=
396 std::max
<int>(1, font_metrics
.tmHeight
- font_metrics
.tmInternalLeading
);
398 if (font_metrics
.tmItalic
)
399 style
|= Font::ITALIC
;
400 if (font_metrics
.tmUnderlined
)
401 style
|= Font::UNDERLINE
;
402 if (font_metrics
.tmWeight
>= kTextMetricWeightBold
)
405 return new HFontRef(font
, font_size
, height
, baseline
, cap_height
,
406 ave_char_width
, style
);
409 Font
PlatformFontWin::DeriveWithCorrectedSize(HFONT base_font
) {
410 base::win::ScopedGetDC
screen_dc(NULL
);
411 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
413 base::win::ScopedGDIObject
<HFONT
> best_font(base_font
);
414 TEXTMETRIC best_font_metrics
;
415 GetTextMetricsForFont(screen_dc
, best_font
, &best_font_metrics
);
418 GetObject(base_font
, sizeof(LOGFONT
), &font_info
);
420 // Set |lfHeight| to negative value to indicate it's the size, not the height.
422 -(best_font_metrics
.tmHeight
- best_font_metrics
.tmInternalLeading
);
425 // Increment font size. Prefer font with greater size if its height isn't
426 // greater than height of base font.
427 font_info
.lfHeight
= AdjustFontSize(font_info
.lfHeight
, 1);
428 base::win::ScopedGDIObject
<HFONT
> font(CreateFontIndirect(&font_info
));
429 TEXTMETRIC font_metrics
;
430 GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
431 if (font_metrics
.tmHeight
> best_font_metrics
.tmHeight
)
433 best_font
.Set(font
.release());
434 best_font_metrics
= font_metrics
;
437 return Font(new PlatformFontWin(CreateHFontRef(best_font
.release())));
441 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRefFromSkia(
443 LOGFONT font_info
= {0};
444 GetObject(gdi_font
, sizeof(LOGFONT
), &font_info
);
446 int skia_style
= SkTypeface::kNormal
;
447 if (font_info
.lfWeight
>= FW_SEMIBOLD
&&
448 font_info
.lfWeight
<= FW_ULTRABOLD
) {
449 skia_style
|= SkTypeface::kBold
;
451 if (font_info
.lfItalic
)
452 skia_style
|= SkTypeface::kItalic
;
454 // Skia does not return all values we need for font metrics. For e.g.
455 // the cap height which indicates the height of capital letters is not
456 // returned even though it is returned by DirectWrite.
458 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
459 // DirectWrite and remove the code here which retrieves metrics from
460 // DirectWrite to calculate the cap height.
461 base::win::ScopedComPtr
<IDWriteFont
> dwrite_font
;
462 HRESULT hr
= GetMatchingDirectWriteFont(font_info
,
464 direct_write_factory_
,
465 dwrite_font
.Receive());
471 DWRITE_FONT_METRICS dwrite_font_metrics
= {0};
472 dwrite_font
->GetMetrics(&dwrite_font_metrics
);
474 skia::RefPtr
<SkTypeface
> skia_face
= skia::AdoptRef(
475 SkTypeface::CreateFromName(
476 base::SysWideToUTF8(font_info
.lfFaceName
).c_str(),
477 static_cast<SkTypeface::Style
>(skia_style
)));
479 BOOL antialiasing
= TRUE
;
480 SystemParametersInfo(SPI_GETFONTSMOOTHING
, 0, &antialiasing
, 0);
483 paint
.setAntiAlias(!!antialiasing
);
484 paint
.setTypeface(skia_face
.get());
485 paint
.setTextSize(abs(font_info
.lfHeight
));
486 SkPaint::FontMetrics skia_metrics
;
487 paint
.getFontMetrics(&skia_metrics
);
489 // The calculations below are similar to those in the CreateHFontRef
491 const int height
= std::round(skia_metrics
.fDescent
- skia_metrics
.fAscent
);
492 const int baseline
= std::max
<int>(1, std::round(-skia_metrics
.fAscent
));
493 const int cap_height
= std::round(-font_info
.lfHeight
*
494 dwrite_font_metrics
.capHeight
/ dwrite_font_metrics
.designUnitsPerEm
);
496 // The metrics retrieved from skia don't have the average character width. In
497 // any case if we get the average character width from skia then use that or
498 // use the text extent technique as documented by microsoft. See
499 // GetAverageCharWidthInDialogUnits for details.
500 const int ave_char_width
=
501 skia_metrics
.fAvgCharWidth
== 0 ?
502 HFontRef::GetAverageCharWidthInDialogUnits(gdi_font
)
503 : skia_metrics
.fAvgCharWidth
;
505 // tmAscent - tmInternalLeading in gdi font land gives us the cap height.
506 // We can use fAscent - cap_height in DirectWrite land to get the internal
508 const int internal_leading
= -skia_metrics
.fAscent
- cap_height
;
509 const int font_size
= std::max
<int>(1, height
- internal_leading
);
512 if (skia_style
& SkTypeface::kItalic
)
513 style
|= Font::ITALIC
;
514 if (font_info
.lfUnderline
)
515 style
|= Font::UNDERLINE
;
516 if (font_info
.lfWeight
>= kTextMetricWeightBold
)
518 return new HFontRef(gdi_font
, font_size
, height
, baseline
, cap_height
,
519 ave_char_width
, style
);
522 PlatformFontWin::PlatformFontWin(HFontRef
* hfont_ref
) : font_ref_(hfont_ref
) {
525 ////////////////////////////////////////////////////////////////////////////////
526 // PlatformFontWin::HFontRef:
528 PlatformFontWin::HFontRef::HFontRef(HFONT hfont
,
536 font_size_(font_size
),
539 cap_height_(cap_height
),
540 ave_char_width_(ave_char_width
),
543 requested_font_size_(font_size
) {
547 GetObject(hfont_
, sizeof(LOGFONT
), &font_info
);
548 font_name_
= base::UTF16ToUTF8(base::string16(font_info
.lfFaceName
));
549 if (font_info
.lfHeight
< 0)
550 requested_font_size_
= -font_info
.lfHeight
;
553 int PlatformFontWin::HFontRef::GetDluBaseX() {
554 if (dlu_base_x_
!= -1)
557 dlu_base_x_
= GetAverageCharWidthInDialogUnits(hfont_
);
562 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
564 base::win::ScopedGetDC
screen_dc(NULL
);
565 base::win::ScopedSelectObject
font(screen_dc
, gdi_font
);
566 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
568 // Yes, this is how Microsoft recommends calculating the dialog unit
569 // conversions. See: http://support.microsoft.com/kb/125681
571 GetTextExtentPoint32(screen_dc
,
572 L
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
574 int dlu_base_x
= (ave_text_size
.cx
/ 26 + 1) / 2;
576 DCHECK_NE(dlu_base_x
, -1);
580 PlatformFontWin::HFontRef::~HFontRef() {
581 DeleteObject(hfont_
);
584 ////////////////////////////////////////////////////////////////////////////////
585 // PlatformFont, public:
588 PlatformFont
* PlatformFont::CreateDefault() {
589 return new PlatformFontWin
;
593 PlatformFont
* PlatformFont::CreateFromNativeFont(NativeFont native_font
) {
594 return new PlatformFontWin(native_font
);
598 PlatformFont
* PlatformFont::CreateFromNameAndSize(const std::string
& font_name
,
600 return new PlatformFontWin(font_name
, font_size
);