/*
 * Copyright (C) 2011 Adobe Systems Incorporated. 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 THE COPYRIGHT HOLDER "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 THE COPYRIGHT HOLDER 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.
 */

#pragma once

#include "RenderBlockFlow.h"
#include "RenderFragmentContainer.h"
#include <wtf/HashCountedSet.h>
#include <wtf/ListHashSet.h>
#include <wtf/PassRefPtr.h>
#include <wtf/UnusedParam.h>

namespace WebCore {

class CurrentRenderFragmentContainerMaintainer;
struct LayerFragment;
typedef Vector<LayerFragment, 1> LayerFragments;
class RenderFragmentedFlow;
class RenderStyle;
class RootInlineBox;

typedef ListHashSet<RenderFragmentContainer*> RenderFragmentContainerList;
typedef Vector<RenderLayer*> RenderLayerList;
typedef HashMap<const RootInlineBox*, RenderFragmentContainer*> ContainingRegionMap;

// RenderFragmentedFlow is used to collect all the render objects that participate in a
// flow thread. It will also help in doing the layout. However, it will not render
// directly to screen. Instead, RenderFragmentContainer objects will redirect their paint 
// and nodeAtPoint methods to this object. Each RenderFragmentContainer will actually be a viewPort
// of the RenderFragmentedFlow.

class RenderFragmentedFlow: public RenderBlockFlow {
public:
    explicit RenderFragmentedFlow(Document&, PassOwnPtr<RenderStyle>);
    virtual ~RenderFragmentedFlow() { };

    // Always create a RenderLayer for the RenderFragmentedFlow so that we 
    // can easily avoid drawing the children directly.
    virtual bool requiresLayer() const FINAL { return true; }
    
    virtual void removeFlowChildInfo(RenderElement&);
#ifndef NDEBUG
    bool hasChildInfo(RenderObject* child) const { return child && child->isBox() && m_fragmentRangeMap.contains(toRenderBox(child)); }
#endif

#if !ASSERT_WITH_SECURITY_IMPLICATION_DISABLED
    bool checkLinesConsistency(const RenderBlockFlow&) const;
#endif

    virtual void deleteLines() final;

    virtual void addFragmentToThread(RenderFragmentContainer*) = 0;
    virtual void removeRegionFromThread(RenderFragmentContainer*);
    const RenderFragmentContainerList& renderRegionList() const { return m_fragmentList; }

    virtual void updateLogicalWidth() FINAL;
    virtual LogicalExtentComputedValues computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop) const OVERRIDE;

    bool hasFragments() const { return m_fragmentList.size(); }
    virtual void regionChangedWritingMode(RenderFragmentContainer*) { }

    void invalidateFragments(MarkingBehavior = MarkContainingBlockChain);
    void validateRegions();
    bool hasValidFragmentInfo() const { return !m_regionsInvalidated && !m_fragmentList.isEmpty(); }

    // Called when a descendant box's layout is finished and it has been positioned within its container.
    virtual void fragmentedFlowDescendantBoxLaidOut(RenderBox*) { }

    virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;

    void repaintRectangleInRegions(const LayoutRect&);

    LayoutPoint adjustedPositionRelativeToOffsetParent(const RenderBoxModelObject&, const LayoutPoint&) const;

    LayoutUnit pageLogicalTopForOffset(LayoutUnit) const;
    LayoutUnit pageLogicalWidthForOffset(LayoutUnit) const;
    LayoutUnit pageLogicalHeightForOffset(LayoutUnit) const;
    LayoutUnit pageRemainingLogicalHeightForOffset(LayoutUnit, PageBoundaryRule = IncludePageBoundary) const;

    virtual void setPageBreak(const RenderBlock*, LayoutUnit /*offset*/, LayoutUnit /*spaceShortage*/) { }
    virtual void updateMinimumPageHeight(const RenderBlock*, LayoutUnit /*offset*/, LayoutUnit /*minHeight*/) { }

    virtual RenderFragmentContainer* fragmentAtBlockOffset(const RenderBox*, LayoutUnit, bool extendLastRegion = false) const;

    bool regionsHaveUniformLogicalWidth() const { return m_regionsHaveUniformLogicalWidth; }
    bool regionsHaveUniformLogicalHeight() const { return m_regionsHaveUniformLogicalHeight; }

    virtual RenderFragmentContainer* mapFromFlowToFragment(TransformState&) const;

    void removeRenderBoxFragmentInfo(RenderBox&);
    void logicalWidthChangedInRegionsForBlock(const RenderBlock*, bool&);

