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 // Returns a matching IDWriteFont for the |font_info| passed in. If we fail
69 // to find a matching font, then we return the IDWriteFont corresponding to
70 // the default font on the system.
71 // Returns S_OK on success.
72 HRESULT
GetMatchingDirectWriteFont(const LOGFONT
& font_info
,
74 IDWriteFactory
* factory
,
75 IDWriteFont
** dwrite_font
) {
76 // First try the GDI compat route to convert the LOGFONT to a IDWriteFont
77 // If that succeeds then we are good. If that fails then try and find a
78 // match from the DirectWrite font collection.
79 base::win::ScopedComPtr
<IDWriteGdiInterop
> gdi_interop
;
80 HRESULT hr
= factory
->GetGdiInterop(gdi_interop
.Receive());
86 hr
= gdi_interop
->CreateFontFromLOGFONT(&font_info
, dwrite_font
);
90 // Get the matching font from the system font collection exposed by
92 base::win::ScopedComPtr
<IDWriteFontCollection
> font_collection
;
93 hr
= factory
->GetSystemFontCollection(font_collection
.Receive());
100 // This mirrors skia.
101 // 1. Attempt to find a DirectWrite font family based on the face name in the
102 // font. That may not work at all times, as the face name could be random
103 // GDI has its own font system where in it creates a font matching the
104 // characteristics in the LOGFONT structure passed into
105 // CreateFontIndirect. DirectWrite does not do that. If this succeeds then
106 // return the matching IDWriteFont from the family.
107 // 2. If step 1 fails then repeat with the default system font. This has the
108 // same limitations with the face name as mentioned above.
109 // 3. If step 2 fails then return the first family from the collection and
111 base::win::ScopedComPtr
<IDWriteFontFamily
> font_family
;
114 hr
= font_collection
->FindFamilyName(font_info
.lfFaceName
, &index
, &exists
);
115 // If we fail to find a match then try fallback to the default font on the
116 // system. This is what skia does as well.
117 if (FAILED(hr
) || (index
== UINT_MAX
) || !exists
) {
118 NONCLIENTMETRICS metrics
= {0};
119 metrics
.cbSize
= sizeof(metrics
);
120 if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS
,
127 hr
= font_collection
->FindFamilyName(metrics
.lfMessageFont
.lfFaceName
,
132 if (index
!= UINT_MAX
&& exists
) {
133 hr
= font_collection
->GetFontFamily(index
, font_family
.Receive());
135 // If we fail to find a matching font, then fallback to the first font in
136 // the list. This is what skia does as well.
137 hr
= font_collection
->GetFontFamily(0, font_family
.Receive());
145 DWRITE_FONT_WEIGHT weight
= (font_style
& SkTypeface::kBold
)
146 ? DWRITE_FONT_WEIGHT_BOLD
147 : DWRITE_FONT_WEIGHT_NORMAL
;
148 DWRITE_FONT_STRETCH stretch
= DWRITE_FONT_STRETCH_NORMAL
;
149 DWRITE_FONT_STYLE italic
= (font_style
& SkTypeface::kItalic
)
150 ? DWRITE_FONT_STYLE_ITALIC
151 : DWRITE_FONT_STYLE_NORMAL
;
153 // The IDWriteFontFamily::GetFirstMatchingFont call fails on certain machines
154 // for fonts like MS UI Gothic, Segoe UI, etc. It is not clear why these
155 // fonts could be accessible to GDI and not to DirectWrite.
156 // The code below adds some debug fields to help track down these failures.
157 // 1. We get the matching font list for the font attributes passed in.
158 // 2. We get the font count in the family with a debug alias variable.
159 // 3. If GetFirstMatchingFont fails then we CHECK as before.
160 // Next step would be to remove the CHECKs in this function and fallback to
162 // http://crbug.com/434425
164 // Remove the GetMatchingFonts and related code here once we get to a stable
166 base::win::ScopedComPtr
<IDWriteFontList
> matching_font_list
;
167 hr
= font_family
->GetMatchingFonts(weight
, stretch
, italic
,
168 matching_font_list
.Receive());
169 uint32 matching_font_count
= 0;
171 matching_font_count
= matching_font_list
->GetFontCount();
173 hr
= font_family
->GetFirstMatchingFont(weight
, stretch
, italic
,
176 base::debug::Alias(&matching_font_count
);
187 PlatformFontWin::HFontRef
* PlatformFontWin::base_font_ref_
;
190 PlatformFontWin::AdjustFontCallback
191 PlatformFontWin::adjust_font_callback
= nullptr;
192 PlatformFontWin::GetMinimumFontSizeCallback
193 PlatformFontWin::get_minimum_font_size_callback
= NULL
;
195 IDWriteFactory
* PlatformFontWin::direct_write_factory_
= nullptr;
197 ////////////////////////////////////////////////////////////////////////////////
198 // PlatformFontWin, public
200 PlatformFontWin::PlatformFontWin() : font_ref_(GetBaseFontRef()) {
203 PlatformFontWin::PlatformFontWin(NativeFont native_font
) {
204 InitWithCopyOfHFONT(native_font
);
207 PlatformFontWin::PlatformFontWin(const std::string
& font_name
,
209 InitWithFontNameAndSize(font_name
, font_size
);
212 Font
PlatformFontWin::DeriveFontWithHeight(int height
, int style
) {
213 DCHECK_GE(height
, 0);
215 // Create a font with a height near that of the target height.
217 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
218 font_info
.lfHeight
= height
;
219 SetLogFontStyle(style
, &font_info
);
221 HFONT hfont
= CreateFontIndirect(&font_info
);
222 Font
font(new PlatformFontWin(CreateHFontRef(hfont
)));
224 // Respect the minimum font size constraint.
225 const int min_font_size
= GetMinimumFontSize();
227 // Used to avoid shrinking the font and expanding it.
228 bool ran_shrink_loop
= false;
230 // Iterate to find the largest font with a height <= |height|.
231 while ((font
.GetHeight() > height
) &&
232 (font
.GetFontSize() >= min_font_size
)) {
233 ran_shrink_loop
= true;
234 Font derived_font
= font
.Derive(-1, style
);
235 // Break the loop if the derived font is too small or hasn't shrunk at all.
236 if ((derived_font
.GetFontSize() < min_font_size
) ||
237 ((derived_font
.GetFontSize() == font
.GetFontSize()) &&
238 (derived_font
.GetHeight() == font
.GetHeight())))
243 while ((!ran_shrink_loop
&& font
.GetHeight() <= height
) ||
244 (font
.GetFontSize() < min_font_size
)) {
245 Font derived_font
= font
.Derive(1, style
);
246 // Break the loop if the derived font is too large or hasn't grown at all.
247 if (((derived_font
.GetHeight() > height
) &&
248 (font
.GetFontSize() >= min_font_size
)) ||
249 ((derived_font
.GetFontSize() == font
.GetFontSize()) &&
250 (derived_font
.GetHeight() == font
.GetHeight())))
257 ////////////////////////////////////////////////////////////////////////////////
258 // PlatformFontWin, PlatformFont implementation:
260 Font
PlatformFontWin::DeriveFont(int size_delta
, int style
) const {
262 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
263 const int requested_font_size
= font_ref_
->requested_font_size();
264 font_info
.lfHeight
= AdjustFontSize(-requested_font_size
, size_delta
);
265 SetLogFontStyle(style
, &font_info
);
267 HFONT hfont
= CreateFontIndirect(&font_info
);
268 return Font(new PlatformFontWin(CreateHFontRef(hfont
)));
271 int PlatformFontWin::GetHeight() const {
272 return font_ref_
->height();
275 int PlatformFontWin::GetBaseline() const {
276 return font_ref_
->baseline();
279 int PlatformFontWin::GetCapHeight() const {
280 return font_ref_
->cap_height();
283 int PlatformFontWin::GetExpectedTextWidth(int length
) const {
284 return length
* std::min(font_ref_
->GetDluBaseX(),
285 font_ref_
->ave_char_width());
288 int PlatformFontWin::GetStyle() const {
289 return font_ref_
->style();
292 std::string
PlatformFontWin::GetFontName() const {
293 return font_ref_
->font_name();
296 std::string
PlatformFontWin::GetActualFontNameForTesting() const {
297 // With the current implementation on Windows, HFontRef::font_name() returns
298 // the font name taken from the HFONT handle, but it's not the name that comes
299 // from the font's metadata. See http://crbug.com/327287
300 return font_ref_
->font_name();
303 std::string
PlatformFontWin::GetLocalizedFontName() const {
304 base::win::ScopedCreateDC
memory_dc(CreateCompatibleDC(NULL
));
305 if (!memory_dc
.Get())
306 return GetFontName();
308 // When a font has a localized name for a language matching the system
309 // locale, GetTextFace() returns the localized name.
310 base::win::ScopedSelectObject
font(memory_dc
.Get(), font_ref_
->hfont());
311 wchar_t localized_font_name
[LF_FACESIZE
];
312 int length
= GetTextFace(memory_dc
.Get(), arraysize(localized_font_name
),
313 &localized_font_name
[0]);
315 return GetFontName();
316 return base::SysWideToUTF8(localized_font_name
);
319 int PlatformFontWin::GetFontSize() const {
320 return font_ref_
->font_size();
323 const FontRenderParams
& PlatformFontWin::GetFontRenderParams() {
324 CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams
, params
,
325 (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(false), NULL
)));
329 NativeFont
PlatformFontWin::GetNativeFont() const {
330 return font_ref_
->hfont();
334 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory
* factory
) {
335 // We grab a reference on the DirectWrite factory. This reference is
336 // leaked, which is ok because skia leaks it as well.
338 direct_write_factory_
= factory
;
342 void PlatformFontWin::GetTextMetricsForFont(HDC hdc
,
344 TEXTMETRIC
* text_metrics
) {
345 base::win::ScopedSelectObject
scoped_font(hdc
, font
);
346 GetTextMetrics(hdc
, text_metrics
);
350 int PlatformFontWin::GetFontSize(const LOGFONT
& font_info
) {
351 if (font_info
.lfHeight
< 0)
352 return -font_info
.lfHeight
;
354 base::win::ScopedGetDC
screen_dc(NULL
);
355 base::win::ScopedGDIObject
<HFONT
> font(CreateFontIndirect(&font_info
));
357 TEXTMETRIC font_metrics
= {0};
358 PlatformFontWin::GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
359 return font_metrics
.tmAscent
;
362 ////////////////////////////////////////////////////////////////////////////////
365 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont
) {
368 GetObject(hfont
, sizeof(LOGFONT
), &font_info
);
369 font_ref_
= CreateHFontRef(CreateFontIndirect(&font_info
));
372 void PlatformFontWin::InitWithFontNameAndSize(const std::string
& font_name
,
374 HFONT hf
= ::CreateFont(-font_size
, 0, 0, 0, FW_DONTCARE
, FALSE
, FALSE
, FALSE
,
379 DEFAULT_PITCH
| FF_DONTCARE
,
380 base::UTF8ToUTF16(font_name
).c_str());
381 font_ref_
= CreateHFontRef(hf
);
385 PlatformFontWin::HFontRef
* PlatformFontWin::GetBaseFontRef() {
386 if (base_font_ref_
== NULL
) {
387 NONCLIENTMETRICS_XP metrics
;
388 base::win::GetNonClientMetrics(&metrics
);
390 if (adjust_font_callback
)
391 adjust_font_callback(&metrics
.lfMessageFont
);
392 metrics
.lfMessageFont
.lfHeight
=
393 AdjustFontSize(metrics
.lfMessageFont
.lfHeight
, 0);
394 HFONT font
= CreateFontIndirect(&metrics
.lfMessageFont
);
396 base_font_ref_
= PlatformFontWin::CreateHFontRef(font
);
397 // base_font_ref_ is global, up the ref count so it's never deleted.
398 base_font_ref_
->AddRef();
400 return base_font_ref_
;
403 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRef(HFONT font
) {
404 TEXTMETRIC font_metrics
;
407 base::win::ScopedGetDC
screen_dc(NULL
);
408 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
409 GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
412 if (direct_write_factory_
)
413 return CreateHFontRefFromSkia(font
, font_metrics
);
415 return CreateHFontRefFromGDI(font
, font_metrics
);
418 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRefFromGDI(
420 const TEXTMETRIC
& font_metrics
) {
421 const int height
= std::max
<int>(1, font_metrics
.tmHeight
);
422 const int baseline
= std::max
<int>(1, font_metrics
.tmAscent
);
423 const int cap_height
=
424 std::max
<int>(1, font_metrics
.tmAscent
- font_metrics
.tmInternalLeading
);
425 const int ave_char_width
= std::max
<int>(1, font_metrics
.tmAveCharWidth
);
426 const int font_size
=
427 std::max
<int>(1, font_metrics
.tmHeight
- font_metrics
.tmInternalLeading
);
429 if (font_metrics
.tmItalic
)
430 style
|= Font::ITALIC
;
431 if (font_metrics
.tmUnderlined
)
432 style
|= Font::UNDERLINE
;
433 if (font_metrics
.tmWeight
>= kTextMetricWeightBold
)
436 return new HFontRef(font
, font_size
, height
, baseline
, cap_height
,
437 ave_char_width
, style
);
441 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRefFromSkia(
443 const TEXTMETRIC
& font_metrics
) {
444 LOGFONT font_info
= {0};
445 GetObject(gdi_font
, sizeof(LOGFONT
), &font_info
);
447 // If the font height is passed in as 0, assume the height to be -1 to ensure
448 // that we return the metrics for a 1 point font.
449 // If the font height is positive it represents the rasterized font's cell
450 // height. Calculate the actual height accordingly.
451 if (font_info
.lfHeight
> 0) {
453 font_metrics
.tmInternalLeading
- font_metrics
.tmHeight
;
454 } else if (font_info
.lfHeight
== 0) {
455 font_info
.lfHeight
= -1;
458 int skia_style
= SkTypeface::kNormal
;
459 if (font_info
.lfWeight
>= FW_SEMIBOLD
&&
460 font_info
.lfWeight
<= FW_ULTRABOLD
) {
461 skia_style
|= SkTypeface::kBold
;
463 if (font_info
.lfItalic
)
464 skia_style
|= SkTypeface::kItalic
;
466 // Skia does not return all values we need for font metrics. For e.g.
467 // the cap height which indicates the height of capital letters is not
468 // returned even though it is returned by DirectWrite.
470 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
471 // DirectWrite and remove the code here which retrieves metrics from
472 // DirectWrite to calculate the cap height.
473 base::win::ScopedComPtr
<IDWriteFont
> dwrite_font
;
474 HRESULT hr
= GetMatchingDirectWriteFont(font_info
,
476 direct_write_factory_
,
477 dwrite_font
.Receive());
483 DWRITE_FONT_METRICS dwrite_font_metrics
= {0};
484 dwrite_font
->GetMetrics(&dwrite_font_metrics
);
486 skia::RefPtr
<SkTypeface
> skia_face
= skia::AdoptRef(
487 SkTypeface::CreateFromName(
488 base::SysWideToUTF8(font_info
.lfFaceName
).c_str(),
489 static_cast<SkTypeface::Style
>(skia_style
)));
491 BOOL antialiasing
= TRUE
;
492 SystemParametersInfo(SPI_GETFONTSMOOTHING
, 0, &antialiasing
, 0);
495 paint
.setAntiAlias(!!antialiasing
);
496 paint
.setTypeface(skia_face
.get());
497 paint
.setTextSize(-font_info
.lfHeight
);
498 SkPaint::FontMetrics skia_metrics
;
499 paint
.getFontMetrics(&skia_metrics
);
501 // The calculations below are similar to those in the CreateHFontRef
502 // function. The height, baseline and cap height are rounded up to ensure
503 // that they match up closely with GDI.
504 const int height
= std::ceil(skia_metrics
.fDescent
- skia_metrics
.fAscent
);
505 const int baseline
= std::max
<int>(1, std::ceil(-skia_metrics
.fAscent
));
506 const int cap_height
= std::ceil(paint
.getTextSize() *
507 static_cast<double>(dwrite_font_metrics
.capHeight
) /
508 dwrite_font_metrics
.designUnitsPerEm
);
510 // The metrics retrieved from skia don't have the average character width. In
511 // any case if we get the average character width from skia then use that or
512 // the average character width in the TEXTMETRIC structure.
513 // TODO(ananta): Investigate whether it is possible to retrieve this value
515 const int ave_char_width
=
516 skia_metrics
.fAvgCharWidth
== 0 ? font_metrics
.tmAveCharWidth
517 : skia_metrics
.fAvgCharWidth
;
520 if (skia_style
& SkTypeface::kItalic
)
521 style
|= Font::ITALIC
;
522 if (font_info
.lfUnderline
)
523 style
|= Font::UNDERLINE
;
524 if (font_info
.lfWeight
>= kTextMetricWeightBold
)
526 return new HFontRef(gdi_font
, -font_info
.lfHeight
, height
, baseline
,
527 cap_height
, ave_char_width
, style
);
530 PlatformFontWin::PlatformFontWin(HFontRef
* hfont_ref
) : font_ref_(hfont_ref
) {
533 ////////////////////////////////////////////////////////////////////////////////
534 // PlatformFontWin::HFontRef:
536 PlatformFontWin::HFontRef::HFontRef(HFONT hfont
,
544 font_size_(font_size
),
547 cap_height_(cap_height
),
548 ave_char_width_(ave_char_width
),
551 requested_font_size_(font_size
) {
555 GetObject(hfont_
, sizeof(LOGFONT
), &font_info
);
556 font_name_
= base::UTF16ToUTF8(base::string16(font_info
.lfFaceName
));
558 // Retrieve the font size from the GetTextMetrics API instead of referencing
559 // it from the LOGFONT structure. This is because the height as reported by
560 // the LOGFONT structure is not always correct. For small fonts with size 1
561 // the LOGFONT structure reports the height as -1, while the actual font size
562 // is different. (2 on my XP machine).
563 base::win::ScopedGetDC
screen_dc(NULL
);
564 TEXTMETRIC font_metrics
= {0};
565 PlatformFontWin::GetTextMetricsForFont(screen_dc
, hfont_
, &font_metrics
);
566 requested_font_size_
= font_metrics
.tmHeight
- font_metrics
.tmInternalLeading
;
569 int PlatformFontWin::HFontRef::GetDluBaseX() {
570 if (dlu_base_x_
!= -1)
573 dlu_base_x_
= GetAverageCharWidthInDialogUnits(hfont_
);
578 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
580 base::win::ScopedGetDC
screen_dc(NULL
);
581 base::win::ScopedSelectObject
font(screen_dc
, gdi_font
);
582 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
584 // Yes, this is how Microsoft recommends calculating the dialog unit
585 // conversions. See: http://support.microsoft.com/kb/125681
587 GetTextExtentPoint32(screen_dc
,
588 L
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
590 int dlu_base_x
= (ave_text_size
.cx
/ 26 + 1) / 2;
592 DCHECK_NE(dlu_base_x
, -1);
596 PlatformFontWin::HFontRef::~HFontRef() {
597 DeleteObject(hfont_
);
600 ////////////////////////////////////////////////////////////////////////////////
601 // PlatformFont, public:
604 PlatformFont
* PlatformFont::CreateDefault() {
605 return new PlatformFontWin
;
609 PlatformFont
* PlatformFont::CreateFromNativeFont(NativeFont native_font
) {
610 return new PlatformFontWin(native_font
);
614 PlatformFont
* PlatformFont::CreateFromNameAndSize(const std::string
& font_name
,
616 return new PlatformFontWin(font_name
, font_size
);