/*
 * Copyright (C) 2007, 2008, 2010, 2011 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "CSSFontFaceSource.h"

#include "CachedFont.h"
#include "CSSFontFace.h"
#include "CSSFontSelector.h"
#include "CachedResourceLoader.h"
#include "Document.h"
#include "Font.h"
#include "FontCache.h"
#include "FontDescription.h"
#include "SimpleFontData.h"
#include "SVGToOTFFontConversion.h"

#if ENABLE(SVG_FONTS)
#include "CachedSVGFont.h"
#include "FontCustomPlatformData.h"
#include "SVGFontData.h"
#include "SVGFontElement.h"
#include "SVGFontFaceElement.h"
#include "SVGNames.h"
#include "SVGURIReference.h"
#endif

namespace WebCore {

inline void CSSFontFaceSource::setStatus(Status newStatus)
{
    switch (newStatus) {
    case Pending:
        ASSERT_NOT_REACHED();
        break;
    case Loading:
        ASSERT(status() == Pending);
        break;
    case Success:
        ASSERT(status() == Loading);
        break;
    case Failure:
        ASSERT(status() == Loading);
        break;
    }
    m_status = newStatus;
}

CSSFontFaceSource::CSSFontFaceSource(CSSFontFace* owner, const String& familyNameOrURI, CachedFont* font, SVGFontFaceElement* fontFace)
    : m_familyNameOrURI(familyNameOrURI)
    , m_font(font)
    , m_face(owner)
#if ENABLE(SVG_FONTS) || ENABLE(SVG_OTF_CONVERTER)
	, m_svgFontFaceElement(fontFace ? makeWeakPtr(fontFace) : WeakPtr<SVGFontFaceElement>())
#endif
	, m_status(Pending)
#if ENABLE(SVG_FONTS)
    , m_hasSVGFontFaceElement(m_svgFontFaceElement)
#endif
{
#if !(ENABLE(SVG_FONTS) || ENABLE(SVG_OTF_CONVERTER))
    UNUSED_PARAM(fontFace);
#endif

    // This may synchronously call fontLoaded().
    if (m_font)
        m_font->addClient(this);

    if (status() == Pending && (!m_font || m_font->isLoaded())) {
        setStatus(Loading);
        if (m_font && m_font->errorOccurred())
            setStatus(Failure);
        else
            setStatus(Success);
    }
}

CSSFontFaceSource::~CSSFontFaceSource()
{
    if (m_font)
        m_font->removeClient(this);
}

void CSSFontFaceSource::fontLoaded(CachedFont* loadedFont)
{
    ASSERT_UNUSED(loadedFont, loadedFont == m_font.get());

    RefPtr<CSSFontFace> protectedFace(m_face);

    // If the font is in the cache, this will be synchronously called from CachedFont::addClient().
    if (m_status == Pending)
        setStatus(Loading);
    else if (m_status == Failure) {
        // This function may be called twice if loading was cancelled.
        ASSERT(m_font->errorOccurred());
        return;
    }

    if (m_font->errorOccurred() || !m_font->ensureCustomFontData(m_familyNameOrURI))
        setStatus(Failure);
    else
        setStatus(Success);

    m_face->fontLoaded(this);
}

void CSSFontFaceSource::load(CSSFontSelector* fontSelector)
{
    setStatus(Loading);

    fontSelector->beginLoadingFontSoon(m_font.get());
}

RefPtr<SimpleFontData> CSSFontFaceSource::font(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic)
{
    ASSERT(status() == Status::Success);

#if ENABLE(SVG_FONTS)
    bool usesInDocumentSVGFont = m_hasSVGFontFaceElement;
#else
    bool usesInDocumentSVGFont = false;
#endif

    if (!m_font && !usesInDocumentSVGFont) {
        // We're local. Just return a SimpleFontData from the normal cache.
        return fontCache().fontForFamily(fontDescription, m_familyNameOrURI);
    }

	if (m_font) {
        auto success = m_font->ensureCustomFontData(m_familyNameOrURI);
        ASSERT_UNUSED(success, success);

        ASSERT(status() == Status::Success);
        RefPtr<SimpleFontData> result = m_font->getFontData(fontDescription, m_familyNameOrURI, syntheticBold, syntheticItalic);
        ASSERT(result);
        return result.release();
	}

    if (!usesInDocumentSVGFont)
        return nullptr;

#if ENABLE(SVG_FONTS)
#if ENABLE(SVG_OTF_CONVERTER)
	if (!m_svgFontFaceElement || !isSVGFontElement(m_svgFontFaceElement->parentNode()))
		return nullptr;
    if (!m_inDocumentCustomPlatformData) {
		SVGFontElement& fontElement = *toSVGFontElement(m_svgFontFaceElement->parentNode());
		if (auto otfFont = convertSVGToOTFFont(fontElement))
			m_generatedOTFBuffer = SharedBuffer::adoptVector(otfFont.value());
		if (!m_generatedOTFBuffer)
			return nullptr;
		m_inDocumentCustomPlatformData = adoptPtr(createFontCustomPlatformData(*m_generatedOTFBuffer));
    }
	if (!m_inDocumentCustomPlatformData)
		return nullptr;
#if PLATFORM(COCOA)
	return Font::create(m_inDocumentCustomPlatformData->fontPlatformData(fontDescription, syntheticBold, syntheticItalic, fontFaceFeatures, fontFaceVariantSettings), true, false);
#else
	return m_inDocumentCustomPlatformData->fontPlatformData(fontDescription, syntheticBold, syntheticItalic, fontDescription.orientation());
#endif
#else
    if (!m_svgFontFaceElement)
        return nullptr;
	return SimpleFontData::create(SVGFontData::create(m_svgFontFaceElement.get()), fontDescription, syntheticBold, syntheticItalic);
#endif
#endif

    ASSERT_NOT_REACHED();
    return nullptr;
}

#if ENABLE(SVG_FONTS)
bool CSSFontFaceSource::isSVGFontFaceSource() const
{
    return m_hasSVGFontFaceElement || (m_font.get() && m_font.get()->type() == CachedResource::SVGFontResource);
}
#endif

}
