<commit_before>/*************************************************************************
 *
 *  $RCSfile: VCartesianGrid.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: bm $ $Date: 2004-01-26 09:13:11 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2003 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include "VCartesianGrid.hxx"
#include "TickmarkHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "ShapeFactory.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"

#ifndef _COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_
#include <com/sun/star/chart2/XIdentifiable.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

#include <vector>
#include <memory>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

struct GridLinePoints
{
    uno::Sequence< double > P0;
    uno::Sequence< double > P1;
    uno::Sequence< double > P2;

    GridLinePoints( const PlottingPositionHelper* pPosHelper, sal_Int32 nDimensionIndex );
    void update( double fScaledTickValue );

    sal_Int32 m_nDimensionIndex;
};

GridLinePoints::GridLinePoints( const PlottingPositionHelper* pPosHelper, sal_Int32 nDimensionIndex )
                : m_nDimensionIndex(nDimensionIndex)
{
    double MinX = pPosHelper->getLogicMinX();
    double MinY = pPosHelper->getLogicMinY();
    double MinZ = pPosHelper->getLogicMinZ();
    double MaxX = pPosHelper->getLogicMaxX();
    double MaxY = pPosHelper->getLogicMaxY();
    double MaxZ = pPosHelper->getLogicMaxZ();

    pPosHelper->doLogicScaling( &MinX,&MinY,&MinZ );
    pPosHelper->doLogicScaling( &MaxX,&MaxY,&MaxZ );

    if(!pPosHelper->isMathematicalOrientationX())
    {
        double fHelp = MinX;
        MinX = MaxX;
        MaxX = fHelp;
    }
    if(!pPosHelper->isMathematicalOrientationY())
    {
        double fHelp = MinY;
        MinY = MaxY;
        MaxY = fHelp;
    }
    if(pPosHelper->isMathematicalOrientationZ())//z axis in draw is reverse to mathematical
    {
        double fHelp = MinZ;
        MinZ = MaxZ;
        MaxZ = fHelp;
    }

    P0.realloc(3);
    P1.realloc(3);
    P2.realloc(3);

    P0[0]=P1[0]=P2[0]=MinX;
    P0[1]=P1[1]=P2[1]=MinY;
    P0[2]=P1[2]=P2[2]=MinZ;

    if(m_nDimensionIndex==0)
    {
        P0[1]=MaxY;
        P2[2]=MaxZ;
    }
    else if(m_nDimensionIndex==1)
    {
        P0[0]=MaxX;
        P2[2]=MaxZ;
    }
    else if(m_nDimensionIndex==2)
    {
        P0[0]=MaxX;
        P2[1]=MaxY;
    }
}

void GridLinePoints::update( double fScaledTickValue )
{
    P0[m_nDimensionIndex] = P1[m_nDimensionIndex] = P2[m_nDimensionIndex] = fScaledTickValue;
}

void addLine2D( drawing::PointSequenceSequence& rPoints, sal_Int32 nIndex
             , const GridLinePoints& rScaledLogicPoints
             , const uno::Reference< XTransformation > & xTransformation
              )
{
    drawing::Position3D aPA = SequenceToPosition3D( xTransformation->transform( rScaledLogicPoints.P0 ) );
    drawing::Position3D aPB = SequenceToPosition3D( xTransformation->transform( rScaledLogicPoints.P1 ) );

    rPoints[nIndex].realloc(2);
    rPoints[nIndex][0].X = static_cast<sal_Int32>(aPA.PositionX);
    rPoints[nIndex][0].Y = static_cast<sal_Int32>(aPA.PositionY);
    rPoints[nIndex][1].X = static_cast<sal_Int32>(aPB.PositionX);
    rPoints[nIndex][1].Y = static_cast<sal_Int32>(aPB.PositionY);
}

void addLine3D( drawing::PolyPolygonShape3D& rPoints, sal_Int32 nIndex
            , const GridLinePoints& rBasePoints
            , const uno::Reference< XTransformation > & xTransformation )
{
    drawing::Position3D aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P0 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
    aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P1 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
    aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P2 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
}

//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------

VCartesianGrid::VCartesianGrid( const uno::Reference< XGrid >& xGrid, sal_Int32 nDimensionCount )
            : VMeterBase( uno::Reference<XMeter>::query(xGrid), nDimensionCount )
{
    m_pPosHelper = new PlottingPositionHelper();
}

VCartesianGrid::~VCartesianGrid()
{
    delete m_pPosHelper;
    m_pPosHelper = NULL;
}

//static
void VCartesianGrid::fillLinePropertiesFromGridModel( ::std::vector<VLineProperties>& rLinePropertiesList
                                     , uno::Reference< beans::XPropertySet > xProps )
{
    rLinePropertiesList.clear();
    VLineProperties aLineProperties;
    aLineProperties.initFromPropertySet( xProps );
    rLinePropertiesList.assign(2,aLineProperties);
};

void SAL_CALL VCartesianGrid::createShapes()
{
    if( !m_xMeter.is())
        return;
    uno::Reference< beans::XPropertySet > xGridProps( m_xMeter, uno::UNO_QUERY );
    if(!xGridProps.is())
        return;
    //somehow equal to axis tickmarks

    //-----------------------------------------
    //create named group shape
    uno::Reference< XIdentifiable > xIdent( m_xMeter, uno::UNO_QUERY );
    if( ! xIdent.is())
        return;

    uno::Reference< drawing::XShapes > xGroupShape_Shapes(
        this->createGroupShape( m_xLogicTarget
        , ObjectIdentifier::createClassifiedIdentifier(
                OBJECTTYPE_GRID, xIdent->getIdentifier() )
        ) );

    //-----------------------------------------

    sal_Int32 nDimensionIndex = m_xMeter->getRepresentedDimension();
    ::std::vector<VLineProperties> aLinePropertiesList;
    fillLinePropertiesFromGridModel( aLinePropertiesList, xGridProps );

    //-----------------------------------------
    //create all scaled tickmark values
    std::auto_ptr< TickmarkHelper > apTickmarkHelper( this->createTickmarkHelper() );
    TickmarkHelper& aTickmarkHelper = *apTickmarkHelper.get();
    ::std::vector< ::std::vector< TickInfo > > aAllTickInfos;
    aTickmarkHelper.getAllTicks( aAllTickInfos );

    //-----------------------------------------
    //create tick mark line shapes
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = aAllTickInfos.begin();
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = aAllTickInfos.end();

    if(aDepthIter == aDepthEnd)//no tickmarks at all
        return;

    if(2==m_nDimension)
    {
        drawing::PointSequenceSequence aHandlesPoints(1);

        sal_Int32 nLinePropertiesCount = aLinePropertiesList.size();
        for( sal_Int32 nDepth=0
            ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
            ; aDepthIter++, nDepth++ )
        {
            GridLinePoints aGridLinePoints( m_pPosHelper, nDimensionIndex );

            sal_Int32 nPointCount = (*aDepthIter).size();
            drawing::PointSequenceSequence aPoints(nPointCount);

            ::std::vector< TickInfo >::const_iterator       aTickIter = (*aDepthIter).begin();
            const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
            sal_Int32 nRealPointCount = 0;
            for( ; aTickIter != aTickEnd; aTickIter++ )
            {
                if( !(*aTickIter).bPaintIt )
                    continue;
                aGridLinePoints.update( (*aTickIter).fScaledTickValue );
                addLine2D( aPoints, nRealPointCount, aGridLinePoints, m_pPosHelper->getTransformationLogicToScene() );
                nRealPointCount++;
            }
            aPoints.realloc(nRealPointCount);
            m_pShapeFactory->createLine2D( xGroupShape_Shapes, aPoints, aLinePropertiesList[nDepth] );

            //prepare polygon for handle shape:
            sal_Int32 nOldHandleCount = aHandlesPoints[0].getLength();
            aHandlesPoints[0].realloc(nOldHandleCount+nRealPointCount);
            for( sal_Int32 nN = 0; nN<nRealPointCount; nN++)
                aHandlesPoints[0][nOldHandleCount+nN] = aPoints[nN][1];
        }

        //create handle shape:
        VLineProperties aHandleLineProperties;
        aHandleLineProperties.LineStyle    = uno::makeAny( drawing::LineStyle_NONE );
        uno::Reference< drawing::XShape > xHandleShape =
            m_pShapeFactory->createLine2D( xGroupShape_Shapes, aHandlesPoints, aHandleLineProperties );
        m_pShapeFactory->setShapeName( xHandleShape, C2U("HandlesOnly") );
    }
    //-----------------------------------------
    else //if(2!=m_nDimension)
    {
        sal_Int32 nLinePropertiesCount = aLinePropertiesList.size();
        for( sal_Int32 nDepth=0
            ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
            ; aDepthIter++, nDepth++ )
        {
            GridLinePoints aGridLinePoints( m_pPosHelper, nDimensionIndex );

            sal_Int32 nPointCount = (*aDepthIter).size();
            drawing::PolyPolygonShape3D aPoints;
            aPoints.SequenceX.realloc(nPointCount);
            aPoints.SequenceY.realloc(nPointCount);
            aPoints.SequenceZ.realloc(nPointCount);

            ::std::vector< TickInfo >::const_iterator       aTickIter = (*aDepthIter).begin();
            const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
            sal_Int32 nRealPointCount = 0;
            for( ; aTickIter != aTickEnd; aTickIter++ )
            {
                if( !(*aTickIter).bPaintIt )
                    continue;

                aGridLinePoints.update( (*aTickIter).fScaledTickValue );
                addLine3D( aPoints, nRealPointCount, aGridLinePoints, m_pPosHelper->getTransformationLogicToScene() );
                nRealPointCount+=3;
            }
            aPoints.SequenceX.realloc(nRealPointCount);
            aPoints.SequenceY.realloc(nRealPointCount);
            aPoints.SequenceZ.realloc(nRealPointCount);
            m_pShapeFactory->createLine3D( xGroupShape_Shapes, aPoints, aLinePropertiesList[nDepth] );
        }
    }
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.110); FILE MERGED 2005/09/05 18:43:40 rt 1.3.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VCartesianGrid.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:38:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include "VCartesianGrid.hxx"
#include "TickmarkHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "ShapeFactory.hxx"
#include "chartview/ObjectIdentifier.hxx"
#include "macros.hxx"
#include "CommonConverters.hxx"

#ifndef _COM_SUN_STAR_CHART2_XIDENTIFIABLE_HPP_
#include <com/sun/star/chart2/XIdentifiable.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POINTSEQUENCESEQUENCE_HPP_
#include <com/sun/star/drawing/PointSequenceSequence.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_LINESTYLE_HPP_
#include <com/sun/star/drawing/LineStyle.hpp>
#endif

#include <vector>
#include <memory>

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

struct GridLinePoints
{
    uno::Sequence< double > P0;
    uno::Sequence< double > P1;
    uno::Sequence< double > P2;

    GridLinePoints( const PlottingPositionHelper* pPosHelper, sal_Int32 nDimensionIndex );
    void update( double fScaledTickValue );

    sal_Int32 m_nDimensionIndex;
};

GridLinePoints::GridLinePoints( const PlottingPositionHelper* pPosHelper, sal_Int32 nDimensionIndex )
                : m_nDimensionIndex(nDimensionIndex)
{
    double MinX = pPosHelper->getLogicMinX();
    double MinY = pPosHelper->getLogicMinY();
    double MinZ = pPosHelper->getLogicMinZ();
    double MaxX = pPosHelper->getLogicMaxX();
    double MaxY = pPosHelper->getLogicMaxY();
    double MaxZ = pPosHelper->getLogicMaxZ();

    pPosHelper->doLogicScaling( &MinX,&MinY,&MinZ );
    pPosHelper->doLogicScaling( &MaxX,&MaxY,&MaxZ );

    if(!pPosHelper->isMathematicalOrientationX())
    {
        double fHelp = MinX;
        MinX = MaxX;
        MaxX = fHelp;
    }
    if(!pPosHelper->isMathematicalOrientationY())
    {
        double fHelp = MinY;
        MinY = MaxY;
        MaxY = fHelp;
    }
    if(pPosHelper->isMathematicalOrientationZ())//z axis in draw is reverse to mathematical
    {
        double fHelp = MinZ;
        MinZ = MaxZ;
        MaxZ = fHelp;
    }

    P0.realloc(3);
    P1.realloc(3);
    P2.realloc(3);

    P0[0]=P1[0]=P2[0]=MinX;
    P0[1]=P1[1]=P2[1]=MinY;
    P0[2]=P1[2]=P2[2]=MinZ;

    if(m_nDimensionIndex==0)
    {
        P0[1]=MaxY;
        P2[2]=MaxZ;
    }
    else if(m_nDimensionIndex==1)
    {
        P0[0]=MaxX;
        P2[2]=MaxZ;
    }
    else if(m_nDimensionIndex==2)
    {
        P0[0]=MaxX;
        P2[1]=MaxY;
    }
}

void GridLinePoints::update( double fScaledTickValue )
{
    P0[m_nDimensionIndex] = P1[m_nDimensionIndex] = P2[m_nDimensionIndex] = fScaledTickValue;
}

void addLine2D( drawing::PointSequenceSequence& rPoints, sal_Int32 nIndex
             , const GridLinePoints& rScaledLogicPoints
             , const uno::Reference< XTransformation > & xTransformation
              )
{
    drawing::Position3D aPA = SequenceToPosition3D( xTransformation->transform( rScaledLogicPoints.P0 ) );
    drawing::Position3D aPB = SequenceToPosition3D( xTransformation->transform( rScaledLogicPoints.P1 ) );

    rPoints[nIndex].realloc(2);
    rPoints[nIndex][0].X = static_cast<sal_Int32>(aPA.PositionX);
    rPoints[nIndex][0].Y = static_cast<sal_Int32>(aPA.PositionY);
    rPoints[nIndex][1].X = static_cast<sal_Int32>(aPB.PositionX);
    rPoints[nIndex][1].Y = static_cast<sal_Int32>(aPB.PositionY);
}

void addLine3D( drawing::PolyPolygonShape3D& rPoints, sal_Int32 nIndex
            , const GridLinePoints& rBasePoints
            , const uno::Reference< XTransformation > & xTransformation )
{
    drawing::Position3D aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P0 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
    aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P1 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
    aPoint = SequenceToPosition3D( xTransformation->transform( rBasePoints.P2 ) );
    AddPointToPoly( rPoints, aPoint, nIndex );
}

//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------
//---------------------------------------------------------------------------------

VCartesianGrid::VCartesianGrid( const uno::Reference< XGrid >& xGrid, sal_Int32 nDimensionCount )
            : VMeterBase( uno::Reference<XMeter>::query(xGrid), nDimensionCount )
{
    m_pPosHelper = new PlottingPositionHelper();
}

VCartesianGrid::~VCartesianGrid()
{
    delete m_pPosHelper;
    m_pPosHelper = NULL;
}

//static
void VCartesianGrid::fillLinePropertiesFromGridModel( ::std::vector<VLineProperties>& rLinePropertiesList
                                     , uno::Reference< beans::XPropertySet > xProps )
{
    rLinePropertiesList.clear();
    VLineProperties aLineProperties;
    aLineProperties.initFromPropertySet( xProps );
    rLinePropertiesList.assign(2,aLineProperties);
};

void SAL_CALL VCartesianGrid::createShapes()
{
    if( !m_xMeter.is())
        return;
    uno::Reference< beans::XPropertySet > xGridProps( m_xMeter, uno::UNO_QUERY );
    if(!xGridProps.is())
        return;
    //somehow equal to axis tickmarks

    //-----------------------------------------
    //create named group shape
    uno::Reference< XIdentifiable > xIdent( m_xMeter, uno::UNO_QUERY );
    if( ! xIdent.is())
        return;

    uno::Reference< drawing::XShapes > xGroupShape_Shapes(
        this->createGroupShape( m_xLogicTarget
        , ObjectIdentifier::createClassifiedIdentifier(
                OBJECTTYPE_GRID, xIdent->getIdentifier() )
        ) );

    //-----------------------------------------

    sal_Int32 nDimensionIndex = m_xMeter->getRepresentedDimension();
    ::std::vector<VLineProperties> aLinePropertiesList;
    fillLinePropertiesFromGridModel( aLinePropertiesList, xGridProps );

    //-----------------------------------------
    //create all scaled tickmark values
    std::auto_ptr< TickmarkHelper > apTickmarkHelper( this->createTickmarkHelper() );
    TickmarkHelper& aTickmarkHelper = *apTickmarkHelper.get();
    ::std::vector< ::std::vector< TickInfo > > aAllTickInfos;
    aTickmarkHelper.getAllTicks( aAllTickInfos );

    //-----------------------------------------
    //create tick mark line shapes
    ::std::vector< ::std::vector< TickInfo > >::iterator aDepthIter             = aAllTickInfos.begin();
    const ::std::vector< ::std::vector< TickInfo > >::const_iterator aDepthEnd  = aAllTickInfos.end();

    if(aDepthIter == aDepthEnd)//no tickmarks at all
        return;

    if(2==m_nDimension)
    {
        drawing::PointSequenceSequence aHandlesPoints(1);

        sal_Int32 nLinePropertiesCount = aLinePropertiesList.size();
        for( sal_Int32 nDepth=0
            ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
            ; aDepthIter++, nDepth++ )
        {
            GridLinePoints aGridLinePoints( m_pPosHelper, nDimensionIndex );

            sal_Int32 nPointCount = (*aDepthIter).size();
            drawing::PointSequenceSequence aPoints(nPointCount);

            ::std::vector< TickInfo >::const_iterator       aTickIter = (*aDepthIter).begin();
            const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
            sal_Int32 nRealPointCount = 0;
            for( ; aTickIter != aTickEnd; aTickIter++ )
            {
                if( !(*aTickIter).bPaintIt )
                    continue;
                aGridLinePoints.update( (*aTickIter).fScaledTickValue );
                addLine2D( aPoints, nRealPointCount, aGridLinePoints, m_pPosHelper->getTransformationLogicToScene() );
                nRealPointCount++;
            }
            aPoints.realloc(nRealPointCount);
            m_pShapeFactory->createLine2D( xGroupShape_Shapes, aPoints, aLinePropertiesList[nDepth] );

            //prepare polygon for handle shape:
            sal_Int32 nOldHandleCount = aHandlesPoints[0].getLength();
            aHandlesPoints[0].realloc(nOldHandleCount+nRealPointCount);
            for( sal_Int32 nN = 0; nN<nRealPointCount; nN++)
                aHandlesPoints[0][nOldHandleCount+nN] = aPoints[nN][1];
        }

        //create handle shape:
        VLineProperties aHandleLineProperties;
        aHandleLineProperties.LineStyle    = uno::makeAny( drawing::LineStyle_NONE );
        uno::Reference< drawing::XShape > xHandleShape =
            m_pShapeFactory->createLine2D( xGroupShape_Shapes, aHandlesPoints, aHandleLineProperties );
        m_pShapeFactory->setShapeName( xHandleShape, C2U("HandlesOnly") );
    }
    //-----------------------------------------
    else //if(2!=m_nDimension)
    {
        sal_Int32 nLinePropertiesCount = aLinePropertiesList.size();
        for( sal_Int32 nDepth=0
            ; aDepthIter != aDepthEnd && nDepth < nLinePropertiesCount
            ; aDepthIter++, nDepth++ )
        {
            GridLinePoints aGridLinePoints( m_pPosHelper, nDimensionIndex );

            sal_Int32 nPointCount = (*aDepthIter).size();
            drawing::PolyPolygonShape3D aPoints;
            aPoints.SequenceX.realloc(nPointCount);
            aPoints.SequenceY.realloc(nPointCount);
            aPoints.SequenceZ.realloc(nPointCount);

            ::std::vector< TickInfo >::const_iterator       aTickIter = (*aDepthIter).begin();
            const ::std::vector< TickInfo >::const_iterator aTickEnd  = (*aDepthIter).end();
            sal_Int32 nRealPointCount = 0;
            for( ; aTickIter != aTickEnd; aTickIter++ )
            {
                if( !(*aTickIter).bPaintIt )
                    continue;

                aGridLinePoints.update( (*aTickIter).fScaledTickValue );
                addLine3D( aPoints, nRealPointCount, aGridLinePoints, m_pPosHelper->getTransformationLogicToScene() );
                nRealPointCount+=3;
            }
            aPoints.SequenceX.realloc(nRealPointCount);
            aPoints.SequenceY.realloc(nRealPointCount);
            aPoints.SequenceZ.realloc(nRealPointCount);
            m_pShapeFactory->createLine3D( xGroupShape_Shapes, aPoints, aLinePropertiesList[nDepth] );
        }
    }
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before><commit_msg>vcl::ITiledRenderable: getTextSelection() can be pure virtual now<commit_after><|endoftext|>


<commit_before>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2002 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_BASICIMAGEVIEW_HXX
#define VIGRA_BASICIMAGEVIEW_HXX

#include "vigra/imageiterator.hxx"

namespace vigra {

/********************************************************/
/*                                                      */
/*                     BasicImageView                   */
/*                                                      */
/********************************************************/

