2 * Copyright (C) 2013 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27 #include "core/css/FontFaceSet.h"
29 #include "bindings/core/v8/Dictionary.h"
30 #include "bindings/core/v8/ScriptPromiseResolver.h"
31 #include "bindings/core/v8/ScriptState.h"
32 #include "core/css/CSSFontSelector.h"
33 #include "core/css/CSSSegmentedFontFace.h"
34 #include "core/css/FontFaceCache.h"
35 #include "core/css/FontFaceSetLoadEvent.h"
36 #include "core/css/StylePropertySet.h"
37 #include "core/css/parser/CSSParser.h"
38 #include "core/css/resolver/StyleResolver.h"
39 #include "core/dom/Document.h"
40 #include "core/dom/StyleEngine.h"
41 #include "core/frame/FrameView.h"
42 #include "core/frame/LocalFrame.h"
43 #include "core/rendering/style/StyleInheritedData.h"
44 #include "public/platform/Platform.h"
48 static const int defaultFontSize = 10;
49 static const char defaultFontFamily[] = "sans-serif";
51 class LoadFontPromiseResolver FINAL : public FontFace::LoadFontCallback {
53 static PassRefPtrWillBeRawPtr<LoadFontPromiseResolver> create(FontFaceArray faces, ScriptState* scriptState)
55 return adoptRefWillBeNoop(new LoadFontPromiseResolver(faces, scriptState));
58 void loadFonts(ExecutionContext*);
59 ScriptPromise promise() { return m_resolver->promise(); }
61 virtual void notifyLoaded(FontFace*) OVERRIDE;
62 virtual void notifyError(FontFace*) OVERRIDE;
64 virtual void trace(Visitor*) OVERRIDE;
67 LoadFontPromiseResolver(FontFaceArray faces, ScriptState* scriptState)
68 : m_numLoading(faces.size())
69 , m_errorOccured(false)
70 , m_resolver(ScriptPromiseResolver::create(scriptState))
72 m_fontFaces.swap(faces);
75 WillBeHeapVector<RefPtrWillBeMember<FontFace> > m_fontFaces;
78 RefPtr<ScriptPromiseResolver> m_resolver;
81 void LoadFontPromiseResolver::loadFonts(ExecutionContext* context)
84 m_resolver->resolve(m_fontFaces);
88 for (size_t i = 0; i < m_fontFaces.size(); i++)
89 m_fontFaces[i]->loadWithCallback(this, context);
92 void LoadFontPromiseResolver::notifyLoaded(FontFace* fontFace)
95 if (m_numLoading || m_errorOccured)
98 m_resolver->resolve(m_fontFaces);
101 void LoadFontPromiseResolver::notifyError(FontFace* fontFace)
104 if (!m_errorOccured) {
105 m_errorOccured = true;
106 m_resolver->reject(fontFace->error());
110 void LoadFontPromiseResolver::trace(Visitor* visitor)
112 visitor->trace(m_fontFaces);
113 LoadFontCallback::trace(visitor);
116 class FontsReadyPromiseResolver {
118 static PassOwnPtr<FontsReadyPromiseResolver> create(ScriptState* scriptState)
120 return adoptPtr(new FontsReadyPromiseResolver(scriptState));
123 void resolve(PassRefPtrWillBeRawPtr<FontFaceSet> fontFaceSet)
125 m_resolver->resolve(fontFaceSet);
128 ScriptPromise promise() { return m_resolver->promise(); }
131 explicit FontsReadyPromiseResolver(ScriptState* scriptState)
132 : m_resolver(ScriptPromiseResolver::create(scriptState))
136 RefPtr<ScriptPromiseResolver> m_resolver;
139 FontFaceSet::FontFaceSet(Document& document)
140 : ActiveDOMObject(&document)
141 , m_shouldFireLoadingEvent(false)
142 , m_asyncRunner(this, &FontFaceSet::handlePendingEventsAndPromises)
147 FontFaceSet::~FontFaceSet()
151 Document* FontFaceSet::document() const
153 return toDocument(executionContext());
156 bool FontFaceSet::inActiveDocumentContext() const
158 ExecutionContext* context = executionContext();
159 return context && toDocument(context)->isActive();
162 void FontFaceSet::addFontFacesToFontFaceCache(FontFaceCache* fontFaceCache, CSSFontSelector* fontSelector)
164 for (WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >::iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it)
165 fontFaceCache->addFontFace(fontSelector, *it, false);
168 const AtomicString& FontFaceSet::interfaceName() const
170 return EventTargetNames::FontFaceSet;
173 ExecutionContext* FontFaceSet::executionContext() const
175 return ActiveDOMObject::executionContext();
178 AtomicString FontFaceSet::status() const
180 DEFINE_STATIC_LOCAL(AtomicString, loading, ("loading", AtomicString::ConstructFromLiteral));
181 DEFINE_STATIC_LOCAL(AtomicString, loaded, ("loaded", AtomicString::ConstructFromLiteral));
182 return (!m_loadingFonts.isEmpty() || hasLoadedFonts()) ? loading : loaded;
185 void FontFaceSet::handlePendingEventsAndPromisesSoon()
187 // m_asyncRunner will be automatically stopped on destruction.
188 m_asyncRunner.runAsync();
191 void FontFaceSet::didLayout()
193 if (document()->frame()->isMainFrame() && m_loadingFonts.isEmpty())
194 m_histogram.record();
195 if (!m_loadingFonts.isEmpty() || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
197 handlePendingEventsAndPromisesSoon();
200 void FontFaceSet::handlePendingEventsAndPromises()
203 fireDoneEventIfPossible();
206 void FontFaceSet::fireLoadingEvent()
208 if (m_shouldFireLoadingEvent) {
209 m_shouldFireLoadingEvent = false;
210 dispatchEvent(FontFaceSetLoadEvent::createForFontFaces(EventTypeNames::loading));
214 void FontFaceSet::suspend()
216 m_asyncRunner.suspend();
219 void FontFaceSet::resume()
221 m_asyncRunner.resume();
224 void FontFaceSet::stop()
226 m_asyncRunner.stop();
229 void FontFaceSet::beginFontLoading(FontFace* fontFace)
231 m_histogram.incrementCount();
232 addToLoadingFonts(fontFace);
235 void FontFaceSet::fontLoaded(FontFace* fontFace)
237 m_histogram.updateStatus(fontFace);
238 m_loadedFonts.append(fontFace);
239 removeFromLoadingFonts(fontFace);
242 void FontFaceSet::loadError(FontFace* fontFace)
244 m_histogram.updateStatus(fontFace);
245 m_failedFonts.append(fontFace);
246 removeFromLoadingFonts(fontFace);
249 void FontFaceSet::addToLoadingFonts(PassRefPtrWillBeRawPtr<FontFace> fontFace)
251 if (m_loadingFonts.isEmpty() && !hasLoadedFonts()) {
252 m_shouldFireLoadingEvent = true;
253 handlePendingEventsAndPromisesSoon();
255 m_loadingFonts.add(fontFace);
258 void FontFaceSet::removeFromLoadingFonts(PassRefPtrWillBeRawPtr<FontFace> fontFace)
260 m_loadingFonts.remove(fontFace);
261 if (m_loadingFonts.isEmpty())
262 handlePendingEventsAndPromisesSoon();
265 ScriptPromise FontFaceSet::ready(ScriptState* scriptState)
267 if (!inActiveDocumentContext())
268 return ScriptPromise();
269 OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(scriptState);
270 ScriptPromise promise = resolver->promise();
271 m_readyResolvers.append(resolver.release());
272 handlePendingEventsAndPromisesSoon();
276 void FontFaceSet::add(FontFace* fontFace, ExceptionState& exceptionState)
278 if (!inActiveDocumentContext())
281 exceptionState.throwTypeError("The argument is not a FontFace.");
284 if (m_nonCSSConnectedFaces.contains(fontFace))
286 if (isCSSConnectedFontFace(fontFace)) {
287 exceptionState.throwDOMException(InvalidModificationError, "Cannot add a CSS-connected FontFace.");
290 CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
291 m_nonCSSConnectedFaces.add(fontFace);
292 fontSelector->fontFaceCache()->addFontFace(fontSelector, fontFace, false);
293 if (fontFace->loadStatus() == FontFace::Loading)
294 addToLoadingFonts(fontFace);
295 fontSelector->fontFaceInvalidated();
298 void FontFaceSet::clear()
300 if (!inActiveDocumentContext() || m_nonCSSConnectedFaces.isEmpty())
302 CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
303 FontFaceCache* fontFaceCache = fontSelector->fontFaceCache();
304 for (WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >::iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it) {
305 fontFaceCache->removeFontFace(it->get(), false);
306 if ((*it)->loadStatus() == FontFace::Loading)
307 removeFromLoadingFonts(*it);
309 m_nonCSSConnectedFaces.clear();
310 fontSelector->fontFaceInvalidated();
313 bool FontFaceSet::remove(FontFace* fontFace, ExceptionState& exceptionState)
315 if (!inActiveDocumentContext())
318 exceptionState.throwTypeError("The argument is not a FontFace.");
321 WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >::iterator it = m_nonCSSConnectedFaces.find(fontFace);
322 if (it != m_nonCSSConnectedFaces.end()) {
323 m_nonCSSConnectedFaces.remove(it);
324 CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
325 fontSelector->fontFaceCache()->removeFontFace(fontFace, false);
326 if (fontFace->loadStatus() == FontFace::Loading)
327 removeFromLoadingFonts(fontFace);
328 fontSelector->fontFaceInvalidated();
331 if (isCSSConnectedFontFace(fontFace))
332 exceptionState.throwDOMException(InvalidModificationError, "Cannot delete a CSS-connected FontFace.");
336 bool FontFaceSet::has(FontFace* fontFace, ExceptionState& exceptionState) const
338 if (!inActiveDocumentContext())
341 exceptionState.throwTypeError("The argument is not a FontFace.");
344 return m_nonCSSConnectedFaces.contains(fontFace) || isCSSConnectedFontFace(fontFace);
347 const WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >& FontFaceSet::cssConnectedFontFaceList() const
349 Document* d = document();
350 d->ensureStyleResolver(); // Flush pending style changes.
351 return d->styleEngine()->fontSelector()->fontFaceCache()->cssConnectedFontFaces();
354 bool FontFaceSet::isCSSConnectedFontFace(FontFace* fontFace) const
356 return cssConnectedFontFaceList().contains(fontFace);
359 void FontFaceSet::forEach(FontFaceSetForEachCallback* callback, const ScriptValue& thisArg) const
361 forEachInternal(callback, &thisArg);
364 void FontFaceSet::forEach(FontFaceSetForEachCallback* callback) const
366 forEachInternal(callback, 0);
369 void FontFaceSet::forEachInternal(FontFaceSetForEachCallback* callback, const ScriptValue* thisArg) const
371 if (!inActiveDocumentContext())
373 const WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >& cssConnectedFaces = cssConnectedFontFaceList();
374 WillBeHeapVector<RefPtrWillBeMember<FontFace> > fontFaces;
375 fontFaces.reserveInitialCapacity(cssConnectedFaces.size() + m_nonCSSConnectedFaces.size());
376 for (WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >::const_iterator it = cssConnectedFaces.begin(); it != cssConnectedFaces.end(); ++it)
377 fontFaces.append(*it);
378 for (WillBeHeapListHashSet<RefPtrWillBeMember<FontFace> >::const_iterator it = m_nonCSSConnectedFaces.begin(); it != m_nonCSSConnectedFaces.end(); ++it)
379 fontFaces.append(*it);
381 for (size_t i = 0; i < fontFaces.size(); ++i) {
382 FontFace* face = fontFaces[i].get();
384 callback->handleItem(*thisArg, face, face, const_cast<FontFaceSet*>(this));
386 callback->handleItem(face, face, const_cast<FontFaceSet*>(this));
390 unsigned long FontFaceSet::size() const
392 if (!inActiveDocumentContext())
393 return m_nonCSSConnectedFaces.size();
394 return cssConnectedFontFaceList().size() + m_nonCSSConnectedFaces.size();
397 void FontFaceSet::fireDoneEventIfPossible()
399 if (m_shouldFireLoadingEvent)
401 if (!m_loadingFonts.isEmpty() || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
404 // If the layout was invalidated in between when we thought layout
405 // was updated and when we're ready to fire the event, just wait
406 // until after the next layout before firing events.
407 Document* d = document();
408 if (!d->view() || d->view()->needsLayout())
411 if (hasLoadedFonts()) {
412 RefPtrWillBeRawPtr<FontFaceSetLoadEvent> doneEvent = nullptr;
413 RefPtrWillBeRawPtr<FontFaceSetLoadEvent> errorEvent = nullptr;
414 doneEvent = FontFaceSetLoadEvent::createForFontFaces(EventTypeNames::loadingdone, m_loadedFonts);
415 m_loadedFonts.clear();
416 if (!m_failedFonts.isEmpty()) {
417 errorEvent = FontFaceSetLoadEvent::createForFontFaces(EventTypeNames::loadingerror, m_failedFonts);
418 m_failedFonts.clear();
420 dispatchEvent(doneEvent);
422 dispatchEvent(errorEvent);
425 if (!m_readyResolvers.isEmpty()) {
426 Vector<OwnPtr<FontsReadyPromiseResolver> > resolvers;
427 m_readyResolvers.swap(resolvers);
428 for (size_t index = 0; index < resolvers.size(); ++index)
429 resolvers[index]->resolve(this);
433 ScriptPromise FontFaceSet::load(ScriptState* scriptState, const String& fontString, const String& text)
435 if (!inActiveDocumentContext())
436 return ScriptPromise();
439 if (!resolveFontStyle(fontString, font)) {
440 RefPtr<ScriptPromiseResolver> resolver = ScriptPromiseResolver::create(scriptState);
441 ScriptPromise promise = resolver->promise();
442 resolver->reject(DOMException::create(SyntaxError, "Could not resolve '" + fontString + "' as a font."));
446 FontFaceCache* fontFaceCache = document()->styleEngine()->fontSelector()->fontFaceCache();
448 for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
449 CSSSegmentedFontFace* segmentedFontFace = fontFaceCache->get(font.fontDescription(), f->family());
450 if (segmentedFontFace)
451 segmentedFontFace->match(text, faces);
454 RefPtrWillBeRawPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(faces, scriptState);
455 ScriptPromise promise = resolver->promise();
456 resolver->loadFonts(executionContext()); // After this, resolver->promise() may return null.
460 bool FontFaceSet::check(const String& fontString, const String& text, ExceptionState& exceptionState)
462 if (!inActiveDocumentContext())
466 if (!resolveFontStyle(fontString, font)) {
467 exceptionState.throwDOMException(SyntaxError, "Could not resolve '" + fontString + "' as a font.");
471 CSSFontSelector* fontSelector = document()->styleEngine()->fontSelector();
472 FontFaceCache* fontFaceCache = fontSelector->fontFaceCache();
474 bool hasLoadedFaces = false;
475 for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
476 CSSSegmentedFontFace* face = fontFaceCache->get(font.fontDescription(), f->family());
478 if (!face->checkFont(text))
480 hasLoadedFaces = true;
485 for (const FontFamily* f = &font.fontDescription().family(); f; f = f->next()) {
486 if (fontSelector->isPlatformFontAvailable(font.fontDescription(), f->family()))
492 bool FontFaceSet::resolveFontStyle(const String& fontString, Font& font)
494 if (fontString.isEmpty())
497 // Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
498 RefPtrWillBeRawPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
499 CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
500 if (parsedStyle->isEmpty())
503 String fontValue = parsedStyle->getPropertyValue(CSSPropertyFont);
504 if (fontValue == "inherit" || fontValue == "initial")
507 RefPtr<RenderStyle> style = RenderStyle::create();
509 FontFamily fontFamily;
510 fontFamily.setFamily(defaultFontFamily);
512 FontDescription defaultFontDescription;
513 defaultFontDescription.setFamily(fontFamily);
514 defaultFontDescription.setSpecifiedSize(defaultFontSize);
515 defaultFontDescription.setComputedSize(defaultFontSize);
517 style->setFontDescription(defaultFontDescription);
519 style->font().update(style->font().fontSelector());
521 // Now map the font property longhands into the style.
522 CSSPropertyValue properties[] = {
523 CSSPropertyValue(CSSPropertyFontFamily, *parsedStyle),
524 CSSPropertyValue(CSSPropertyFontStretch, *parsedStyle),
525 CSSPropertyValue(CSSPropertyFontStyle, *parsedStyle),
526 CSSPropertyValue(CSSPropertyFontVariant, *parsedStyle),
527 CSSPropertyValue(CSSPropertyFontWeight, *parsedStyle),
528 CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
529 CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
531 StyleResolver& styleResolver = document()->ensureStyleResolver();
532 styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
534 font = style->font();
535 font.update(document()->styleEngine()->fontSelector());
539 void FontFaceSet::FontLoadHistogram::updateStatus(FontFace* fontFace)
541 if (m_status == Reported)
543 if (fontFace->hadBlankText())
544 m_status = HadBlankText;
545 else if (m_status == NoWebFonts)
546 m_status = DidNotHaveBlankText;
549 void FontFaceSet::FontLoadHistogram::record()
553 blink::Platform::current()->histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
555 if (m_status == HadBlankText || m_status == DidNotHaveBlankText) {
556 blink::Platform::current()->histogramEnumeration("WebFont.HadBlankText", m_status == HadBlankText ? 1 : 0, 2);
561 static const char* supplementName()
563 return "FontFaceSet";
566 PassRefPtrWillBeRawPtr<FontFaceSet> FontFaceSet::from(Document& document)
568 RefPtrWillBeRawPtr<FontFaceSet> fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName()));
570 fonts = FontFaceSet::create(document);
571 SupplementType::provideTo(document, supplementName(), fonts);
574 return fonts.release();
577 void FontFaceSet::didLayout(Document& document)
579 if (FontFaceSet* fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName())))
584 void FontFaceSet::trace(Visitor* visitor)
586 visitor->trace(m_loadingFonts);
587 visitor->trace(m_loadedFonts);
588 visitor->trace(m_failedFonts);
589 visitor->trace(m_nonCSSConnectedFaces);
590 DocumentSupplement::trace(visitor);
591 EventTargetWithInlineData::trace(visitor);