[Cronet] Handle redirects in CronetHttpURLConnection
[chromium-blink-merge.git] / ui / gfx / font_fallback_win.cc
blobb5537ff1ea87ce1abd288a6cb3b3e62d91e7658f
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/font_fallback_win.h"
7 #include <usp10.h>
9 #include <map>
11 #include "base/memory/singleton.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/win/registry.h"
17 #include "ui/gfx/font.h"
18 #include "ui/gfx/font_fallback.h"
20 namespace gfx {
22 namespace {
24 // Queries the registry to get a mapping from font filenames to font names.
25 void QueryFontsFromRegistry(std::map<std::string, std::string>* map) {
26 const wchar_t* kFonts =
27 L"Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
29 base::win::RegistryValueIterator it(HKEY_LOCAL_MACHINE, kFonts);
30 for (; it.Valid(); ++it) {
31 const std::string filename =
32 base::StringToLowerASCII(base::WideToUTF8(it.Value()));
33 (*map)[filename] = base::WideToUTF8(it.Name());
37 // Fills |font_names| with a list of font families found in the font file at
38 // |filename|. Takes in a |font_map| from font filename to font families, which
39 // is filled-in by querying the registry, if empty.
40 void GetFontNamesFromFilename(const std::string& filename,
41 std::map<std::string, std::string>* font_map,
42 std::vector<std::string>* font_names) {
43 if (font_map->empty())
44 QueryFontsFromRegistry(font_map);
46 std::map<std::string, std::string>::const_iterator it =
47 font_map->find(base::StringToLowerASCII(filename));
48 if (it == font_map->end())
49 return;
51 internal::ParseFontFamilyString(it->second, font_names);
54 // Returns true if |text| contains only ASCII digits.
55 bool ContainsOnlyDigits(const std::string& text) {
56 return text.find_first_not_of("0123456789") == base::string16::npos;
59 // Appends a Font with the given |name| and |size| to |fonts| unless the last
60 // entry is already a font with that name.
61 void AppendFont(const std::string& name, int size, std::vector<Font>* fonts) {
62 if (fonts->empty() || fonts->back().GetFontName() != name)
63 fonts->push_back(Font(name, size));
66 // Queries the registry to get a list of linked fonts for |font|.
67 void QueryLinkedFontsFromRegistry(const Font& font,
68 std::map<std::string, std::string>* font_map,
69 std::vector<Font>* linked_fonts) {
70 const wchar_t* kSystemLink =
71 L"Software\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink";
73 base::win::RegKey key;
74 if (FAILED(key.Open(HKEY_LOCAL_MACHINE, kSystemLink, KEY_READ)))
75 return;
77 const std::wstring original_font_name = base::UTF8ToWide(font.GetFontName());
78 std::vector<std::wstring> values;
79 if (FAILED(key.ReadValues(original_font_name.c_str(), &values))) {
80 key.Close();
81 return;
84 std::string filename;
85 std::string font_name;
86 for (size_t i = 0; i < values.size(); ++i) {
87 internal::ParseFontLinkEntry(
88 base::WideToUTF8(values[i]), &filename, &font_name);
89 // If the font name is present, add that directly, otherwise add the
90 // font names corresponding to the filename.
91 if (!font_name.empty()) {
92 AppendFont(font_name, font.GetFontSize(), linked_fonts);
93 } else if (!filename.empty()) {
94 std::vector<std::string> font_names;
95 GetFontNamesFromFilename(filename, font_map, &font_names);
96 for (size_t i = 0; i < font_names.size(); ++i)
97 AppendFont(font_names[i], font.GetFontSize(), linked_fonts);
101 key.Close();
104 // CachedFontLinkSettings is a singleton cache of the Windows font settings
105 // from the registry. It maintains a cached view of the registry's list of
106 // system fonts and their font link chains.
107 class CachedFontLinkSettings {
108 public:
109 static CachedFontLinkSettings* GetInstance();
111 // Returns the linked fonts list correspond to |font|. Returned value will
112 // never be null.
113 const std::vector<Font>* GetLinkedFonts(const Font& font);
115 private:
116 friend struct DefaultSingletonTraits<CachedFontLinkSettings>;
118 CachedFontLinkSettings();
119 virtual ~CachedFontLinkSettings();
121 // Map of system fonts, from file names to font families.
122 std::map<std::string, std::string> cached_system_fonts_;
124 // Map from font names to vectors of linked fonts.
125 std::map<std::string, std::vector<Font> > cached_linked_fonts_;
127 DISALLOW_COPY_AND_ASSIGN(CachedFontLinkSettings);
130 // static
131 CachedFontLinkSettings* CachedFontLinkSettings::GetInstance() {
132 return Singleton<CachedFontLinkSettings,
133 LeakySingletonTraits<CachedFontLinkSettings> >::get();
136 const std::vector<Font>* CachedFontLinkSettings::GetLinkedFonts(
137 const Font& font) {
138 const std::string& font_name = font.GetFontName();
139 std::map<std::string, std::vector<Font> >::const_iterator it =
140 cached_linked_fonts_.find(font_name);
141 if (it != cached_linked_fonts_.end())
142 return &it->second;
144 cached_linked_fonts_[font_name] = std::vector<Font>();
145 std::vector<Font>* linked_fonts = &cached_linked_fonts_[font_name];
147 // TODO(vadimt): Remove ScopedTracker below once crbug.com/431326 is fixed.
148 tracked_objects::ScopedTracker tracking_profile(
149 FROM_HERE_WITH_EXPLICIT_FUNCTION(
150 "431326 CachedFontLinkSettings::GetLinkedFonts"));
152 QueryLinkedFontsFromRegistry(font, &cached_system_fonts_, linked_fonts);
153 return linked_fonts;
156 CachedFontLinkSettings::CachedFontLinkSettings() {
159 CachedFontLinkSettings::~CachedFontLinkSettings() {
162 // Callback to |EnumEnhMetaFile()| to intercept font creation.
163 int CALLBACK MetaFileEnumProc(HDC hdc,
164 HANDLETABLE* table,
165 CONST ENHMETARECORD* record,
166 int table_entries,
167 LPARAM log_font) {
168 if (record->iType == EMR_EXTCREATEFONTINDIRECTW) {
169 const EMREXTCREATEFONTINDIRECTW* create_font_record =
170 reinterpret_cast<const EMREXTCREATEFONTINDIRECTW*>(record);
171 *reinterpret_cast<LOGFONT*>(log_font) = create_font_record->elfw.elfLogFont;
173 return 1;
176 } // namespace
178 namespace internal {
180 void ParseFontLinkEntry(const std::string& entry,
181 std::string* filename,
182 std::string* font_name) {
183 std::vector<std::string> parts;
184 base::SplitString(entry, ',', &parts);
185 filename->clear();
186 font_name->clear();
187 if (parts.size() > 0)
188 *filename = parts[0];
189 // The second entry may be the font name or the first scaling factor, if the
190 // entry does not contain a font name. If it contains only digits, assume it
191 // is a scaling factor.
192 if (parts.size() > 1 && !ContainsOnlyDigits(parts[1]))
193 *font_name = parts[1];
196 void ParseFontFamilyString(const std::string& family,
197 std::vector<std::string>* font_names) {
198 // The entry is comma separated, having the font filename as the first value
199 // followed optionally by the font family name and a pair of integer scaling
200 // factors.
201 // TODO(asvitkine): Should we support these scaling factors?
202 base::SplitString(family, '&', font_names);
203 if (!font_names->empty()) {
204 const size_t index = font_names->back().find('(');
205 if (index != std::string::npos) {
206 font_names->back().resize(index);
207 base::TrimWhitespace(font_names->back(), base::TRIM_TRAILING,
208 &font_names->back());
213 LinkedFontsIterator::LinkedFontsIterator(Font font)
214 : original_font_(font),
215 next_font_set_(false),
216 linked_fonts_(NULL),
217 linked_font_index_(0) {
218 SetNextFont(original_font_);
221 LinkedFontsIterator::~LinkedFontsIterator() {
224 void LinkedFontsIterator::SetNextFont(Font font) {
225 next_font_ = font;
226 next_font_set_ = true;
229 bool LinkedFontsIterator::NextFont(Font* font) {
230 if (next_font_set_) {
231 next_font_set_ = false;
232 current_font_ = next_font_;
233 *font = current_font_;
234 return true;
237 // First time through, get the linked fonts list.
238 if (linked_fonts_ == NULL)
239 linked_fonts_ = GetLinkedFonts();
241 if (linked_font_index_ == linked_fonts_->size())
242 return false;
244 current_font_ = linked_fonts_->at(linked_font_index_++);
245 *font = current_font_;
246 return true;
249 const std::vector<Font>* LinkedFontsIterator::GetLinkedFonts() const {
250 CachedFontLinkSettings* font_link = CachedFontLinkSettings::GetInstance();
252 // First, try to get the list for the original font.
253 const std::vector<Font>* fonts = font_link->GetLinkedFonts(original_font_);
255 // If there are no linked fonts for the original font, try querying the
256 // ones for the current font. This may happen if the first font is a custom
257 // font that has no linked fonts in the registry.
259 // Note: One possibility would be to always merge both lists of fonts,
260 // but it is not clear whether there are any real world scenarios
261 // where this would actually help.
262 if (fonts->empty())
263 fonts = font_link->GetLinkedFonts(current_font_);
265 return fonts;
268 } // namespace internal
270 std::vector<std::string> GetFallbackFontFamilies(
271 const std::string& font_family) {
272 // LinkedFontsIterator doesn't care about the font size, so we always pass 10.
273 internal::LinkedFontsIterator linked_fonts(Font(font_family, 10));
274 std::vector<std::string> fallback_fonts;
275 Font current;
276 while (linked_fonts.NextFont(&current))
277 fallback_fonts.push_back(current.GetFontName());
278 return fallback_fonts;
281 bool GetUniscribeFallbackFont(const Font& font,
282 const wchar_t* text,
283 int text_length,
284 Font* result) {
285 // Adapted from WebKit's |FontCache::GetFontDataForCharacters()|.
286 // Uniscribe doesn't expose a method to query fallback fonts, so this works by
287 // drawing the text to an EMF object with Uniscribe's ScriptStringOut and then
288 // inspecting the EMF object to figure out which font Uniscribe used.
290 // DirectWrite in Windows 8.1 provides a cleaner alternative:
291 // http://msdn.microsoft.com/en-us/library/windows/desktop/dn280480.aspx
293 static HDC hdc = CreateCompatibleDC(NULL);
295 // Use a meta file to intercept the fallback font chosen by Uniscribe.
296 HDC meta_file_dc = CreateEnhMetaFile(hdc, NULL, NULL, NULL);
297 if (!meta_file_dc)
298 return false;
300 SelectObject(meta_file_dc, font.GetNativeFont());
302 SCRIPT_STRING_ANALYSIS script_analysis;
303 HRESULT hresult =
304 ScriptStringAnalyse(meta_file_dc, text, text_length, 0, -1,
305 SSA_METAFILE | SSA_FALLBACK | SSA_GLYPHS | SSA_LINK,
306 0, NULL, NULL, NULL, NULL, NULL, &script_analysis);
308 if (SUCCEEDED(hresult)) {
309 hresult = ScriptStringOut(script_analysis, 0, 0, 0, NULL, 0, 0, FALSE);
310 ScriptStringFree(&script_analysis);
313 bool found_fallback = false;
314 HENHMETAFILE meta_file = CloseEnhMetaFile(meta_file_dc);
315 if (SUCCEEDED(hresult)) {
316 LOGFONT log_font;
317 log_font.lfFaceName[0] = 0;
318 EnumEnhMetaFile(0, meta_file, MetaFileEnumProc, &log_font, NULL);
319 if (log_font.lfFaceName[0]) {
320 *result = Font(base::UTF16ToUTF8(log_font.lfFaceName),
321 font.GetFontSize());
322 found_fallback = true;
325 DeleteEnhMetaFile(meta_file);
327 return found_fallback;
330 } // namespace gfx