/** \brief BasicImage using foreign memory.

    This class provides the same interface as \ref vigra::BasicImage
    (with the exception of <tt>resize()</tt>) but the image's
    memory is provided from the outside instead of allocated internally.

    \#include "vigra/basicimageview.hxx"

    Namespace: vigra
*/
template <class PIXELTYPE>
class BasicImageView
{
  public:

        /** the BasicImageView's pixel type
        */
    typedef PIXELTYPE value_type;

        /** the BasicImageView's pixel type
        */
    typedef PIXELTYPE PixelType;

        /** the BasicImageView's reference type (i.e. the
            return type of image[diff] and image(dx,dy))
        */
    typedef PIXELTYPE &       reference;

        /** the BasicImageView's const reference type (i.e. the
            return type of image[diff] and image(dx,dy) when image is const)
        */
    typedef PIXELTYPE const & const_reference;

        /** the BasicImageView's pointer type
        */
    typedef PIXELTYPE *       pointer;

        /** the BasicImageView's const pointer type
        */
    typedef PIXELTYPE const * const_pointer;

        /** the BasicImageView's 1D random access iterator
            (note: lower case 'iterator' is a STL compatible 1D random
             access iterator, don't confuse with capitalized Iterator)
        */
    typedef PIXELTYPE * iterator;

