<commit_before>/*************************************************************************
 *
 *  $RCSfile: colrowst.cxx,v $
 *
 *  $Revision: 1.26 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-21 13:22:30 $
 *
 *  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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

#include "colrowst.hxx"

#include <string.h>

#include "document.hxx"
#include "root.hxx"

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
#ifndef SC_XLTABLE_HXX
#include "xltable.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif

// for filter manager
#include "excimp8.hxx"

ColRowSettings::ColRowSettings( RootData& rRootData ) :
    ExcRoot( &rRootData )
{
    nDefWidth = nDefHeight = 0;

    pWidth = new INT32 [ MAXCOL + 1 ];
    pColHidden = new BOOL [ MAXCOL + 1 ];

    pHeight = new UINT16 [ MAXROW + 1 ];
    pRowFlags = new INT8[ MAXROW + 1 ];

    Reset();
}

ColRowSettings::~ColRowSettings()
{
    delete[] pRowFlags;
    delete[] pHeight;
    delete[] pColHidden;
    delete[] pWidth;
}

void ColRowSettings::Reset( void )
{
    SCCOL   nC;
    for( nC = 0 ; nC <= MAXCOL ; nC++ )
    {
        pColHidden[ nC ] = FALSE;
        pWidth[ nC ] = -1;
    }

    memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );

    bDirty = TRUE;
    nMaxRow = -1;

    bSetByStandard = FALSE;
}

void ColRowSettings::Apply( SCTAB nScTab )
{
    if( !bDirty )
        return;

    SCCOLROW                nC;
    SCROW                   nStart = 0;
    UINT16                  nWidth;
    UINT16                  nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;
    ScDocument&             rD = pExcRoot->pIR->GetDoc();

    rD.IncSizeRecalcLevel( nScTab );

    // Column-Bemachung
    for( nC = 0 ; nC <= MAXCOL ; nC++ )
    {
        if( pWidth[ nC ] >= 0 )
            // eingestellte Width
            nWidth = ( UINT16 ) pWidth[ nC ];
        else
            // Default-Width
            nWidth = nDefWidth;

        if( nWidth == 0 )
        {
            pColHidden[ nC ] = TRUE;
            // Column hidden: remember original column width and set width 0.
            // Needed for #i11776#, no HIDDEN flags in the document, until
            // filters and outlines are inserted.
            pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );
        }
        rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );
    }

    // Row-Bemachung

    INT8                    nFlags;
    nStart = 0;
    UINT16                  nHeight;

    UINT16                  nLastHeight;
    nFlags = pRowFlags[ 0 ];
    if( nFlags & ROWFLAG_USED )
    {
        if( nFlags & ROWFLAG_DEFAULT )
            nLastHeight = nDefHeight;
        else
        {
            nLastHeight = pHeight[ 0 ];
            if( !nLastHeight )
                nLastHeight = nDefHeight;
        }
    }
    else
        nLastHeight = nDefHeight;

    for( nC = 0 ; nC <= nMaxRow ; nC++ )
    {
        nFlags = pRowFlags[ nC ];

        if( nFlags & ROWFLAG_USED )
        {
            if( nFlags & ROWFLAG_DEFAULT )
                nHeight = nDefHeight;
            else
            {
                nHeight = pHeight[ nC ];
                if( !nHeight )
                    nHeight = nDefHeight;
            }

            if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )
            {
                BYTE        nSCFlags = rD.GetRowFlags( nC , nScTab );

                if( nFlags & ROWFLAG_MAN )
                    nSCFlags |= CR_MANUALSIZE;

                rD.SetRowFlags( nC, nScTab, nSCFlags );
            }
        }
        else
            nHeight = nDefHeight;

        if( !nHeight )
        {
            pRowFlags[ nC ] |= ROWFLAG_HIDDEN;
            // Row hidden: remember original row height and set height 0.
            // Needed for #i11776#, no HIDDEN flags in the document, until
            // filters and outlines are inserted.
            pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );
        }

        if( nLastHeight != nHeight )
        {
            DBG_ASSERT( nC > 0, "ColRowSettings::Apply(): Algorithmus-Fehler!" );

            if( nLastHeight )
                rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );

            nStart = nC;
            nLastHeight = nHeight;
        }
    }

    if( nLastHeight && nMaxRow >= 0 )
        rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );

    bDirty = FALSE; // jetzt stimmt Tabelle im ScDocument

    rD.DecSizeRecalcLevel( nScTab );
}

void ColRowSettings::SetHiddenFlags( SCTAB nScTab )
{
    ScDocument& rDoc = pExcRoot->pIR->GetDoc();

    for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )
    {
        if( pColHidden[ nScCol ] )
        {
            // set original width, needed to unhide the column
            if( pWidth[ nScCol ] > 0 )
                rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );
            // really hide the column
            rDoc.ShowCol( nScCol, nScTab, FALSE );
        }
    }

    // #i38093# rows hidden by filter need extra flag
    SCROW nFirstFilterScRow = SCROW_MAX;
    SCROW nLastFilterScRow = SCROW_MAX;
    if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )
    {
        const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );
        if( pFilter && pFilter->IsActive() )
        {
            nFirstFilterScRow = pFilter->StartRow();
            nLastFilterScRow = pFilter->EndRow();
        }
    }

    for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )
    {
        if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )
        {
            // set original height, needed to unhide the row
            if( pHeight[ nScRow ] > 0 )
                rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );
            // really hide the row
            rDoc.ShowRow( nScRow, nScTab, FALSE );
            // #i38093# rows hidden by filter need extra flag
            if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )
                rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );
        }
    }
}

void ColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )
{
    DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::HideColRange(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::HideColRange(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    BOOL*   pHidden;
    BOOL*   pFinish;
    pHidden = &pColHidden[ nColFirst ];
    pFinish = &pColHidden[ nColLast ];
    while( pHidden <= pFinish )
        *( pHidden++ ) = TRUE;
}

void ColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )
{
    DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::SetColWidthRange(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::SetColWidthRange(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    INT32*  pWidthCount;
    INT32*  pFinish;
    pWidthCount = &pWidth[ nColFirst ];
    pFinish = &pWidth[ nColLast ];

    while( pWidthCount <= pFinish )
        *( pWidthCount++ ) = nNew;
}

void ColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )
{
    DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::SetDefaultXF(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::SetDefaultXF(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    const XclImpRoot& rRoot = *pExcRoot->pIR;

    // #109555# assign the default column formatting here to ensure
    // that explicit cell formatting is not overwritten.
    for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )
        rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );
}

void ColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )
{
    nDefWidth = nWidth;
    nDefHeight = nHeight;
}

void ColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )
{
    pHeight[ nRow ] = nExcelHeight & 0x7FFF;

    INT8    nFlags = ROWFLAG_USED;

    if( nExcelHeight & 0x8000 )
        nFlags |= ROWFLAG_DEFAULT;

    if( nGrbit & EXC_ROW_UNSYNCED )
        nFlags |= ROWFLAG_MAN;

    if( nGrbit &  EXC_ROW_HIDDEN )
        nFlags |= ROWFLAG_HIDDEN;

    pRowFlags[ nRow ] = nFlags;

    if( nRow > nMaxRow )
        nMaxRow = nRow;
}

<commit_msg>INTEGRATION: CWS dr34 (1.26.2); FILE MERGED 2005/03/17 16:20:51 dr 1.26.2.1: #i45209# rename classes with name already used somewhere<commit_after>/*************************************************************************
 *
 *  $RCSfile: colrowst.cxx,v $
 *
 *  $Revision: 1.27 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 13:36:04 $
 *
 *  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: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

#include "colrowst.hxx"

#include <string.h>

#include "document.hxx"
#include "root.hxx"

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
#ifndef SC_XLTABLE_HXX
#include "xltable.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif

// for filter manager
#include "excimp8.hxx"

XclImpColRowSettings::XclImpColRowSettings( RootData& rRootData ) :
    ExcRoot( &rRootData )
{
    nDefWidth = nDefHeight = 0;

    pWidth = new INT32 [ MAXCOL + 1 ];
    pColHidden = new BOOL [ MAXCOL + 1 ];

    pHeight = new UINT16 [ MAXROW + 1 ];
    pRowFlags = new INT8[ MAXROW + 1 ];

    Reset();
}

XclImpColRowSettings::~XclImpColRowSettings()
{
    delete[] pRowFlags;
    delete[] pHeight;
    delete[] pColHidden;
    delete[] pWidth;
}

void XclImpColRowSettings::Reset( void )
{
    SCCOL   nC;
    for( nC = 0 ; nC <= MAXCOL ; nC++ )
    {
        pColHidden[ nC ] = FALSE;
        pWidth[ nC ] = -1;
    }

    memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );

    bDirty = TRUE;
    nMaxRow = -1;

    bSetByStandard = FALSE;
}

void XclImpColRowSettings::Apply( SCTAB nScTab )
{
    if( !bDirty )
        return;

    SCCOLROW                nC;
    SCROW                   nStart = 0;
    UINT16                  nWidth;
    UINT16                  nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;
    ScDocument&             rD = pExcRoot->pIR->GetDoc();

    rD.IncSizeRecalcLevel( nScTab );

    // Column-Bemachung
    for( nC = 0 ; nC <= MAXCOL ; nC++ )
    {
        if( pWidth[ nC ] >= 0 )
            // eingestellte Width
            nWidth = ( UINT16 ) pWidth[ nC ];
        else
            // Default-Width
            nWidth = nDefWidth;

        if( nWidth == 0 )
        {
            pColHidden[ nC ] = TRUE;
            // Column hidden: remember original column width and set width 0.
            // Needed for #i11776#, no HIDDEN flags in the document, until
            // filters and outlines are inserted.
            pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );
        }
        rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );
    }

    // Row-Bemachung

    INT8                    nFlags;
    nStart = 0;
    UINT16                  nHeight;

    UINT16                  nLastHeight;
    nFlags = pRowFlags[ 0 ];
    if( nFlags & ROWFLAG_USED )
    {
        if( nFlags & ROWFLAG_DEFAULT )
            nLastHeight = nDefHeight;
        else
        {
            nLastHeight = pHeight[ 0 ];
            if( !nLastHeight )
                nLastHeight = nDefHeight;
        }
    }
    else
        nLastHeight = nDefHeight;

    for( nC = 0 ; nC <= nMaxRow ; nC++ )
    {
        nFlags = pRowFlags[ nC ];

        if( nFlags & ROWFLAG_USED )
        {
            if( nFlags & ROWFLAG_DEFAULT )
                nHeight = nDefHeight;
            else
            {
                nHeight = pHeight[ nC ];
                if( !nHeight )
                    nHeight = nDefHeight;
            }

            if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )
            {
                BYTE        nSCFlags = rD.GetRowFlags( nC , nScTab );

                if( nFlags & ROWFLAG_MAN )
                    nSCFlags |= CR_MANUALSIZE;

                rD.SetRowFlags( nC, nScTab, nSCFlags );
            }
        }
        else
            nHeight = nDefHeight;

        if( !nHeight )
        {
            pRowFlags[ nC ] |= ROWFLAG_HIDDEN;
            // Row hidden: remember original row height and set height 0.
            // Needed for #i11776#, no HIDDEN flags in the document, until
            // filters and outlines are inserted.
            pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );
        }

        if( nLastHeight != nHeight )
        {
            DBG_ASSERT( nC > 0, "XclImpColRowSettings::Apply(): Algorithmus-Fehler!" );

            if( nLastHeight )
                rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );

            nStart = nC;
            nLastHeight = nHeight;
        }
    }

    if( nLastHeight && nMaxRow >= 0 )
        rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );

    bDirty = FALSE; // jetzt stimmt Tabelle im ScDocument

    rD.DecSizeRecalcLevel( nScTab );
}

void XclImpColRowSettings::SetHiddenFlags( SCTAB nScTab )
{
    ScDocument& rDoc = pExcRoot->pIR->GetDoc();

    for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )
    {
        if( pColHidden[ nScCol ] )
        {
            // set original width, needed to unhide the column
            if( pWidth[ nScCol ] > 0 )
                rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );
            // really hide the column
            rDoc.ShowCol( nScCol, nScTab, FALSE );
        }
    }

    // #i38093# rows hidden by filter need extra flag
    SCROW nFirstFilterScRow = SCROW_MAX;
    SCROW nLastFilterScRow = SCROW_MAX;
    if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )
    {
        const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );
        if( pFilter && pFilter->IsActive() )
        {
            nFirstFilterScRow = pFilter->StartRow();
            nLastFilterScRow = pFilter->EndRow();
        }
    }

    for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )
    {
        if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )
        {
            // set original height, needed to unhide the row
            if( pHeight[ nScRow ] > 0 )
                rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );
            // really hide the row
            rDoc.ShowRow( nScRow, nScTab, FALSE );
            // #i38093# rows hidden by filter need extra flag
            if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )
                rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );
        }
    }
}

void XclImpColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )
{
    DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::HideColRange(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::HideColRange(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    BOOL*   pHidden;
    BOOL*   pFinish;
    pHidden = &pColHidden[ nColFirst ];
    pFinish = &pColHidden[ nColLast ];
    while( pHidden <= pFinish )
        *( pHidden++ ) = TRUE;
}

void XclImpColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )
{
    DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::SetColWidthRange(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::SetColWidthRange(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    INT32*  pWidthCount;
    INT32*  pFinish;
    pWidthCount = &pWidth[ nColFirst ];
    pFinish = &pWidth[ nColLast ];

    while( pWidthCount <= pFinish )
        *( pWidthCount++ ) = nNew;
}

void XclImpColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )
{
    DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::SetDefaultXF(): First > Last?!" );
    DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::SetDefaultXF(): ungueltige Column" );

    if( !ValidCol(nColLast) )
        nColLast = MAXCOL;

    const XclImpRoot& rRoot = *pExcRoot->pIR;

    // #109555# assign the default column formatting here to ensure
    // that explicit cell formatting is not overwritten.
    for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )
        rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );
}

void XclImpColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )
{
    nDefWidth = nWidth;
    nDefHeight = nHeight;
}

void XclImpColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )
{
    pHeight[ nRow ] = nExcelHeight & 0x7FFF;

    INT8    nFlags = ROWFLAG_USED;

    if( nExcelHeight & 0x8000 )
        nFlags |= ROWFLAG_DEFAULT;

    if( nGrbit & EXC_ROW_UNSYNCED )
        nFlags |= ROWFLAG_MAN;

    if( nGrbit &  EXC_ROW_HIDDEN )
        nFlags |= ROWFLAG_HIDDEN;

    pRowFlags[ nRow ] = nFlags;

    if( nRow > nMaxRow )
        nMaxRow = nRow;
}

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <algorithm>
#include <stdio.h>
#include <vector>

#include "NETEQTEST_RTPpacket.h"

/*********************/
/* Misc. definitions */
/*********************/

