/*
 * (C) 1999-2003 Lars Knoll (knoll@kde.org)
 * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
 *
 * 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.
 */

#pragma once

#include "CSSPropertyNames.h"
#include "CSSUnits.h"
#include "CSSValue.h"
#include "CSSValueKeywords.h"
#include "Color.h"
#include "LayoutTypes.h"
#include <wtf/Forward.h>
#include <wtf/HashSet.h>
#include <wtf/MathExtras.h>
#include <wtf/PassRefPtr.h>

namespace WebCore {

class CSSBasicShape;
class CSSCalcValue;
class CSSToLengthConversionData;
class Counter;
class DashboardRegion;
class DeprecatedCSSOMPrimitiveValue;
class FontDescription;
class FontMetrics;
class Pair;
class Quad;
class RGBColor;
class Rect;
class RenderStyle;
class RenderView;

struct CSSFontFamily;
struct Length;
struct LengthSize;

// Max/min values for CSS, needs to slightly smaller/larger than the true max/min values to allow for rounding without overflowing.
// Subtract two (rather than one) to allow for values to be converted to float and back without exceeding the LayoutUnit::max.
const int maxValueForCssLength = intMaxForLayoutUnit - 2;
const int minValueForCssLength = intMinForLayoutUnit + 2;

// Dimension calculations are imprecise, often resulting in values of e.g.
// 44.99998. We need to go ahead and round if we're really close to the next
// integer value.
template<typename T> inline T roundForImpreciseConversion(double value)
{
    value += (value < 0) ? -0.01 : +0.01;
    return ((value > std::numeric_limits<T>::max()) || (value < std::numeric_limits<T>::min())) ? 0 : static_cast<T>(value);
}

template<> inline float roundForImpreciseConversion(double value)
{
    double ceiledValue = ceil(value);
    double proximityToNextInt = ceiledValue - value;
    if (proximityToNextInt <= 0.01 && value > 0)
        return static_cast<float>(ceiledValue);
    if (proximityToNextInt >= 0.99 && value < 0)
        return static_cast<float>(floor(value));
    return static_cast<float>(value);
}

class CSSPrimitiveValue : public CSSValue {
public:
    static constexpr bool isLength(CSSUnitType);

    // FIXME: Some of these use primitiveUnitType() and some use primitiveType(). Many that use primitiveUnitType() are likely broken with calc().
	bool isAngle() const { return unitCategory(primitiveType()) == CSSUnitCategory::Angle; }
    bool isAttr() const { return primitiveUnitType() == CSSUnitType::CSS_ATTR; }
    bool isCounter() const { return primitiveUnitType() == CSSUnitType::CSS_COUNTER; }
    bool isFontIndependentLength() const { return isFontIndependentLength(primitiveUnitType()); }
	bool isFontRelativeLength() const { return isFontRelativeLength(primitiveUnitType()); }
    bool isParentFontRelativeLength() const { return isPercentage() || (isFontRelativeLength() && primitiveType() != CSSUnitType::CSS_REMS && primitiveType() != CSSUnitType::CSS_RLHS); }
	bool isQuirkyEms() const { return primitiveType() == CSSUnitType::CSS_QUIRKY_EMS; }
    bool isViewportPercentageLength() const { return isViewportPercentageLength(primitiveUnitType()); }
    bool isLength() const { return isLength(primitiveType()); }
    bool isNumber() const { return primitiveType() == CSSUnitType::CSS_NUMBER; }
    bool isPercentage() const { return primitiveType() == CSSUnitType::CSS_PERCENTAGE; }
    bool isPx() const { return primitiveType() == CSSUnitType::CSS_PX; }
    bool isRect() const { return primitiveUnitType() == CSSUnitType::CSS_RECT; }
    bool isPair() const { return primitiveUnitType() == CSSUnitType::CSS_PAIR; }
    bool isPropertyID() const { return primitiveUnitType() == CSSUnitType::CSS_PROPERTY_ID; }
    bool isRGBColor() const { return primitiveUnitType() == CSSUnitType::CSS_RGBCOLOR; }
    bool isShape() const { return primitiveUnitType() == CSSUnitType::CSS_SHAPE; }
    bool isString() const { return primitiveUnitType() == CSSUnitType::CSS_STRING; }
    bool isFontFamily() const { return primitiveUnitType() == CSSUnitType::CSS_FONT_FAMILY; }
    bool isTime() const { return unitCategory(primitiveUnitType()) == CSSUnitCategory::Time; }
	bool isFrequency() const { return unitCategory(primitiveType()) == CSSUnitCategory::Frequency; }
	bool isURI() const { return primitiveUnitType() == CSSUnitType::CSS_URI; }
    bool isCalculated() const { return primitiveUnitType() == CSSUnitType::CSS_CALC; }
    bool isCalculatedPercentageWithNumber() const { return primitiveType() == CSSUnitType::CSS_CALC_PERCENTAGE_WITH_NUMBER; }
    bool isCalculatedPercentageWithLength() const { return primitiveType() == CSSUnitType::CSS_CALC_PERCENTAGE_WITH_LENGTH; }
    bool isDotsPerInch() const { return primitiveType() == CSSUnitType::CSS_DPI; }
	bool isDotsPerPixel() const { return primitiveType() == CSSUnitType::CSS_DPPX; }
	bool isDotsPerCentimeter() const { return primitiveType() == CSSUnitType::CSS_DPCM; }
	bool isX() const { return primitiveType() == CSSUnitType::CSS_X; }
	bool isResolution() const { return unitCategory(primitiveType()) == CSSUnitCategory::Resolution; }
	bool isViewportPercentageWidth() const { return primitiveUnitType() == CSSUnitType::CSS_VW; }
    bool isViewportPercentageHeight() const { return primitiveUnitType() == CSSUnitType::CSS_VH; }
    bool isViewportPercentageMax() const { return primitiveUnitType() == CSSUnitType::CSS_VMAX; }
    bool isViewportPercentageMin() const { return primitiveUnitType() == CSSUnitType::CSS_VMIN; }
    bool isValueID() const { return primitiveUnitType() == CSSUnitType::CSS_VALUE_ID; }
    bool isFlex() const { return primitiveType() == CSSUnitType::CSS_FR; }
    bool isCustomIdent() const { return primitiveUnitType() == CSSUnitType::CustomIdent; }