        /** deprecated, use <TT>iterator</TT> instead
        */
    typedef PIXELTYPE * ScanOrderIterator;

        /** the BasicImageView's 1D random access const iterator
            (note: lower case 'const_iterator' is a STL compatible 1D
            random access const iterator)
        */
    typedef PIXELTYPE const * const_iterator;

        /** deprecated, use <TT>const_iterator</TT> instead
        */
    typedef PIXELTYPE const * ConstScanOrderIterator;

        /** the BasicImageView's 2D random access iterator ('traverser')
        */
    typedef ImageIterator<value_type> traverser;

        /** deprecated, use <TT>traverser</TT> instead
        */
    typedef ImageIterator<value_type> Iterator;

        /** the BasicImageView's 2D random access const iterator ('const traverser')
        */
    typedef ConstImageIterator<value_type> const_traverser;

        /** deprecated, use <TT>const_traverser</TT> instead
        */
    typedef ConstImageIterator<value_type> ConstIterator;

        /** the BasicImageView's difference type (argument type of image[diff])
        */
    typedef Diff2D difference_type;

         /** the BasicImageView's size type (result type of image.size())
        */
    typedef Size2D size_type;

       /** the BasicImageView's default accessor
        */
    typedef typename
          IteratorTraits<traverser>::DefaultAccessor Accessor;

        /** the BasicImageView's default const accessor
        */
    typedef typename
          IteratorTraits<const_traverser>::DefaultAccessor ConstAccessor;

        /** construct image of size 0x0
        */
    BasicImageView()
    : data_(0),
      width_(0),
      height_(0)
    {}

        /** construct view of size w x h
        */
    BasicImageView(const_pointer data, int w, int h)
    : data_(const_cast<pointer>(data)),
      width_(w),
      height_(h)
    {}

        /** construct view of size size.x x size.y
        */
    BasicImageView(const_pointer data, difference_type const & size)
    : data_(const_cast<pointer>(data)),
      width_(size.x),
      height_(size.y)
    {}

        /** set Image with const value
        */
    BasicImageView & init(value_type const & pixel)
    {
        ScanOrderIterator i = begin();
        ScanOrderIterator iend = end();

        for(; i != iend; ++i) *i = pixel;

        return *this;
    }

        /** width of Image
        */
    int width() const
    {
        return width_;
    }

        /** height of Image
        */
    int height() const
    {
        return height_;
    }

        /** size of Image
        */
    size_type size() const
    {
        return size_type(width(), height());
    }

        /** test whether a given coordinate is inside the image
        */
    bool isInside(difference_type const & d) const
    {
        return d.x >= 0 && d.y >= 0 &&
               d.x < width() && d.y < height();
    }

        /** access pixel at given location.

	    usage: <TT> value_type value = image[Diff2D(1,2)] </TT>
        */
    reference operator[](difference_type const & d)
    {
        return data_[d.y*width() + d.x];
    }

        /** read pixel at given location.

	    usage: <TT> value_type value = image[Diff2D(1,2)] </TT>
        */
    const_reference operator[](difference_type const & d) const
    {
        return data_[d.y*width() + d.x];
    }

        /** access pixel at given location.

	    usage: <TT> value_type value = image(1,2) </TT>
        */
    reference operator()(int dx, int dy)
    {
        return data_[dy*width() + dx];
    }

        /** read pixel at given location.

	    usage: <TT> value_type value = image(1,2) </TT>
        */
    const_reference operator()(int dx, int dy) const
    {
        return data_[dy*width() + dx];
    }

        /** access pixel at given location.
	        Note that the 'x' index is the trailing index.

	    usage: <TT> value_type value = image[2][1] </TT>
        */
    pointer operator[](int dy)
    {
        return data_ + dy*width();
    }

        /** read pixel at given location.
	        Note that the 'x' index is the trailing index.

	    usage: <TT> value_type value = image[2][1] </TT>
        */
    const_pointer operator[](int dy) const
    {
        return data_ + dy*width();
    }

        /** init 2D random access iterator poining to upper left pixel
        */
    traverser upperLeft()
    {
        return traverser(data_, width());
    }

        /** init 2D random access iterator poining to
         pixel(width, height), i.e. one pixel right and below lower right
         corner of the image as is common in C/C++.
        */
    traverser lowerRight()
    {
        return upperLeft() + size();
    }