    LayoutUnit contentLogicalWidthOfFirstFragment() const;
    LayoutUnit contentLogicalHeightOfFirstFragment() const;
    LayoutUnit contentLogicalLeftOfFirstFragment() const;
    
    RenderFragmentContainer* firstFragment() const;
    RenderFragmentContainer* lastFragment() const;

    virtual void setFragmentRangeForBox(const RenderBox&, RenderFragmentContainer*, RenderFragmentContainer*);
    bool getFragmentRangeForBox(const RenderBox&, RenderFragmentContainer*& startRegion, RenderFragmentContainer*& endRegion) const;
    bool computedFragmentRangeForBox(const RenderBox*, RenderFragmentContainer*& startRegion, RenderFragmentContainer*& endRegion) const;
    bool hasCachedRegionRangeForBox(const RenderBox&) const;

    // Check if the object is in region and the region is part of this flow thread.
    bool objectInFlowFragment(const RenderObject*, const RenderFragmentContainer*) const;

    // Check if the object should be painted in this region and if the region is part of this flow thread.
    bool objectShouldFragmentInFlowRegion(const RenderObject*, const RenderFragmentContainer*) const;

    virtual bool isPageLogicalHeightKnown() const { return true; }
    bool pageLogicalSizeChanged() const { return m_pageLogicalSizeChanged; }

    void markFragmentsForOverflowLayoutIfNeeded();

    virtual bool addForcedFragmentBreak(const RenderBlock*, LayoutUnit, RenderBox& breakChild, bool isBefore, LayoutUnit* offsetBreakAdjustment = 0);
    virtual void applyBreakAfterContent(LayoutUnit) { }

    void collectLayerFragments(LayerFragments&, const LayoutRect& layerBoundingBox, const LayoutRect& dirtyRect);
    LayoutRect fragmentsBoundingBox(const LayoutRect& layerBoundingBox);

    void clearRenderBoxRegionInfoAndCustomStyle(const RenderBox&, const RenderFragmentContainer*, const RenderFragmentContainer*, const RenderFragmentContainer*, const RenderFragmentContainer*);
    LayoutUnit offsetFromLogicalTopOfFirstRegion(const RenderBlock*) const;

    void addRegionsVisualEffectOverflow(const RenderBox&);
    void addRegionsVisualOverflowFromTheme(const RenderBlock&);
    void addRegionsOverflowFromChild(const RenderBox&, const RenderBox&, const LayoutSize&);
    void addRegionsLayoutOverflow(const RenderBox&, const LayoutRect&);
    void addFragmentsVisualOverflow(const RenderBox&, const LayoutRect&);
    void clearRegionsOverflow(const RenderBox&);

    LayoutRect mapFromFragmentedFlowToLocal(const RenderBox*, const LayoutRect&) const;
    LayoutRect mapFromLocalToFragmentedFlow(const RenderBox*, const LayoutRect&) const;

    void flipForWritingModeLocalCoordinates(LayoutRect&) const;

    // Used to estimate the maximum height of the flow thread.
    static LayoutUnit maxLogicalHeight() { return LayoutUnit::max() / 2; }

    bool regionInRange(const RenderFragmentContainer* targetRegion, const RenderFragmentContainer* startRegion, const RenderFragmentContainer* endRegion) const;

    bool absoluteQuadsForBox(Vector<FloatQuad>&, bool*, const RenderBox*) const;

    virtual void layout() OVERRIDE;

    void setCurrentRegionMaintainer(CurrentRenderFragmentContainerMaintainer* currentRegionMaintainer) { m_currentRegionMaintainer = currentRegionMaintainer; }
    RenderFragmentContainer* currentRegion() const;

    ContainingRegionMap& containingRegionMap();

    virtual bool cachedEnclosingFragmentedFlowNeedsUpdate() const OVERRIDE { return false; }

    // FIXME: Eventually as column and region flow threads start nesting, this may end up changing.
    virtual bool shouldCheckColumnBreaks() const { return false; }

protected:

    virtual RenderFragmentedFlow* locateEnclosingFragmentedFlow() const OVERRIDE { return const_cast<RenderFragmentedFlow*>(this); }

    virtual const char* renderName() const = 0;

    // Overridden by columns/pages to set up an initial logical width of the page width even when
    // no regions have been generated yet.
    virtual LayoutUnit initialLogicalWidth() const { return 0; };

    void clearLinesToRegionMap();
    virtual void willBeDestroyed() OVERRIDE;

    virtual void mapLocalToContainer(RenderLayerModelObject* repaintContainer, TransformState&, OptionSet<MapCoordinatesMode>, bool* wasFixed) const OVERRIDE;