#define FIRSTLINELEN 40

bool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b)
{
    return (a->time() < b->time());
}

int main(int argc, char* argv[])
{
	FILE *inFile=fopen(argv[1],"rb");
	if (!inFile)
    {
        printf("Cannot open input file %s\n", argv[1]);
        return(-1);
    }
    printf("Input RTP file: %s\n",argv[1]);

    FILE *statFile=fopen(argv[2],"rt");
	if (!statFile)
    {
        printf("Cannot open timing file %s\n", argv[2]);
        return(-1);
    }
    printf("Timing file: %s\n",argv[2]);

	FILE *outFile=fopen(argv[3],"wb");
	if (!outFile)
    {
        printf("Cannot open output file %s\n", argv[3]);
        return(-1);
    }
	printf("Output RTP file: %s\n\n",argv[3]);

    // read all statistics and insert into map
    // read first line
    char tempStr[100];
    fgets(tempStr, 100, statFile);

    // define map
    std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_Word32> packetStats;
    WebRtc_UWord16 seqNo;
    WebRtc_UWord32 ts;
    WebRtc_Word32 sendTime;

    while(fscanf(statFile, "%hu %lu %ld\n", &seqNo, &ts, &sendTime) == 3)
    {
        std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair = std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);

        packetStats[tempPair] = sendTime;
    }

    fclose(statFile);

    // read file header and write directly to output file
	char firstline[FIRSTLINELEN];
	fgets(firstline, FIRSTLINELEN, inFile);
	fputs(firstline, outFile);
	fread(firstline, 4+4+4+2+2, 1, inFile); // start_sec + start_usec	+ source + port + padding
	fwrite(firstline, 4+4+4+2+2, 1, outFile);

    std::vector<NETEQTEST_RTPpacket *> packetVec;
    int i = 0;

    while (1)
    {
        // insert in vector
        NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();
        if (newPacket->readFromFile(inFile) < 0)
        {
            // end of file
            break;
        }

        // look for new send time in statistics vector
        std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
            std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());

        WebRtc_Word32 newSendTime = packetStats[tempPair];
        if (newSendTime >= 0)
        {
            newPacket->setTime(newSendTime); // set new send time
            packetVec.push_back(newPacket); // insert in vector
        }
        else
        {
            // negative value represents lost packet
            // don't insert, but delete packet object
            delete newPacket;
        }

    }

    // sort the vector according to send times
    std::sort(packetVec.begin(), packetVec.end(), pktCmp);

    std::vector<NETEQTEST_RTPpacket *>::iterator it;
    for (it = packetVec.begin(); it != packetVec.end(); it++)
    {
        // write to out file
        if ((*it)->writeToFile(outFile) < 0)
        {
            printf("Error writing to file\n");
            return(-1);
        }

        // delete packet
        delete *it;
    }

    fclose(inFile);
    fclose(outFile);

    return 0;
}
<commit_msg>Update test tool RTPchange<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <algorithm>
#include <stdio.h>
#include <vector>