        /** init 2D random access const iterator poining to upper left pixel
        */
    const_traverser upperLeft() const
    {
        return const_traverser(data_, width());
    }

        /** init 2D random access const iterator poining to
         pixel(width, height), i.e. one pixel right and below lower right
         corner of the image as is common in C/C++.
        */
    const_traverser lowerRight() const
    {
        return upperLeft() + size();
    }

        /** init 1D random access iterator pointing to first pixel
        */
    iterator begin()
    {
        return data_;
    }

        /** init 1D random access iterator pointing past the end
        */
    iterator end()
    {
        return data_ + width() * height();
    }

        /** init 1D random access const iterator pointing to first pixel
        */
    const_iterator begin() const
    {
        return data_;
    }

        /** init 1D random access const iterator pointing past the end
        */
    const_iterator end() const
    {
        return data_ + width() * height();
    }

        /** return default accessor
        */
    Accessor accessor()
    {
        return Accessor();
    }

        /** return default const accessor
        */
    ConstAccessor accessor() const
    {
        return ConstAccessor();
    }

  private:

    pointer data_;
    int width_, height_;
};

/********************************************************/
/*                                                      */
/*              argument object factories               */
/*                                                      */
/********************************************************/

template <class PixelType, class Accessor>
inline triple<typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::const_traverser, Accessor>
srcImageRange(BasicImageView<PixelType> const & img, Accessor a)
{
    return triple<typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::const_traverser,
          Accessor>(img.upperLeft(),
                    img.lowerRight(),
                    a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::const_traverser, Accessor>
srcImage(BasicImageView<PixelType> const & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                Accessor>(img.upperLeft(), a);
}

template <class PixelType, class Accessor>
inline triple<typename BasicImageView<PixelType>::traverser,
              typename BasicImageView<PixelType>::traverser, Accessor>
destImageRange(BasicImageView<PixelType> & img, Accessor a)
{
    return triple<typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::traverser,
          Accessor>(img.upperLeft(),
                    img.lowerRight(),
                    a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::traverser, Accessor>
destImage(BasicImageView<PixelType> & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::traverser,
                Accessor>(img.upperLeft(), a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::const_traverser, Accessor>
maskImage(BasicImageView<PixelType> const & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                Accessor>(img.upperLeft(), a);
}

/****************************************************************/

template <class PixelType>
inline triple<typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::ConstAccessor>
srcImageRange(BasicImageView<PixelType> const & img)
{
    return triple<typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                     img.lowerRight(),
                                                                     img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::const_traverser,
             typename BasicImageView<PixelType>::ConstAccessor>
srcImage(BasicImageView<PixelType> const & img)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                   img.accessor());
}

template <class PixelType>
inline triple< typename BasicImageView<PixelType>::traverser,
               typename BasicImageView<PixelType>::traverser,
               typename BasicImageView<PixelType>::Accessor>
destImageRange(BasicImageView<PixelType> & img)
{
    return triple<typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::Accessor>(img.upperLeft(),
                                                                img.lowerRight(),
                                                                img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::traverser,
             typename BasicImageView<PixelType>::Accessor>
destImage(BasicImageView<PixelType> & img)
{
    return pair<typename BasicImageView<PixelType>::traverser,
                typename BasicImageView<PixelType>::Accessor>(img.upperLeft(),
                                                              img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::const_traverser,
             typename BasicImageView<PixelType>::ConstAccessor>
maskImage(BasicImageView<PixelType> const & img)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                   img.accessor());
}

} // namespace vigra

#endif /* VIGRA_BASICIMAGEVIEW_HXX */
<commit_msg>added stride to distinguish between logical and physical image width<commit_after>/************************************************************************/
/*                                                                      */
/*               Copyright 1998-2002 by Ullrich Koethe                  */
/*       Cognitive Systems Group, University of Hamburg, Germany        */
/*                                                                      */
/*    This file is part of the VIGRA computer vision library.           */
/*    You may use, modify, and distribute this software according       */
/*    to the terms stated in the LICENSE file included in               */
/*    the VIGRA distribution.                                           */
/*                                                                      */
/*    The VIGRA Website is                                              */
/*        http://kogs-www.informatik.uni-hamburg.de/~koethe/vigra/      */
/*    Please direct questions, bug reports, and contributions to        */
/*        koethe@informatik.uni-hamburg.de                              */
/*                                                                      */
/*  THIS SOFTWARE IS PROVIDED AS IS AND WITHOUT ANY EXPRESS OR          */
/*  IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED      */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
/*                                                                      */
/************************************************************************/

#ifndef VIGRA_BASICIMAGEVIEW_HXX
#define VIGRA_BASICIMAGEVIEW_HXX

#include "vigra/imageiterator.hxx"
#include "vigra/initimage.hxx"

namespace vigra {

/********************************************************/
/*                                                      */
/*                     BasicImageView                   */
/*                                                      */
/********************************************************/

/** \brief BasicImage using foreign memory.

    This class provides the same interface as \ref vigra::BasicImage
    (with the exception of <tt>resize()</tt>) but the image's
    memory is provided from the outside instead of allocated internally.

    \#include "vigra/basicimageview.hxx"

    Namespace: vigra
*/
template <class PIXELTYPE>
class BasicImageView
{
  public:

        /** the BasicImageView's pixel type
        */
    typedef PIXELTYPE value_type;

        /** the BasicImageView's pixel type
        */
    typedef PIXELTYPE PixelType;

        /** the BasicImageView's reference type (i.e. the
            return type of image[diff] and image(dx,dy))
        */
    typedef PIXELTYPE &       reference;

        /** the BasicImageView's const reference type (i.e. the
            return type of image[diff] and image(dx,dy) when image is const)
        */
    typedef PIXELTYPE const & const_reference;

        /** the BasicImageView's pointer type
        */
    typedef PIXELTYPE *       pointer;

        /** the BasicImageView's const pointer type
        */
    typedef PIXELTYPE const * const_pointer;

        /** the BasicImageView's 1D random access iterator
            (note: lower case 'iterator' is a STL compatible 1D random
             access iterator, don't confuse with capitalized Iterator)
        */
    typedef PIXELTYPE * iterator;

        /** deprecated, use <TT>iterator</TT> instead
        */
    typedef PIXELTYPE * ScanOrderIterator;

        /** the BasicImageView's 1D random access const iterator
            (note: lower case 'const_iterator' is a STL compatible 1D
            random access const iterator)
        */
    typedef PIXELTYPE const * const_iterator;

        /** deprecated, use <TT>const_iterator</TT> instead
        */
    typedef PIXELTYPE const * ConstScanOrderIterator;

        /** the BasicImageView's 2D random access iterator ('traverser')
        */
    typedef ImageIterator<value_type> traverser;

        /** deprecated, use <TT>traverser</TT> instead
        */
    typedef ImageIterator<value_type> Iterator;

        /** the BasicImageView's 2D random access const iterator ('const traverser')
        */
    typedef ConstImageIterator<value_type> const_traverser;

        /** deprecated, use <TT>const_traverser</TT> instead
        */
    typedef ConstImageIterator<value_type> ConstIterator;

        /** the BasicImageView's difference type (argument type of image[diff])
        */
    typedef Diff2D difference_type;

         /** the BasicImageView's size type (result type of image.size())
        */
    typedef Size2D size_type;

       /** the BasicImageView's default accessor
        */
    typedef typename
          IteratorTraits<traverser>::DefaultAccessor Accessor;

        /** the BasicImageView's default const accessor
        */
    typedef typename
          IteratorTraits<const_traverser>::DefaultAccessor ConstAccessor;

        /** construct image of size 0x0
        */
    BasicImageView()
    : data_(0),
      width_(0),
      height_(0),
      stride_(0)
    {}

        /** construct view of size w x h
        */
    BasicImageView(const_pointer data, int w, int h, int stride = 0)
    : data_(const_cast<pointer>(data)),
      width_(w),
      height_(h),
      stride_(stride == 0 ? w : stride)
    {}

        /** construct view of size size.x x size.y
        */
    BasicImageView(const_pointer data, difference_type const & size, int stride = 0)
    : data_(const_cast<pointer>(data)),
      width_(size.x),
      height_(size.y),
      stride_(stride == 0 ? size.x : stride)
    {}

        /** set Image with const value
        */
    BasicImageView & init(value_type const & pixel)
    {
        initImage(upperLeft(), lowerRight(), accessor(), pixel);

        return *this;
    }

        /** width of Image
        */
    int width() const
    {
        return width_;
    }

        /** height of Image
        */
    int height() const
    {
        return height_;
    }

        /** stride of Image.
            Memory offset between the start of two successive rows.
        */
    int stride() const
    {
        return stride_;
    }

        /** size of Image
        */
    size_type size() const
    {
        return size_type(width(), height());
    }

        /** test whether a given coordinate is inside the image
        */
    bool isInside(difference_type const & d) const
    {
        return d.x >= 0 && d.y >= 0 &&
               d.x < width() && d.y < height();
    }

        /** access pixel at given location.

	    usage: <TT> value_type value = image[Diff2D(1,2)] </TT>
        */
    reference operator[](difference_type const & d)
    {
        return data_[d.y*stride_ + d.x];
    }

        /** read pixel at given location.

	    usage: <TT> value_type value = image[Diff2D(1,2)] </TT>
        */
    const_reference operator[](difference_type const & d) const
    {
        return data_[d.y*stride_ + d.x];
    }

        /** access pixel at given location.

	    usage: <TT> value_type value = image(1,2) </TT>
        */
    reference operator()(int dx, int dy)
    {
        return data_[dy*stride_ + dx];
    }

        /** read pixel at given location.

	    usage: <TT> value_type value = image(1,2) </TT>
        */
    const_reference operator()(int dx, int dy) const
    {
        return data_[dy*stride_ + dx];
    }

        /** access pixel at given location.
	        Note that the 'x' index is the trailing index.

	    usage: <TT> value_type value = image[2][1] </TT>
        */
    pointer operator[](int dy)
    {
        return data_ + dy*stride_;
    }

        /** read pixel at given location.
	        Note that the 'x' index is the trailing index.

	    usage: <TT> value_type value = image[2][1] </TT>
        */
    const_pointer operator[](int dy) const
    {
        return data_ + dy*stride_;
    }

        /** init 2D random access iterator poining to upper left pixel
        */
    traverser upperLeft()
    {
        return traverser(data_, stride_);
    }

        /** init 2D random access iterator poining to
         pixel(width, height), i.e. one pixel right and below lower right
         corner of the image as is common in C/C++.
        */
    traverser lowerRight()
    {
        return upperLeft() + size();
    }

        /** init 2D random access const iterator poining to upper left pixel
        */
    const_traverser upperLeft() const
    {
        return const_traverser(data_, stride_);
    }

        /** init 2D random access const iterator poining to
         pixel(width, height), i.e. one pixel right and below lower right
         corner of the image as is common in C/C++.
        */
    const_traverser lowerRight() const
    {
        return upperLeft() + size();
    }

        /** init 1D random access iterator pointing to first pixel.
            Note: Only works if stride equals width.
        */
    iterator begin()
    {
        vigra_precondition(stride_ == width_,
            "BasicImageView::begin(): "
            "can only create scan order iterator if width() == stride().");
        return data_;
    }

        /** init 1D random access iterator pointing past the end.
            Note: Only works if stride equals width.
        */
    iterator end()
    {
        vigra_precondition(stride_ == width_,
            "BasicImageView::end(): "
            "can only create scan order iterator if width() == stride().");
        return data_ + width() * height();
    }

        /** init 1D random access const iterator pointing to first pixel.
            Note: Only works if stride equals width.
        */
    const_iterator begin() const
    {
        vigra_precondition(stride_ == width_,
            "BasicImageView::begin(): "
            "can only create scan order iterator if width() == stride().");
        return data_;
    }

        /** init 1D random access const iterator pointing past the end.
            Note: Only works if stride equals width.
        */
    const_iterator end() const
    {
        vigra_precondition(stride_ == width_,
            "BasicImageView::end(): "
            "can only create scan order iterator if width() == stride().");
        return data_ + width() * height();
    }

        /** return default accessor
        */
    Accessor accessor()
    {
        return Accessor();
    }

        /** return default const accessor
        */
    ConstAccessor accessor() const
    {
        return ConstAccessor();
    }

  private:

    pointer data_;
    int width_, height_, stride_;
};

/********************************************************/
/*                                                      */
/*              argument object factories               */
/*                                                      */
/********************************************************/

template <class PixelType, class Accessor>
inline triple<typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::const_traverser, Accessor>
srcImageRange(BasicImageView<PixelType> const & img, Accessor a)
{
    return triple<typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::const_traverser,
          Accessor>(img.upperLeft(),
                    img.lowerRight(),
                    a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::const_traverser, Accessor>
srcImage(BasicImageView<PixelType> const & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                Accessor>(img.upperLeft(), a);
}

template <class PixelType, class Accessor>
inline triple<typename BasicImageView<PixelType>::traverser,
              typename BasicImageView<PixelType>::traverser, Accessor>
destImageRange(BasicImageView<PixelType> & img, Accessor a)
{
    return triple<typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::traverser,
          Accessor>(img.upperLeft(),
                    img.lowerRight(),
                    a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::traverser, Accessor>
destImage(BasicImageView<PixelType> & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::traverser,
                Accessor>(img.upperLeft(), a);
}

template <class PixelType, class Accessor>
inline pair<typename BasicImageView<PixelType>::const_traverser, Accessor>
maskImage(BasicImageView<PixelType> const & img, Accessor a)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                Accessor>(img.upperLeft(), a);
}

/****************************************************************/

template <class PixelType>
inline triple<typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::const_traverser,
              typename BasicImageView<PixelType>::ConstAccessor>
srcImageRange(BasicImageView<PixelType> const & img)
{
    return triple<typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::const_traverser,
                  typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                     img.lowerRight(),
                                                                     img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::const_traverser,
             typename BasicImageView<PixelType>::ConstAccessor>
srcImage(BasicImageView<PixelType> const & img)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                   img.accessor());
}

template <class PixelType>
inline triple< typename BasicImageView<PixelType>::traverser,
               typename BasicImageView<PixelType>::traverser,
               typename BasicImageView<PixelType>::Accessor>
destImageRange(BasicImageView<PixelType> & img)
{
    return triple<typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::traverser,
                  typename BasicImageView<PixelType>::Accessor>(img.upperLeft(),
                                                                img.lowerRight(),
                                                                img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::traverser,
             typename BasicImageView<PixelType>::Accessor>
destImage(BasicImageView<PixelType> & img)
{
    return pair<typename BasicImageView<PixelType>::traverser,
                typename BasicImageView<PixelType>::Accessor>(img.upperLeft(),
                                                              img.accessor());
}

template <class PixelType>
inline pair< typename BasicImageView<PixelType>::const_traverser,
             typename BasicImageView<PixelType>::ConstAccessor>
maskImage(BasicImageView<PixelType> const & img)
{
    return pair<typename BasicImageView<PixelType>::const_traverser,
                typename BasicImageView<PixelType>::ConstAccessor>(img.upperLeft(),
                                                                   img.accessor());
}

} // namespace vigra

#endif /* VIGRA_BASICIMAGEVIEW_HXX */
<|endoftext|>


<commit_before><commit_msg>Don't print "playing" when we are a non-audio score.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>
#include <string>

#include "build/build_config.h"
#if defined(OS_WIN)
#include <shlwapi.h>
#endif

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/net/url_request_slow_download_job.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

const wchar_t kDocRoot[] = L"chrome/test/data";

#if defined(OS_WIN)
// Checks if the volume supports Alternate Data Streams. This is required for
// the Zone Identifier implementation.
bool VolumeSupportsADS(const std::wstring path) {
  wchar_t drive[MAX_PATH] = {0};
  wcscpy_s(drive, MAX_PATH, path.c_str());

  EXPECT_TRUE(PathStripToRootW(drive));

  DWORD fs_flags = 0;
  EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL,
                                    0));

  if (fs_flags & FILE_NAMED_STREAMS)
    return true;

  return false;
}

// Checks if the ZoneIdentifier is correctly set to "Internet" (3)
void CheckZoneIdentifier(const std::wstring full_path) {
  const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

  std::wstring path = full_path + L":Zone.Identifier";
  HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL,
                           OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  ASSERT_TRUE(INVALID_HANDLE_VALUE != file);

  char buffer[100] = {0};
  DWORD read = 0;
  ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL));
  CloseHandle(file);

  const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3";
  ASSERT_EQ(arraysize(kIdentifier), read);

  ASSERT_EQ(0, strcmp(kIdentifier, buffer));
}
#endif  // defined(OS_WIN)

class DownloadTest : public UITest {
 protected:
  DownloadTest() : UITest() {}

  void CleanUpDownload(const FilePath& client_filename,
                       const FilePath& server_filename) {
    // Find the path on the client.
    FilePath file_on_client = download_prefix_.Append(client_filename);
    EXPECT_TRUE(file_util::PathExists(file_on_client));

    // Find the path on the server.
    FilePath file_on_server;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
                                 &file_on_server));
    file_on_server = file_on_server.Append(server_filename);
    ASSERT_TRUE(file_util::PathExists(file_on_server));

    // Check that we downloaded the file correctly.
    EXPECT_TRUE(file_util::ContentsEqual(file_on_server,
                                         file_on_client));

#if defined(OS_WIN)
    // Check if the Zone Identifier is correctly set.
    if (VolumeSupportsADS(file_on_client.value()))
      CheckZoneIdentifier(file_on_client.value());
#endif

    // Delete the client copy of the file.
    EXPECT_TRUE(file_util::Delete(file_on_client, false));
  }

  void CleanUpDownload(const FilePath& file) {
    CleanUpDownload(file, file);
  }

  virtual void SetUp() {
    UITest::SetUp();
    download_prefix_ = FilePath::FromWStringHack(GetDownloadDirectory());
  }

 protected:
  void RunSizeTest(const GURL& url,
                   const std::wstring& expected_title_in_progress,
                   const std::wstring& expected_title_finished) {
    {
      EXPECT_EQ(1, GetTabCount());

      NavigateToURL(url);
      // Downloads appear in the shelf
      WaitUntilTabCount(1);
      // TODO(tc): check download status text

      // Complete sending the request.  We do this by loading a second URL in a
      // separate tab.
      scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
      EXPECT_TRUE(window->AppendTab(GURL(
          URLRequestSlowDownloadJob::kFinishDownloadUrl)));
      EXPECT_EQ(2, GetTabCount());
      // TODO(tc): check download status text

      // Make sure the download shelf is showing.
      EXPECT_TRUE(WaitForDownloadShelfVisible(window.get()));
    }

    FilePath filename;
    net::FileURLToFilePath(url, &filename);
    filename = filename.BaseName();
    FilePath download_path = download_prefix_.Append(filename);
    EXPECT_TRUE(file_util::PathExists(download_path));

    // Delete the file we just downloaded.
    for (int i = 0; i < 10; ++i) {
      if (file_util::Delete(download_path, false))
        break;
      PlatformThread::Sleep(action_max_timeout_ms() / 10);
    }
    EXPECT_FALSE(file_util::PathExists(download_path));
  }

  FilePath download_prefix_;
};

// Download a file with non-viewable content, verify that the
// download tab opened and the file exists.
TEST_F(DownloadTest, DownloadMimeType) {
  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  // No new tabs created, downloads appear in the current tab's download shelf.
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(file);

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
}

// Access a file with a viewable mime-type, verify that a download
// did not initiate.
TEST_F(DownloadTest, NoDownload) {
  FilePath file(FILE_PATH_LITERAL("download-test2.html"));
  FilePath file_path = download_prefix_.Append(file);

  if (file_util::PathExists(file_path))
    ASSERT_TRUE(file_util::Delete(file_path, false));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait to see if the file will be downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  EXPECT_FALSE(file_util::PathExists(file_path));
  if (file_util::PathExists(file_path))
    ASSERT_TRUE(file_util::Delete(file_path, false));

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_FALSE(WaitForDownloadShelfVisible(browser.get()));
}

// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header.  This also ensures we properly handle empty file downloads.
TEST_F(DownloadTest, ContentDisposition) {
  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(download_file, file);

  // Ensure the download shelf is visible on the window.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
}

// Test that the download shelf is per-window by starting a download in one
// tab, opening a second tab, closing the shelf, going back to the first tab,
// and checking that the shelf is closed.
TEST_F(DownloadTest, PerWindowShelf) {
  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(download_file, file);

  // Ensure the download shelf is visible on the window.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));

  // Open a second tab
  browser->AppendTab(GURL(""));
  WaitUntilTabCount(2);

  // Hide shelf
  browser->SetShelfVisible(false);
  EXPECT_TRUE(WaitForDownloadShelfInvisible(browser.get()));

  // Go to first tab
  EXPECT_TRUE(browser->ActivateTab(0));
  int tab_count;
  EXPECT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(2, tab_count);

  bool shelf_visible;
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_visible));
  ASSERT_FALSE(shelf_visible);
}

// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish.  At that time, the download will finish.
// Flaky on Linux: http://code.google.com/p/chromium/issues/detail?id=14746
TEST_F(DownloadTest, UnknownSize) {
  GURL url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
  FilePath filename;
  net::FileURLToFilePath(url, &filename);
  filename = filename.BaseName();
  RunSizeTest(url, L"32.0 KB - " + filename.ToWStringHack(),
              L"100% - " + filename.ToWStringHack());
}

// http://b/1158253
TEST_F(DownloadTest, DISABLED_KnownSize) {
  GURL url(URLRequestSlowDownloadJob::kKnownSizeUrl);
  FilePath filename;
  net::FileURLToFilePath(url, &filename);
  filename = filename.BaseName();
  RunSizeTest(url, L"71% - " + filename.ToWStringHack(),
              L"100% - " + filename.ToWStringHack());
}

// Test that when downloading an item in Incognito mode, we don't crash when
// closing the last Incognito window (http://crbug.com/13983).
TEST_F(DownloadTest, IncognitoDownload) {
  // Open a regular window and sanity check default values for window / tab
  // count and shelf visibility.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  int window_count = 0;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(1, window_count);
  EXPECT_EQ(1, GetTabCount());
  bool is_shelf_visible;
  browser->IsShelfVisible(&is_shelf_visible);
  EXPECT_FALSE(is_shelf_visible);

  // Open an Incognito window.
  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
  scoped_refptr<TabProxy> tab(incognito->GetTab(0));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(2, window_count);

  // Download something.
  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
  //PlatformThread::Sleep(1000);
  ASSERT_TRUE(tab->NavigateToURL(
      URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())));
  PlatformThread::Sleep(action_timeout_ms());

  // Verify that the download shelf is showing for the Incognito window.
  EXPECT_TRUE(WaitForDownloadShelfVisible(incognito.get()));

  // Close the Incognito window and don't crash.
  ASSERT_TRUE(incognito->RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(1, window_count);

  // Verify that the regular window does not have a download shelf.
  browser->IsShelfVisible(&is_shelf_visible);
  EXPECT_FALSE(is_shelf_visible);

  CleanUpDownload(file);
}

}  // namespace
<commit_msg>Disable flakey DownloadTest::ContentDisposition<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <sstream>
#include <string>

#include "build/build_config.h"
#if defined(OS_WIN)
#include <shlwapi.h>
#endif

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/net/url_request_slow_download_job.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

const wchar_t kDocRoot[] = L"chrome/test/data";

#if defined(OS_WIN)
// Checks if the volume supports Alternate Data Streams. This is required for
// the Zone Identifier implementation.
bool VolumeSupportsADS(const std::wstring path) {
  wchar_t drive[MAX_PATH] = {0};
  wcscpy_s(drive, MAX_PATH, path.c_str());

  EXPECT_TRUE(PathStripToRootW(drive));

  DWORD fs_flags = 0;
  EXPECT_TRUE(GetVolumeInformationW(drive, NULL, 0, 0, NULL, &fs_flags, NULL,
                                    0));

  if (fs_flags & FILE_NAMED_STREAMS)
    return true;

  return false;
}

// Checks if the ZoneIdentifier is correctly set to "Internet" (3)
void CheckZoneIdentifier(const std::wstring full_path) {
  const DWORD kShare = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;

  std::wstring path = full_path + L":Zone.Identifier";
  HANDLE file = CreateFile(path.c_str(), GENERIC_READ, kShare, NULL,
                           OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  ASSERT_TRUE(INVALID_HANDLE_VALUE != file);

  char buffer[100] = {0};
  DWORD read = 0;
  ASSERT_TRUE(ReadFile(file, buffer, 100, &read, NULL));
  CloseHandle(file);

  const char kIdentifier[] = "[ZoneTransfer]\nZoneId=3";
  ASSERT_EQ(arraysize(kIdentifier), read);

  ASSERT_EQ(0, strcmp(kIdentifier, buffer));
}
#endif  // defined(OS_WIN)

class DownloadTest : public UITest {
 protected:
  DownloadTest() : UITest() {}

  void CleanUpDownload(const FilePath& client_filename,
                       const FilePath& server_filename) {
    // Find the path on the client.
    FilePath file_on_client = download_prefix_.Append(client_filename);
    EXPECT_TRUE(file_util::PathExists(file_on_client));

    // Find the path on the server.
    FilePath file_on_server;
    ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA,
                                 &file_on_server));
    file_on_server = file_on_server.Append(server_filename);
    ASSERT_TRUE(file_util::PathExists(file_on_server));

    // Check that we downloaded the file correctly.
    EXPECT_TRUE(file_util::ContentsEqual(file_on_server,
                                         file_on_client));

#if defined(OS_WIN)
    // Check if the Zone Identifier is correctly set.
    if (VolumeSupportsADS(file_on_client.value()))
      CheckZoneIdentifier(file_on_client.value());
#endif

    // Delete the client copy of the file.
    EXPECT_TRUE(file_util::Delete(file_on_client, false));
  }

  void CleanUpDownload(const FilePath& file) {
    CleanUpDownload(file, file);
  }

  virtual void SetUp() {
    UITest::SetUp();
    download_prefix_ = FilePath::FromWStringHack(GetDownloadDirectory());
  }

 protected:
  void RunSizeTest(const GURL& url,
                   const std::wstring& expected_title_in_progress,
                   const std::wstring& expected_title_finished) {
    {
      EXPECT_EQ(1, GetTabCount());

      NavigateToURL(url);
      // Downloads appear in the shelf
      WaitUntilTabCount(1);
      // TODO(tc): check download status text

      // Complete sending the request.  We do this by loading a second URL in a
      // separate tab.
      scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0));
      EXPECT_TRUE(window->AppendTab(GURL(
          URLRequestSlowDownloadJob::kFinishDownloadUrl)));
      EXPECT_EQ(2, GetTabCount());
      // TODO(tc): check download status text

      // Make sure the download shelf is showing.
      EXPECT_TRUE(WaitForDownloadShelfVisible(window.get()));
    }

    FilePath filename;
    net::FileURLToFilePath(url, &filename);
    filename = filename.BaseName();
    FilePath download_path = download_prefix_.Append(filename);
    EXPECT_TRUE(file_util::PathExists(download_path));

    // Delete the file we just downloaded.
    for (int i = 0; i < 10; ++i) {
      if (file_util::Delete(download_path, false))
        break;
      PlatformThread::Sleep(action_max_timeout_ms() / 10);
    }
    EXPECT_FALSE(file_util::PathExists(download_path));
  }

  FilePath download_prefix_;
};

