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);
214 if (GetHeight() == height
&& GetStyle() == style
)
217 // CreateFontIndirect() doesn't return the largest size for the given height
218 // when decreasing the height. Iterate to find it.
219 if (GetHeight() > height
) {
220 const int min_font_size
= GetMinimumFontSize();
221 Font font
= DeriveFont(-1, style
);
222 int font_height
= font
.GetHeight();
223 int font_size
= font
.GetFontSize();
224 while (font_height
> height
&& font_size
!= min_font_size
) {
225 font
= font
.Derive(-1, style
);
226 if (font_height
== font
.GetHeight() && font_size
== font
.GetFontSize())
228 font_height
= font
.GetHeight();
229 font_size
= font
.GetFontSize();
235 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
236 font_info
.lfHeight
= height
;
237 SetLogFontStyle(style
, &font_info
);
239 HFONT hfont
= CreateFontIndirect(&font_info
);
240 return DeriveWithCorrectedSize(hfont
);
243 ////////////////////////////////////////////////////////////////////////////////
244 // PlatformFontWin, PlatformFont implementation:
246 Font
PlatformFontWin::DeriveFont(int size_delta
, int style
) const {
248 GetObject(GetNativeFont(), sizeof(LOGFONT
), &font_info
);
249 const int requested_font_size
= font_ref_
->requested_font_size();
250 font_info
.lfHeight
= AdjustFontSize(-requested_font_size
, size_delta
);
251 SetLogFontStyle(style
, &font_info
);
253 HFONT hfont
= CreateFontIndirect(&font_info
);
254 return Font(new PlatformFontWin(CreateHFontRef(hfont
)));
257 int PlatformFontWin::GetHeight() const {
258 return font_ref_
->height();
261 int PlatformFontWin::GetBaseline() const {
262 return font_ref_
->baseline();
265 int PlatformFontWin::GetCapHeight() const {
266 return font_ref_
->cap_height();
269 int PlatformFontWin::GetExpectedTextWidth(int length
) const {
270 return length
* std::min(font_ref_
->GetDluBaseX(),
271 font_ref_
->ave_char_width());
274 int PlatformFontWin::GetStyle() const {
275 return font_ref_
->style();
278 std::string
PlatformFontWin::GetFontName() const {
279 return font_ref_
->font_name();
282 std::string
PlatformFontWin::GetActualFontNameForTesting() const {
283 // With the current implementation on Windows, HFontRef::font_name() returns
284 // the font name taken from the HFONT handle, but it's not the name that comes
285 // from the font's metadata. See http://crbug.com/327287
286 return font_ref_
->font_name();
289 std::string
PlatformFontWin::GetLocalizedFontName() const {
290 base::win::ScopedCreateDC
memory_dc(CreateCompatibleDC(NULL
));
291 if (!memory_dc
.Get())
292 return GetFontName();
294 // When a font has a localized name for a language matching the system
295 // locale, GetTextFace() returns the localized name.
296 base::win::ScopedSelectObject
font(memory_dc
.Get(), font_ref_
->hfont());
297 wchar_t localized_font_name
[LF_FACESIZE
];
298 int length
= GetTextFace(memory_dc
.Get(), arraysize(localized_font_name
),
299 &localized_font_name
[0]);
301 return GetFontName();
302 return base::SysWideToUTF8(localized_font_name
);
305 int PlatformFontWin::GetFontSize() const {
306 return font_ref_
->font_size();
309 const FontRenderParams
& PlatformFontWin::GetFontRenderParams() {
310 CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams
, params
,
311 (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(false), NULL
)));
315 NativeFont
PlatformFontWin::GetNativeFont() const {
316 return font_ref_
->hfont();
320 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory
* factory
) {
321 // We grab a reference on the DirectWrite factory. This reference is
322 // leaked, which is ok because skia leaks it as well.
324 direct_write_factory_
= factory
;
328 void PlatformFontWin::GetTextMetricsForFont(HDC hdc
,
330 TEXTMETRIC
* text_metrics
) {
331 base::win::ScopedSelectObject
scoped_font(hdc
, font
);
332 GetTextMetrics(hdc
, text_metrics
);
336 int PlatformFontWin::GetFontSize(const LOGFONT
& font_info
) {
337 if (font_info
.lfHeight
< 0)
338 return -font_info
.lfHeight
;
340 base::win::ScopedGetDC
screen_dc(NULL
);
341 base::win::ScopedGDIObject
<HFONT
> font(CreateFontIndirect(&font_info
));
343 TEXTMETRIC font_metrics
= {0};
344 PlatformFontWin::GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
345 return font_metrics
.tmAscent
;
348 ////////////////////////////////////////////////////////////////////////////////
351 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont
) {
354 GetObject(hfont
, sizeof(LOGFONT
), &font_info
);
355 font_ref_
= CreateHFontRef(CreateFontIndirect(&font_info
));
358 void PlatformFontWin::InitWithFontNameAndSize(const std::string
& font_name
,
360 HFONT hf
= ::CreateFont(-font_size
, 0, 0, 0, FW_DONTCARE
, FALSE
, FALSE
, FALSE
,
365 DEFAULT_PITCH
| FF_DONTCARE
,
366 base::UTF8ToUTF16(font_name
).c_str());
367 font_ref_
= CreateHFontRef(hf
);
371 PlatformFontWin::HFontRef
* PlatformFontWin::GetBaseFontRef() {
372 if (base_font_ref_
== NULL
) {
373 NONCLIENTMETRICS_XP metrics
;
374 base::win::GetNonClientMetrics(&metrics
);
376 if (adjust_font_callback
)
377 adjust_font_callback(&metrics
.lfMessageFont
);
378 metrics
.lfMessageFont
.lfHeight
=
379 AdjustFontSize(metrics
.lfMessageFont
.lfHeight
, 0);
380 HFONT font
= CreateFontIndirect(&metrics
.lfMessageFont
);
382 base_font_ref_
= PlatformFontWin::CreateHFontRef(font
);
383 // base_font_ref_ is global, up the ref count so it's never deleted.
384 base_font_ref_
->AddRef();
386 return base_font_ref_
;
389 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRef(HFONT font
) {
390 TEXTMETRIC font_metrics
;
393 base::win::ScopedGetDC
screen_dc(NULL
);
394 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
395 GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
398 if (direct_write_factory_
)
399 return CreateHFontRefFromSkia(font
, font_metrics
);
401 return CreateHFontRefFromGDI(font
, font_metrics
);
404 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRefFromGDI(
406 const TEXTMETRIC
& font_metrics
) {
407 const int height
= std::max
<int>(1, font_metrics
.tmHeight
);
408 const int baseline
= std::max
<int>(1, font_metrics
.tmAscent
);
409 const int cap_height
=
410 std::max
<int>(1, font_metrics
.tmAscent
- font_metrics
.tmInternalLeading
);
411 const int ave_char_width
= std::max
<int>(1, font_metrics
.tmAveCharWidth
);
412 const int font_size
=
413 std::max
<int>(1, font_metrics
.tmHeight
- font_metrics
.tmInternalLeading
);
415 if (font_metrics
.tmItalic
)
416 style
|= Font::ITALIC
;
417 if (font_metrics
.tmUnderlined
)
418 style
|= Font::UNDERLINE
;
419 if (font_metrics
.tmWeight
>= kTextMetricWeightBold
)
422 return new HFontRef(font
, font_size
, height
, baseline
, cap_height
,
423 ave_char_width
, style
);
426 Font
PlatformFontWin::DeriveWithCorrectedSize(HFONT base_font
) {
427 base::win::ScopedGetDC
screen_dc(NULL
);
428 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
430 base::win::ScopedGDIObject
<HFONT
> best_font(base_font
);
431 TEXTMETRIC best_font_metrics
;
432 GetTextMetricsForFont(screen_dc
, best_font
, &best_font_metrics
);
435 GetObject(base_font
, sizeof(LOGFONT
), &font_info
);
437 // Set |lfHeight| to negative value to indicate it's the size, not the height.
439 -(best_font_metrics
.tmHeight
- best_font_metrics
.tmInternalLeading
);
442 // Increment font size. Prefer font with greater size if its height isn't
443 // greater than height of base font.
444 font_info
.lfHeight
= AdjustFontSize(font_info
.lfHeight
, 1);
445 base::win::ScopedGDIObject
<HFONT
> font(CreateFontIndirect(&font_info
));
446 TEXTMETRIC font_metrics
;
447 GetTextMetricsForFont(screen_dc
, font
, &font_metrics
);
448 if (font_metrics
.tmHeight
> best_font_metrics
.tmHeight
)
450 best_font
.Set(font
.release());
451 best_font_metrics
= font_metrics
;
454 return Font(new PlatformFontWin(CreateHFontRef(best_font
.release())));
458 PlatformFontWin::HFontRef
* PlatformFontWin::CreateHFontRefFromSkia(
460 const TEXTMETRIC
& font_metrics
) {
461 LOGFONT font_info
= {0};
462 GetObject(gdi_font
, sizeof(LOGFONT
), &font_info
);
464 // If the font height is passed in as 0, assume the height to be -1 to ensure
465 // that we return the metrics for a 1 point font.
466 // If the font height is positive it represents the rasterized font's cell
467 // height. Calculate the actual height accordingly.
468 if (font_info
.lfHeight
> 0) {
470 font_metrics
.tmInternalLeading
- font_metrics
.tmHeight
;
471 } else if (font_info
.lfHeight
== 0) {
472 font_info
.lfHeight
= -1;
475 int skia_style
= SkTypeface::kNormal
;
476 if (font_info
.lfWeight
>= FW_SEMIBOLD
&&
477 font_info
.lfWeight
<= FW_ULTRABOLD
) {
478 skia_style
|= SkTypeface::kBold
;
480 if (font_info
.lfItalic
)
481 skia_style
|= SkTypeface::kItalic
;
483 // Skia does not return all values we need for font metrics. For e.g.
484 // the cap height which indicates the height of capital letters is not
485 // returned even though it is returned by DirectWrite.
487 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
488 // DirectWrite and remove the code here which retrieves metrics from
489 // DirectWrite to calculate the cap height.
490 base::win::ScopedComPtr
<IDWriteFont
> dwrite_font
;
491 HRESULT hr
= GetMatchingDirectWriteFont(font_info
,
493 direct_write_factory_
,
494 dwrite_font
.Receive());
500 DWRITE_FONT_METRICS dwrite_font_metrics
= {0};
501 dwrite_font
->GetMetrics(&dwrite_font_metrics
);
503 skia::RefPtr
<SkTypeface
> skia_face
= skia::AdoptRef(
504 SkTypeface::CreateFromName(
505 base::SysWideToUTF8(font_info
.lfFaceName
).c_str(),
506 static_cast<SkTypeface::Style
>(skia_style
)));
508 BOOL antialiasing
= TRUE
;
509 SystemParametersInfo(SPI_GETFONTSMOOTHING
, 0, &antialiasing
, 0);
512 paint
.setAntiAlias(!!antialiasing
);
513 paint
.setTypeface(skia_face
.get());
514 paint
.setTextSize(-font_info
.lfHeight
);
515 SkPaint::FontMetrics skia_metrics
;
516 paint
.getFontMetrics(&skia_metrics
);
518 // The calculations below are similar to those in the CreateHFontRef
519 // function. The height, baseline and cap height are rounded up to ensure
520 // that they match up closely with GDI.
521 const int height
= std::ceil(
522 skia_metrics
.fDescent
- skia_metrics
.fAscent
+ skia_metrics
.fLeading
);
523 const int baseline
= std::max
<int>(1, std::ceil(-skia_metrics
.fAscent
));
524 const int cap_height
= std::ceil(paint
.getTextSize() *
525 static_cast<double>(dwrite_font_metrics
.capHeight
) /
526 dwrite_font_metrics
.designUnitsPerEm
);
528 // The metrics retrieved from skia don't have the average character width. In
529 // any case if we get the average character width from skia then use that or
530 // use the text extent technique as documented by microsoft. See
531 // GetAverageCharWidthInDialogUnits for details.
532 const int ave_char_width
=
533 skia_metrics
.fAvgCharWidth
== 0 ?
534 HFontRef::GetAverageCharWidthInDialogUnits(gdi_font
)
535 : skia_metrics
.fAvgCharWidth
;
538 if (skia_style
& SkTypeface::kItalic
)
539 style
|= Font::ITALIC
;
540 if (font_info
.lfUnderline
)
541 style
|= Font::UNDERLINE
;
542 if (font_info
.lfWeight
>= kTextMetricWeightBold
)
544 return new HFontRef(gdi_font
, -font_info
.lfHeight
, height
, baseline
,
545 cap_height
, ave_char_width
, style
);
548 PlatformFontWin::PlatformFontWin(HFontRef
* hfont_ref
) : font_ref_(hfont_ref
) {
551 ////////////////////////////////////////////////////////////////////////////////
552 // PlatformFontWin::HFontRef:
554 PlatformFontWin::HFontRef::HFontRef(HFONT hfont
,
562 font_size_(font_size
),
565 cap_height_(cap_height
),
566 ave_char_width_(ave_char_width
),
569 requested_font_size_(font_size
) {
573 GetObject(hfont_
, sizeof(LOGFONT
), &font_info
);
574 font_name_
= base::UTF16ToUTF8(base::string16(font_info
.lfFaceName
));
575 if (font_info
.lfHeight
< 0)
576 requested_font_size_
= -font_info
.lfHeight
;
579 int PlatformFontWin::HFontRef::GetDluBaseX() {
580 if (dlu_base_x_
!= -1)
583 dlu_base_x_
= GetAverageCharWidthInDialogUnits(hfont_
);
588 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
590 base::win::ScopedGetDC
screen_dc(NULL
);
591 base::win::ScopedSelectObject
font(screen_dc
, gdi_font
);
592 gfx::ScopedSetMapMode
mode(screen_dc
, MM_TEXT
);
594 // Yes, this is how Microsoft recommends calculating the dialog unit
595 // conversions. See: http://support.microsoft.com/kb/125681
597 GetTextExtentPoint32(screen_dc
,
598 L
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
600 int dlu_base_x
= (ave_text_size
.cx
/ 26 + 1) / 2;
602 DCHECK_NE(dlu_base_x
, -1);
606 PlatformFontWin::HFontRef::~HFontRef() {
607 DeleteObject(hfont_
);
610 ////////////////////////////////////////////////////////////////////////////////
611 // PlatformFont, public:
614 PlatformFont
* PlatformFont::CreateDefault() {
615 return new PlatformFontWin
;
619 PlatformFont
* PlatformFont::CreateFromNativeFont(NativeFont native_font
) {
620 return new PlatformFontWin(native_font
);
624 PlatformFont
* PlatformFont::CreateFromNameAndSize(const std::string
& font_name
,
626 return new PlatformFontWin(font_name
, font_size
);