Pass the ArrayBuffer::Allocator via the Isolate::CreateParams
[chromium-blink-merge.git] / ui / gfx / platform_font_win.cc
blob3cd6c29e50f56d062a37f57d9f389399ae691db3
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 <algorithm>
8 #include <dwrite.h>
9 #include <math.h>
10 #include <windows.h>
12 #include "base/debug/alias.h"
13 #include "base/logging.h"
14 #include "base/macros.h"
15 #include "base/strings/string16.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/sys_string_conversions.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/win/scoped_comptr.h"
20 #include "base/win/scoped_gdi_object.h"
21 #include "base/win/scoped_hdc.h"
22 #include "base/win/scoped_select_object.h"
23 #include "base/win/win_util.h"
24 #include "third_party/skia/include/core/SkTypeface.h"
25 #include "ui/gfx/canvas.h"
26 #include "ui/gfx/font.h"
27 #include "ui/gfx/font_render_params.h"
28 #include "ui/gfx/win/scoped_set_map_mode.h"
30 namespace {
32 // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
33 // font is bold.
34 const int kTextMetricWeightBold = 700;
36 // Returns the minimum font size, using the minimum size callback, if set.
37 int GetMinimumFontSize() {
38 int min_font_size = 0;
39 if (gfx::PlatformFontWin::get_minimum_font_size_callback)
40 min_font_size = gfx::PlatformFontWin::get_minimum_font_size_callback();
41 return min_font_size;
44 // Returns either minimum font allowed for a current locale or
45 // lf_height + size_delta value.
46 int AdjustFontSize(int lf_height, int size_delta) {
47 if (lf_height < 0) {
48 lf_height -= size_delta;
49 } else {
50 lf_height += size_delta;
52 const int min_font_size = GetMinimumFontSize();
53 // Make sure lf_height is not smaller than allowed min font size for current
54 // locale.
55 if (abs(lf_height) < min_font_size) {
56 return lf_height < 0 ? -min_font_size : min_font_size;
57 } else {
58 return lf_height;
62 // Sets style properties on |font_info| based on |font_style|.
63 void SetLogFontStyle(int font_style, LOGFONT* font_info) {
64 font_info->lfUnderline = (font_style & gfx::Font::UNDERLINE) != 0;
65 font_info->lfItalic = (font_style & gfx::Font::ITALIC) != 0;
66 font_info->lfWeight = (font_style & gfx::Font::BOLD) ? FW_BOLD : FW_NORMAL;
69 // Returns the family name for the |IDWriteFont| interface passed in.
70 // The family name is returned in the |family_name_ret| parameter.
71 // Returns S_OK on success.
72 // TODO(ananta)
73 // Remove the CHECKs in this function once this stabilizes on the field.
74 HRESULT GetFamilyNameFromDirectWriteFont(IDWriteFont* dwrite_font,
75 base::string16* family_name_ret) {
76 base::win::ScopedComPtr<IDWriteFontFamily> font_family;
77 HRESULT hr = dwrite_font->GetFontFamily(font_family.Receive());
78 if (FAILED(hr))
79 CHECK(false);
81 base::win::ScopedComPtr<IDWriteLocalizedStrings> family_name;
82 hr = font_family->GetFamilyNames(family_name.Receive());
83 if (FAILED(hr))
84 CHECK(false);
86 // TODO(ananta)
87 // Add support for retrieving the family for the current locale.
88 wchar_t family_name_for_locale[MAX_PATH] = {0};
89 hr = family_name->GetString(0,
90 family_name_for_locale,
91 arraysize(family_name_for_locale));
92 if (FAILED(hr))
93 CHECK(false);
95 *family_name_ret = family_name_for_locale;
96 return hr;
99 // Uses the GDI interop functionality exposed by DirectWrite to find a
100 // matching DirectWrite font for the LOGFONT passed in. If we fail to
101 // find a direct match then we try the DirectWrite font substitution
102 // route to find a match.
103 // The contents of the LOGFONT pointer |font_info| may be modified on
104 // return.
105 HRESULT FindDirectWriteFontForLOGFONT(IDWriteFactory* factory,
106 LOGFONT* font_info,
107 IDWriteFont** dwrite_font) {
108 base::win::ScopedComPtr<IDWriteGdiInterop> gdi_interop;
109 HRESULT hr = factory->GetGdiInterop(gdi_interop.Receive());
110 if (FAILED(hr)) {
111 CHECK(false);
112 return hr;
115 hr = gdi_interop->CreateFontFromLOGFONT(font_info, dwrite_font);
116 if (SUCCEEDED(hr))
117 return hr;
119 base::win::ScopedComPtr<IDWriteFontCollection> font_collection;
120 hr = factory->GetSystemFontCollection(font_collection.Receive());
121 if (FAILED(hr)) {
122 CHECK(false);
123 return hr;
126 // We try to find a matching font by triggering DirectWrite to substitute the
127 // font passed in with a matching font (FontSubstitutes registry key)
128 // If this succeeds we return the matched font.
129 base::win::ScopedGDIObject<HFONT> font(::CreateFontIndirect(font_info));
130 base::win::ScopedGetDC screen_dc(NULL);
131 base::win::ScopedSelectObject scoped_font(screen_dc, font);
133 base::win::ScopedComPtr<IDWriteFontFace> font_face;
134 hr = gdi_interop->CreateFontFaceFromHdc(screen_dc, font_face.Receive());
135 if (FAILED(hr))
136 return hr;
138 LOGFONT converted_font = {0};
139 hr = gdi_interop->ConvertFontFaceToLOGFONT(font_face.get(), &converted_font);
140 if (SUCCEEDED(hr)) {
141 hr = font_collection->GetFontFromFontFace(font_face.get(), dwrite_font);
142 if (SUCCEEDED(hr)) {
143 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
144 converted_font.lfFaceName);
147 return hr;
150 // Returns a matching IDWriteFont for the |font_info| passed in. If we fail
151 // to find a matching font, then we return the IDWriteFont corresponding to
152 // the default font on the system.
153 // Returns S_OK on success.
154 // The contents of the LOGFONT pointer |font_info| may be modified on
155 // return.
156 HRESULT GetMatchingDirectWriteFont(LOGFONT* font_info,
157 int font_style,
158 IDWriteFactory* factory,
159 IDWriteFont** dwrite_font) {
160 // First try the GDI compat route to get a matching DirectWrite font.
161 // If that succeeds then we are good. If that fails then try and find a
162 // match from the DirectWrite font collection.
163 HRESULT hr = FindDirectWriteFontForLOGFONT(factory, font_info, dwrite_font);
164 if (SUCCEEDED(hr))
165 return hr;
167 // Get a matching font from the system font collection exposed by
168 // DirectWrite.
169 base::win::ScopedComPtr<IDWriteFontCollection> font_collection;
170 hr = factory->GetSystemFontCollection(font_collection.Receive());
171 if (FAILED(hr)) {
172 CHECK(false);
173 return hr;
176 // Steps as below:-
177 // This mirrors skia.
178 // 1. Attempt to find a DirectWrite font family based on the face name in the
179 // font. That may not work at all times, as the face name could be random
180 // GDI has its own font system where in it creates a font matching the
181 // characteristics in the LOGFONT structure passed into
182 // CreateFontIndirect. DirectWrite does not do that. If this succeeds then
183 // return the matching IDWriteFont from the family.
184 // 2. If step 1 fails then repeat with the default system font. This has the
185 // same limitations with the face name as mentioned above.
186 // 3. If step 2 fails then return the first family from the collection and
187 // use that.
188 base::win::ScopedComPtr<IDWriteFontFamily> font_family;
189 BOOL exists = FALSE;
190 uint32 index = 0;
191 hr = font_collection->FindFamilyName(font_info->lfFaceName, &index, &exists);
192 // If we fail to find a match then try fallback to the default font on the
193 // system. This is what skia does as well.
194 if (FAILED(hr) || (index == UINT_MAX) || !exists) {
195 NONCLIENTMETRICS metrics = {0};
196 metrics.cbSize = sizeof(metrics);
197 if (!SystemParametersInfoW(SPI_GETNONCLIENTMETRICS,
198 sizeof(metrics),
199 &metrics,
200 0)) {
201 CHECK(false);
202 return E_FAIL;
205 if (base::strncmp16(font_info->lfFaceName, metrics.lfMessageFont.lfFaceName,
206 arraysize(font_info->lfFaceName))) {
207 // First try the GDI compat route to get a matching DirectWrite font. If
208 // that succeeds we are good. If not find a matching font from the font
209 // collection.
210 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
211 metrics.lfMessageFont.lfFaceName);
212 hr = FindDirectWriteFontForLOGFONT(factory, font_info, dwrite_font);
213 if (SUCCEEDED(hr))
214 return hr;
216 // Best effort to find a matching font from the system font collection.
217 hr = font_collection->FindFamilyName(metrics.lfMessageFont.lfFaceName,
218 &index,
219 &exists);
223 if (index != UINT_MAX && exists) {
224 hr = font_collection->GetFontFamily(index, font_family.Receive());
225 } else {
226 // If we fail to find a matching font, then fallback to the first font in
227 // the list. This is what skia does as well.
228 hr = font_collection->GetFontFamily(0, font_family.Receive());
231 if (FAILED(hr)) {
232 CHECK(false);
233 return hr;
236 DWRITE_FONT_WEIGHT weight = (font_style & SkTypeface::kBold)
237 ? DWRITE_FONT_WEIGHT_BOLD
238 : DWRITE_FONT_WEIGHT_NORMAL;
239 DWRITE_FONT_STRETCH stretch = DWRITE_FONT_STRETCH_NORMAL;
240 DWRITE_FONT_STYLE italic = (font_style & SkTypeface::kItalic)
241 ? DWRITE_FONT_STYLE_ITALIC
242 : DWRITE_FONT_STYLE_NORMAL;
244 // The IDWriteFontFamily::GetFirstMatchingFont call fails on certain machines
245 // for fonts like MS UI Gothic, Segoe UI, etc. It is not clear why these
246 // fonts could be accessible to GDI and not to DirectWrite.
247 // The code below adds some debug fields to help track down these failures.
248 // 1. We get the matching font list for the font attributes passed in.
249 // 2. We get the font count in the family with a debug alias variable.
250 // 3. If GetFirstMatchingFont fails then we CHECK as before.
251 // Next step would be to remove the CHECKs in this function and fallback to
252 // GDI.
253 // http://crbug.com/434425
254 // TODO(ananta)
255 // Remove the GetMatchingFonts and related code here once we get to a stable
256 // state in canary.
257 base::win::ScopedComPtr<IDWriteFontList> matching_font_list;
258 hr = font_family->GetMatchingFonts(weight, stretch, italic,
259 matching_font_list.Receive());
260 uint32 matching_font_count = 0;
261 if (SUCCEEDED(hr))
262 matching_font_count = matching_font_list->GetFontCount();
264 hr = font_family->GetFirstMatchingFont(weight, stretch, italic,
265 dwrite_font);
266 if (FAILED(hr)) {
267 base::debug::Alias(&matching_font_count);
268 CHECK(false);
271 base::string16 font_name;
272 GetFamilyNameFromDirectWriteFont(*dwrite_font, &font_name);
273 wcscpy_s(font_info->lfFaceName, arraysize(font_info->lfFaceName),
274 font_name.c_str());
275 return hr;
278 } // namespace
280 namespace gfx {
282 // static
283 PlatformFontWin::HFontRef* PlatformFontWin::base_font_ref_;
285 // static
286 PlatformFontWin::AdjustFontCallback
287 PlatformFontWin::adjust_font_callback = nullptr;
288 PlatformFontWin::GetMinimumFontSizeCallback
289 PlatformFontWin::get_minimum_font_size_callback = NULL;
291 IDWriteFactory* PlatformFontWin::direct_write_factory_ = nullptr;
293 ////////////////////////////////////////////////////////////////////////////////
294 // PlatformFontWin, public
296 PlatformFontWin::PlatformFontWin() : font_ref_(GetBaseFontRef()) {
299 PlatformFontWin::PlatformFontWin(NativeFont native_font) {
300 InitWithCopyOfHFONT(native_font);
303 PlatformFontWin::PlatformFontWin(const std::string& font_name,
304 int font_size) {
305 InitWithFontNameAndSize(font_name, font_size);
308 Font PlatformFontWin::DeriveFontWithHeight(int height, int style) {
309 DCHECK_GE(height, 0);
311 // Create a font with a height near that of the target height.
312 LOGFONT font_info;
313 GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
314 font_info.lfHeight = height;
315 SetLogFontStyle(style, &font_info);
317 HFONT hfont = CreateFontIndirect(&font_info);
318 Font font(new PlatformFontWin(CreateHFontRef(hfont)));
320 // Respect the minimum font size constraint.
321 const int min_font_size = GetMinimumFontSize();
323 // Used to avoid shrinking the font and expanding it.
324 bool ran_shrink_loop = false;
326 // Iterate to find the largest font with a height <= |height|.
327 while ((font.GetHeight() > height) &&
328 (font.GetFontSize() >= min_font_size)) {
329 ran_shrink_loop = true;
330 Font derived_font = font.Derive(-1, style);
331 // Break the loop if the derived font is too small or hasn't shrunk at all.
332 if ((derived_font.GetFontSize() < min_font_size) ||
333 ((derived_font.GetFontSize() == font.GetFontSize()) &&
334 (derived_font.GetHeight() == font.GetHeight())))
335 break;
336 font = derived_font;
339 while ((!ran_shrink_loop && font.GetHeight() <= height) ||
340 (font.GetFontSize() < min_font_size)) {
341 Font derived_font = font.Derive(1, style);
342 // Break the loop if the derived font is too large or hasn't grown at all.
343 if (((derived_font.GetHeight() > height) &&
344 (font.GetFontSize() >= min_font_size)) ||
345 ((derived_font.GetFontSize() == font.GetFontSize()) &&
346 (derived_font.GetHeight() == font.GetHeight())))
347 break;
348 font = derived_font;
350 return font;
353 ////////////////////////////////////////////////////////////////////////////////
354 // PlatformFontWin, PlatformFont implementation:
356 Font PlatformFontWin::DeriveFont(int size_delta, int style) const {
357 LOGFONT font_info;
358 GetObject(GetNativeFont(), sizeof(LOGFONT), &font_info);
359 const int requested_font_size = font_ref_->requested_font_size();
360 font_info.lfHeight = AdjustFontSize(-requested_font_size, size_delta);
361 SetLogFontStyle(style, &font_info);
363 HFONT hfont = CreateFontIndirect(&font_info);
364 return Font(new PlatformFontWin(CreateHFontRef(hfont)));
367 int PlatformFontWin::GetHeight() const {
368 return font_ref_->height();
371 int PlatformFontWin::GetBaseline() const {
372 return font_ref_->baseline();
375 int PlatformFontWin::GetCapHeight() const {
376 return font_ref_->cap_height();
379 int PlatformFontWin::GetExpectedTextWidth(int length) const {
380 return length * std::min(font_ref_->GetDluBaseX(),
381 font_ref_->ave_char_width());
384 int PlatformFontWin::GetStyle() const {
385 return font_ref_->style();
388 std::string PlatformFontWin::GetFontName() const {
389 return font_ref_->font_name();
392 std::string PlatformFontWin::GetActualFontNameForTesting() const {
393 // With the current implementation on Windows, HFontRef::font_name() returns
394 // the font name taken from the HFONT handle, but it's not the name that comes
395 // from the font's metadata. See http://crbug.com/327287
396 return font_ref_->font_name();
399 std::string PlatformFontWin::GetLocalizedFontName() const {
400 base::win::ScopedCreateDC memory_dc(CreateCompatibleDC(NULL));
401 if (!memory_dc.Get())
402 return GetFontName();
404 // When a font has a localized name for a language matching the system
405 // locale, GetTextFace() returns the localized name.
406 base::win::ScopedSelectObject font(memory_dc.Get(), font_ref_->hfont());
407 wchar_t localized_font_name[LF_FACESIZE];
408 int length = GetTextFace(memory_dc.Get(), arraysize(localized_font_name),
409 &localized_font_name[0]);
410 if (length <= 0)
411 return GetFontName();
412 return base::SysWideToUTF8(localized_font_name);
415 int PlatformFontWin::GetFontSize() const {
416 return font_ref_->font_size();
419 const FontRenderParams& PlatformFontWin::GetFontRenderParams() {
420 CR_DEFINE_STATIC_LOCAL(const gfx::FontRenderParams, params,
421 (gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), NULL)));
422 return params;
425 NativeFont PlatformFontWin::GetNativeFont() const {
426 return font_ref_->hfont();
429 // static
430 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory* factory) {
431 // We grab a reference on the DirectWrite factory. This reference is
432 // leaked, which is ok because skia leaks it as well.
433 factory->AddRef();
434 direct_write_factory_ = factory;
437 // static
438 void PlatformFontWin::GetTextMetricsForFont(HDC hdc,
439 HFONT font,
440 TEXTMETRIC* text_metrics) {
441 base::win::ScopedSelectObject scoped_font(hdc, font);
442 GetTextMetrics(hdc, text_metrics);
445 // static
446 int PlatformFontWin::GetFontSize(const LOGFONT& font_info) {
447 if (font_info.lfHeight < 0)
448 return -font_info.lfHeight;
450 base::win::ScopedGetDC screen_dc(NULL);
451 base::win::ScopedGDIObject<HFONT> font(CreateFontIndirect(&font_info));
453 TEXTMETRIC font_metrics = {0};
454 PlatformFontWin::GetTextMetricsForFont(screen_dc, font, &font_metrics);
455 return font_metrics.tmAscent;
458 ////////////////////////////////////////////////////////////////////////////////
459 // Font, private:
461 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont) {
462 DCHECK(hfont);
463 LOGFONT font_info;
464 GetObject(hfont, sizeof(LOGFONT), &font_info);
465 font_ref_ = CreateHFontRef(CreateFontIndirect(&font_info));
468 void PlatformFontWin::InitWithFontNameAndSize(const std::string& font_name,
469 int font_size) {
470 HFONT hf = ::CreateFont(-font_size, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
471 DEFAULT_CHARSET,
472 OUT_DEFAULT_PRECIS,
473 CLIP_DEFAULT_PRECIS,
474 DEFAULT_QUALITY,
475 DEFAULT_PITCH | FF_DONTCARE,
476 base::UTF8ToUTF16(font_name).c_str());
477 font_ref_ = CreateHFontRef(hf);
480 // static
481 PlatformFontWin::HFontRef* PlatformFontWin::GetBaseFontRef() {
482 if (base_font_ref_ == NULL) {
483 NONCLIENTMETRICS_XP metrics;
484 base::win::GetNonClientMetrics(&metrics);
486 if (adjust_font_callback)
487 adjust_font_callback(&metrics.lfMessageFont);
488 metrics.lfMessageFont.lfHeight =
489 AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
490 HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
491 DLOG_ASSERT(font);
492 base_font_ref_ = PlatformFontWin::CreateHFontRef(font);
493 // base_font_ref_ is global, up the ref count so it's never deleted.
494 base_font_ref_->AddRef();
496 return base_font_ref_;
499 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRef(HFONT font) {
500 TEXTMETRIC font_metrics;
503 base::win::ScopedGetDC screen_dc(NULL);
504 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
505 GetTextMetricsForFont(screen_dc, font, &font_metrics);
508 if (direct_write_factory_)
509 return CreateHFontRefFromSkia(font, font_metrics);
511 return CreateHFontRefFromGDI(font, font_metrics);
514 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromGDI(
515 HFONT font,
516 const TEXTMETRIC& font_metrics) {
517 const int height = std::max<int>(1, font_metrics.tmHeight);
518 const int baseline = std::max<int>(1, font_metrics.tmAscent);
519 const int cap_height =
520 std::max<int>(1, font_metrics.tmAscent - font_metrics.tmInternalLeading);
521 const int ave_char_width = std::max<int>(1, font_metrics.tmAveCharWidth);
522 const int font_size =
523 std::max<int>(1, font_metrics.tmHeight - font_metrics.tmInternalLeading);
524 int style = 0;
525 if (font_metrics.tmItalic)
526 style |= Font::ITALIC;
527 if (font_metrics.tmUnderlined)
528 style |= Font::UNDERLINE;
529 if (font_metrics.tmWeight >= kTextMetricWeightBold)
530 style |= Font::BOLD;
532 return new HFontRef(font, font_size, height, baseline, cap_height,
533 ave_char_width, style);
536 // static
537 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromSkia(
538 HFONT gdi_font,
539 const TEXTMETRIC& font_metrics) {
540 LOGFONT font_info = {0};
541 GetObject(gdi_font, sizeof(LOGFONT), &font_info);
543 // If the font height is passed in as 0, assume the height to be -1 to ensure
544 // that we return the metrics for a 1 point font.
545 // If the font height is positive it represents the rasterized font's cell
546 // height. Calculate the actual height accordingly.
547 if (font_info.lfHeight > 0) {
548 font_info.lfHeight =
549 font_metrics.tmInternalLeading - font_metrics.tmHeight;
550 } else if (font_info.lfHeight == 0) {
551 font_info.lfHeight = -1;
554 int skia_style = SkTypeface::kNormal;
555 if (font_info.lfWeight >= FW_SEMIBOLD &&
556 font_info.lfWeight <= FW_ULTRABOLD) {
557 skia_style |= SkTypeface::kBold;
559 if (font_info.lfItalic)
560 skia_style |= SkTypeface::kItalic;
562 // Skia does not return all values we need for font metrics. For e.g.
563 // the cap height which indicates the height of capital letters is not
564 // returned even though it is returned by DirectWrite.
565 // TODO(ananta)
566 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
567 // DirectWrite and remove the code here which retrieves metrics from
568 // DirectWrite to calculate the cap height.
569 base::win::ScopedComPtr<IDWriteFont> dwrite_font;
570 HRESULT hr = GetMatchingDirectWriteFont(&font_info,
571 skia_style,
572 direct_write_factory_,
573 dwrite_font.Receive());
574 if (FAILED(hr)) {
575 CHECK(false);
576 return nullptr;
579 DWRITE_FONT_METRICS dwrite_font_metrics = {0};
580 dwrite_font->GetMetrics(&dwrite_font_metrics);
582 skia::RefPtr<SkTypeface> skia_face = skia::AdoptRef(
583 SkTypeface::CreateFromName(
584 base::SysWideToUTF8(font_info.lfFaceName).c_str(),
585 static_cast<SkTypeface::Style>(skia_style)));
587 gfx::FontRenderParams font_params =
588 gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr);
589 SkFontHost::SetSubpixelOrder(
590 gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrder(
591 font_params.subpixel_rendering));
592 SkFontHost::SetSubpixelOrientation(
593 gfx::FontRenderParams::SubpixelRenderingToSkiaLCDOrientation(
594 font_params.subpixel_rendering));
596 SkPaint paint;
597 paint.setAntiAlias(font_params.antialiasing);
598 paint.setTypeface(skia_face.get());
599 paint.setTextSize(-font_info.lfHeight);
600 SkPaint::FontMetrics skia_metrics;
601 paint.getFontMetrics(&skia_metrics);
603 // The calculations below are similar to those in the CreateHFontRef
604 // function. The height, baseline and cap height are rounded up to ensure
605 // that they match up closely with GDI.
606 const int height = std::ceil(skia_metrics.fDescent - skia_metrics.fAscent);
607 const int baseline = std::max<int>(1, std::ceil(-skia_metrics.fAscent));
608 const int cap_height = std::ceil(paint.getTextSize() *
609 static_cast<double>(dwrite_font_metrics.capHeight) /
610 dwrite_font_metrics.designUnitsPerEm);
612 // The metrics retrieved from skia don't have the average character width. In
613 // any case if we get the average character width from skia then use that or
614 // the average character width in the TEXTMETRIC structure.
615 // TODO(ananta): Investigate whether it is possible to retrieve this value
616 // from DirectWrite.
617 const int ave_char_width =
618 skia_metrics.fAvgCharWidth == 0 ? font_metrics.tmAveCharWidth
619 : skia_metrics.fAvgCharWidth;
621 int style = 0;
622 if (skia_style & SkTypeface::kItalic)
623 style |= Font::ITALIC;
624 if (font_info.lfUnderline)
625 style |= Font::UNDERLINE;
626 if (font_info.lfWeight >= kTextMetricWeightBold)
627 style |= Font::BOLD;
629 // DirectWrite may have substituted the GDI font name with a fallback
630 // font. Ensure that it is updated here.
631 DeleteObject(gdi_font);
632 gdi_font = ::CreateFontIndirect(&font_info);
633 return new HFontRef(gdi_font, -font_info.lfHeight, height, baseline,
634 cap_height, ave_char_width, style);
637 PlatformFontWin::PlatformFontWin(HFontRef* hfont_ref) : font_ref_(hfont_ref) {
640 ////////////////////////////////////////////////////////////////////////////////
641 // PlatformFontWin::HFontRef:
643 PlatformFontWin::HFontRef::HFontRef(HFONT hfont,
644 int font_size,
645 int height,
646 int baseline,
647 int cap_height,
648 int ave_char_width,
649 int style)
650 : hfont_(hfont),
651 font_size_(font_size),
652 height_(height),
653 baseline_(baseline),
654 cap_height_(cap_height),
655 ave_char_width_(ave_char_width),
656 style_(style),
657 dlu_base_x_(-1),
658 requested_font_size_(font_size) {
659 DLOG_ASSERT(hfont);
661 LOGFONT font_info;
662 GetObject(hfont_, sizeof(LOGFONT), &font_info);
663 font_name_ = base::UTF16ToUTF8(base::string16(font_info.lfFaceName));
665 // Retrieve the font size from the GetTextMetrics API instead of referencing
666 // it from the LOGFONT structure. This is because the height as reported by
667 // the LOGFONT structure is not always correct. For small fonts with size 1
668 // the LOGFONT structure reports the height as -1, while the actual font size
669 // is different. (2 on my XP machine).
670 base::win::ScopedGetDC screen_dc(NULL);
671 TEXTMETRIC font_metrics = {0};
672 PlatformFontWin::GetTextMetricsForFont(screen_dc, hfont_, &font_metrics);
673 requested_font_size_ = font_metrics.tmHeight - font_metrics.tmInternalLeading;
676 int PlatformFontWin::HFontRef::GetDluBaseX() {
677 if (dlu_base_x_ != -1)
678 return dlu_base_x_;
680 dlu_base_x_ = GetAverageCharWidthInDialogUnits(hfont_);
681 return dlu_base_x_;
684 // static
685 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
686 HFONT gdi_font) {
687 base::win::ScopedGetDC screen_dc(NULL);
688 base::win::ScopedSelectObject font(screen_dc, gdi_font);
689 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
691 // Yes, this is how Microsoft recommends calculating the dialog unit
692 // conversions. See: http://support.microsoft.com/kb/125681
693 SIZE ave_text_size;
694 GetTextExtentPoint32(screen_dc,
695 L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
696 52, &ave_text_size);
697 int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
699 DCHECK_NE(dlu_base_x, -1);
700 return dlu_base_x;
703 PlatformFontWin::HFontRef::~HFontRef() {
704 DeleteObject(hfont_);
707 ////////////////////////////////////////////////////////////////////////////////
708 // PlatformFont, public:
710 // static
711 PlatformFont* PlatformFont::CreateDefault() {
712 return new PlatformFontWin;
715 // static
716 PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) {
717 return new PlatformFontWin(native_font);
720 // static
721 PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name,
722 int font_size) {
723 return new PlatformFontWin(font_name, font_size);
726 } // namespace gfx