// Download a file with non-viewable content, verify that the
// download tab opened and the file exists.
TEST_F(DownloadTest, DownloadMimeType) {
  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  // No new tabs created, downloads appear in the current tab's download shelf.
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(file);

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
}

// Access a file with a viewable mime-type, verify that a download
// did not initiate.
TEST_F(DownloadTest, NoDownload) {
  FilePath file(FILE_PATH_LITERAL("download-test2.html"));
  FilePath file_path = download_prefix_.Append(file);

  if (file_util::PathExists(file_path))
    ASSERT_TRUE(file_util::Delete(file_path, false));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait to see if the file will be downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  EXPECT_FALSE(file_util::PathExists(file_path));
  if (file_util::PathExists(file_path))
    ASSERT_TRUE(file_util::Delete(file_path, false));

  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_FALSE(WaitForDownloadShelfVisible(browser.get()));
}

// Download a 0-size file with a content-disposition header, verify that the
// download tab opened and the file exists as the filename specified in the
// header.  This also ensures we properly handle empty file downloads.
TEST_F(DownloadTest, DISABLED_ContentDisposition) {
  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(download_file, file);

  // Ensure the download shelf is visible on the window.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
}

// Test that the download shelf is per-window by starting a download in one
// tab, opening a second tab, closing the shelf, going back to the first tab,
// and checking that the shelf is closed.
TEST_F(DownloadTest, PerWindowShelf) {
  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));

  EXPECT_EQ(1, GetTabCount());

  NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack()));
  WaitUntilTabCount(1);

  // Wait until the file is downloaded.
  PlatformThread::Sleep(action_timeout_ms());

  CleanUpDownload(download_file, file);

  // Ensure the download shelf is visible on the window.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser.get());
  EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));

  // Open a second tab
  browser->AppendTab(GURL(""));
  WaitUntilTabCount(2);

  // Hide shelf
  browser->SetShelfVisible(false);
  EXPECT_TRUE(WaitForDownloadShelfInvisible(browser.get()));

  // Go to first tab
  EXPECT_TRUE(browser->ActivateTab(0));
  int tab_count;
  EXPECT_TRUE(browser->GetTabCount(&tab_count));
  ASSERT_EQ(2, tab_count);

  bool shelf_visible;
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_visible));
  ASSERT_FALSE(shelf_visible);
}