    bool isInitialValue() const { return valueID() == CSSValueInitial; }
    bool isImplicitInitialValue() const { return isInitialValue() && m_isImplicit; }
    bool isInheritValue() const { return valueID() == CSSValueInherit; }
    bool isUnsetValue() const { return valueID() == CSSValueUnset; }
    bool isRevertValue() const { return valueID() == CSSValueRevert; }
    bool isCSSWideKeyword() const;

    static Ref<CSSPrimitiveValue> createIdentifier(CSSValueID valueID) { return adoptRef(*new CSSPrimitiveValue(valueID)); }
    static Ref<CSSPrimitiveValue> createIdentifier(CSSPropertyID propertyID) { return adoptRef(*new CSSPrimitiveValue(propertyID)); }

    static Ref<CSSPrimitiveValue> createColor(const Color& color) { return adoptRef(*new CSSPrimitiveValue(color)); }
    static Ref<CSSPrimitiveValue> create(double value, CSSUnitType type) { return adoptRef(*new CSSPrimitiveValue(value, type)); }
    static Ref<CSSPrimitiveValue> create(const String& value, CSSUnitType type) { return adoptRef(*new CSSPrimitiveValue(value, type)); }
    static Ref<CSSPrimitiveValue> create(const Length& value, const RenderStyle* style) { return adoptRef(*new CSSPrimitiveValue(value, style)); }
    static Ref<CSSPrimitiveValue> create(const LengthSize& value, const RenderStyle* style) { return adoptRef(*new CSSPrimitiveValue(value, style)); }

    static Ref<CSSPrimitiveValue> create(const String& value) WTF_DELETED_FUNCTION;

    template<typename T> static ALWAYS_INLINE Ref<CSSPrimitiveValue> create(T&& value)
    {
        return adoptRef(*new CSSPrimitiveValue(std::forward<T>(value)));
    }

    template<typename T> static Ref<CSSPrimitiveValue> create(T&&, CSSPropertyID);

    // This value is used to handle quirky margins in reflow roots (body, td, and th) like WinIE.
    // The basic idea is that a stylesheet can use the value __qem (for quirky em) instead of em.
    // When the quirky value is used, if you're in quirks mode, the margin will collapse away
    // inside a table cell.
    static Ref<CSSPrimitiveValue> createAllowingMarginQuirk(double value, CSSUnitType type)
    {
    	Ref<CSSPrimitiveValue> quirkValue = adoptRef(*new CSSPrimitiveValue(value, type));
        quirkValue->m_isQuirkValue = true;
        return quirkValue;
    }

    ~CSSPrimitiveValue();

    void cleanup();

    CSSUnitType primitiveType() const;
    float getFloatValue(CSSUnitType type, ExceptionCode& ec) const;

    double computeDegrees() const;

