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"
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"
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())
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
)))
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
))) {
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
);
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
{
109 static CachedFontLinkSettings
* GetInstance();
111 // Returns the linked fonts list correspond to |font|. Returned value will
113 const std::vector
<Font
>* GetLinkedFonts(const Font
& font
);
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
);
131 CachedFontLinkSettings
* CachedFontLinkSettings::GetInstance() {
132 return Singleton
<CachedFontLinkSettings
,
133 LeakySingletonTraits
<CachedFontLinkSettings
> >::get();
136 const std::vector
<Font
>* CachedFontLinkSettings::GetLinkedFonts(
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())
144 cached_linked_fonts_
[font_name
] = std::vector
<Font
>();
145 std::vector
<Font
>* linked_fonts
= &cached_linked_fonts_
[font_name
];
147 // TODO(ckocagil): Remove ScopedTracker below once crbug.com/441028 is fixed.
148 tracked_objects::ScopedTracker
tracking_profile(
149 FROM_HERE_WITH_EXPLICIT_FUNCTION(
150 "441028 QueryLinkedFontsFromRegistry()"));
152 QueryLinkedFontsFromRegistry(font
, &cached_system_fonts_
, linked_fonts
);
156 CachedFontLinkSettings::CachedFontLinkSettings() {
159 CachedFontLinkSettings::~CachedFontLinkSettings() {
162 // Callback to |EnumEnhMetaFile()| to intercept font creation.
163 int CALLBACK
MetaFileEnumProc(HDC hdc
,
165 CONST ENHMETARECORD
* record
,
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
;
180 void ParseFontLinkEntry(const std::string
& entry
,
181 std::string
* filename
,
182 std::string
* font_name
) {
183 std::vector
<std::string
> parts
= base::SplitString(
184 entry
, ",", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
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
201 // TODO(asvitkine): Should we support these scaling factors?
202 *font_names
= base::SplitString(
203 family
, "&", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
204 if (!font_names
->empty()) {
205 const size_t index
= font_names
->back().find('(');
206 if (index
!= std::string::npos
) {
207 font_names
->back().resize(index
);
208 base::TrimWhitespace(font_names
->back(), base::TRIM_TRAILING
,
209 &font_names
->back());
214 LinkedFontsIterator::LinkedFontsIterator(Font font
)
215 : original_font_(font
),
216 next_font_set_(false),
218 linked_font_index_(0) {
219 SetNextFont(original_font_
);
222 LinkedFontsIterator::~LinkedFontsIterator() {
225 void LinkedFontsIterator::SetNextFont(Font font
) {
227 next_font_set_
= true;
230 bool LinkedFontsIterator::NextFont(Font
* font
) {
231 if (next_font_set_
) {
232 next_font_set_
= false;
233 current_font_
= next_font_
;
234 *font
= current_font_
;
238 // First time through, get the linked fonts list.
239 if (linked_fonts_
== NULL
)
240 linked_fonts_
= GetLinkedFonts();
242 if (linked_font_index_
== linked_fonts_
->size())
245 current_font_
= linked_fonts_
->at(linked_font_index_
++);
246 *font
= current_font_
;
250 const std::vector
<Font
>* LinkedFontsIterator::GetLinkedFonts() const {
251 CachedFontLinkSettings
* font_link
= CachedFontLinkSettings::GetInstance();
253 // First, try to get the list for the original font.
254 const std::vector
<Font
>* fonts
= font_link
->GetLinkedFonts(original_font_
);
256 // If there are no linked fonts for the original font, try querying the
257 // ones for the current font. This may happen if the first font is a custom
258 // font that has no linked fonts in the registry.
260 // Note: One possibility would be to always merge both lists of fonts,
261 // but it is not clear whether there are any real world scenarios
262 // where this would actually help.
264 fonts
= font_link
->GetLinkedFonts(current_font_
);
269 } // namespace internal
271 std::vector
<std::string
> GetFallbackFontFamilies(
272 const std::string
& font_family
) {
273 // LinkedFontsIterator doesn't care about the font size, so we always pass 10.
274 internal::LinkedFontsIterator
linked_fonts(Font(font_family
, 10));
275 std::vector
<std::string
> fallback_fonts
;
277 while (linked_fonts
.NextFont(¤t
))
278 fallback_fonts
.push_back(current
.GetFontName());
279 return fallback_fonts
;
282 bool GetUniscribeFallbackFont(const Font
& font
,
286 // Adapted from WebKit's |FontCache::GetFontDataForCharacters()|.
287 // Uniscribe doesn't expose a method to query fallback fonts, so this works by
288 // drawing the text to an EMF object with Uniscribe's ScriptStringOut and then
289 // inspecting the EMF object to figure out which font Uniscribe used.
291 // DirectWrite in Windows 8.1 provides a cleaner alternative:
292 // http://msdn.microsoft.com/en-us/library/windows/desktop/dn280480.aspx
294 static HDC hdc
= CreateCompatibleDC(NULL
);
296 // Use a meta file to intercept the fallback font chosen by Uniscribe.
297 HDC meta_file_dc
= CreateEnhMetaFile(hdc
, NULL
, NULL
, NULL
);
301 SelectObject(meta_file_dc
, font
.GetNativeFont());
303 SCRIPT_STRING_ANALYSIS script_analysis
;
305 ScriptStringAnalyse(meta_file_dc
, text
, text_length
, 0, -1,
306 SSA_METAFILE
| SSA_FALLBACK
| SSA_GLYPHS
| SSA_LINK
,
307 0, NULL
, NULL
, NULL
, NULL
, NULL
, &script_analysis
);
309 if (SUCCEEDED(hresult
)) {
310 hresult
= ScriptStringOut(script_analysis
, 0, 0, 0, NULL
, 0, 0, FALSE
);
311 ScriptStringFree(&script_analysis
);
314 bool found_fallback
= false;
315 HENHMETAFILE meta_file
= CloseEnhMetaFile(meta_file_dc
);
316 if (SUCCEEDED(hresult
)) {
318 log_font
.lfFaceName
[0] = 0;
319 EnumEnhMetaFile(0, meta_file
, MetaFileEnumProc
, &log_font
, NULL
);
320 if (log_font
.lfFaceName
[0]) {
321 *result
= Font(base::UTF16ToUTF8(log_font
.lfFaceName
),
323 found_fallback
= true;
326 DeleteEnhMetaFile(meta_file
);
328 return found_fallback
;