// UnknownSize and KnownSize are tests which depend on
// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
// The test will first attempt to download a file; but the server will "pause"
// in the middle until the server receives a second request for
// "download-finish.  At that time, the download will finish.
// Flaky on Linux: http://code.google.com/p/chromium/issues/detail?id=14746
TEST_F(DownloadTest, UnknownSize) {
  GURL url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
  FilePath filename;
  net::FileURLToFilePath(url, &filename);
  filename = filename.BaseName();
  RunSizeTest(url, L"32.0 KB - " + filename.ToWStringHack(),
              L"100% - " + filename.ToWStringHack());
}

// http://b/1158253
TEST_F(DownloadTest, DISABLED_KnownSize) {
  GURL url(URLRequestSlowDownloadJob::kKnownSizeUrl);
  FilePath filename;
  net::FileURLToFilePath(url, &filename);
  filename = filename.BaseName();
  RunSizeTest(url, L"71% - " + filename.ToWStringHack(),
              L"100% - " + filename.ToWStringHack());
}

// Test that when downloading an item in Incognito mode, we don't crash when
// closing the last Incognito window (http://crbug.com/13983).
TEST_F(DownloadTest, IncognitoDownload) {
  // Open a regular window and sanity check default values for window / tab
  // count and shelf visibility.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  int window_count = 0;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(1, window_count);
  EXPECT_EQ(1, GetTabCount());
  bool is_shelf_visible;
  browser->IsShelfVisible(&is_shelf_visible);
  EXPECT_FALSE(is_shelf_visible);

  // Open an Incognito window.
  ASSERT_TRUE(browser->RunCommand(IDC_NEW_INCOGNITO_WINDOW));
  scoped_refptr<BrowserProxy> incognito(automation()->GetBrowserWindow(1));
  scoped_refptr<TabProxy> tab(incognito->GetTab(0));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(2, window_count);

  // Download something.
  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
  //PlatformThread::Sleep(1000);
  ASSERT_TRUE(tab->NavigateToURL(
      URLRequestMockHTTPJob::GetMockUrl(file.ToWStringHack())));
  PlatformThread::Sleep(action_timeout_ms());

  // Verify that the download shelf is showing for the Incognito window.
  EXPECT_TRUE(WaitForDownloadShelfVisible(incognito.get()));

  // Close the Incognito window and don't crash.
  ASSERT_TRUE(incognito->RunCommand(IDC_CLOSE_WINDOW));
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&window_count));
  ASSERT_EQ(1, window_count);

  // Verify that the regular window does not have a download shelf.
  browser->IsShelfVisible(&is_shelf_visible);
  EXPECT_FALSE(is_shelf_visible);

  CleanUpDownload(file);
}

}  // namespace
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