    enum TimeUnit { Seconds, Milliseconds };
    template <typename T, TimeUnit timeUnit> T computeTime()
    {
        if (timeUnit == Seconds && primitiveType() == CSSUnitType::CSS_S)
            return getValue<T>();
        if (timeUnit == Seconds && primitiveType() == CSSUnitType::CSS_MS)
            return getValue<T>() / 1000;
        if (timeUnit == Milliseconds && primitiveType() == CSSUnitType::CSS_MS)
            return getValue<T>();
        if (timeUnit == Milliseconds && primitiveType() == CSSUnitType::CSS_S)
            return getValue<T>() * 1000;
        ASSERT_NOT_REACHED();
        return 0;
    }

    /*
     * computes a length in pixels out of the given CSSValue. Need the RenderStyle to get
     * the fontinfo in case val is defined in em or ex.
     *
     * The metrics have to be a bit different for screen and printer output.
     * For screen output we assume 1 inch == 72 px, for printer we assume 300 dpi
     *
     * this is screen/printer dependent, so we probably need a config option for this,
     * and some tool to calibrate.
     */
    template<typename T> T computeLength(const CSSToLengthConversionData&) const;

    // Converts to a Length, mapping various unit types appropriately.
    template<int> Length convertToLength(const CSSToLengthConversionData&) const;

    bool convertingToLengthRequiresNonNullStyle(int lengthConversion) const;

    CSSUnitType primitiveUnitType() const { return m_primitiveUnitType; }
	void setPrimitiveUnitType(CSSUnitType type) { m_primitiveUnitType = type; }

    double doubleValue(CSSUnitType type) const;

    // It's usually wrong to call this; it can trigger type conversion in calc without sufficient context to resolve relative length units.
    double doubleValue() const;

    // These return nullopt for calc, for which range checking is not done at parse time: <https://www.w3.org/TR/css3-values/#calc-range>.
    Optional<bool> isZero() const;
    Optional<bool> isPositive() const;
    Optional<bool> isNegative() const;

    float floatValue(CSSUnitType type) const { return getValue<float>(type); }
    float floatValue() const { return getValue<float>(); }

    int intValue(CSSUnitType type) const { return getValue<int>(type); }
    int intValue() const { return getValue<int>(); }

    WEBCORE_EXPORT String stringValue() const;

    template<typename T> inline T getValue(CSSUnitType type) const { return clampTo<T>(doubleValue(type)); }
    template<typename T> inline T getValue() const { return clampTo<T>(doubleValue()); }

    Counter* getCounterValue(ExceptionCode&) const;

    Rect* getRectValue(ExceptionCode&) const;

    Quad* getQuadValue(ExceptionCode&) const;

    PassRefPtr<RGBColor> getRGBColorValue(ExceptionCode&) const;
    RGBA32 getRGBA32Value() const { return primitiveUnitType() != CSSUnitType::CSS_RGBCOLOR ? 0 : m_value.rgbcolor; }
    Color color() const { return primitiveUnitType() != CSSUnitType::CSS_RGBCOLOR ? Color() : Color(m_value.rgbcolor); }

    Pair* getPairValue(ExceptionCode&) const;

#if ENABLE(DASHBOARD_SUPPORT) || ENABLE(WIDGET_REGION)
    DashboardRegion* getDashboardRegionValue() const { return primitiveUnitType() != CSSUnitType::CSS_DASHBOARD_REGION ? 0 : m_value.region; }
#endif

    Counter* counterValue() const { return primitiveUnitType() != CSSUnitType::CSS_COUNTER ? 0 : m_value.counter; }
    const CSSFontFamily& fontFamily() const { ASSERT(primitiveUnitType() == CSSUnitType::CSS_FONT_FAMILY); return *m_value.fontFamily; }
    CSSCalcValue* cssCalcValue() const { return primitiveUnitType() != CSSUnitType::CSS_CALC ? 0 : m_value.calc; }
    Pair* pairValue() const { return primitiveUnitType() != CSSUnitType::CSS_PAIR ? 0 : m_value.pair; }
    Quad* quadValue() const { return primitiveUnitType() != CSSUnitType::CSS_QUAD ? 0 : m_value.quad; }
    Rect* rectValue() const { return primitiveUnitType() != CSSUnitType::CSS_RECT ? 0 : m_value.rect; }
    CSSBasicShape* shapeValue() const { return primitiveUnitType() != CSSUnitType::CSS_SHAPE ? 0 : m_value.shape; }

    CSSPropertyID propertyID() const { return primitiveUnitType() == CSSUnitType::CSS_PROPERTY_ID ? m_value.propertyID : CSSPropertyInvalid; }