    void updateRegionsFlowThreadPortionRect();
    bool shouldRepaint(const LayoutRect&) const;

    bool getFragmentRangeForBoxFromCachedInfo(const RenderBox&, RenderFragmentContainer*& startRegion, RenderFragmentContainer*& endRegion) const;

    void removeLineRegionInfo(const RenderBlockFlow&);

    RenderFragmentContainerList m_fragmentList;

    class RenderRegionRange {
    public:
        RenderRegionRange()
    	: m_rangeInvalidated(true)
        {
        }

        RenderRegionRange(RenderFragmentContainer* start, RenderFragmentContainer* end)
        {
            setRange(start, end);
        }
        
        void setRange(RenderFragmentContainer* start, RenderFragmentContainer* end)
        {
            m_startRegion = makeWeakPtr(start);
            m_endRegion = makeWeakPtr(end);
            m_rangeInvalidated = true;
        }

        RenderFragmentContainer* startRegion() const { return m_startRegion.get(); }
        RenderFragmentContainer* endRegion() const { return m_endRegion.get(); }
        bool rangeInvalidated() const { return m_rangeInvalidated; }
        void clearRangeInvalidated() { m_rangeInvalidated = false; }

    private:
        WeakPtr<RenderFragmentContainer> m_startRegion;
        WeakPtr<RenderFragmentContainer> m_endRegion;
        bool m_rangeInvalidated;
    };

    typedef PODInterval<LayoutUnit, WeakPtr<RenderFragmentContainer>> RegionInterval;
    typedef PODIntervalTree<LayoutUnit, WeakPtr<RenderFragmentContainer>> RegionIntervalTree;

    class RegionSearchAdapter {
    public:
        RegionSearchAdapter(LayoutUnit offset)
            : m_offset(offset)
        {
        }

        const LayoutUnit& lowValue() const { return m_offset; }
        const LayoutUnit& highValue() const { return m_offset; }
        void collectIfNeeded(const RegionInterval&);

        RenderFragmentContainer* result() const { return m_result.get(); }

    private:
        LayoutUnit m_offset;
        WeakPtr<RenderFragmentContainer> m_result;
    };

    // Map a line to its containing region.
    OwnPtr<ContainingRegionMap> m_lineToFragmentMap;

    // A maps from RenderBox
    typedef HashMap<const RenderBox*, RenderRegionRange> RenderRegionRangeMap;
    RenderRegionRangeMap m_fragmentRangeMap;

    typedef HashMap<RenderObject*, RenderFragmentContainer*> RenderObjectToRegionMap;
    RenderObjectToRegionMap m_breakBeforeToRegionMap;
    RenderObjectToRegionMap m_breakAfterToRegionMap;

    RegionIntervalTree m_regionIntervalTree;

    CurrentRenderFragmentContainerMaintainer* m_currentRegionMaintainer;

    unsigned m_regionsInvalidated : 1;
    unsigned m_regionsHaveUniformLogicalWidth : 1;
    unsigned m_regionsHaveUniformLogicalHeight : 1;
    unsigned m_pageLogicalSizeChanged : 1;
};

inline RenderFragmentedFlow* toRenderFragmentedFlow(RenderObject* object)
{
    ASSERT(!object || object->isRenderFragmentedFlow());
    return static_cast<RenderFragmentedFlow*>(object);
}

inline RenderFragmentedFlow& toRenderFragmentedFlow(RenderObject& object)
{
    ASSERT(object.isRenderFragmentedFlow());
    return static_cast<RenderFragmentedFlow&>(object);
}

inline const RenderFragmentedFlow* toRenderFragmentedFlow(const RenderObject* object)
{
    ASSERT(!object || object->isRenderFragmentedFlow());
    return static_cast<const RenderFragmentedFlow*>(object);
}

inline const RenderFragmentedFlow& toRenderFragmentedFlow(const RenderObject& object)
{
    ASSERT(object.isRenderFragmentedFlow());
    return static_cast<const RenderFragmentedFlow&>(object);
}

// This will catch anyone doing an unnecessary cast.
void toRenderFragmentedFlow(const RenderFragmentedFlow*);
void toRenderFragmentedFlow(const RenderFragmentedFlow&);

// These structures are used by PODIntervalTree for debugging.
#ifndef NDEBUG
template <> struct ValueToString<LayoutUnit> {
    static String string(const LayoutUnit value) { return String::number(value.toFloat()); }
};

template <> struct ValueToString<RenderFragmentContainer*> {
    static String string(const RenderFragmentContainer* value) { return String::format("%p", value); }
};
#endif

} // namespace WebCore