#include "NETEQTEST_RTPpacket.h"

/*********************/
/* Misc. definitions */
/*********************/

#define FIRSTLINELEN 40

bool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b)
{
    return (a->time() < b->time());
}

int main(int argc, char* argv[])
{
	FILE *inFile=fopen(argv[1],"rb");
	if (!inFile)
    {
        printf("Cannot open input file %s\n", argv[1]);
        return(-1);
    }
    printf("Input RTP file: %s\n",argv[1]);

    FILE *statFile=fopen(argv[2],"rt");
	if (!statFile)
    {
        printf("Cannot open timing file %s\n", argv[2]);
        return(-1);
    }
    printf("Timing file: %s\n",argv[2]);

	FILE *outFile=fopen(argv[3],"wb");
	if (!outFile)
    {
        printf("Cannot open output file %s\n", argv[3]);
        return(-1);
    }
	printf("Output RTP file: %s\n\n",argv[3]);

    // read all statistics and insert into map
    // read first line
    char tempStr[100];
    fgets(tempStr, 100, statFile);

    // define map
    std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_UWord32>
        packetStats;
    WebRtc_UWord16 seqNo;
    WebRtc_UWord32 ts;
    WebRtc_UWord32 sendTime;

    while(fscanf(statFile, "%u %u %u %*i\n", &seqNo, &ts, &sendTime) == 3)
    {
        std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
            std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);

        packetStats[tempPair] = sendTime;
    }

    fclose(statFile);

    // read file header and write directly to output file
	char firstline[FIRSTLINELEN];
	fgets(firstline, FIRSTLINELEN, inFile);
	fputs(firstline, outFile);
	fread(firstline, 4+4+4+2+2, 1, inFile); // start_sec + start_usec	+ source + port + padding
	fwrite(firstline, 4+4+4+2+2, 1, outFile);

    std::vector<NETEQTEST_RTPpacket *> packetVec;
    int i = 0;

    while (1)
    {
        // insert in vector
        NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();
        if (newPacket->readFromFile(inFile) < 0)
        {
            // end of file
            break;
        }

        // look for new send time in statistics vector
        std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
            std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());

        WebRtc_UWord32 newSendTime = packetStats[tempPair];
        if (newSendTime >= 0)
        {
            newPacket->setTime(newSendTime); // set new send time
            packetVec.push_back(newPacket); // insert in vector
        }
        else
        {
            // negative value represents lost packet
            // don't insert, but delete packet object
            delete newPacket;
        }

    }

    // sort the vector according to send times
    std::sort(packetVec.begin(), packetVec.end(), pktCmp);

    std::vector<NETEQTEST_RTPpacket *>::iterator it;
    for (it = packetVec.begin(); it != packetVec.end(); it++)
    {
        // write to out file
        if ((*it)->writeToFile(outFile) < 0)
        {
            printf("Error writing to file\n");
            return(-1);
        }

        // delete packet
        delete *it;
    }

    fclose(inFile);
    fclose(outFile);

    return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/experimental/ruy/context.h"