    ALWAYS_INLINE CSSPropertyID getPropertyID() const { return propertyID(); }
    CSSValueID getValueID() const { return primitiveUnitType() == CSSUnitType::CSS_VALUE_ID ? m_value.valueID : CSSValueInvalid; }
    CSSValueID valueID() const { return primitiveUnitType() == CSSUnitType::CSS_VALUE_ID ? m_value.valueID : CSSValueInvalid; }

    template<typename T> ALWAYS_INLINE operator T() const; // Defined in CSSPrimitiveValueMappings.h

    String customCSSText() const;

    // FIXME-NEWPARSER: Can ditch the boolean and just use the unit type once old parser is gone.
    bool isQuirkValue() const { return m_isQuirkValue || primitiveType() == CSSUnitType::CSS_QUIRKY_EMS; }

    bool equals(const CSSPrimitiveValue&) const;

    static double conversionToCanonicalUnitsScaleFactor(CSSUnitType type);

    static String unitTypeString(CSSUnitType);

    static double computeUnzoomedNonCalcLengthDouble(CSSUnitType, double value, CSSPropertyID, const FontMetrics* = nullptr, const FontDescription* = nullptr, const FontDescription* rootFontDescription = nullptr, const RenderView* = nullptr);
	static double computeNonCalcLengthDouble(const CSSToLengthConversionData&, CSSUnitType, double value);
	// True if computeNonCalcLengthDouble would produce identical results when resolved against both these styles.
	static bool equalForLengthResolution(const RenderStyle&, const RenderStyle&);

    Ref<DeprecatedCSSOMPrimitiveValue> createDeprecatedCSSOMPrimitiveWrapper(CSSStyleDeclaration&) const;

    void collectDirectComputationalDependencies(HashSet<CSSPropertyID>&) const;
    void collectDirectRootComputationalDependencies(HashSet<CSSPropertyID>&) const;

private:
    friend class CSSValuePool;

    CSSPrimitiveValue(CSSValueID);
    CSSPrimitiveValue(CSSPropertyID);
    CSSPrimitiveValue(const Color& color);
    CSSPrimitiveValue(const Length&);
    CSSPrimitiveValue(const Length&, const RenderStyle*);
    CSSPrimitiveValue(const LengthSize&, const RenderStyle*);
    CSSPrimitiveValue(const String&, CSSUnitType);
    CSSPrimitiveValue(double, CSSUnitType);

    enum ImplicitInitialValueTag { ImplicitInitialValue };
    CSSPrimitiveValue(ImplicitInitialValueTag);

    template<typename T> ALWAYS_INLINE CSSPrimitiveValue(T); // Defined in CSSPrimitiveValueMappings.h
    template<typename T> ALWAYS_INLINE CSSPrimitiveValue(T, CSSPropertyID); // Defined in CSSPrimitiveValueMappings.h

    template<typename T> CSSPrimitiveValue(Ref<T>&& value)
        : CSSValue(PrimitiveClass)
    {
        init(WTFMove(value));
    }

    template<typename T> CSSPrimitiveValue(PassRefPtr<T> value)
        : CSSValue(PrimitiveClass)
    {
        init(value);
    }

    static void create(int); // compile-time guard
    static void create(unsigned); // compile-time guard
    template<typename T> operator T*(); // compile-time guard

    void init(const Length&);
    void init(const LengthSize&, const RenderStyle*);
    void init(Ref<Counter>&&);
    void init(Ref<Pair>&&);
    void init(PassRefPtr<Rect>);
    void init(PassRefPtr<Pair>);
    void init(PassRefPtr<Quad>);
    void init(PassRefPtr<DashboardRegion>); // FIXME: Dashboard region should not be a primitive value.
    void init(PassRefPtr<CSSBasicShape>);
    void init(PassRefPtr<CSSCalcValue>);
    Optional<double> doubleValueInternal(CSSUnitType targetUnitType) const;

    double computeLengthDouble(const CSSToLengthConversionData&) const;

    String formatNumberForcustomCSSText() const;
    template <unsigned characterCount>
    PassRefPtr<StringImpl> formatNumberValue(const char (&characters)[characterCount]) const;
    NEVER_INLINE PassRefPtr<StringImpl> formatNumberValue(const char* suffix, unsigned suffixLength) const;

    static constexpr bool isFontIndependentLength(CSSUnitType);
    static constexpr bool isFontRelativeLength(CSSUnitType);
    static constexpr bool isResolution(CSSUnitType);
    static constexpr bool isViewportPercentageLength(CSSUnitType);

