Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / ui / gfx / platform_font_win.cc
blob1f8ca3e03fa8ee231ce6635eaa5745a7efdc3390
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"
7 #include <dwrite.h>
8 #include <math.h>
9 #include <wchar.h>
10 #include <windows.h>
12 #include <algorithm>
14 #include "base/debug/alias.h"
15 #include "base/logging.h"
16 #include "base/macros.h"
17 #include "base/strings/string16.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/sys_string_conversions.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/win/scoped_comptr.h"
22 #include "base/win/scoped_gdi_object.h"
23 #include "base/win/scoped_hdc.h"
24 #include "base/win/scoped_select_object.h"
25 #include "base/win/win_util.h"
26 #include "third_party/skia/include/core/SkTypeface.h"
27 #include "ui/gfx/canvas.h"
28 #include "ui/gfx/font.h"
29 #include "ui/gfx/font_render_params.h"
30 #include "ui/gfx/win/scoped_set_map_mode.h"
32 namespace {
34 // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
35 // font is bold.
36 const int kTextMetricWeightBold = 700;
38 // Returns the minimum font size, using the minimum size callback, if set.
39 int GetMinimumFontSize() {
40 int min_font_size = 0;
41 if (gfx::PlatformFontWin::get_minimum_font_size_callback)
42 min_font_size = gfx::PlatformFontWin::get_minimum_font_size_callback();
43 return min_font_size;
46 // Returns either minimum font allowed for a current locale or
47 // lf_height + size_delta value.
48 int AdjustFontSize(int lf_height, int size_delta) {
49 if (lf_height < 0) {
50 lf_height -= size_delta;
51 } else {
52 lf_height += size_delta;
54 const int min_font_size = GetMinimumFontSize();
55 // Make sure lf_height is not smaller than allowed min font size for current
56 // locale.
57 if (abs(lf_height) < min_font_size) {
58 return lf_height < 0 ? -min_font_size : min_font_size;
59 } else {
60 return lf_height;
64 // Sets style properties on |font_info| based on |font_style|.
65 void SetLogFontStyle(int font_style, LOGFONT* font_info) {
66 font_info->lfUnderline = (font_style & gfx::Font::UNDERLINE) != 0;
67 font_info->lfItalic = (font_style & gfx::Font::ITALIC) != 0;
68 font_info->lfWeight = (font_style & gfx::Font::BOLD) ? FW_BOLD : FW_NORMAL;
71 // Returns the family name for the |IDWriteFont| interface passed in.
72 // The family name is returned in the |family_name_ret| parameter.
73 // Returns S_OK on success.
74 // TODO(ananta)
75 // Remove the CHECKs in this function once this stabilizes on the field.
76 HRESULT GetFamilyNameFromDirectWriteFont(IDWriteFont* dwrite_font,
77 base::string16* family_name_ret) {
78 base::win::ScopedComPtr<IDWriteFontFamily> font_family;
79 HRESULT hr = dwrite_font->GetFontFamily(font_family.Receive());
80 if (FAILED(hr))
81 CHECK(false);
83 base::win::ScopedComPtr<IDWriteLocalizedStrings> family_name;
84 hr = font_family->GetFamilyNames(family_name.Receive());
85 if (FAILED(hr))
86 CHECK(false);
88 // TODO(ananta)
89 // Add support for retrieving the family for the current locale.
90 wchar_t family_name_for_locale[MAX_PATH] = {0};
91 hr = family_name->GetString(0,
92 family_name_for_locale,
93 arraysize(family_name_for_locale));
94 if (FAILED(hr))
95 CHECK(false);
97 *family_name_ret = family_name_for_locale;
98 return hr;
101 // Uses the GDI interop functionality exposed by DirectWrite to find a
102 // matching DirectWrite font for the LOGFONT passed in. If we fail to
103 // find a direct match then we try the DirectWrite font substitution
104 // route to find a match.
105 // The contents of the LOGFONT pointer |font_info| may be modified on
106 // return.
107 HRESULT FindDirectWriteFontForLOGFONT(IDWriteFactory* factory,
108 LOGFONT* font_info,
109 IDWriteFont** dwrite_font) {
110 base::win::ScopedComPtr<IDWriteGdiInterop> gdi_interop;
111 HRESULT hr = factory->GetGdiInterop(gdi_interop.Receive());
112 if (FAILED(hr)) {
113 CHECK(false);
114 return hr;
117 hr = gdi_interop->CreateFontFromLOGFONT(font_info, dwrite_font);
118 if (SUCCEEDED(hr))
119 return hr;
121 base::win::ScopedComPtr<IDWriteFontCollection> font_collection;
122 hr = factory->GetSystemFontCollection(font_collection.Receive());
123 if (FAILED(hr)) {
124 CHECK(false);
125 return hr;
128 // We try to find a matching font by triggering DirectWrite to substitute the
129 // font passed in with a matching font (FontSubstitutes registry key)
130 // If this succeeds we return the matched font.
131 base::win::ScopedGDIObject<HFONT> font(::CreateFontIndirect(font_info));
132 base::win::ScopedGetDC screen_dc(NULL);
133 base::win::ScopedSelectObject scoped_font(screen_dc, font);
135 base::win::ScopedComPtr<IDWriteFontFace> font_face;
136 hr = gdi_interop->CreateFontFaceFromHdc(screen_dc, font_face.Receive());
137 if (FAILED(hr))
138 return hr;
140 LOGFONT converted_font = {0};
141 hr = gdi_interop->ConvertFontFaceToLOGFONT(font_face.get(), &converted_font);
142 if (SUCCEEDED(hr)) {
143 hr = font_collection->GetFontFromFontFace(font_face.get(), dwrite_font);
144 if (SUCCEEDED(hr)) {
145 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
146 converted_font.lfFaceName);
149 return hr;
152 // Returns a matching IDWriteFont for the |font_info| passed in. If we fail
153 // to find a matching font, then we return the IDWriteFont corresponding to
154 // the default font on the system.
155 // Returns S_OK on success.
156 // The contents of the LOGFONT pointer |font_info| may be modified on
157 // return.
158 HRESULT GetMatchingDirectWriteFont(LOGFONT* font_info,
159 int font_style,
160 IDWriteFactory* factory,
161 IDWriteFont** dwrite_font) {
162 // First try the GDI compat route to get a matching DirectWrite font.
163 // If that succeeds then we are good. If that fails then try and find a
164 // match from the DirectWrite font collection.
165 HRESULT hr = FindDirectWriteFontForLOGFONT(factory, font_info, dwrite_font);
166 if (SUCCEEDED(hr))
167 return hr;
169 // Get a matching font from the system font collection exposed by
170 // DirectWrite.
171 base::win::ScopedComPtr<IDWriteFontCollection> font_collection;
172 hr = factory->GetSystemFontCollection(font_collection.Receive());
173 if (FAILED(hr)) {
174 CHECK(false);
175 return hr;
178 // Steps as below:-
179 // This mirrors skia.
180 // 1. Attempt to find a DirectWrite font family based on the face name in the
181 // font. That may not work at all times, as the face name could be random
182 // GDI has its own font system where in it creates a font matching the
183 // characteristics in the LOGFONT structure passed into
184 // CreateFontIndirect. DirectWrite does not do that. If this succeeds then
185 // return the matching IDWriteFont from the family.
186 // 2. If step 1 fails then repeat with the default system font. This has the
187 // same limitations with the face name as mentioned above.
188 // 3. If step 2 fails then return the first family from the collection and
189 // use that.
190 base::win::ScopedComPtr<IDWriteFontFamily> font_family;
191 BOOL exists = FALSE;
192 uint32 index = 0;
193 hr = font_collection->FindFamilyName(font_info->lfFaceName, &index, &exists);
194 // If we fail to find a match then try fallback to the default font on the
195 // system. This is what skia does as well.
196 if (FAILED(hr) || (index == UINT_MAX) || !exists) {
197 NONCLIENTMETRICS metrics = {0};
198 metrics.cbSize = sizeof(metrics);
199 if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,
200 sizeof(metrics),
201 &metrics,
202 0)) {
203 CHECK(false);
204 return E_FAIL;
207 if (wcsncmp(font_info->lfFaceName, metrics.lfMessageFont.lfFaceName,
208 arraysize(font_info->lfFaceName))) {
209 // First try the GDI compat route to get a matching DirectWrite font. If
210 // that succeeds we are good. If not find a matching font from the font
211 // collection.
212 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
213 metrics.lfMessageFont.lfFaceName);
214 hr = FindDirectWriteFontForLOGFONT(factory, font_info, dwrite_font);
215 if (SUCCEEDED(hr))
216 return hr;
218 // Best effort to find a matching font from the system font collection.
219 hr = font_collection->FindFamilyName(metrics.lfMessageFont.lfFaceName,
220 &index,
221 &exists);
225 if (index != UINT_MAX && exists) {
226 hr = font_collection->GetFontFamily(index, font_family.Receive());
227 } else {
228 // If we fail to find a matching font, then fallback to the first font in
229 // the list. This is what skia does as well.
230 hr = font_collection->GetFontFamily(0, font_family.Receive());
233 if (FAILED(hr)) {
234 CHECK(false);
235 return hr;
238 DWRITE_FONT_WEIGHT weight = (font_style & SkTypeface::kBold)
239 ? DWRITE_FONT_WEIGHT_BOLD
240 : DWRITE_FONT_WEIGHT_NORMAL;
241 DWRITE_FONT_STRETCH stretch = DWRITE_FONT_STRETCH_NORMAL;
242 DWRITE_FONT_STYLE italic = (font_style & SkTypeface::kItalic)
243 ? DWRITE_FONT_STYLE_ITALIC
244 : DWRITE_FONT_STYLE_NORMAL;
246 // The IDWriteFontFamily::GetFirstMatchingFont call fails on certain machines
247 // for fonts like MS UI Gothic, Segoe UI, etc. It is not clear why these
248 // fonts could be accessible to GDI and not to DirectWrite.
249 // The code below adds some debug fields to help track down these failures.
250 // 1. We get the matching font list for the font attributes passed in.
251 // 2. We get the font count in the family with a debug alias variable.
252 // 3. If GetFirstMatchingFont fails then we CHECK as before.
253 // Next step would be to remove the CHECKs in this function and fallback to
254 // GDI.
255 // http://crbug.com/434425
256 // TODO(ananta)
257 // Remove the GetMatchingFonts and related code here once we get to a stable
258 // state in canary.
259 base::win::ScopedComPtr<IDWriteFontList> matching_font_list;
260 hr = font_family->GetMatchingFonts(weight, stretch, italic,
261 matching_font_list.Receive());
262 uint32 matching_font_count = 0;
263 if (SUCCEEDED(hr))
264 matching_font_count = matching_font_list->GetFontCount();
266 hr = font_family->GetFirstMatchingFont(weight, stretch, italic,
267 dwrite_font);
268 if (FAILED(hr)) {
269 base::debug::Alias(&matching_font_count);
270 CHECK(false);
273 base::string16 font_name;
274 GetFamilyNameFromDirectWriteFont(*dwrite_font, &font_name);
275 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
276 font_name.c_str());
277 return hr;
280 } // namespace
282 namespace gfx {
284 // static
285 PlatformFontWin::HFontRef* PlatformFontWin::base_font_ref_;
287 // static
288 PlatformFontWin::AdjustFontCallback
289 PlatformFontWin::adjust_font_callback = nullptr;
290 PlatformFontWin::GetMinimumFontSizeCallback
291 PlatformFontWin::get_minimum_font_size_callback = NULL;
293 IDWriteFactory* PlatformFontWin::direct_write_factory_ = nullptr;
295 ////////////////////////////////////////////////////////////////////////////////
296 // PlatformFontWin, public
298 PlatformFontWin::PlatformFontWin() : font_ref_(GetBaseFontRef()) {
301 PlatformFontWin::PlatformFontWin(NativeFont native_font) {
302 InitWithCopyOfHFONT(native_font);
305 PlatformFontWin::PlatformFontWin(const std::string& font_name,
306 int font_size) {
307 InitWithFontNameAndSize(font_name, font_size);
310 Font PlatformFontWin::DeriveFontWithHeight(int height, int style) {
311 DCHECK_GE(height, 0);
313 // Create a font with a height near that of the target height.
314 LOGFONT font_info;
315 GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
316 font_info.lfHeight = height;
317 SetLogFontStyle(style, &font_info);
319 HFONT hfont = CreateFontIndirect(&font_info);
320 Font font(new PlatformFontWin(CreateHFontRef(hfont)));
322 // Respect the minimum font size constraint.
323 const int min_font_size = GetMinimumFontSize();
325 // Used to avoid shrinking the font and expanding it.
326 bool ran_shrink_loop = false;
328 // Iterate to find the largest font with a height <= |height|.
329 while ((font.GetHeight() > height) &&
330 (font.GetFontSize() >= min_font_size)) {
331 ran_shrink_loop = true;
332 Font derived_font = font.Derive(-1, style);
333 // Break the loop if the derived font is too small or hasn't shrunk at all.
334 if ((derived_font.GetFontSize() < min_font_size) ||
335 ((derived_font.GetFontSize() == font.GetFontSize()) &&
336 (derived_font.GetHeight() == font.GetHeight())))
337 break;
338 font = derived_font;
341 while ((!ran_shrink_loop && font.GetHeight() <= height) ||
342 (font.GetFontSize() < min_font_size)) {
343 Font derived_font = font.Derive(1, style);
344 // Break the loop if the derived font is too large or hasn't grown at all.
345 if (((derived_font.GetHeight() > height) &&
346 (font.GetFontSize() >= min_font_size)) ||
347 ((derived_font.GetFontSize() == font.GetFontSize()) &&
348 (derived_font.GetHeight() == font.GetHeight())))
349 break;
350 font = derived_font;
352 return font;
355 ////////////////////////////////////////////////////////////////////////////////
356 // PlatformFontWin, PlatformFont implementation:
358 Font PlatformFontWin::DeriveFont(int size_delta, int style) const {
359 LOGFONT font_info;
360 GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
361 const int requested_font_size = font_ref_->requested_font_size();
362 font_info.lfHeight = AdjustFontSize(-requested_font_size, size_delta);
363 SetLogFontStyle(style, &font_info);
365 HFONT hfont = CreateFontIndirect(&font_info);
366 return Font(new PlatformFontWin(CreateHFontRef(hfont)));
369 int PlatformFontWin::GetHeight() const {
370 return font_ref_->height();
373 int PlatformFontWin::GetBaseline() const {
374 return font_ref_->baseline();
377 int PlatformFontWin::GetCapHeight() const {
378 return font_ref_->cap_height();
381 int PlatformFontWin::GetExpectedTextWidth(int length) const {
382 return length * std::min(font_ref_->GetDluBaseX(),
383 font_ref_->ave_char_width());
386 int PlatformFontWin::GetStyle() const {
387 return font_ref_->style();
390 std::string PlatformFontWin::GetFontName() const {
391 return font_ref_->font_name();
394 std::string PlatformFontWin::GetActualFontNameForTesting() const {
395 // With the current implementation on Windows, HFontRef::font_name() returns
396 // the font name taken from the HFONT handle, but it's not the name that comes
397 // from the font's metadata. See http://crbug.com/327287
398 return font_ref_->font_name();
401 std::string PlatformFontWin::GetLocalizedFontName() const {
402 base::win::ScopedCreateDC memory_dc(CreateCompatibleDC(NULL));
403 if (!memory_dc.Get())
404 return GetFontName();
406 // When a font has a localized name for a language matching the system
407 // locale, GetTextFace() returns the localized name.
408 base::win::ScopedSelectObject font(memory_dc.Get(), font_ref_->hfont());
409 wchar_t localized_font_name[LF_FACESIZE];
410 int length = GetTextFace(memory_dc.Get(), arraysize(localized_font_name),
411 &localized_font_name[0]);
412 if (length <= 0)
413 return GetFontName();
414 return base::SysWideToUTF8(localized_font_name);
417 int PlatformFontWin::GetFontSize() const {
418 return font_ref_->font_size();
421 const FontRenderParams& PlatformFontWin::GetFontRenderParams() {
422 CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams, params,
423 (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), NULL)));
424 return params;
427 NativeFont PlatformFontWin::GetNativeFont() const {
428 return font_ref_->hfont();
431 // static
432 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory* factory) {
433 // We grab a reference on the DirectWrite factory. This reference is
434 // leaked, which is ok because skia leaks it as well.
435 factory->AddRef();
436 direct_write_factory_ = factory;
439 // static
440 void PlatformFontWin::GetTextMetricsForFont(HDC hdc,
441 HFONT font,
442 TEXTMETRIC* text_metrics) {
443 base::win::ScopedSelectObject scoped_font(hdc, font);
444 GetTextMetrics(hdc, text_metrics);
447 // static
448 int PlatformFontWin::GetFontSize(const LOGFONT& font_info) {
449 if (font_info.lfHeight < 0)
450 return -font_info.lfHeight;
452 base::win::ScopedGetDC screen_dc(NULL);
453 base::win::ScopedGDIObject<HFONT> font(CreateFontIndirect(&font_info));
455 TEXTMETRIC font_metrics = {0};
456 PlatformFontWin::GetTextMetricsForFont(screen_dc, font, &font_metrics);
457 return font_metrics.tmAscent;
460 ////////////////////////////////////////////////////////////////////////////////
461 // Font, private:
463 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont) {
464 DCHECK(hfont);
465 LOGFONT font_info;
466 GetObject(hfont, sizeof(LOGFONT), &font_info);
467 font_ref_ = CreateHFontRef(CreateFontIndirect(&font_info));
470 void PlatformFontWin::InitWithFontNameAndSize(const std::string& font_name,
471 int font_size) {
472 HFONT hf = ::CreateFont(-font_size, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
473 DEFAULT_CHARSET,
474 OUT_DEFAULT_PRECIS,
475 CLIP_DEFAULT_PRECIS,
476 DEFAULT_QUALITY,
477 DEFAULT_PITCH | FF_DONTCARE,
478 base::UTF8ToUTF16(font_name).c_str());
479 font_ref_ = CreateHFontRef(hf);
482 // static
483 PlatformFontWin::HFontRef* PlatformFontWin::GetBaseFontRef() {
484 if (base_font_ref_ == NULL) {
485 NONCLIENTMETRICS_XP metrics;
486 base::win::GetNonClientMetrics(&metrics);
488 if (adjust_font_callback)
489 adjust_font_callback(&metrics.lfMessageFont);
490 metrics.lfMessageFont.lfHeight =
491 AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
492 HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
493 DLOG_ASSERT(font);
494 base_font_ref_ = PlatformFontWin::CreateHFontRef(font);
495 // base_font_ref_ is global, up the ref count so it's never deleted.
496 base_font_ref_->AddRef();
498 return base_font_ref_;
501 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRef(HFONT font) {
502 TEXTMETRIC font_metrics;
505 base::win::ScopedGetDC screen_dc(NULL);
506 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
507 GetTextMetricsForFont(screen_dc, font, &font_metrics);
510 if (direct_write_factory_)
511 return CreateHFontRefFromSkia(font, font_metrics);
513 return CreateHFontRefFromGDI(font, font_metrics);
516 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromGDI(
517 HFONT font,
518 const TEXTMETRIC& font_metrics) {
519 const int height = std::max<int>(1, font_metrics.tmHeight);
520 const int baseline = std::max<int>(1, font_metrics.tmAscent);
521 const int cap_height =
522 std::max<int>(1, font_metrics.tmAscent - font_metrics.tmInternalLeading);
523 const int ave_char_width = std::max<int>(1, font_metrics.tmAveCharWidth);
524 const int font_size =
525 std::max<int>(1, font_metrics.tmHeight - font_metrics.tmInternalLeading);
526 int style = 0;
527 if (font_metrics.tmItalic)
528 style |= Font::ITALIC;
529 if (font_metrics.tmUnderlined)
530 style |= Font::UNDERLINE;
531 if (font_metrics.tmWeight >= kTextMetricWeightBold)
532 style |= Font::BOLD;
534 return new HFontRef(font, font_size, height, baseline, cap_height,
535 ave_char_width, style);
538 // static
539 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromSkia(
540 HFONT gdi_font,
541 const TEXTMETRIC& font_metrics) {
542 LOGFONT font_info = {0};
543 GetObject(gdi_font, sizeof(LOGFONT), &font_info);
545 // If the font height is passed in as 0, assume the height to be -1 to ensure
546 // that we return the metrics for a 1 point font.
547 // If the font height is positive it represents the rasterized font's cell
548 // height. Calculate the actual height accordingly.
549 if (font_info.lfHeight > 0) {
550 font_info.lfHeight =
551 font_metrics.tmInternalLeading - font_metrics.tmHeight;
552 } else if (font_info.lfHeight == 0) {
553 font_info.lfHeight = -1;
556 int skia_style = SkTypeface::kNormal;
557 if (font_info.lfWeight >= FW_SEMIBOLD &&
558 font_info.lfWeight <= FW_ULTRABOLD) {
559 skia_style |= SkTypeface::kBold;
561 if (font_info.lfItalic)
562 skia_style |= SkTypeface::kItalic;
564 // Skia does not return all values we need for font metrics. For e.g.
565 // the cap height which indicates the height of capital letters is not
566 // returned even though it is returned by DirectWrite.
567 // TODO(ananta)
568 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
569 // DirectWrite and remove the code here which retrieves metrics from
570 // DirectWrite to calculate the cap height.
571 base::win::ScopedComPtr<IDWriteFont> dwrite_font;
572 HRESULT hr = GetMatchingDirectWriteFont(&font_info,
573 skia_style,
574 direct_write_factory_,
575 dwrite_font.Receive());
576 if (FAILED(hr)) {
577 CHECK(false);
578 return nullptr;
581 DWRITE_FONT_METRICS dwrite_font_metrics = {0};
582 dwrite_font->GetMetrics(&dwrite_font_metrics);
584 skia::RefPtr<SkTypeface> skia_face = skia::AdoptRef(
585 SkTypeface::CreateFromName(
586 base::SysWideToUTF8(font_info.lfFaceName).c_str(),
587 static_cast<SkTypeface::Style>(skia_style)));
589 gfx::FontRenderParams font_params =
590 gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr);
591 SkFontHost::SetSubpixelOrder(
592 gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrder(
593 font_params.subpixel_rendering));
594 SkFontHost::SetSubpixelOrientation(
595 gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrientation(
596 font_params.subpixel_rendering));
598 SkPaint paint;
599 paint.setAntiAlias(font_params.antialiasing);
600 paint.setTypeface(skia_face.get());
601 paint.setTextSize(-font_info.lfHeight);
602 SkPaint::FontMetrics skia_metrics;
603 paint.getFontMetrics(&skia_metrics);
605 // The calculations below are similar to those in the CreateHFontRef
606 // function. The height, baseline and cap height are rounded up to ensure
607 // that they match up closely with GDI.
608 const int height = std::ceil(skia_metrics.fDescent - skia_metrics.fAscent);
609 const int baseline = std::max<int>(1, std::ceil(-skia_metrics.fAscent));
610 const int cap_height = std::ceil(paint.getTextSize() *
611 static_cast<double>(dwrite_font_metrics.capHeight) /
612 dwrite_font_metrics.designUnitsPerEm);
614 // The metrics retrieved from skia don't have the average character width. In
615 // any case if we get the average character width from skia then use that or
616 // the average character width in the TEXTMETRIC structure.
617 // TODO(ananta): Investigate whether it is possible to retrieve this value
618 // from DirectWrite.
619 const int ave_char_width =
620 skia_metrics.fAvgCharWidth == 0 ? font_metrics.tmAveCharWidth
621 : skia_metrics.fAvgCharWidth;
623 int style = 0;
624 if (skia_style & SkTypeface::kItalic)
625 style |= Font::ITALIC;
626 if (font_info.lfUnderline)
627 style |= Font::UNDERLINE;
628 if (font_info.lfWeight >= kTextMetricWeightBold)
629 style |= Font::BOLD;
631 // DirectWrite may have substituted the GDI font name with a fallback
632 // font. Ensure that it is updated here.
633 DeleteObject(gdi_font);
634 gdi_font = ::CreateFontIndirect(&font_info);
635 return new HFontRef(gdi_font, -font_info.lfHeight, height, baseline,
636 cap_height, ave_char_width, style);
639 PlatformFontWin::PlatformFontWin(HFontRef* hfont_ref) : font_ref_(hfont_ref) {
642 PlatformFontWin::~PlatformFontWin() {
645 ////////////////////////////////////////////////////////////////////////////////
646 // PlatformFontWin::HFontRef:
648 PlatformFontWin::HFontRef::HFontRef(HFONT hfont,
649 int font_size,
650 int height,
651 int baseline,
652 int cap_height,
653 int ave_char_width,
654 int style)
655 : hfont_(hfont),
656 font_size_(font_size),
657 height_(height),
658 baseline_(baseline),
659 cap_height_(cap_height),
660 ave_char_width_(ave_char_width),
661 style_(style),
662 dlu_base_x_(-1),
663 requested_font_size_(font_size) {
664 DLOG_ASSERT(hfont);
666 LOGFONT font_info;
667 GetObject(hfont_, sizeof(LOGFONT), &font_info);
668 font_name_ = base::UTF16ToUTF8(base::string16(font_info.lfFaceName));
670 // Retrieve the font size from the GetTextMetrics API instead of referencing
671 // it from the LOGFONT structure. This is because the height as reported by
672 // the LOGFONT structure is not always correct. For small fonts with size 1
673 // the LOGFONT structure reports the height as -1, while the actual font size
674 // is different. (2 on my XP machine).
675 base::win::ScopedGetDC screen_dc(NULL);
676 TEXTMETRIC font_metrics = {0};
677 PlatformFontWin::GetTextMetricsForFont(screen_dc, hfont_, &font_metrics);
678 requested_font_size_ = font_metrics.tmHeight - font_metrics.tmInternalLeading;
681 int PlatformFontWin::HFontRef::GetDluBaseX() {
682 if (dlu_base_x_ != -1)
683 return dlu_base_x_;
685 dlu_base_x_ = GetAverageCharWidthInDialogUnits(hfont_);
686 return dlu_base_x_;
689 // static
690 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
691 HFONT gdi_font) {
692 base::win::ScopedGetDC screen_dc(NULL);
693 base::win::ScopedSelectObject font(screen_dc, gdi_font);
694 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
696 // Yes, this is how Microsoft recommends calculating the dialog unit
697 // conversions. See: http://support.microsoft.com/kb/125681
698 SIZE ave_text_size;
699 GetTextExtentPoint32(screen_dc,
700 L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
701 52, &ave_text_size);
702 int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
704 DCHECK_NE(dlu_base_x, -1);
705 return dlu_base_x;
708 PlatformFontWin::HFontRef::~HFontRef() {
709 DeleteObject(hfont_);
712 ////////////////////////////////////////////////////////////////////////////////
713 // PlatformFont, public:
715 // static
716 PlatformFont* PlatformFont::CreateDefault() {
717 return new PlatformFontWin;
720 // static
721 PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) {
722 return new PlatformFontWin(native_font);
725 // static
726 PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name,
727 int font_size) {
728 return new PlatformFontWin(font_name, font_size);
731 } // namespace gfx