#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/detect_arm.h"
#include "tensorflow/lite/experimental/ruy/detect_x86.h"
#include "tensorflow/lite/experimental/ruy/have_built_path_for.h"
#include "tensorflow/lite/experimental/ruy/platform.h"

namespace ruy {

void Context::SetRuntimeEnabledPaths(Path paths) {
  runtime_enabled_paths_ = paths;
}

Path Context::GetRuntimeEnabledPaths() {
  // This function should always return the same value on a given machine.
  // When runtime_enabled_paths_ has its initial value kNone, it performs
  // some platform detection to resolve it to specific Path values.

  // Fast path: already resolved.
  if (runtime_enabled_paths_ != Path::kNone) {
    return runtime_enabled_paths_;
  }

  // Need to resolve now. Start by considering all paths enabled.
  runtime_enabled_paths_ = kAllPaths;

#if RUY_PLATFORM(ARM)
  // Now selectively disable paths that aren't supported on this machine.
  if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {
    if (!DetectDotprod()) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);
    }
  }
#endif  // RUY_PLATFORM(ARM)

#if RUY_PLATFORM(X86)
  if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {
    if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);
    }
  }

  if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {
    if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);
    }
  }
#endif  // RUY_PLATFORM(X86)

  // Sanity check. We can't possibly have disabled all paths, as some paths
  // are universally available (kReference, kStandardCpp).
  RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);
  return runtime_enabled_paths_;
}

}  // namespace ruy
<commit_msg>Ruy: Add mechanism to mask out paths.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/lite/experimental/ruy/context.h"

#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/detect_arm.h"
#include "tensorflow/lite/experimental/ruy/detect_x86.h"
#include "tensorflow/lite/experimental/ruy/have_built_path_for.h"
#include "tensorflow/lite/experimental/ruy/platform.h"

namespace ruy {

void Context::SetRuntimeEnabledPaths(Path paths) {
  runtime_enabled_paths_ = paths;
}

Path Context::GetRuntimeEnabledPaths() {
  // This function should always return the same value on a given machine.
  // When runtime_enabled_paths_ has its initial value kNone, it performs
  // some platform detection to resolve it to specific Path values.

  // Fast path: already resolved.
  if (runtime_enabled_paths_ != Path::kNone) {
    return runtime_enabled_paths_;
  }

  // Need to resolve now. Start by considering all paths enabled.
  runtime_enabled_paths_ = kAllPaths;

  // This mechanism is intended to be used for testing and benchmarking. For
  // example, one can set RUY_FORCE_DISABLE_PATHS to Path::kAvx512 in order to
  // evaluate AVX2 performance on an AVX-512 machine.
#ifdef RUY_FORCE_DISABLE_PATHS
  runtime_enabled_paths_ = runtime_enabled_paths_ & ~(RUY_FORCE_DISABLE_PATHS);
#endif

#if RUY_PLATFORM(ARM)
  // Now selectively disable paths that aren't supported on this machine.
  if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {
    if (!DetectDotprod()) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);
    }
  }
#endif  // RUY_PLATFORM(ARM)

#if RUY_PLATFORM(X86)
  if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {
    if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);
    }
  }

  if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {
    if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {
      runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;
      // Sanity check.
      RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);
    }
  }
#endif  // RUY_PLATFORM(X86)

  // Sanity check. We can't possibly have disabled all paths, as some paths
  // are universally available (kReference, kStandardCpp).
  RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);
  return runtime_enabled_paths_;
}

}  // namespace ruy
<|endoftext|>


<commit_before>/*

*/

#include "lineFollowing.h"
#include "../control.h"

using namespace std;
using namespace cv;

void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);

void draw_lines(const Mat &image, const vector<Vec2f> &lines);

vector<Vec2f> condense_lines(vector<Vec2f> &lines);

void LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {

  Mat hsv;
  Mat mask;
  Mat image;

  cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
  Canny(mask, mask, 50, 200, 3);

  vector<Vec2f> lines;
  HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);

  printf("Adding in %d lines\n", (int) lines.size());

  vector<Vec2f> condensed = condense_lines(lines);
  draw_lines(original_frame, condensed);

}

vector<Vec2f> condense_lines(vector<Vec2f> lines) {
  vector<Vec2f> condensed;
  vector<Vec2f> tmp_list;
  for (int i = 0; i < lines.size(); i++) {
    if (lines[i][1] > CV_PI / 2) {
      lines[i][1] -= CV_PI;
      lines[i][0] *= -1;
    }
    else if (lines[i][1] < ((CV_PI / 2) * -1)) {
      lines[i][1] += CV_PI;
      lines[i][0] *= -1;
    }

    //put in order of theta, rho
    swap(lines[i][0], lines[i][1]);
  }

  //Order from least to greatest theta
  sort(lines.begin(), lines.end(),
       [](const Vec2f &a, const Vec2f &b) {
         return a[0] < b[0];
       });

  while (!lines.empty()) {
    Vec2f to_manipulate = lines.front();
    lines.erase(lines.begin());

    if (tmp_list.empty()) {
      tmp_list.push_back(to_manipulate);
      continue;
    } else {
      if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
        //The angles are similar
        if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
          //the distances are similar
          tmp_list.push_back(to_manipulate);
          continue;
        }
      } else {
        //Need to clear out the tmp_list
        compress_lines(condensed, tmp_list);

        tmp_list.clear();
        tmp_list.push_back(to_manipulate);

      }
    }
  }
  if (!tmp_list.empty()) {
    compress_lines(condensed, tmp_list);
  }
  return condensed;
}

void draw_lines(const Mat &image, const vector<Vec2f> &lines) {
  for (size_t i = 0; i < lines.size(); i++) {
    float theta = lines[i][0], rho = lines[i][1];
    // float rho = lines[i][0], theta = lines[i][1];
    Point pt1, pt2;
    double a = cos(theta), b = sin(theta);
    double x0 = a * rho, y0 = b * rho;
    pt1.x = cvRound(x0 + 1000 * (-b));
    pt1.y = cvRound(y0 + 1000 * (a));
    pt2.x = cvRound(x0 - 1000 * (-b));
    pt2.y = cvRound(y0 - 1000 * (a));
    line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
  }
}

void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
  Vec2f new_point;
  float angle_sum = 0;
  float rho_sum = 0;
  for (int j = 0; j < tmp_list.size(); ++j) {
    angle_sum += tmp_list[j][0];
    rho_sum += tmp_list[j][1];
  }
  angle_sum /= tmp_list.size();
  rho_sum /= tmp_list.size();

  new_point[0] = angle_sum;
  new_point[1] = rho_sum;

  condensed.push_back(new_point);
}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  minH = 50;
  minS = 20;
  minV = 150;
  maxH = 125;
  maxS = 100;
  maxV = 255;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image, 1);

  return;
}
<commit_msg>fixes<commit_after>/*

*/

#include "lineFollowing.h"
#include "../control.h"

using namespace std;
using namespace cv;

void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);

void draw_lines(Mat &image, const vector<Vec2f> &lines);

vector<Vec2f> condense_lines(vector<Vec2f> lines);

void LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {

  Mat hsv;
  Mat mask;
  Mat image;

  cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV

  Scalar lower(minH, minS, minV);
  Scalar upper(maxH, maxS, maxV);
  inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
  Canny(mask, mask, 50, 200, 3);

  vector<Vec2f> lines;
  HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);

  printf("Adding in %d lines\n", (int) lines.size());

  vector<Vec2f> condensed = condense_lines(lines);
  draw_lines(original_frame, condensed);

}

vector<Vec2f> condense_lines(vector<Vec2f> lines) {
  vector<Vec2f> condensed;
  vector<Vec2f> tmp_list;
  for (int i = 0; i < lines.size(); i++) {
    if (lines[i][1] > CV_PI / 2) {
      lines[i][1] -= CV_PI;
      lines[i][0] *= -1;
    }
    else if (lines[i][1] < ((CV_PI / 2) * -1)) {
      lines[i][1] += CV_PI;
      lines[i][0] *= -1;
    }

    //put in order of theta, rho
    swap(lines[i][0], lines[i][1]);
  }

  //Order from least to greatest theta
  sort(lines.begin(), lines.end(),
       [](const Vec2f &a, const Vec2f &b) {
         return a[0] < b[0];
       });

  while (!lines.empty()) {
    Vec2f to_manipulate = lines.front();
    lines.erase(lines.begin());

    if (tmp_list.empty()) {
      tmp_list.push_back(to_manipulate);
      continue;
    } else {
      if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
        //The angles are similar
        if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
          //the distances are similar
          tmp_list.push_back(to_manipulate);
          continue;
        }
      } else {
        //Need to clear out the tmp_list
        compress_lines(condensed, tmp_list);

        tmp_list.clear();
        tmp_list.push_back(to_manipulate);

      }
    }
  }
  if (!tmp_list.empty()) {
    compress_lines(condensed, tmp_list);
  }
  return condensed;
}

void draw_lines(Mat &image, const vector<Vec2f> &lines) {
  for (size_t i = 0; i < lines.size(); i++) {
    float theta = lines[i][0], rho = lines[i][1];
    // float rho = lines[i][0], theta = lines[i][1];
    Point pt1, pt2;
    double a = cos(theta), b = sin(theta);
    double x0 = a * rho, y0 = b * rho;
    pt1.x = cvRound(x0 + 1000 * (-b));
    pt1.y = cvRound(y0 + 1000 * (a));
    pt2.x = cvRound(x0 - 1000 * (-b));
    pt2.y = cvRound(y0 - 1000 * (a));
    line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
  }
}

void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
  Vec2f new_point;
  float angle_sum = 0;
  float rho_sum = 0;
  for (int j = 0; j < tmp_list.size(); ++j) {
    angle_sum += tmp_list[j][0];
    rho_sum += tmp_list[j][1];
  }
  angle_sum /= tmp_list.size();
  rho_sum /= tmp_list.size();

  new_point[0] = angle_sum;
  new_point[1] = rho_sum;

  condensed.push_back(new_point);
}

LineFollowing::LineFollowing(Control *control) {
  namedWindow("line_window", CV_WINDOW_NORMAL);
  control_ptr = control;
  minH = 50;
  minS = 20;
  minV = 150;
  maxH = 125;
  maxS = 100;
  maxV = 255;
  return;
}

void LineFollowing::close() {
  return;
}

void LineFollowing::fly() {

  control_ptr->velocities.vx = 0;
  control_ptr->velocities.vy = 0;
  control_ptr->velocities.vz = 0;
  control_ptr->velocities.vr = 0;

  detect_lines(control_ptr->image, 1);

  return;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: namebuff.cxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 11:50:23 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include "namebuff.hxx"

#include <tools/urlobj.hxx>
#include <string.h>

#include "rangenam.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scextopt.hxx"

#include "root.hxx"
#include "tokstack.hxx"

#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

UINT32 StringHashEntry::MakeHashCode( const String& r )
{
    register UINT32                 n = 0;
    const sal_Unicode*              pAkt = r.GetBuffer();
    register sal_Unicode            cAkt = *pAkt;

    while( cAkt )
    {
        n *= 70;
        n += ( UINT32 ) cAkt;
        pAkt++;
        cAkt = *pAkt;
    }

    return n;
}

NameBuffer::~NameBuffer()
{
    register StringHashEntry*   pDel = ( StringHashEntry* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( StringHashEntry* ) List::Next();
    }
}

//void NameBuffer::operator <<( const SpString &rNewString )
void NameBuffer::operator <<( const String &rNewString )
{
    DBG_ASSERT( Count() + nBase < 0xFFFF,
        "*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!" );

    List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );
}

void NameBuffer::Reset()
{
    register StringHashEntry*   pDel = ( StringHashEntry* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( StringHashEntry* ) List::Next();
    }
    Clear();
}

BOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )
{
    StringHashEntry             aRefEntry( String::CreateFromAscii( pRefName ) );

    register StringHashEntry*   pFind = ( StringHashEntry* ) List::First();
    register UINT16             nCnt = nBase;
    while( pFind )
    {
        if( *pFind == aRefEntry )
        {
            rIndex = nCnt;
            return TRUE;
        }
        pFind = ( StringHashEntry* ) List::Next();
        nCnt++;
    }

    return FALSE;
}

#ifdef DBG_UTIL
UINT16  nShrCnt;
#endif

size_t
ShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const
{
    // Use something simple, it is just a hash.
    return (static_cast <UINT16> (addr.Row()) << 0) |
           (static_cast <UINT8> (addr.Col()) << 16) |
           (static_cast <UINT8> (addr.Tab()) << 24);
}

static const UINT16 nBase = 16384;  // Range~ und Shared~ Dingens mit jeweils der Haelfte Ids
ShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :
    ExcRoot( pRD ),
    cur_index (nBase)
{
#ifdef DBG_UTIL
    nShrCnt = 0;
#endif
}

ShrfmlaBuffer::~ShrfmlaBuffer()
{
}

void ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )
{
    String          aName( CreateName( rRange.aStart ) );

    DBG_ASSERT( cur_index <= 0xFFFF, "*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!" );

    ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );
    pData->SetIndex (cur_index);
    pExcRoot->pIR->GetNamedRanges().Insert( pData );
    index_hash[rRange.aStart] = cur_index;
    index_list.push_front (rRange);
    cur_index++;
}

UINT16 ShrfmlaBuffer::Find( const ScAddress & aAddr ) const
{
    ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);
    if (hash != index_hash.end())
        return hash->second;

    // It was not hashed on the top left corner ?  do a brute force search
    unsigned int ind = nBase;
    for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)
        if ((--ptr)->In (aAddr))
            return ind;
    return cur_index;
}

#define SHRFMLA_BASENAME    "SHARED_FORMULA_"

String ShrfmlaBuffer::CreateName( const ScRange& r )
{
    String          aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );
    aName += String::CreateFromInt32( r.aStart.Col() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aStart.Row() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aEnd.Col() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aEnd.Row() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aStart.Tab() );

    return aName;
}

