[Cronet] Handle redirects in CronetHttpURLConnection
[chromium-blink-merge.git] / ui / gfx / platform_font_win.cc
blob477e609948af889d5bf3f9aae237ab5e5ecfa627
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/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"
29 namespace {
31 // If the tmWeight field of a TEXTMETRIC structure has a value >= this, the
32 // font is bold.
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();
40 return min_font_size;
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) {
46 if (lf_height < 0) {
47 lf_height -= size_delta;
48 } else {
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
53 // locale.
54 if (abs(lf_height) < min_font_size) {
55 return lf_height < 0 ? -min_font_size : min_font_size;
56 } else {
57 return lf_height;
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,
73 int font_style,
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());
81 if (FAILED(hr)) {
82 CHECK(false);
83 return hr;
86 hr = gdi_interop->CreateFontFromLOGFONT(&font_info, dwrite_font);
87 if (SUCCEEDED(hr))
88 return hr;
90 // Get the matching font from the system font collection exposed by
91 // DirectWrite.
92 base::win::ScopedComPtr<IDWriteFontCollection> font_collection;
93 hr = factory->GetSystemFontCollection(font_collection.Receive());
94 if (FAILED(hr)) {
95 CHECK(false);
96 return hr;
99 // Steps as below:-
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
110 // use that.
111 base::win::ScopedComPtr<IDWriteFontFamily> font_family;
112 BOOL exists = FALSE;
113 uint32 index = 0;
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,
121 sizeof(metrics),
122 &metrics,
123 0)) {
124 CHECK(false);
125 return E_FAIL;
127 hr = font_collection->FindFamilyName(metrics.lfMessageFont.lfFaceName,
128 &index,
129 &exists);
132 if (index != UINT_MAX && exists) {
133 hr = font_collection->GetFontFamily(index, font_family.Receive());
134 } else {
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());
140 if (FAILED(hr)) {
141 CHECK(false);
142 return hr;
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
161 // GDI.
162 // http://crbug.com/434425
163 // TODO(ananta)
164 // Remove the GetMatchingFonts and related code here once we get to a stable
165 // state in canary.
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;
170 if (SUCCEEDED(hr))
171 matching_font_count = matching_font_list->GetFontCount();
173 hr = font_family->GetFirstMatchingFont(weight, stretch, italic,
174 dwrite_font);
175 if (FAILED(hr)) {
176 base::debug::Alias(&matching_font_count);
177 CHECK(false);
179 return hr;
182 } // namespace
184 namespace gfx {
186 // static
187 PlatformFontWin::HFontRef* PlatformFontWin::base_font_ref_;
189 // static
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,
208 int font_size) {
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)
215 return Font(this);
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())
227 break;
228 font_height = font.GetHeight();
229 font_size = font.GetFontSize();
231 return font;
234 LOGFONT font_info;
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 {
247 LOGFONT font_info;
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]);
300 if (length <= 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)));
312 return params;
315 NativeFont PlatformFontWin::GetNativeFont() const {
316 return font_ref_->hfont();
319 void PlatformFontWin::SetDirectWriteFactory(IDWriteFactory* factory) {
320 // We grab a reference on the DirectWrite factory. This reference is
321 // leaked, which is ok because skia leaks it as well.
322 factory->AddRef();
323 direct_write_factory_ = factory;
326 void PlatformFontWin::GetTextMetricsForFont(HDC hdc,
327 HFONT font,
328 TEXTMETRIC* text_metrics) {
329 base::win::ScopedSelectObject scoped_font(hdc, font);
330 GetTextMetrics(hdc, text_metrics);
333 ////////////////////////////////////////////////////////////////////////////////
334 // Font, private:
336 void PlatformFontWin::InitWithCopyOfHFONT(HFONT hfont) {
337 DCHECK(hfont);
338 LOGFONT font_info;
339 GetObject(hfont, sizeof(LOGFONT), &font_info);
340 font_ref_ = CreateHFontRef(CreateFontIndirect(&font_info));
343 void PlatformFontWin::InitWithFontNameAndSize(const std::string& font_name,
344 int font_size) {
345 HFONT hf = ::CreateFont(-font_size, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE,
346 DEFAULT_CHARSET,
347 OUT_DEFAULT_PRECIS,
348 CLIP_DEFAULT_PRECIS,
349 DEFAULT_QUALITY,
350 DEFAULT_PITCH | FF_DONTCARE,
351 base::UTF8ToUTF16(font_name).c_str());
352 font_ref_ = CreateHFontRef(hf);
355 // static
356 PlatformFontWin::HFontRef* PlatformFontWin::GetBaseFontRef() {
357 if (base_font_ref_ == NULL) {
358 NONCLIENTMETRICS_XP metrics;
359 base::win::GetNonClientMetrics(&metrics);
361 if (adjust_font_callback)
362 adjust_font_callback(&metrics.lfMessageFont);
363 metrics.lfMessageFont.lfHeight =
364 AdjustFontSize(metrics.lfMessageFont.lfHeight, 0);
365 HFONT font = CreateFontIndirect(&metrics.lfMessageFont);
366 DLOG_ASSERT(font);
367 base_font_ref_ = PlatformFontWin::CreateHFontRef(font);
368 // base_font_ref_ is global, up the ref count so it's never deleted.
369 base_font_ref_->AddRef();
371 return base_font_ref_;
374 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRef(HFONT font) {
375 TEXTMETRIC font_metrics;
378 base::win::ScopedGetDC screen_dc(NULL);
379 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
380 GetTextMetricsForFont(screen_dc, font, &font_metrics);
383 if (direct_write_factory_)
384 return CreateHFontRefFromSkia(font, font_metrics);
386 return CreateHFontRefFromGDI(font, font_metrics);
389 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromGDI(
390 HFONT font,
391 const TEXTMETRIC& font_metrics) {
392 const int height = std::max<int>(1, font_metrics.tmHeight);
393 const int baseline = std::max<int>(1, font_metrics.tmAscent);
394 const int cap_height =
395 std::max<int>(1, font_metrics.tmAscent - font_metrics.tmInternalLeading);
396 const int ave_char_width = std::max<int>(1, font_metrics.tmAveCharWidth);
397 const int font_size =
398 std::max<int>(1, font_metrics.tmHeight - font_metrics.tmInternalLeading);
399 int style = 0;
400 if (font_metrics.tmItalic)
401 style |= Font::ITALIC;
402 if (font_metrics.tmUnderlined)
403 style |= Font::UNDERLINE;
404 if (font_metrics.tmWeight >= kTextMetricWeightBold)
405 style |= Font::BOLD;
407 return new HFontRef(font, font_size, height, baseline, cap_height,
408 ave_char_width, style);
411 Font PlatformFontWin::DeriveWithCorrectedSize(HFONT base_font) {
412 base::win::ScopedGetDC screen_dc(NULL);
413 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
415 base::win::ScopedGDIObject<HFONT> best_font(base_font);
416 TEXTMETRIC best_font_metrics;
417 GetTextMetricsForFont(screen_dc, best_font, &best_font_metrics);
419 LOGFONT font_info;
420 GetObject(base_font, sizeof(LOGFONT), &font_info);
422 // Set |lfHeight| to negative value to indicate it's the size, not the height.
423 font_info.lfHeight =
424 -(best_font_metrics.tmHeight - best_font_metrics.tmInternalLeading);
426 do {
427 // Increment font size. Prefer font with greater size if its height isn't
428 // greater than height of base font.
429 font_info.lfHeight = AdjustFontSize(font_info.lfHeight, 1);
430 base::win::ScopedGDIObject<HFONT> font(CreateFontIndirect(&font_info));
431 TEXTMETRIC font_metrics;
432 GetTextMetricsForFont(screen_dc, font, &font_metrics);
433 if (font_metrics.tmHeight > best_font_metrics.tmHeight)
434 break;
435 best_font.Set(font.release());
436 best_font_metrics = font_metrics;
437 } while (true);
439 return Font(new PlatformFontWin(CreateHFontRef(best_font.release())));
442 // static
443 PlatformFontWin::HFontRef* PlatformFontWin::CreateHFontRefFromSkia(
444 HFONT gdi_font,
445 const TEXTMETRIC& font_metrics) {
446 LOGFONT font_info = {0};
447 GetObject(gdi_font, sizeof(LOGFONT), &font_info);
449 // If the font height is passed in as 0, assume the height to be -1 to ensure
450 // that we return the metrics for a 1 point font.
451 // If the font height is positive it represents the rasterized font's cell
452 // height. Calculate the actual height accordingly.
453 if (font_info.lfHeight > 0) {
454 font_info.lfHeight =
455 font_metrics.tmInternalLeading - font_metrics.tmHeight;
456 } else if (font_info.lfHeight == 0) {
457 font_info.lfHeight = -1;
460 int skia_style = SkTypeface::kNormal;
461 if (font_info.lfWeight >= FW_SEMIBOLD &&
462 font_info.lfWeight <= FW_ULTRABOLD) {
463 skia_style |= SkTypeface::kBold;
465 if (font_info.lfItalic)
466 skia_style |= SkTypeface::kItalic;
468 // Skia does not return all values we need for font metrics. For e.g.
469 // the cap height which indicates the height of capital letters is not
470 // returned even though it is returned by DirectWrite.
471 // TODO(ananta)
472 // Fix SkScalerContext_win_dw.cpp to return all metrics we need from
473 // DirectWrite and remove the code here which retrieves metrics from
474 // DirectWrite to calculate the cap height.
475 base::win::ScopedComPtr<IDWriteFont> dwrite_font;
476 HRESULT hr = GetMatchingDirectWriteFont(font_info,
477 skia_style,
478 direct_write_factory_,
479 dwrite_font.Receive());
480 if (FAILED(hr)) {
481 CHECK(false);
482 return nullptr;
485 DWRITE_FONT_METRICS dwrite_font_metrics = {0};
486 dwrite_font->GetMetrics(&dwrite_font_metrics);
488 skia::RefPtr<SkTypeface> skia_face = skia::AdoptRef(
489 SkTypeface::CreateFromName(
490 base::SysWideToUTF8(font_info.lfFaceName).c_str(),
491 static_cast<SkTypeface::Style>(skia_style)));
493 BOOL antialiasing = TRUE;
494 SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &antialiasing, 0);
496 SkPaint paint;
497 paint.setAntiAlias(!!antialiasing);
498 paint.setTypeface(skia_face.get());
499 paint.setTextSize(-font_info.lfHeight);
500 SkPaint::FontMetrics skia_metrics;
501 paint.getFontMetrics(&skia_metrics);
503 // The calculations below are similar to those in the CreateHFontRef
504 // function. The height, baseline and cap height are rounded up to ensure
505 // that they match up closely with GDI.
506 const int height = std::ceil(
507 skia_metrics.fDescent - skia_metrics.fAscent + skia_metrics.fLeading);
508 const int baseline = std::max<int>(1, std::ceil(-skia_metrics.fAscent));
509 const int cap_height = std::ceil(paint.getTextSize() *
510 static_cast<double>(dwrite_font_metrics.capHeight) /
511 dwrite_font_metrics.designUnitsPerEm);
513 // The metrics retrieved from skia don't have the average character width. In
514 // any case if we get the average character width from skia then use that or
515 // use the text extent technique as documented by microsoft. See
516 // GetAverageCharWidthInDialogUnits for details.
517 const int ave_char_width =
518 skia_metrics.fAvgCharWidth == 0 ?
519 HFontRef::GetAverageCharWidthInDialogUnits(gdi_font)
520 : skia_metrics.fAvgCharWidth;
522 int style = 0;
523 if (skia_style & SkTypeface::kItalic)
524 style |= Font::ITALIC;
525 if (font_info.lfUnderline)
526 style |= Font::UNDERLINE;
527 if (font_info.lfWeight >= kTextMetricWeightBold)
528 style |= Font::BOLD;
529 return new HFontRef(gdi_font, -font_info.lfHeight, height, baseline,
530 cap_height, ave_char_width, style);
533 PlatformFontWin::PlatformFontWin(HFontRef* hfont_ref) : font_ref_(hfont_ref) {
536 ////////////////////////////////////////////////////////////////////////////////
537 // PlatformFontWin::HFontRef:
539 PlatformFontWin::HFontRef::HFontRef(HFONT hfont,
540 int font_size,
541 int height,
542 int baseline,
543 int cap_height,
544 int ave_char_width,
545 int style)
546 : hfont_(hfont),
547 font_size_(font_size),
548 height_(height),
549 baseline_(baseline),
550 cap_height_(cap_height),
551 ave_char_width_(ave_char_width),
552 style_(style),
553 dlu_base_x_(-1),
554 requested_font_size_(font_size) {
555 DLOG_ASSERT(hfont);
557 LOGFONT font_info;
558 GetObject(hfont_, sizeof(LOGFONT), &font_info);
559 font_name_ = base::UTF16ToUTF8(base::string16(font_info.lfFaceName));
560 if (font_info.lfHeight < 0)
561 requested_font_size_ = -font_info.lfHeight;
564 int PlatformFontWin::HFontRef::GetDluBaseX() {
565 if (dlu_base_x_ != -1)
566 return dlu_base_x_;
568 dlu_base_x_ = GetAverageCharWidthInDialogUnits(hfont_);
569 return dlu_base_x_;
572 // static
573 int PlatformFontWin::HFontRef::GetAverageCharWidthInDialogUnits(
574 HFONT gdi_font) {
575 base::win::ScopedGetDC screen_dc(NULL);
576 base::win::ScopedSelectObject font(screen_dc, gdi_font);
577 gfx::ScopedSetMapMode mode(screen_dc, MM_TEXT);
579 // Yes, this is how Microsoft recommends calculating the dialog unit
580 // conversions. See: http://support.microsoft.com/kb/125681
581 SIZE ave_text_size;
582 GetTextExtentPoint32(screen_dc,
583 L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
584 52, &ave_text_size);
585 int dlu_base_x = (ave_text_size.cx / 26 + 1) / 2;
587 DCHECK_NE(dlu_base_x, -1);
588 return dlu_base_x;
591 PlatformFontWin::HFontRef::~HFontRef() {
592 DeleteObject(hfont_);
595 ////////////////////////////////////////////////////////////////////////////////
596 // PlatformFont, public:
598 // static
599 PlatformFont* PlatformFont::CreateDefault() {
600 return new PlatformFontWin;
603 // static
604 PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) {
605 return new PlatformFontWin(native_font);
608 // static
609 PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name,
610 int font_size) {
611 return new PlatformFontWin(font_name, font_size);
614 } // namespace gfx