#include "app/sql/connection.h"
#include "app/sql/statement.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class MultipartResponseUITest : public UITest {
};

#if defined(NDEBUG)
// http://code.google.com/p/chromium/issues/detail?id=37746
// Running this test only for release builds as it fails in debug test
// runs
TEST_F(MultipartResponseUITest, SingleVisit) {
  // Make sure that visiting a multipart/x-mixed-replace site only
  // creates one entry in the visits table.
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab_proxy(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  NavigateToURL(server->TestServerPageW(L"multipart"));
  std::wstring title;
  EXPECT_TRUE(tab_proxy->GetTabTitle(&title));
  EXPECT_EQ(L"page 9", title);
  CloseBrowserAndServer();

  // The browser has shutdown now.  Check the contents of the history
  // table.  We should have only one visit for the URL even though it
  // had 10 parts.
  sql::Connection db;
  FilePath history =
      user_data_dir_.AppendASCII("Default").AppendASCII("History");
  ASSERT_TRUE(file_util::PathExists(history));
  ASSERT_TRUE(db.Open(history));
  std::string query(
      "SELECT COUNT(1) FROM visits, urls WHERE visits.url = urls.id"
      " AND urls.url LIKE 'http://localhost:%/multipart'");
  {
    sql::Statement statement(db.GetUniqueStatement(query.c_str()));
    EXPECT_TRUE(statement);
    EXPECT_TRUE(statement.Step());
    EXPECT_EQ(1, statement.ColumnInt(0));
  }
  db.Close();
}
#endif

}  // namespace
<commit_msg>Fix the build, missed a remaining TestServerPageW in code that is compiled only in Release builds.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/ui/ui_test.h"

#include "app/sql/connection.h"
#include "app/sql/statement.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class MultipartResponseUITest : public UITest {
};

#if defined(NDEBUG)
// http://code.google.com/p/chromium/issues/detail?id=37746
// Running this test only for release builds as it fails in debug test
// runs
TEST_F(MultipartResponseUITest, SingleVisit) {
  // Make sure that visiting a multipart/x-mixed-replace site only
  // creates one entry in the visits table.
  const wchar_t kDocRoot[] = L"chrome/test/data";
  scoped_refptr<HTTPTestServer> server =
      HTTPTestServer::CreateServer(kDocRoot, NULL);
  ASSERT_TRUE(NULL != server.get());

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  ASSERT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab_proxy(browser_proxy->GetActiveTab());
  ASSERT_TRUE(tab_proxy.get());
  NavigateToURL(server->TestServerPage("multipart"));
  std::wstring title;
  EXPECT_TRUE(tab_proxy->GetTabTitle(&title));
  EXPECT_EQ(L"page 9", title);
  CloseBrowserAndServer();

  // The browser has shutdown now.  Check the contents of the history
  // table.  We should have only one visit for the URL even though it
  // had 10 parts.
  sql::Connection db;
  FilePath history =
      user_data_dir_.AppendASCII("Default").AppendASCII("History");
  ASSERT_TRUE(file_util::PathExists(history));
  ASSERT_TRUE(db.Open(history));
  std::string query(
      "SELECT COUNT(1) FROM visits, urls WHERE visits.url = urls.id"
      " AND urls.url LIKE 'http://localhost:%/multipart'");
  {
    sql::Statement statement(db.GetUniqueStatement(query.c_str()));
    EXPECT_TRUE(statement);
    EXPECT_TRUE(statement.Step());
    EXPECT_EQ(1, statement.ColumnInt(0));
  }
  db.Close();
}
#endif

}  // namespace
<|endoftext|>