ExtSheetBuffer::~ExtSheetBuffer()
{
    Cont    *pAkt = ( Cont * ) List::First();
    while( pAkt )
    {
        delete pAkt;
        pAkt = ( Cont * ) List::Next();
    }
}

void ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )
{
    List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );
}

BOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )
{
    DBG_ASSERT( nExcIndex,
        "*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!" );

    nExcIndex--;
    Cont*       pCur = ( Cont * ) List::GetObject( nExcIndex );
    UINT16&     rTabNum = pCur->nTabNum;

    if( pCur )
    {
        if( rTabNum < 0xFFFD )
        {
            rScIndex = rTabNum;
            return TRUE;
        }

        if( rTabNum == 0xFFFF )
        {// neue Tabelle erzeugen
            SCTAB   nNewTabNum;
            if( pCur->bSWB )
            {// Tabelle ist im selben Workbook!
                if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )
                {
                    rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
                    return TRUE;
                }
                else
                    rTabNum = 0xFFFD;
            }
            else if( pExcRoot->pIR->GetDocShell() )
            {// Tabelle ist 'echt' extern
                if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )
                {
                    String      aURL( ScGlobal::GetAbsDocName( pCur->aFile,
                                        pExcRoot->pIR->GetDocShell() ) );
                    String      aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );
                    if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )
                    {
                        rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
                        return TRUE;
                    }
                    else
                        rTabNum = 0xFFFE;       // Tabelle einmal nicht angelegt -> wird
                                                //  wohl auch nicht mehr gehen...
                }
                else
                    rTabNum = 0xFFFE;

            }
        }
    }

    return FALSE;
}

BOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsLink(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
        return pRet->bLink;
    else
        return FALSE;
}

BOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::GetLink(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
    {
        rAppl = pRet->aFile;
        rDoc = pRet->aTab;
        return TRUE;
    }
    else
        return FALSE;
}

BOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsExternal(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
        return !pRet->bSWB;
    else
        return FALSE;
}

void ExtSheetBuffer::Reset( void )
{
    Cont    *pAkt = ( Cont * ) List::First();
    while( pAkt )
    {
        delete pAkt;
        pAkt = ( Cont * ) List::Next();
    }

    List::Clear();
}

BOOL ExtName::IsDDE( void ) const
{
    return ( nFlags & 0x0001 ) != 0;
}

BOOL ExtName::IsOLE( void ) const
{
    return ( nFlags & 0x0002 ) != 0;
}

BOOL ExtName::IsName( void ) const
{
    return ( nFlags & 0x0004 ) != 0;
}

const sal_Char* ExtNameBuff::pJoostTest = "Joost ist immer noch doof!";

ExtNameBuff::~ExtNameBuff()
{
    ExtName*    pDel = ( ExtName* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( ExtName* ) List::Next();
    }
}

void ExtNameBuff::AddDDE( const String& rName )
{
    ExtName*    pNew = new ExtName( rName );
    pNew->nFlags = 0x0001;

    List::Insert( pNew, LIST_APPEND );
}

void ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )
{
    ExtName*    pNew = new ExtName( rName );
    pNew->nFlags = 0x0002;
    pNew->nStorageId = nStorageId;

    List::Insert( pNew, LIST_APPEND );
}

void ExtNameBuff::AddName( const String& rName )
{
    ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );
    pNew->nFlags = 0x0004;

    List::Insert( pNew, LIST_APPEND );
}

const ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const
{
    DBG_ASSERT( nExcelIndex > 0, "*ExtNameBuff::GetName(): Index kann nur >0 sein!" );

    return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );
}

void ExtNameBuff::Reset( void )
{
    ExtName*    pDel = ( ExtName* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( ExtName* ) List::Next();
    }

    sal_Char cTmp = *pJoostTest;
    cTmp++;

    List::Clear();
}

<commit_msg>INTEGRATION: CWS calcwarnings (1.23.110); FILE MERGED 2006/12/01 14:42:24 dr 1.23.110.1: #i69284# remove compiler warnings for wntmsci10<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: namebuff.cxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 12:23:43 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include "namebuff.hxx"

#include <tools/urlobj.hxx>
#include <string.h>

#include "rangenam.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scextopt.hxx"

#include "root.hxx"
#include "tokstack.hxx"

#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

UINT32 StringHashEntry::MakeHashCode( const String& r )
{
    register UINT32                 n = 0;
    const sal_Unicode*              pAkt = r.GetBuffer();
    register sal_Unicode            cAkt = *pAkt;

    while( cAkt )
    {
        n *= 70;
        n += ( UINT32 ) cAkt;
        pAkt++;
        cAkt = *pAkt;
    }

    return n;
}

NameBuffer::~NameBuffer()
{
    register StringHashEntry*   pDel = ( StringHashEntry* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( StringHashEntry* ) List::Next();
    }
}

//void NameBuffer::operator <<( const SpString &rNewString )
void NameBuffer::operator <<( const String &rNewString )
{
    DBG_ASSERT( Count() + nBase < 0xFFFF,
        "*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!" );

    List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );
}

void NameBuffer::Reset()
{
    register StringHashEntry*   pDel = ( StringHashEntry* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( StringHashEntry* ) List::Next();
    }
    Clear();
}

BOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )
{
    StringHashEntry             aRefEntry( String::CreateFromAscii( pRefName ) );

    register StringHashEntry*   pFind = ( StringHashEntry* ) List::First();
    register UINT16             nCnt = nBase;
    while( pFind )
    {
        if( *pFind == aRefEntry )
        {
            rIndex = nCnt;
            return TRUE;
        }
        pFind = ( StringHashEntry* ) List::Next();
        nCnt++;
    }

    return FALSE;
}

#ifdef DBG_UTIL
UINT16  nShrCnt;
#endif

size_t ShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const
{
    // Use something simple, it is just a hash.
    return (static_cast <UINT16> (addr.Row()) << 0) |
           (static_cast <UINT8> (addr.Col()) << 16) |
           (static_cast <UINT8> (addr.Tab()) << 24);
}

const size_t nBase = 16384; // Range~ und Shared~ Dingens mit jeweils der Haelfte Ids
ShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :
    ExcRoot( pRD ),
    mnCurrIdx (nBase)
{
#ifdef DBG_UTIL
    nShrCnt = 0;
#endif
}

ShrfmlaBuffer::~ShrfmlaBuffer()
{
}

void ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )
{
    String          aName( CreateName( rRange.aStart ) );

    DBG_ASSERT( mnCurrIdx <= 0xFFFF, "*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!" );

    ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );
    pData->SetIndex( static_cast< USHORT >( mnCurrIdx ) );
    pExcRoot->pIR->GetNamedRanges().Insert( pData );
    index_hash[rRange.aStart] = static_cast< USHORT >( mnCurrIdx );
    index_list.push_front (rRange);
    ++mnCurrIdx;
}