    union {
        CSSPropertyID propertyID;
        CSSValueID valueID;
        double num;
        StringImpl* string;
        Counter* counter;
        Rect* rect;
        Quad* quad;
        unsigned rgbcolor;
        Pair* pair;
        DashboardRegion* region;
        CSSBasicShape* shape;
        CSSCalcValue* calc;
        CSSFontFamily* fontFamily;
    } m_value;
};

CSS_VALUE_TYPE_CASTS(PrimitiveValue)

inline constexpr bool CSSPrimitiveValue::isFontIndependentLength(CSSUnitType type)
{
    return type == CSSUnitType::CSS_PX
        || type == CSSUnitType::CSS_CM
        || type == CSSUnitType::CSS_MM
        || type == CSSUnitType::CSS_IN
        || type == CSSUnitType::CSS_PT
        || type == CSSUnitType::CSS_PC;
}

inline constexpr bool CSSPrimitiveValue::isFontRelativeLength(CSSUnitType type)
{
    return type == CSSUnitType::CSS_EMS
        || type == CSSUnitType::CSS_EXS
        || type == CSSUnitType::CSS_LHS
        || type == CSSUnitType::CSS_RLHS
        || type == CSSUnitType::CSS_REMS
        || type == CSSUnitType::CSS_CHS
        || type == CSSUnitType::CSS_IC
        || type == CSSUnitType::CSS_QUIRKY_EMS;
}

inline constexpr bool CSSPrimitiveValue::isLength(CSSUnitType type)
{
    return type == CSSUnitType::CSS_EMS
        || type == CSSUnitType::CSS_EXS
        || type == CSSUnitType::CSS_PX
        || type == CSSUnitType::CSS_CM
        || type == CSSUnitType::CSS_MM
        || type == CSSUnitType::CSS_IN
        || type == CSSUnitType::CSS_PT
        || type == CSSUnitType::CSS_PC
        || type == CSSUnitType::CSS_REMS
        || type == CSSUnitType::CSS_CHS
        || type == CSSUnitType::CSS_IC
        || type == CSSUnitType::CSS_Q
        || type == CSSUnitType::CSS_LHS
        || type == CSSUnitType::CSS_RLHS
        || isViewportPercentageLength(type)
        || type == CSSUnitType::CSS_QUIRKY_EMS;
}

inline constexpr bool CSSPrimitiveValue::isResolution(CSSUnitType type)
{
    return type == CSSUnitType::CSS_DPPX
        || type == CSSUnitType::CSS_DPI
        || type == CSSUnitType::CSS_DPCM;
}

inline constexpr bool CSSPrimitiveValue::isViewportPercentageLength(CSSUnitType type)
{
    return type >= CSSUnitType::FirstViewportCSSUnitType && type <= CSSUnitType::LastViewporCSSUnitType;
}

template<> inline int CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return roundForImpreciseConversion<int>(computeLengthDouble(conversionData));
}

template<> inline unsigned CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return roundForImpreciseConversion<unsigned>(computeLengthDouble(conversionData));
}

template<> inline short CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return roundForImpreciseConversion<short>(computeLengthDouble(conversionData));
}

template<> inline unsigned short CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return roundForImpreciseConversion<unsigned short>(computeLengthDouble(conversionData));
}

template<> inline float CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return static_cast<float>(computeLengthDouble(conversionData));
}

template<> inline double CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return computeLengthDouble(conversionData);
}

template<> inline LayoutUnit CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData) const
{
    return LayoutUnit(computeLengthDouble(conversionData));
}

inline CSSPrimitiveValue::CSSPrimitiveValue(CSSValueID valueID)
    : CSSValue(PrimitiveClass)
{
	setPrimitiveUnitType(CSSUnitType::CSS_VALUE_ID);
    m_value.valueID = valueID;
}

inline CSSPrimitiveValue::CSSPrimitiveValue(CSSPropertyID propertyID)
    : CSSValue(PrimitiveClass)
{
	setPrimitiveUnitType(CSSUnitType::CSS_PROPERTY_ID);
    m_value.propertyID = propertyID;
}

inline CSSPrimitiveValue::CSSPrimitiveValue(double num, CSSUnitType type)
    : CSSValue(PrimitiveClass)
{
	setPrimitiveUnitType(type);
    ASSERT(isfinite(num));
    m_value.num = num;
}

template<typename T> inline Ref<CSSPrimitiveValue> CSSPrimitiveValue::create(T&& value, CSSPropertyID propertyID)
{
    return adoptRef(*new CSSPrimitiveValue(std::forward<T>(value), propertyID));
}

} // namespace WebCore