<commit_before>/* -*- mode:linux -*- */
/**
 * \file pbnf_search.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-29
 */

#include <assert.h>
#include <math.h>

#include <vector>

#include "pbnf_search.h"
#include "search.h"
#include "state.h"

using namespace std;
using namespace PBNF;

PBNFSearch::PBNFThread::PBNFThread(NBlockGraph *graph, PBNFSearch *search)
	: graph(graph), search(search) {}

PBNFSearch::PBNFThread::~PBNFThread(void) {}

/**
 * Run the search thread.
 */
void PBNFSearch::PBNFThread::run(void)
{
	vector<const State *> *path;
	NBlock *n = NULL;

	do {
		n = graph->next_nblock(n, search->detect_livelocks);
		if (n) {
			expansions = 0;
			path = search_nblock(n);

			if (path)
				search->set_path(path);
		}
	} while (n);

	graph->set_done();
}

/**
 * Search a single NBlock.
 */
vector<const State *> *PBNFSearch::PBNFThread::search_nblock(NBlock *n)
{
	vector<const State *> *path = NULL;
	OpenList *open = &n->open;
	ClosedList *closed = &n->closed;

	while (!open->empty() && !should_switch(n)) {
		const State *s = open->take();
		const State *dup = closed->lookup(s);

		if (s->get_f() >= search->bound
		    || (dup && dup->get_f() <= s->get_f())) {
			delete s;
			continue;
		}

		closed->add(s);

		if (s->is_goal()) {
			path = s->get_path();
			break;
		}

		expansions += 1;

		vector<const State *> *children = search->expand(s);
		vector<const State *>::iterator iter;

 		for (iter = children->begin(); iter != children->end(); iter++) {
			unsigned int block = search->project->project(*iter);
			OpenList *next_open = &graph->get_nblock(block)->open;

			if ((*iter)->get_f() < search->bound)
				next_open->add(*iter);
			else
				delete *iter;
		}
		delete children;
	}

	return path;
}

/**
 * Test the graph to see if we should switch to a new NBlock.
 * \param n The current NBlock.
 *
 * \note We should make this more complex... we should also check our
 *       successor NBlocks.
 */
bool PBNFSearch::PBNFThread::should_switch(NBlock *n)
{
	bool ret;
	double cur, scope, free;

	if (expansions < search->min_expansions)
		return false;

	if (search->detect_livelocks)
		scope = graph->best_in_scope(n);
	else
		scope = INFINITY;
	free = graph->next_nblock_f_value();
	cur = n->open.peek()->get_f();

	ret = free < cur || scope < cur;

	if (!ret && search->detect_livelocks)
		graph->wont_release(n);
	return ret;
}

/************************************************************/

PBNFSearch::PBNFSearch(unsigned int n_threads,
		       unsigned int min_expansions,
		       bool detect_livelocks)
	: n_threads(n_threads),
	  project(NULL),
	  path(NULL),
	  bound(INFINITY),
	  detect_livelocks(detect_livelocks),
	  min_expansions(min_expansions)
{
	pthread_mutex_init(&path_mutex, NULL);
}

PBNFSearch::~PBNFSearch(void) {}

vector<const State *> *PBNFSearch::search(const State *initial)
{
	project = initial->get_domain()->get_projection();

	vector<Thread *> threads;
	vector<Thread *>::iterator iter;

	NBlockGraph *graph = new NBlockGraph(project, initial);

	for (unsigned int i = 0; i < n_threads; i += 1) {
		Thread *t = new PBNFThread(graph, this);
		threads.push_back(t);
		t->start();
	}

	for (iter = threads.begin(); iter != threads.end(); iter++) {
		(*iter)->join();
		delete *iter;
	}

	delete graph;

	return path;
}

/**
 * Set an incumbant solution.
 */
void PBNFSearch::set_path(vector<const State *> *path)
{
	pthread_mutex_lock(&path_mutex);
	assert(path->at(0)->get_g() == path->at(0)->get_f());
	if (path && bound > path->at(0)->get_g()) {
		this->path = path;
		bound = path->at(0)->get_g();
	}
	pthread_mutex_unlock(&path_mutex);
}
<commit_msg>Check for duplicates *after* pruning.<commit_after>/* -*- mode:linux -*- */
/**
 * \file pbnf_search.cc
 *
 *
 *
 * \author Ethan Burns
 * \date 2008-10-29
 */

#include <assert.h>
#include <math.h>

#include <vector>

#include "pbnf_search.h"
#include "search.h"
#include "state.h"

using namespace std;
using namespace PBNF;

PBNFSearch::PBNFThread::PBNFThread(NBlockGraph *graph, PBNFSearch *search)
	: graph(graph), search(search) {}

PBNFSearch::PBNFThread::~PBNFThread(void) {}

/**
 * Run the search thread.
 */
void PBNFSearch::PBNFThread::run(void)
{
	vector<const State *> *path;
	NBlock *n = NULL;

	do {
		n = graph->next_nblock(n, search->detect_livelocks);
		if (n) {
			expansions = 0;
			path = search_nblock(n);

			if (path)
				search->set_path(path);
		}
	} while (n);

	graph->set_done();
}

/**
 * Search a single NBlock.
 */
vector<const State *> *PBNFSearch::PBNFThread::search_nblock(NBlock *n)
{
	vector<const State *> *path = NULL;
	OpenList *open = &n->open;
	ClosedList *closed = &n->closed;

	while (!open->empty() && !should_switch(n)) {
		const State *s = open->take();

		if (s->get_f() >= search->bound) {
			delete s;
			open->delete_all_states();
			break;
		}

		const State *dup = closed->lookup(s);
		if (dup && dup->get_f() <= s->get_f()) {
			delete s;
			continue;
		}

		closed->add(s);

		if (s->is_goal()) {
			path = s->get_path();
			break;
		}

		expansions += 1;

		vector<const State *> *children = search->expand(s);
		vector<const State *>::iterator iter;

 		for (iter = children->begin(); iter != children->end(); iter++) {
			unsigned int block = search->project->project(*iter);
			OpenList *next_open = &graph->get_nblock(block)->open;

			if ((*iter)->get_f() < search->bound)
				next_open->add(*iter);
			else
				delete *iter;
		}
		delete children;
	}

	return path;
}

/**
 * Test the graph to see if we should switch to a new NBlock.
 * \param n The current NBlock.
 *
 * \note We should make this more complex... we should also check our
 *       successor NBlocks.
 */
bool PBNFSearch::PBNFThread::should_switch(NBlock *n)
{
	bool ret;
	double cur, scope, free;

	if (expansions < search->min_expansions)
		return false;

	if (search->detect_livelocks)
		scope = graph->best_in_scope(n);
	else
		scope = INFINITY;
	free = graph->next_nblock_f_value();
	cur = n->open.peek()->get_f();

	ret = free < cur || scope < cur;

	if (!ret && search->detect_livelocks)
		graph->wont_release(n);
	return ret;
}

/************************************************************/

PBNFSearch::PBNFSearch(unsigned int n_threads,
		       unsigned int min_expansions,
		       bool detect_livelocks)
	: n_threads(n_threads),
	  project(NULL),
	  path(NULL),
	  bound(INFINITY),
	  detect_livelocks(detect_livelocks),
	  min_expansions(min_expansions)
{
	pthread_mutex_init(&path_mutex, NULL);
}

PBNFSearch::~PBNFSearch(void) {}

vector<const State *> *PBNFSearch::search(const State *initial)
{
	project = initial->get_domain()->get_projection();

	vector<Thread *> threads;
	vector<Thread *>::iterator iter;

	NBlockGraph *graph = new NBlockGraph(project, initial);

	for (unsigned int i = 0; i < n_threads; i += 1) {
		Thread *t = new PBNFThread(graph, this);
		threads.push_back(t);
		t->start();
	}

	for (iter = threads.begin(); iter != threads.end(); iter++) {
		(*iter)->join();
		delete *iter;
	}

	delete graph;

	return path;
}

/**
 * Set an incumbant solution.
 */
void PBNFSearch::set_path(vector<const State *> *path)
{
	pthread_mutex_lock(&path_mutex);
	assert(path->at(0)->get_g() == path->at(0)->get_f());
	if (path && bound > path->at(0)->get_g()) {
		this->path = path;
		bound = path->at(0)->get_g();
	}
	pthread_mutex_unlock(&path_mutex);
}
<|endoftext|>