/*
 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "config.h"
#include "FontCustomPlatformData.h"

#include "FontPlatformData.h"
#include "SharedBuffer.h"
#include "WOFFFileFormat.h"
#include "WOFF2FileFormat.h"

#include <ft2build.h>

namespace WebCore {

DLL_PUBLIC int gFontCustomPlatformDataCount;

FontCustomPlatformData::~FontCustomPlatformData()
{
    m_buffer->deref();
    --gFontCustomPlatformDataCount;
}

FontCustomPlatformData::FontCustomPlatformData(SharedBuffer* buffer)
    : m_buffer(buffer)
{
    m_buffer->ref();
    ++gFontCustomPlatformDataCount;
}

FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic,
        FontOrientation, FontWidthVariant, FontRenderingMode)
{
    return FontPlatformData(m_buffer, size, bold, italic);
}

FontCustomPlatformData* createFontCustomPlatformData(SharedBuffer* buffer)
{
    ASSERT_ARG(buffer, buffer);

    RefPtr<SharedBuffer> sfntBuffer;
    if (isWOFF(buffer)) {
        Vector<char> sfnt;
        if (!convertWOFFToSfnt(buffer, sfnt))
            return 0;

        sfntBuffer = SharedBuffer::adoptVector(sfnt);
        buffer = sfntBuffer.get();
    }
    else if (isWOFF2(buffer)) {
		Vector<char> sfnt;
		if (!convertWOFF2ToSfnt(buffer, sfnt))
			return 0;

		sfntBuffer = SharedBuffer::adoptVector(sfnt);
		buffer = sfntBuffer.get();
	}

    static FT_Library library = 0;
    if (!library && FT_Init_FreeType(&library)) {
        library = 0;
        return 0;
    }

    // we only open the face to verify that it is valid. this might
    // be unnecessary; we just want to match the behaviour of cairo.
    FT_Face freeTypeFace;
    if (FT_New_Memory_Face(library, reinterpret_cast<const FT_Byte*>(buffer->data()), buffer->size(), 0, &freeTypeFace))
        return 0;
    FT_Done_Face(freeTypeFace);

    return new FontCustomPlatformData(buffer);
}

bool FontCustomPlatformData::supportsFormat(const String& format)
{
    return
    	equalIgnoringCase(format, ASCIILiteral("truetype")) ||
		equalIgnoringCase(format, ASCIILiteral("opentype")) ||
		equalIgnoringCase(format, ASCIILiteral("woff")) ||
		equalIgnoringCase(format, ASCIILiteral("woff2"));
}

}