USHORT ShrfmlaBuffer::Find( const ScAddress & aAddr ) const
{
    ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);
    if (hash != index_hash.end())
        return hash->second;

    // It was not hashed on the top left corner ?  do a brute force search
    unsigned int ind = nBase;
    for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)
        if ((--ptr)->In (aAddr))
            return static_cast< USHORT >( ind );
    return static_cast< USHORT >( mnCurrIdx );
}

#define SHRFMLA_BASENAME    "SHARED_FORMULA_"

String ShrfmlaBuffer::CreateName( const ScRange& r )
{
    String          aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );
    aName += String::CreateFromInt32( r.aStart.Col() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aStart.Row() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aEnd.Col() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aEnd.Row() );
    aName.Append( '_' );
    aName += String::CreateFromInt32( r.aStart.Tab() );

    return aName;
}

ExtSheetBuffer::~ExtSheetBuffer()
{
    Cont    *pAkt = ( Cont * ) List::First();
    while( pAkt )
    {
        delete pAkt;
        pAkt = ( Cont * ) List::Next();
    }
}

void ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )
{
    List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );
}

BOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )
{
    DBG_ASSERT( nExcIndex,
        "*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!" );

    nExcIndex--;
    Cont*       pCur = ( Cont * ) List::GetObject( nExcIndex );
    UINT16&     rTabNum = pCur->nTabNum;

    if( pCur )
    {
        if( rTabNum < 0xFFFD )
        {
            rScIndex = rTabNum;
            return TRUE;
        }

        if( rTabNum == 0xFFFF )
        {// neue Tabelle erzeugen
            SCTAB   nNewTabNum;
            if( pCur->bSWB )
            {// Tabelle ist im selben Workbook!
                if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )
                {
                    rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
                    return TRUE;
                }
                else
                    rTabNum = 0xFFFD;
            }
            else if( pExcRoot->pIR->GetDocShell() )
            {// Tabelle ist 'echt' extern
                if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )
                {
                    String      aURL( ScGlobal::GetAbsDocName( pCur->aFile,
                                        pExcRoot->pIR->GetDocShell() ) );
                    String      aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );
                    if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )
                    {
                        rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
                        return TRUE;
                    }
                    else
                        rTabNum = 0xFFFE;       // Tabelle einmal nicht angelegt -> wird
                                                //  wohl auch nicht mehr gehen...
                }
                else
                    rTabNum = 0xFFFE;

            }
        }
    }

    return FALSE;
}

BOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsLink(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
        return pRet->bLink;
    else
        return FALSE;
}

BOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::GetLink(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
    {
        rAppl = pRet->aFile;
        rDoc = pRet->aTab;
        return TRUE;
    }
    else
        return FALSE;
}

BOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const
{
    DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsExternal(): Index muss >0 sein!" );
    Cont*   pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );

    if( pRet )
        return !pRet->bSWB;
    else
        return FALSE;
}

void ExtSheetBuffer::Reset( void )
{
    Cont    *pAkt = ( Cont * ) List::First();
    while( pAkt )
    {
        delete pAkt;
        pAkt = ( Cont * ) List::Next();
    }

    List::Clear();
}

BOOL ExtName::IsDDE( void ) const
{
    return ( nFlags & 0x0001 ) != 0;
}

BOOL ExtName::IsOLE( void ) const
{
    return ( nFlags & 0x0002 ) != 0;
}

BOOL ExtName::IsName( void ) const
{
    return ( nFlags & 0x0004 ) != 0;
}

const sal_Char* ExtNameBuff::pJoostTest = "Joost ist immer noch doof!";

ExtNameBuff::~ExtNameBuff()
{
    ExtName*    pDel = ( ExtName* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( ExtName* ) List::Next();
    }
}

void ExtNameBuff::AddDDE( const String& rName )
{
    ExtName*    pNew = new ExtName( rName );
    pNew->nFlags = 0x0001;

    List::Insert( pNew, LIST_APPEND );
}

void ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )
{
    ExtName*    pNew = new ExtName( rName );
    pNew->nFlags = 0x0002;
    pNew->nStorageId = nStorageId;

    List::Insert( pNew, LIST_APPEND );
}

void ExtNameBuff::AddName( const String& rName )
{
    ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );
    pNew->nFlags = 0x0004;

    List::Insert( pNew, LIST_APPEND );
}

const ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const
{
    DBG_ASSERT( nExcelIndex > 0, "*ExtNameBuff::GetName(): Index kann nur >0 sein!" );

    return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );
}

void ExtNameBuff::Reset( void )
{
    ExtName*    pDel = ( ExtName* ) List::First();
    while( pDel )
    {
        delete pDel;
        pDel = ( ExtName* ) List::Next();
    }

    sal_Char cTmp = *pJoostTest;
    cTmp++;

    List::Clear();
}

<|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 "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title) {
    NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
    const int kCheckDelayMs = 100;
    int max_wait_time = 5000;
    while (max_wait_time > 0) {
      max_wait_time -= kCheckDelayMs;
      PlatformThread::Sleep(kCheckDelayMs);
      if (expected_title == GetActiveTabTitle())
        break;
    }

    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"");
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3");
  PlatformThread::Sleep(sleep_timeout_ms() * 2);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success");
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success");
}

// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest_disallowed.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  tab->NavigateToURL(
      server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MAC)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Cause the renderer to crash.
  // TODO(albertb): We need to disable this on Linux since
  // crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
  expected_crashes_ = 1;
#endif
  tab->NavigateToURLAsync(GURL("about:crash"));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}
#endif

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.  We must
  // wait for the error page to update the title.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491.
  tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    if (GetActiveTabTitle() != L"set cookie on unload") {
      // Success, bail out.
      break;
    }
  }
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(server->TestServerPageW(L"files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  tab->NavigateToURLAsync(GURL(redirect_url));
  // Wait for JavaScript redirect to happen.
  PlatformThread::Sleep(sleep_timeout_ms() * 3);
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

}  // namespace
<commit_msg>s/OS_MAC/OS_MACOSX/<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 "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"

namespace {

class ResourceDispatcherTest : public UITest {
 public:
  void CheckTitleTest(const std::wstring& file,
                      const std::wstring& expected_title) {
    NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
    const int kCheckDelayMs = 100;
    int max_wait_time = 5000;
    while (max_wait_time > 0) {
      max_wait_time -= kCheckDelayMs;
      PlatformThread::Sleep(kCheckDelayMs);
      if (expected_title == GetActiveTabTitle())
        break;
    }

    EXPECT_EQ(expected_title, GetActiveTabTitle());
  }

 protected:
  ResourceDispatcherTest() : UITest() {
    dom_automation_enabled_ = true;
  }
};

TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}

TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
  CheckTitleTest(L"nosniff-test.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
  CheckTitleTest(L"content-sniffer-test1.html", L"");
}

TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
  CheckTitleTest(L"content-sniffer-test2.html", L"");
}

TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
  CheckTitleTest(L"content-sniffer-test3.html",
                 L"Content Sniffer Test 3");
  PlatformThread::Sleep(sleep_timeout_ms() * 2);
  EXPECT_EQ(1, GetTabCount());

  // Make sure the download shelf is not showing.
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  bool visible = false;
  ASSERT_TRUE(browser->IsShelfVisible(&visible));
  EXPECT_FALSE(visible);
}

TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
  CheckTitleTest(L"content-disposition-empty.html", L"success");
}

TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
  CheckTitleTest(L"content-disposition-inline.html", L"success");
}

// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSyncRequestSucceed());",
      &success));
  EXPECT_TRUE(success);
}

TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
  tab->NavigateToURL(server->TestServerPageW(
      L"files/sync_xmlhttprequest_disallowed.html"));

  // Let's check the XMLHttpRequest ran successfully.
  bool success = false;
  EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
      L"window.domAutomationController.send(DidSucceed());",
      &success));
  EXPECT_TRUE(success);
}

// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  tab->NavigateToURL(
      server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"sync xhr on unload", tab_title);

  // Navigate to a new page, to dispatch unload event and trigger xhr.
  // (the bug would make this step hang the renderer).
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);

  // Check that the new page got loaded, and that no download was triggered.
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);

  bool shelf_is_visible = false;
  scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
  EXPECT_FALSE(shelf_is_visible);
}

// Tests that onunload is run for cross-site requests.  (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site page, to dispatch unload event and set the
  // cookie.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Check that the cookie was set.
  std::string value_result;
  ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  ASSERT_FALSE(value_result.empty());
  ASSERT_STREQ("foo", value_result.c_str());
}

#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone.  In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
  // This test only works in multi-process mode
  if (in_process_renderer())
    return;

  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Cause the renderer to crash.
  // TODO(albertb): We need to disable this on Linux since
  // crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
  expected_crashes_ = 1;
#endif
  tab->NavigateToURLAsync(GURL("about:crash"));
  // Wait for browser to notice the renderer crash.
  PlatformThread::Sleep(sleep_timeout_ms());

  // Navigate to a new cross-site page.  The browser should not wait around for
  // the old renderer's on{before}unload handlers to run.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");
}
#endif  // !defined(OS_MACOSX)

// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs).  (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
  scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  // Start with an HTTP page.
  CheckTitleTest(L"content-sniffer-test0.html",
                 L"Content Sniffer Test 0");

  // Now load a file:// page, which does not use the BufferedEventHandler.
  // Make sure that the page loads and displays a title, and doesn't get stuck.
  FilePath test_file(test_data_directory_);
  test_file = test_file.AppendASCII("title2.html");
  bool timed_out = false;
  tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
                                action_max_timeout_ms(),
                                &timed_out);
  EXPECT_FALSE(timed_out);
  EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}

// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page.  (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
  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));
  EXPECT_TRUE(browser_proxy.get());
  scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());

  GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
  tab->NavigateToURL(url);

  // Confirm that the page has loaded (since it changes its title during load).
  std::wstring tab_title;
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"set cookie on unload", tab_title);

  // Navigate to a new cross-site URL that results in an error page.  We must
  // wait for the error page to update the title.
  // TODO(creis): If this causes crashes or hangs, it might be for the same
  // reason as ErrorPageTest::DNSError.  See bug 1199491.
  tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
  for (int i = 0; i < 10; ++i) {
    PlatformThread::Sleep(sleep_timeout_ms());
    if (GetActiveTabTitle() != L"set cookie on unload") {
      // Success, bail out.
      break;
    }
  }
  EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());

  // Check that the cookie was set, meaning that the onunload handler ran.
  std::string value_result;
  EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
  EXPECT_FALSE(value_result.empty());
  EXPECT_STREQ("foo", value_result.c_str());

  // Check that renderer-initiated navigations still work.  In a previous bug,
  // the ResourceDispatcherHost would think that such navigations were
  // cross-site, because we didn't clean up from the previous request.  Since
  // TabContents was in the NORMAL state, it would ignore the attempt to run
  // the onunload handler, and the navigation would fail.
  // (Test by redirecting to javascript:window.location='someURL'.)
  GURL test_url(server->TestServerPageW(L"files/title2.html"));
  std::string redirect_url = "javascript:window.location='" +
      test_url.possibly_invalid_spec() + "'";
  tab->NavigateToURLAsync(GURL(redirect_url));
  // Wait for JavaScript redirect to happen.
  PlatformThread::Sleep(sleep_timeout_ms() * 3);
  EXPECT_TRUE(tab->GetTabTitle(&tab_title));
  EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}

}  // namespace
<|endoftext|>


<commit_before>#include <vector>
#include "general.h"
#include "object.h"
#include "expression.h"
#include "../includes/switches.h"
using namespace std;

static vector<string *> string_pool;
Ink_ExpressionList native_exp_list = Ink_ExpressionList();
char *tmp_prog_path = NULL;

string *StrPool_addStr(const char *str)
{
	string *tmp;
	string_pool.push_back(tmp = new string(str ? str : ""));
	return tmp;
}

string *StrPool_addStr(string *str)
{
	string_pool.push_back(str);
	return str;
}

void StrPool_dispose()
{
	unsigned int i;
	for (i = 0; i < string_pool.size(); i++) {
		delete string_pool[i];
	}
	string_pool = vector<string *>();
	return;
}

void cleanAll()
{
	unsigned int i;
	const char *tmp;
	for (i = 0; i < native_exp_list.size(); i++) {
		delete native_exp_list[i];
	}

	// remove(INK_TMP_PATH);
	StrPool_dispose();

	if (isDirExist(tmp = string(INK_TMP_PATH).c_str()))
		removeDir(tmp);
	if (tmp_prog_path)
		free(tmp_prog_path);
}

Ink_Argument::~Ink_Argument()
{
	if (arg)
		delete arg;
	if (is_expand)
		delete expandee;
}<commit_msg>080116#06: fix a tiny problem in memcpy overlap<commit_after>#include <vector>
#include "general.h"
#include "object.h"
#include "expression.h"
#include "../includes/switches.h"
using namespace std;

static vector<string *> string_pool;
Ink_ExpressionList native_exp_list = Ink_ExpressionList();
char *tmp_prog_path = NULL;

string *StrPool_addStr(const char *str)
{
	string *tmp;
	string_pool.push_back(tmp = new string(str ? str : ""));
	return tmp;
}

string *StrPool_addStr(string *str)
{
	string_pool.push_back(str);
	return str;
}

void StrPool_dispose()
{
	unsigned int i;
	for (i = 0; i < string_pool.size(); i++) {
		delete string_pool[i];
	}
	string_pool = vector<string *>();
	return;
}

void cleanAll()
{
	unsigned int i;
	for (i = 0; i < native_exp_list.size(); i++) {
		delete native_exp_list[i];
	}

	// remove(INK_TMP_PATH);
	StrPool_dispose();

	if (isDirExist(string(INK_TMP_PATH).c_str()))
		removeDir(string(INK_TMP_PATH).c_str());
	if (tmp_prog_path)
		free(tmp_prog_path);
}

Ink_Argument::~Ink_Argument()
{
	if (arg)
		delete arg;
	if (is_expand)
		delete expandee;
}<|endoftext|>