<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lineinfo.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:17: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
 *
 ************************************************************************/

#pragma hdrstop

#include "doc.hxx"
#include "lineinfo.hxx"
#include "charfmt.hxx"
#include "poolfmt.hxx"
#include "rootfrm.hxx"
#include "viewsh.hxx"

void SwDoc::SetLineNumberInfo( const SwLineNumberInfo &rNew )
{
    if ( GetRootFrm() &&
         (rNew.IsCountBlankLines() != pLineNumberInfo->IsCountBlankLines() ||
          rNew.IsRestartEachPage() != pLineNumberInfo->IsRestartEachPage()) )
    {
        GetRootFrm()->StartAllAction();
        GetRootFrm()->InvalidateAllCntnt( INV_LINENUM );
        GetRootFrm()->EndAllAction();
    }
    *pLineNumberInfo = rNew;
    SetModified();
}

SwLineNumberInfo::SwLineNumberInfo() :
    nPosFromLeft( MM50 ),
    nCountBy( 5 ),
    nDividerCountBy( 3 ),
    ePos( LINENUMBER_POS_LEFT ),
    bPaintLineNumbers( FALSE ),
    bCountBlankLines( TRUE ),
    bCountInFlys( FALSE ),
    bRestartEachPage( FALSE )
{
}

SwLineNumberInfo::SwLineNumberInfo(const SwLineNumberInfo &rCpy ) :
    aType( rCpy.GetNumType() ),
    aDivider( rCpy.GetDivider() ),
    nPosFromLeft( rCpy.GetPosFromLeft() ),
    nCountBy( rCpy.GetCountBy() ),
    nDividerCountBy( rCpy.GetDividerCountBy() ),
    ePos( rCpy.GetPos() ),
    bPaintLineNumbers( rCpy.IsPaintLineNumbers() ),
    bCountBlankLines( rCpy.IsCountBlankLines() ),
    bCountInFlys( rCpy.IsCountInFlys() ),
    bRestartEachPage( rCpy.IsRestartEachPage() )
{
    if ( rCpy.GetRegisteredIn() )
        ((SwModify*)rCpy.GetRegisteredIn())->Add( this );
}

SwLineNumberInfo& SwLineNumberInfo::operator=(const SwLineNumberInfo &rCpy)
{
    if ( rCpy.GetRegisteredIn() )
        ((SwModify*)rCpy.GetRegisteredIn())->Add( this );
    else if ( GetRegisteredIn() )
        pRegisteredIn->Remove( this );

    aType = rCpy.GetNumType();
    aDivider = rCpy.GetDivider();
    nPosFromLeft = rCpy.GetPosFromLeft();
    nCountBy = rCpy.GetCountBy();
    nDividerCountBy = rCpy.GetDividerCountBy();
    ePos = rCpy.GetPos();
    bPaintLineNumbers = rCpy.IsPaintLineNumbers();
    bCountBlankLines = rCpy.IsCountBlankLines();
    bCountInFlys = rCpy.IsCountInFlys();
    bRestartEachPage = rCpy.IsRestartEachPage();

    return *this;
}

BOOL SwLineNumberInfo::operator==( const SwLineNumberInfo& rInf ) const
{
    return  GetRegisteredIn() == rInf.GetRegisteredIn() &&
            aType.GetNumberingType() == rInf.GetNumType().GetNumberingType() &&
            aDivider == rInf.GetDivider() &&
            nPosFromLeft == rInf.GetPosFromLeft() &&
            nCountBy == rInf.GetCountBy() &&
            nDividerCountBy == rInf.GetDividerCountBy() &&
            ePos == rInf.GetPos() &&
            bPaintLineNumbers == rInf.IsPaintLineNumbers() &&
            bCountBlankLines == rInf.IsCountBlankLines() &&
            bCountInFlys == rInf.IsCountInFlys() &&
            bRestartEachPage == rInf.IsRestartEachPage();
}

SwCharFmt* SwLineNumberInfo::GetCharFmt(SwDoc &rDoc) const
{
    if ( !GetRegisteredIn() )
    {
        SwCharFmt* pFmt = rDoc.GetCharFmtFromPool( RES_POOLCHR_LINENUM );
        pFmt->Add( (SwClient*)this );
    }
    return (SwCharFmt*)GetRegisteredIn();
}

void SwLineNumberInfo::SetCharFmt( SwCharFmt *pChFmt )
{
    ASSERT( pChFmt, "SetCharFmt, 0 is not a valid pointer" );
    pChFmt->Add( this );
}

void SwLineNumberInfo::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
    SwClient::Modify( pOld, pNew );
    SwDoc *pDoc = ((SwCharFmt*)GetRegisteredIn())->GetDoc();
    SwRootFrm* pRoot = pDoc->GetRootFrm();
    if( pRoot && pRoot->GetCurrShell() )
    {
        pRoot->StartAllAction();
        pRoot->GetCurrShell()->AddPaintRect( pRoot->Frm() );
        pRoot->EndAllAction();
    }
}

<commit_msg>INTEGRATION: CWS writercorehandoff (1.4.4); FILE MERGED 2005/11/11 07:56:06 fme 1.4.4.1: #i50348# make SwDoc accessible via interfaces<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lineinfo.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 16:01:26 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#include "doc.hxx"
#include "lineinfo.hxx"
#include "charfmt.hxx"
#include "poolfmt.hxx"
#include "rootfrm.hxx"
#include "viewsh.hxx"

void SwDoc::SetLineNumberInfo( const SwLineNumberInfo &rNew )
{
    if ( GetRootFrm() &&
         (rNew.IsCountBlankLines() != pLineNumberInfo->IsCountBlankLines() ||
          rNew.IsRestartEachPage() != pLineNumberInfo->IsRestartEachPage()) )
    {
        GetRootFrm()->StartAllAction();
        GetRootFrm()->InvalidateAllCntnt( INV_LINENUM );
        GetRootFrm()->EndAllAction();
    }
    *pLineNumberInfo = rNew;
    SetModified();
}

const SwLineNumberInfo& SwDoc::GetLineNumberInfo() const
{
    return *pLineNumberInfo;
}

SwLineNumberInfo::SwLineNumberInfo() :
    nPosFromLeft( MM50 ),
    nCountBy( 5 ),
    nDividerCountBy( 3 ),
    ePos( LINENUMBER_POS_LEFT ),
    bPaintLineNumbers( FALSE ),
    bCountBlankLines( TRUE ),
    bCountInFlys( FALSE ),
    bRestartEachPage( FALSE )
{
}

SwLineNumberInfo::SwLineNumberInfo(const SwLineNumberInfo &rCpy ) :
    aType( rCpy.GetNumType() ),
    aDivider( rCpy.GetDivider() ),
    nPosFromLeft( rCpy.GetPosFromLeft() ),
    nCountBy( rCpy.GetCountBy() ),
    nDividerCountBy( rCpy.GetDividerCountBy() ),
    ePos( rCpy.GetPos() ),
    bPaintLineNumbers( rCpy.IsPaintLineNumbers() ),
    bCountBlankLines( rCpy.IsCountBlankLines() ),
    bCountInFlys( rCpy.IsCountInFlys() ),
    bRestartEachPage( rCpy.IsRestartEachPage() )
{
    if ( rCpy.GetRegisteredIn() )
        ((SwModify*)rCpy.GetRegisteredIn())->Add( this );
}

SwLineNumberInfo& SwLineNumberInfo::operator=(const SwLineNumberInfo &rCpy)
{
    if ( rCpy.GetRegisteredIn() )
        ((SwModify*)rCpy.GetRegisteredIn())->Add( this );
    else if ( GetRegisteredIn() )
        pRegisteredIn->Remove( this );

    aType = rCpy.GetNumType();
    aDivider = rCpy.GetDivider();
    nPosFromLeft = rCpy.GetPosFromLeft();
    nCountBy = rCpy.GetCountBy();
    nDividerCountBy = rCpy.GetDividerCountBy();
    ePos = rCpy.GetPos();
    bPaintLineNumbers = rCpy.IsPaintLineNumbers();
    bCountBlankLines = rCpy.IsCountBlankLines();
    bCountInFlys = rCpy.IsCountInFlys();
    bRestartEachPage = rCpy.IsRestartEachPage();

    return *this;
}

BOOL SwLineNumberInfo::operator==( const SwLineNumberInfo& rInf ) const
{
    return  GetRegisteredIn() == rInf.GetRegisteredIn() &&
            aType.GetNumberingType() == rInf.GetNumType().GetNumberingType() &&
            aDivider == rInf.GetDivider() &&
            nPosFromLeft == rInf.GetPosFromLeft() &&
            nCountBy == rInf.GetCountBy() &&
            nDividerCountBy == rInf.GetDividerCountBy() &&
            ePos == rInf.GetPos() &&
            bPaintLineNumbers == rInf.IsPaintLineNumbers() &&
            bCountBlankLines == rInf.IsCountBlankLines() &&
            bCountInFlys == rInf.IsCountInFlys() &&
            bRestartEachPage == rInf.IsRestartEachPage();
}

SwCharFmt* SwLineNumberInfo::GetCharFmt( IDocumentStylePoolAccess& rIDSPA ) const
{
    if ( !GetRegisteredIn() )
    {
        SwCharFmt* pFmt = rIDSPA.GetCharFmtFromPool( RES_POOLCHR_LINENUM );
        pFmt->Add( (SwClient*)this );
    }
    return (SwCharFmt*)GetRegisteredIn();
}

void SwLineNumberInfo::SetCharFmt( SwCharFmt *pChFmt )
{
    ASSERT( pChFmt, "SetCharFmt, 0 is not a valid pointer" );
    pChFmt->Add( this );
}

void SwLineNumberInfo::Modify( SfxPoolItem* pOld, SfxPoolItem* pNew )
{
    SwClient::Modify( pOld, pNew );
    SwDoc *pDoc = ((SwCharFmt*)GetRegisteredIn())->GetDoc();
    SwRootFrm* pRoot = pDoc->GetRootFrm();
    if( pRoot && pRoot->GetCurrShell() )
    {
        pRoot->StartAllAction();
        pRoot->GetCurrShell()->AddPaintRect( pRoot->Frm() );
        pRoot->EndAllAction();
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: drawdoc.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2004-02-03 16:25:06 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVSTOR_HXX //autogen
#include <so3/svstor.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _FORBIDDENCHARACTERSTABLE_HXX
#include <svx/forbiddencharacterstable.hxx>
#endif

#include <svx/xtable.hxx>

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST
#define ITEMID_DASH_LIST        SID_DASH_LIST
#define ITEMID_LINEEND_LIST     SID_LINEEND_LIST
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _ROOTFRM_HXX
#include <rootfrm.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include <drawdoc.hxx>
#endif
#ifndef _DPAGE_HXX
#include <dpage.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _SW3IO_HXX
#include <sw3io.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

const String GetPalettePath()
{
    SvtPathOptions aPathOpt;
    return aPathOpt.GetPalettePath();
}

SwDrawDocument::SwDrawDocument( SwDoc* pD ) :
    FmFormModel( ::GetPalettePath(), &pD->GetAttrPool(),
                 pD->GetDocShell(), TRUE ),
    pDoc( pD )
{
    SetScaleUnit( MAP_TWIP );
    SetSwapGraphics( TRUE );

    SwDocShell* pDocSh = pDoc->GetDocShell();
    if ( pDocSh )
    {
        SetObjectShell( pDocSh );
        SvxColorTableItem* pColItem = ( SvxColorTableItem* )
                                ( pDocSh->GetItem( ITEMID_COLOR_TABLE ) );
        XColorTable *pXCol = pColItem ? pColItem->GetColorTable() :
                                        XColorTable::GetStdColorTable();
        SetColorTable( pXCol );

        if ( !pColItem )
            pDocSh->PutItem( SvxColorTableItem( pXCol ) );

        pDocSh->PutItem( SvxGradientListItem( GetGradientList() ));
        pDocSh->PutItem( SvxHatchListItem( GetHatchList() ) );
        pDocSh->PutItem( SvxBitmapListItem( GetBitmapList() ) );
        pDocSh->PutItem( SvxDashListItem( GetDashList() ) );
        pDocSh->PutItem( SvxLineEndListItem( GetLineEndList() ) );
        pDocSh->PutItem( SfxUInt16Item(SID_ATTR_LINEEND_WIDTH_DEFAULT, 111) );
        SetObjectShell( pDocSh );
    }
    else
        SetColorTable( XColorTable::GetStdColorTable() );

    // copy all the default values to the SdrModel
    SfxItemPool* pSdrPool = pD->GetAttrPool().GetSecondaryPool();
    if( pSdrPool )
    {
        const USHORT aWhichRanges[] =
            {
                RES_CHRATR_BEGIN, RES_CHRATR_END,
                RES_PARATR_BEGIN, RES_PARATR_END,
                0
            };

        SfxItemPool& rDocPool = pD->GetAttrPool();
        USHORT nEdtWhich, nSlotId;
        const SfxPoolItem* pItem;
        for( const USHORT* pRangeArr = aWhichRanges;
            *pRangeArr; pRangeArr += 2 )
            for( USHORT nW = *pRangeArr, nEnd = *(pRangeArr+1);
                    nW < nEnd; ++nW )
                if( 0 != (pItem = rDocPool.GetPoolDefaultItem( nW )) &&
                    0 != (nSlotId = rDocPool.GetSlotId( nW ) ) &&
                    nSlotId != nW &&
                    0 != (nEdtWhich = pSdrPool->GetWhich( nSlotId )) &&
                    nSlotId != nEdtWhich )
                {
                    SfxPoolItem* pCpy = pItem->Clone();
                    pCpy->SetWhich( nEdtWhich );
                    pSdrPool->SetPoolDefaultItem( *pCpy );
                    delete pCpy;
                }
    }

    SetForbiddenCharsTable( pD->GetForbiddenCharacterTbl() );
    // #87795# Implementation for asian compression
    SetCharCompressType( pD->GetCharCompressType() );
}

/*************************************************************************
|*
|* Konstruktor, fuer einfuegen Document
|*
\************************************************************************/

SwDrawDocument::SwDrawDocument( SfxItemPool *pPool, SwDocShell *pDocSh )
    : FmFormModel( ::GetPalettePath(), pPool, pDocSh, TRUE ),
    pDoc( pDocSh->GetDoc() )
{
    SetScaleUnit( MAP_TWIP );
    SetDefaultFontHeight( 240 );
    SetSwapGraphics( TRUE );

    ASSERT( pDocSh, "DocShell not found" );
    SvxColorTableItem* pColItem = ( SvxColorTableItem* )
                                ( pDocSh->GetItem( ITEMID_COLOR_TABLE ) );
    XColorTable *pXCol = pColItem ? pColItem->GetColorTable() :
                                    XColorTable::GetStdColorTable();
    SetColorTable( pXCol );

    if ( !pColItem )
        pDocSh->PutItem( SvxColorTableItem( pXCol ) );

    // Bug 35371:
    //  fuers "Datei einfuegen" NIE die anderen Items an der DocShell setzen!!!
    // Diese zeigen sonst immer in das temporaere SdrModel !
    SetObjectShell( pDocSh );
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SwDrawDocument::~SwDrawDocument()
{
    Broadcast(SdrHint(HINT_MODELCLEARED));

    Clear();
}

/*************************************************************************
|*
|* Diese Methode erzeugt eine neue Seite (SdPage) und gibt einen Zeiger
|* darauf zurueck. Die Drawing Engine benutzt diese Methode beim Laden
|* zur Erzeugung von Seiten (deren Typ sie ja nicht kennt, da es ABLEITUNGEN
|* der SdrPage sind).
|*
\************************************************************************/

SdrPage* SwDrawDocument::AllocPage(FASTBOOL bMasterPage)
{
    SwDPage* pPage = new SwDPage(*this, bMasterPage);
    pPage->SetName( String::CreateFromAscii(
                                    RTL_CONSTASCII_STRINGPARAM( "Controls" )) );
    return pPage;
}

SvStream* SwDrawDocument::GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const
{
    SvStream* pRet = NULL;
    SvStorageRef xRoot( pDoc->GetDocStorage() );
    String sDrawStrmNm( String::CreateFromAscii(
                    RTL_CONSTASCII_STRINGPARAM( DRAWING_STREAM_NAME )));

     if( xRoot.Is() && SVSTREAM_OK == xRoot->GetError() )
    {
        if( rInfo.maUserData.Len() &&
            ( rInfo.maUserData.GetToken( 0, ':' ) ==
              String( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.Package" ) ) ) )
        {
            const String aPicturePath( rInfo.maUserData.GetToken( 1, ':' ) );

            // graphic from picture stream in picture storage in XML package
            if( aPicturePath.GetTokenCount( '/' ) == 2 )
            {
                SvStorageRef    xPictureStorage;
                const String    aPictureStorageName( aPicturePath.GetToken( 0, '/' ) );
                const String    aPictureStreamName( aPicturePath.GetToken( 1, '/' ) );

                if( xRoot->IsContained( aPictureStorageName ) &&
                    xRoot->IsStorage( aPictureStorageName )  )
                {
                    xPictureStorage = xRoot->OpenUCBStorage( aPictureStorageName,
                                                             STREAM_READ |
                                                             STREAM_SHARE_DENYWRITE |
                                                             STREAM_NOCREATE );
                }

                if( xPictureStorage.Is() &&
                    xPictureStorage->IsContained( aPictureStreamName ) &&
                    xPictureStorage->IsStream( aPictureStreamName ) )
                {
                    pRet = xPictureStorage->OpenSotStream( aPictureStreamName,
                                                           STREAM_READ |
                                                           STREAM_SHARE_DENYWRITE |
                                                           STREAM_NOCREATE );

                    if( pRet )
                    {
                        pRet->SetVersion( xPictureStorage->GetVersion() );
                        pRet->SetKey( xPictureStorage->GetKey() );

                        rInfo.mbDeleteAfterUse = TRUE;
                        rInfo.mpStorageRef = new SvStorageRef( xPictureStorage );
                    }
                }
            }
        }
        else if( xRoot->IsStream( sDrawStrmNm ) )
        {
            long nFFVersion = xRoot->GetVersion();
            ASSERT( nFFVersion == SOFFICE_FILEFORMAT_31 ||
                    nFFVersion == SOFFICE_FILEFORMAT_40 ||
                    nFFVersion == SOFFICE_FILEFORMAT_50,
                    "Am Root-Storage ist keine FF-Version gesetzt!" );

            // Wenn eine 3.1-Clipboard-ID gesetzt ist, die Fileformat-Version
            // auf 3.1 setzten.
            if( SOT_FORMATSTR_ID_STARWRITER_30 == xRoot->GetFormat() &&
                nFFVersion != SOFFICE_FILEFORMAT_31 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_31,
                        "Fileformat-Version auf 3.1 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_31 );
            }
            else if( ( SOT_FORMATSTR_ID_STARWRITER_40 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERWEB_40 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERGLOB_40 == xRoot->GetFormat() ) &&
                     nFFVersion != SOFFICE_FILEFORMAT_40 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_40,
                        "Fileformat-Version auf 4.0 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_40 );
            }
            else if( ( SOT_FORMATSTR_ID_STARWRITER_50 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERWEB_50 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERGLOB_50 == xRoot->GetFormat() ) &&
                     nFFVersion != SOFFICE_FILEFORMAT_50 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_50,
                        "Fileformat-Version auf 4.0 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_50 );
            }

            pRet = xRoot->OpenStream( sDrawStrmNm,
                        STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE );

            if( pRet )
                rInfo.mbDeleteAfterUse = TRUE;
        }

    }
    return pRet;
}

SdrLayerID SwDrawDocument::GetControlExportLayerId( const SdrObject & ) const
{
    //fuer Versionen < 5.0, es gab nur Hell und Heaven
    return (SdrLayerID)pDoc->GetHeavenId();
}

<commit_msg>INTEGRATION: CWS aw009 (1.14.158); FILE MERGED 2004/04/26 11:00:16 aw 1.14.158.1: #116168#<commit_after>/*************************************************************************
 *
 *  $RCSfile: drawdoc.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 14:24:51 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _SVX_SVXIDS_HRC
#include <svx/svxids.hrc>
#endif
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SVSTOR_HXX //autogen
#include <so3/svstor.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _FORBIDDENCHARACTERSTABLE_HXX
#include <svx/forbiddencharacterstable.hxx>
#endif

#include <svx/xtable.hxx>

#define ITEMID_COLOR_TABLE      SID_COLOR_TABLE
#define ITEMID_GRADIENT_LIST    SID_GRADIENT_LIST
#define ITEMID_HATCH_LIST       SID_HATCH_LIST
#define ITEMID_BITMAP_LIST      SID_BITMAP_LIST
#define ITEMID_DASH_LIST        SID_DASH_LIST
#define ITEMID_LINEEND_LIST     SID_LINEEND_LIST
#ifndef _SVX_DRAWITEM_HXX
#include <svx/drawitem.hxx>
#endif

#ifndef _VIEWSH_HXX
#include <viewsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _ROOTFRM_HXX
#include <rootfrm.hxx>
#endif
#ifndef _DRAWDOC_HXX
#include <drawdoc.hxx>
#endif
#ifndef _DPAGE_HXX
#include <dpage.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _SHELLIO_HXX
#include <shellio.hxx>
#endif
#ifndef _SW3IO_HXX
#include <sw3io.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif

/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/

const String GetPalettePath()
{
    SvtPathOptions aPathOpt;
    return aPathOpt.GetPalettePath();
}

SwDrawDocument::SwDrawDocument( SwDoc* pD ) :
    FmFormModel( ::GetPalettePath(), &pD->GetAttrPool(),
                 pD->GetDocShell(), TRUE ),
    pDoc( pD )
{
    SetScaleUnit( MAP_TWIP );
    SetSwapGraphics( TRUE );

    SwDocShell* pDocSh = pDoc->GetDocShell();
    if ( pDocSh )
    {
        SetObjectShell( pDocSh );
        SvxColorTableItem* pColItem = ( SvxColorTableItem* )
                                ( pDocSh->GetItem( ITEMID_COLOR_TABLE ) );
        XColorTable *pXCol = pColItem ? pColItem->GetColorTable() :
                                        XColorTable::GetStdColorTable();
        SetColorTable( pXCol );

        if ( !pColItem )
            pDocSh->PutItem( SvxColorTableItem( pXCol ) );

        pDocSh->PutItem( SvxGradientListItem( GetGradientList() ));
        pDocSh->PutItem( SvxHatchListItem( GetHatchList() ) );
        pDocSh->PutItem( SvxBitmapListItem( GetBitmapList() ) );
        pDocSh->PutItem( SvxDashListItem( GetDashList() ) );
        pDocSh->PutItem( SvxLineEndListItem( GetLineEndList() ) );
        pDocSh->PutItem( SfxUInt16Item(SID_ATTR_LINEEND_WIDTH_DEFAULT, 111) );
        SetObjectShell( pDocSh );
    }
    else
        SetColorTable( XColorTable::GetStdColorTable() );

    // copy all the default values to the SdrModel
    SfxItemPool* pSdrPool = pD->GetAttrPool().GetSecondaryPool();
    if( pSdrPool )
    {
        const USHORT aWhichRanges[] =
            {
                RES_CHRATR_BEGIN, RES_CHRATR_END,
                RES_PARATR_BEGIN, RES_PARATR_END,
                0
            };

        SfxItemPool& rDocPool = pD->GetAttrPool();
        USHORT nEdtWhich, nSlotId;
        const SfxPoolItem* pItem;
        for( const USHORT* pRangeArr = aWhichRanges;
            *pRangeArr; pRangeArr += 2 )
            for( USHORT nW = *pRangeArr, nEnd = *(pRangeArr+1);
                    nW < nEnd; ++nW )
                if( 0 != (pItem = rDocPool.GetPoolDefaultItem( nW )) &&
                    0 != (nSlotId = rDocPool.GetSlotId( nW ) ) &&
                    nSlotId != nW &&
                    0 != (nEdtWhich = pSdrPool->GetWhich( nSlotId )) &&
                    nSlotId != nEdtWhich )
                {
                    SfxPoolItem* pCpy = pItem->Clone();
                    pCpy->SetWhich( nEdtWhich );
                    pSdrPool->SetPoolDefaultItem( *pCpy );
                    delete pCpy;
                }
    }

    SetForbiddenCharsTable( pD->GetForbiddenCharacterTbl() );
    // #87795# Implementation for asian compression
    SetCharCompressType( pD->GetCharCompressType() );
}

/*************************************************************************
|*
|* Konstruktor, fuer einfuegen Document
|*
\************************************************************************/

SwDrawDocument::SwDrawDocument( SfxItemPool *pPool, SwDocShell *pDocSh )
    : FmFormModel( ::GetPalettePath(), pPool, pDocSh, TRUE ),
    pDoc( pDocSh->GetDoc() )
{
    SetScaleUnit( MAP_TWIP );
    SetDefaultFontHeight( 240 );
    SetSwapGraphics( TRUE );

    ASSERT( pDocSh, "DocShell not found" );
    SvxColorTableItem* pColItem = ( SvxColorTableItem* )
                                ( pDocSh->GetItem( ITEMID_COLOR_TABLE ) );
    XColorTable *pXCol = pColItem ? pColItem->GetColorTable() :
                                    XColorTable::GetStdColorTable();
    SetColorTable( pXCol );

    if ( !pColItem )
        pDocSh->PutItem( SvxColorTableItem( pXCol ) );

    // Bug 35371:
    //  fuers "Datei einfuegen" NIE die anderen Items an der DocShell setzen!!!
    // Diese zeigen sonst immer in das temporaere SdrModel !
    SetObjectShell( pDocSh );
}

/*************************************************************************
|*
|* Destruktor
|*
\************************************************************************/

SwDrawDocument::~SwDrawDocument()
{
    Broadcast(SdrHint(HINT_MODELCLEARED));

    // #116168#
    ClearModel(sal_True);
    //Clear();
}

/*************************************************************************
|*
|* Diese Methode erzeugt eine neue Seite (SdPage) und gibt einen Zeiger
|* darauf zurueck. Die Drawing Engine benutzt diese Methode beim Laden
|* zur Erzeugung von Seiten (deren Typ sie ja nicht kennt, da es ABLEITUNGEN
|* der SdrPage sind).
|*
\************************************************************************/

SdrPage* SwDrawDocument::AllocPage(FASTBOOL bMasterPage)
{
    SwDPage* pPage = new SwDPage(*this, bMasterPage);
    pPage->SetName( String::CreateFromAscii(
                                    RTL_CONSTASCII_STRINGPARAM( "Controls" )) );
    return pPage;
}

SvStream* SwDrawDocument::GetDocumentStream( SdrDocumentStreamInfo& rInfo ) const
{
    SvStream* pRet = NULL;
    SvStorageRef xRoot( pDoc->GetDocStorage() );
    String sDrawStrmNm( String::CreateFromAscii(
                    RTL_CONSTASCII_STRINGPARAM( DRAWING_STREAM_NAME )));

     if( xRoot.Is() && SVSTREAM_OK == xRoot->GetError() )
    {
        if( rInfo.maUserData.Len() &&
            ( rInfo.maUserData.GetToken( 0, ':' ) ==
              String( RTL_CONSTASCII_USTRINGPARAM( "vnd.sun.star.Package" ) ) ) )
        {
            const String aPicturePath( rInfo.maUserData.GetToken( 1, ':' ) );

            // graphic from picture stream in picture storage in XML package
            if( aPicturePath.GetTokenCount( '/' ) == 2 )
            {
                SvStorageRef    xPictureStorage;
                const String    aPictureStorageName( aPicturePath.GetToken( 0, '/' ) );
                const String    aPictureStreamName( aPicturePath.GetToken( 1, '/' ) );

                if( xRoot->IsContained( aPictureStorageName ) &&
                    xRoot->IsStorage( aPictureStorageName )  )
                {
                    xPictureStorage = xRoot->OpenUCBStorage( aPictureStorageName,
                                                             STREAM_READ |
                                                             STREAM_SHARE_DENYWRITE |
                                                             STREAM_NOCREATE );
                }

                if( xPictureStorage.Is() &&
                    xPictureStorage->IsContained( aPictureStreamName ) &&
                    xPictureStorage->IsStream( aPictureStreamName ) )
                {
                    pRet = xPictureStorage->OpenSotStream( aPictureStreamName,
                                                           STREAM_READ |
                                                           STREAM_SHARE_DENYWRITE |
                                                           STREAM_NOCREATE );

                    if( pRet )
                    {
                        pRet->SetVersion( xPictureStorage->GetVersion() );
                        pRet->SetKey( xPictureStorage->GetKey() );

                        rInfo.mbDeleteAfterUse = TRUE;
                        rInfo.mpStorageRef = new SvStorageRef( xPictureStorage );
                    }
                }
            }
        }
        else if( xRoot->IsStream( sDrawStrmNm ) )
        {
            long nFFVersion = xRoot->GetVersion();
            ASSERT( nFFVersion == SOFFICE_FILEFORMAT_31 ||
                    nFFVersion == SOFFICE_FILEFORMAT_40 ||
                    nFFVersion == SOFFICE_FILEFORMAT_50,
                    "Am Root-Storage ist keine FF-Version gesetzt!" );

            // Wenn eine 3.1-Clipboard-ID gesetzt ist, die Fileformat-Version
            // auf 3.1 setzten.
            if( SOT_FORMATSTR_ID_STARWRITER_30 == xRoot->GetFormat() &&
                nFFVersion != SOFFICE_FILEFORMAT_31 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_31,
                        "Fileformat-Version auf 3.1 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_31 );
            }
            else if( ( SOT_FORMATSTR_ID_STARWRITER_40 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERWEB_40 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERGLOB_40 == xRoot->GetFormat() ) &&
                     nFFVersion != SOFFICE_FILEFORMAT_40 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_40,
                        "Fileformat-Version auf 4.0 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_40 );
            }
            else if( ( SOT_FORMATSTR_ID_STARWRITER_50 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERWEB_50 == xRoot->GetFormat() ||
                       SOT_FORMATSTR_ID_STARWRITERGLOB_50 == xRoot->GetFormat() ) &&
                     nFFVersion != SOFFICE_FILEFORMAT_50 )
            {
                ASSERT( nFFVersion == SOFFICE_FILEFORMAT_50,
                        "Fileformat-Version auf 4.0 umgesetzt" );
                xRoot->SetVersion( nFFVersion = SOFFICE_FILEFORMAT_50 );
            }

            pRet = xRoot->OpenStream( sDrawStrmNm,
                        STREAM_READ | STREAM_SHARE_DENYWRITE | STREAM_NOCREATE );

            if( pRet )
                rInfo.mbDeleteAfterUse = TRUE;
        }

    }
    return pRet;
}

SdrLayerID SwDrawDocument::GetControlExportLayerId( const SdrObject & ) const
{
    //fuer Versionen < 5.0, es gab nur Hell und Heaven
    return (SdrLayerID)pDoc->GetHeavenId();
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ Trolltech AS. All rights reserved.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include <QtTest/QtTest>

#include <textedit.h>
#include <textdocument.h>
QT_FORWARD_DECLARE_CLASS(TextEdit)

//TESTED_CLASS=
//TESTED_FILES=

class tst_TextEdit : public QObject
{
    Q_OBJECT

public:
    tst_TextEdit();
    virtual ~tst_TextEdit();

private slots:
    void clickInReadOnlyEdit();
    void scrollReadOnly();
    void cursorForPosition();
    void columnNumberIssue();
};

tst_TextEdit::tst_TextEdit()
{
}

tst_TextEdit::~tst_TextEdit()
{
}

void tst_TextEdit::scrollReadOnly()
{
    TextEdit edit;
    QString line = "12434567890\n";
    QString text;
    for (int i=0; i<1000; ++i) {
        text.append(line);
    }
    edit.document()->setText(text);
    edit.setReadOnly(true);
    edit.resize(400, 400);
    edit.show();
    QTest::qWaitForWindowShown(&edit);
//     edit.setCursorPosition(0);
//     edit.verticalScrollBar()->setValue(0);
//    qDebug() << edit.cursorPosition() << edit.verticalScrollBar()->value();
//     QEventLoop loop;
//     loop.exec();
    QTest::keyClick(&edit, Qt::Key_Down);
    QVERIFY(edit.verticalScrollBar()->value() != 0);
}

void tst_TextEdit::clickInReadOnlyEdit()
{
    TextEdit edit;
    QString line = "12434567890\n";
    QString text;
    for (int i=0; i<1000; ++i) {
        text.append(line);
    }
    edit.document()->setText(text);
    edit.setReadOnly(true);
    edit.resize(400, 400);
    edit.show();
    QTest::qWaitForWindowShown(&edit);
//     edit.setCursorPosition(0);
//     edit.verticalScrollBar()->setValue(0);
//    qDebug() << edit.cursorPosition() << edit.verticalScrollBar()->value();
//     QEventLoop loop;
//     loop.exec();
    QTest::mouseClick(edit.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(20, 20));
    QVERIFY(edit.verticalScrollBar()->value() == 0);

}

void tst_TextEdit::cursorForPosition()
{
    TextEdit edit;
    const QString string = "123456";
    QSet<QChar> all;
    for (int i=0; i<all.size(); ++i) {
        all.insert(string.at(i));
    }
    edit.setText(string);
    QFont font;
    font.setPixelSize(10);
    edit.setFont(font);
    edit.resize(500, 500);
    const QRect r = edit.viewport()->rect();
    QPoint pos(0, 0);
    for (int x=r.left(); x<r.right(); ++x) {
        for (int y=r.top(); y<r.bottom(); ++y) {
            TextCursor cursor = edit.cursorForPosition(pos);
            if (!cursor.isValid())
                continue;
            QCOMPARE(cursor.position(), edit.textPositionAt(pos));
            const QChar ch = cursor.cursorCharacter();
            const QChar readChar = edit.readCharacter(cursor.position());
            QCOMPARE(readChar, ch);
            if (all.remove(ch) && all.isEmpty()) {
                goto end;
            }
        }
    }
end:
    QCOMPARE(all.size(), 0);
}

void tst_TextEdit::columnNumberIssue()
{
    QCOMPARE(1, 1);
    return;
    TextEdit edit;
    edit.resize(200, 200);
    edit.setText("This is a very very very long line and it should most certainly wrap around at least once.\n"
                 "This is a shorter line\n"
                 "1\n"
                 "2\n"
                 "3\n"
                 "4\n"
                 "5\n"
                 "6\n"
                 "7\n"
                 "8\n"
                 "9\n"
                 "10\n"
                 "11\n"
                 "12\n");
    edit.show();
    QTest::qWaitForWindowShown(&edit);
    QVERIFY(edit.verticalScrollBar()->maximum() != 0);
    while (edit.cursorPosition() < edit.document()->documentSize()) {
        QCOMPARE(0, edit.textCursor().columnNumber());
        QTest::keyClick(&edit, Qt::Key_Down);
    }
//    QVERIFY(edit.verticalScrollBar()->value() != 0);
    while (edit.cursorPosition() > 0) {
//        qDebug() << edit.cursorPosition();
        QTest::keyClick(&edit, Qt::Key_Up);
        QCOMPARE(0, edit.textCursor().columnNumber());
    }
//     QEventLoop loop;
//     loop.exec();
}

QTEST_MAIN(tst_TextEdit)
#include "tst_textedit.moc"
<commit_msg>add a test for selection with cursor keys<commit_after>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ Trolltech AS. All rights reserved.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include <QtTest/QtTest>

#include <textedit.h>
#include <textdocument.h>
QT_FORWARD_DECLARE_CLASS(TextEdit)

//TESTED_CLASS=
//TESTED_FILES=

class tst_TextEdit : public QObject
{
    Q_OBJECT

public:
    tst_TextEdit();
    virtual ~tst_TextEdit();

private slots:
    void clickInReadOnlyEdit();
    void scrollReadOnly();
    void cursorForPosition();
    void columnNumberIssue();
    void selectionTest();
};

tst_TextEdit::tst_TextEdit()
{
}

tst_TextEdit::~tst_TextEdit()
{
}

void tst_TextEdit::scrollReadOnly()
{
    TextEdit edit;
    QString line = "12434567890\n";
    QString text;
    for (int i=0; i<1000; ++i) {
        text.append(line);
    }
    edit.document()->setText(text);
    edit.setReadOnly(true);
    edit.resize(400, 400);
    edit.show();
    QTest::qWaitForWindowShown(&edit);
//     edit.setCursorPosition(0);
//     edit.verticalScrollBar()->setValue(0);
//    qDebug() << edit.cursorPosition() << edit.verticalScrollBar()->value();
//     QEventLoop loop;
//     loop.exec();
    QTest::keyClick(&edit, Qt::Key_Down);
    QVERIFY(edit.verticalScrollBar()->value() != 0);
}

void tst_TextEdit::clickInReadOnlyEdit()
{
    TextEdit edit;
    QString line = "1234567890\n";
    QString text;
    for (int i=0; i<1000; ++i) {
        text.append(line);
    }
    edit.document()->setText(text);
    edit.setReadOnly(true);
    edit.resize(400, 400);
    edit.show();
    QTest::qWaitForWindowShown(&edit);
//     edit.setCursorPosition(0);
//     edit.verticalScrollBar()->setValue(0);
//    qDebug() << edit.cursorPosition() << edit.verticalScrollBar()->value();
//     QEventLoop loop;
//     loop.exec();
    QTest::mouseClick(edit.viewport(), Qt::LeftButton, Qt::NoModifier, QPoint(20, 20));
    QVERIFY(edit.verticalScrollBar()->value() == 0);

}

void tst_TextEdit::cursorForPosition()
{
    TextEdit edit;
    const QString string = "123456";
    QSet<QChar> all;
    for (int i=0; i<all.size(); ++i) {
        all.insert(string.at(i));
    }
    edit.setText(string);
    QFont font;
    font.setPixelSize(10);
    edit.setFont(font);
    edit.resize(500, 500);
    const QRect r = edit.viewport()->rect();
    QPoint pos(0, 0);
    for (int x=r.left(); x<r.right(); ++x) {
        for (int y=r.top(); y<r.bottom(); ++y) {
            TextCursor cursor = edit.cursorForPosition(pos);
            if (!cursor.isValid())
                continue;
            QCOMPARE(cursor.position(), edit.textPositionAt(pos));
            const QChar ch = cursor.cursorCharacter();
            const QChar readChar = edit.readCharacter(cursor.position());
            QCOMPARE(readChar, ch);
            if (all.remove(ch) && all.isEmpty()) {
                goto end;
            }
        }
    }
end:
    QCOMPARE(all.size(), 0);
}

void tst_TextEdit::columnNumberIssue()
{
    QCOMPARE(1, 1);
    return;
    TextEdit edit;
    edit.resize(200, 200);
    edit.setText("This is a very very very long line and it should most certainly wrap around at least once.\n"
                 "This is a shorter line\n"
                 "1\n"
                 "2\n"
                 "3\n"
                 "4\n"
                 "5\n"
                 "6\n"
                 "7\n"
                 "8\n"
                 "9\n"
                 "10\n"
                 "11\n"
                 "12\n");
    edit.show();
    QTest::qWaitForWindowShown(&edit);
    QVERIFY(edit.verticalScrollBar()->maximum() != 0);
    while (edit.cursorPosition() < edit.document()->documentSize()) {
        QCOMPARE(0, edit.textCursor().columnNumber());
        QTest::keyClick(&edit, Qt::Key_Down);
    }
//    QVERIFY(edit.verticalScrollBar()->value() != 0);
    while (edit.cursorPosition() > 0) {
//        qDebug() << edit.cursorPosition();
        QTest::keyClick(&edit, Qt::Key_Up);
        QCOMPARE(0, edit.textCursor().columnNumber());
    }
//     QEventLoop loop;
//     loop.exec();
}

void tst_TextEdit::selectionTest()
{
    TextEdit edit;
    QString line = "1234567890\n";
    edit.document()->setText(line);
//    edit.setReadOnly(true);
    edit.resize(400, 400);
    edit.show();
    QTest::qWaitForWindowShown(&edit);

    QCOMPARE(edit.selectedText(), QString());
    QVERIFY(!edit.textCursor().hasSelection());

    QTest::keyClick(&edit, Qt::Key_Right, Qt::ShiftModifier);
    QVERIFY(edit.textCursor().hasSelection());
    QCOMPARE(edit.selectedText(), QString("1"));
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 1);

    QTest::keyClick(&edit, Qt::Key_Right, Qt::ShiftModifier);
    QVERIFY(edit.textCursor().hasSelection());
    QCOMPARE(edit.selectedText(), QString("12"));
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 2);

    QTest::keyClick(&edit, Qt::Key_Right, Qt::ShiftModifier);
    QVERIFY(edit.textCursor().hasSelection());
    QCOMPARE(edit.textCursor().selectedText(), QString("123"));
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 3);

    QTest::keyClick(&edit, Qt::Key_Left, Qt::ShiftModifier);
    QVERIFY(edit.textCursor().hasSelection());
    QCOMPARE(edit.textCursor().selectedText(), QString("12"));
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 2);

    QTest::keyClick(&edit, Qt::Key_Left, Qt::ShiftModifier);
    QVERIFY(edit.textCursor().hasSelection());
    QCOMPARE(edit.textCursor().selectedText(), QString("1"));
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 1);

    QTest::keyClick(&edit, Qt::Key_Left, Qt::ShiftModifier);
    QVERIFY(!edit.textCursor().hasSelection());
    QCOMPARE(edit.textCursor().selectedText(), QString());
    QCOMPARE(edit.textCursor().anchor(), 0);
    QCOMPARE(edit.textCursor().position(), 0);
}

QTEST_MAIN(tst_TextEdit)
#include "tst_textedit.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: noteurl.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-26 13:47:07 $
 *
 *  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_sw.hxx"

#include "swtypes.hxx"

#ifndef _SV_OUTDEV_HXX //autogen
#include <vcl/outdev.hxx>
#endif
#ifndef _GOODIES_IMAPRECT_HXX
#include <svtools/imaprect.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif

#include "txttypes.hxx"
#include "noteurl.hxx"

// globale Variable, wird in noteurl.Hxx bekanntgegeben
SwNoteURL *pNoteURL = NULL;

SV_IMPL_PTRARR( SwURLNoteList, SwURLNotePtr )

void SwNoteURL::InsertURLNote( const XubString& rURL, const XubString& rTarget,
    const SwRect& rRect )
{
    MSHORT i;
    MSHORT nCount = aList.Count();
    for( i = 0; i < nCount; i++ )
        if( rRect == aList.GetObject(i)->GetRect() )
            break;
    if( i == nCount )
    {
        SwURLNote *pNew = new SwURLNote( rURL, rTarget, rRect );
        aList.Insert( pNew, nCount );
    }
}

void SwNoteURL::FillImageMap( ImageMap *pMap, const Point &rPos,
    const MapMode& rMap )
{
    ASSERT( pMap, "FillImageMap: No ImageMap, no cookies!" );
    MSHORT nCount = Count();
    if( nCount )
    {
        MapMode aMap( MAP_100TH_MM );
        for( MSHORT i = 0; i < nCount; ++i )
        {
            const SwURLNote &rNote = GetURLNote( i );
            SwRect aSwRect( rNote.GetRect() );
            aSwRect -= rPos;
            Rectangle aRect( OutputDevice::LogicToLogic( aSwRect.SVRect(),
                                                         rMap, aMap ) );
            IMapRectangleObject aObj( aRect, rNote.GetURL(), aEmptyStr, aEmptyStr,
                                      rNote.GetTarget(), aEmptyStr, sal_True, sal_False );
            pMap->InsertIMapObject( aObj );
        }
    }
}

<commit_msg>INTEGRATION: CWS changefileheader (1.5.372); FILE MERGED 2008/04/01 15:57:26 thb 1.5.372.2: #i85898# Stripping all external header guards 2008/03/31 16:54:38 rt 1.5.372.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: noteurl.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "swtypes.hxx"
#include <vcl/outdev.hxx>
#include <svtools/imaprect.hxx>
#include <svtools/imap.hxx>

#include "txttypes.hxx"
#include "noteurl.hxx"

// globale Variable, wird in noteurl.Hxx bekanntgegeben
SwNoteURL *pNoteURL = NULL;

SV_IMPL_PTRARR( SwURLNoteList, SwURLNotePtr )

void SwNoteURL::InsertURLNote( const XubString& rURL, const XubString& rTarget,
    const SwRect& rRect )
{
    MSHORT i;
    MSHORT nCount = aList.Count();
    for( i = 0; i < nCount; i++ )
        if( rRect == aList.GetObject(i)->GetRect() )
            break;
    if( i == nCount )
    {
        SwURLNote *pNew = new SwURLNote( rURL, rTarget, rRect );
        aList.Insert( pNew, nCount );
    }
}

void SwNoteURL::FillImageMap( ImageMap *pMap, const Point &rPos,
    const MapMode& rMap )
{
    ASSERT( pMap, "FillImageMap: No ImageMap, no cookies!" );
    MSHORT nCount = Count();
    if( nCount )
    {
        MapMode aMap( MAP_100TH_MM );
        for( MSHORT i = 0; i < nCount; ++i )
        {
            const SwURLNote &rNote = GetURLNote( i );
            SwRect aSwRect( rNote.GetRect() );
            aSwRect -= rPos;
            Rectangle aRect( OutputDevice::LogicToLogic( aSwRect.SVRect(),
                                                         rMap, aMap ) );
            IMapRectangleObject aObj( aRect, rNote.GetURL(), aEmptyStr, aEmptyStr,
                                      rNote.GetTarget(), aEmptyStr, sal_True, sal_False );
            pMap->InsertIMapObject( aObj );
        }
    }
}

<|endoftext|>


<commit_before>#include "thcrap.h"
#include "http_curl.h"

CurlHandle::CurlHandle()
    : curl(curl_easy_init())
{}

CurlHandle::CurlHandle(CurlHandle&& other)
    : curl(other.curl)
{
    other.curl = nullptr;
}

CurlHandle::~CurlHandle()
{
    if (this->curl) {
        curl_easy_cleanup(this->curl);
    }
}

size_t CurlHandle::writeCallbackStatic(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    auto callback = *static_cast<std::function<size_t(const uint8_t*, size_t)>*>(userdata);
    return callback(reinterpret_cast<const uint8_t*>(ptr), size * nmemb);
};

int CurlHandle::progressCallbackStatic(void *userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t /* ultotal */, curl_off_t /* ulnow */)
{
    auto callback = *static_cast<std::function<bool(size_t, size_t)>*>(userdata);
    if (callback((size_t)dlnow, (size_t)dltotal)) {
        return 0;
    }
    else {
        return -1;
    }
};

HttpStatus CurlHandle::download(const std::string& url, std::function<size_t(const uint8_t*, size_t)> writeCallback, std::function<bool(size_t, size_t)> progressCallback)
{
	curl_easy_setopt(this->curl, CURLOPT_CAINFO, "bin/cacert.pem");
    curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1);

    // Format according to RFC 7231, section 5.5.3
    std::string userAgent = std::string(PROJECT_NAME_SHORT) + "/" + PROJECT_VERSION_STRING + " (" + windows_version() + ")";
    curl_easy_setopt(this->curl, CURLOPT_USERAGENT, userAgent.c_str());

    curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, CurlHandle::writeCallbackStatic);
    curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &writeCallback);

    curl_easy_setopt(this->curl, CURLOPT_NOPROGRESS, 0);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, CurlHandle::progressCallbackStatic);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, &progressCallback);

    char errbuf[CURL_ERROR_SIZE];
    curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, errbuf);
    errbuf[0] = 0;
    curl_easy_setopt(this->curl, CURLOPT_URL, url.c_str());

    CURLcode res = curl_easy_perform(this->curl);

    curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, nullptr);

    std::string error;
    if (res != CURLE_OK) {
        if (errbuf[0]) {
            error = errbuf;
        }
        else {
            error = curl_easy_strerror(res);
        }
        curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, nullptr);
        if (res == CURLE_ABORTED_BY_CALLBACK) {
            return HttpStatus::makeCancelled();
        }
        else {
            return HttpStatus::makeSystemError(res, error);
        }
    }
    curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, nullptr);

    long response_code = 0;
    curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &response_code);
    if (response_code != 200) {
        return HttpStatus::makeNetworkError(response_code);
    }

    return HttpStatus::makeOk();
}
<commit_msg>thcrap_update: encode UTF-8 characters in URLs<commit_after>#include "thcrap.h"
#include "http_curl.h"

CurlHandle::CurlHandle()
    : curl(curl_easy_init())
{}

CurlHandle::CurlHandle(CurlHandle&& other)
    : curl(other.curl)
{
    other.curl = nullptr;
}

CurlHandle::~CurlHandle()
{
    if (this->curl) {
        curl_easy_cleanup(this->curl);
    }
}

size_t CurlHandle::writeCallbackStatic(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    auto callback = *static_cast<std::function<size_t(const uint8_t*, size_t)>*>(userdata);
    return callback(reinterpret_cast<const uint8_t*>(ptr), size * nmemb);
};

int CurlHandle::progressCallbackStatic(void *userdata, curl_off_t dltotal, curl_off_t dlnow, curl_off_t /* ultotal */, curl_off_t /* ulnow */)
{
    auto callback = *static_cast<std::function<bool(size_t, size_t)>*>(userdata);
    if (callback((size_t)dlnow, (size_t)dltotal)) {
        return 0;
    }
    else {
        return -1;
    }
};

static char digit_to_hex(unsigned int digit)
{
    if (digit <= 9) {
        return '0' + digit;
    }
    else if (digit <= 'F') {
        return 'A' + (digit - 10);
    }
    else {
        return '?';
    }
}

static std::string encode_UTF8_char(uint8_t c)
{
    if (c & 0x80) {
        std::string ret = "%";
        ret += digit_to_hex(c >> 4);
        ret += digit_to_hex(c & 0x0F);
        return ret;
    }
    else {
        return std::string() + (char)c;
    }
}

static std::string encode_UTF8_url(std::string in)
{
    std::string out;
    for (auto c : in) {
        out += encode_UTF8_char((uint8_t)c);
    }
    return out;
}

HttpStatus CurlHandle::download(const std::string& url, std::function<size_t(const uint8_t*, size_t)> writeCallback, std::function<bool(size_t, size_t)> progressCallback)
{
	curl_easy_setopt(this->curl, CURLOPT_CAINFO, "bin/cacert.pem");
    curl_easy_setopt(this->curl, CURLOPT_FOLLOWLOCATION, 1);

    // Format according to RFC 7231, section 5.5.3
    std::string userAgent = std::string(PROJECT_NAME_SHORT) + "/" + PROJECT_VERSION_STRING + " (" + windows_version() + ")";
    curl_easy_setopt(this->curl, CURLOPT_USERAGENT, userAgent.c_str());

    curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, CurlHandle::writeCallbackStatic);
    curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, &writeCallback);

    curl_easy_setopt(this->curl, CURLOPT_NOPROGRESS, 0);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, CurlHandle::progressCallbackStatic);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, &progressCallback);

    char errbuf[CURL_ERROR_SIZE];
    curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, errbuf);
    errbuf[0] = 0;

    std::string url_encoded = encode_UTF8_url(url);
    curl_easy_setopt(this->curl, CURLOPT_URL, url_encoded.c_str());

    CURLcode res = curl_easy_perform(this->curl);

    curl_easy_setopt(this->curl, CURLOPT_WRITEFUNCTION, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_WRITEDATA, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFOFUNCTION, nullptr);
    curl_easy_setopt(this->curl, CURLOPT_XFERINFODATA, nullptr);

    std::string error;
    if (res != CURLE_OK) {
        if (errbuf[0]) {
            error = errbuf;
        }
        else {
            error = curl_easy_strerror(res);
        }
        curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, nullptr);
        if (res == CURLE_ABORTED_BY_CALLBACK) {
            return HttpStatus::makeCancelled();
        }
        else {
            return HttpStatus::makeSystemError(res, error);
        }
    }
    curl_easy_setopt(this->curl, CURLOPT_ERRORBUFFER, nullptr);

    long response_code = 0;
    curl_easy_getinfo(this->curl, CURLINFO_RESPONSE_CODE, &response_code);
    if (response_code != 200) {
        return HttpStatus::makeNetworkError(response_code);
    }

    return HttpStatus::makeOk();
}
<|endoftext|>


<commit_before>/*  This file is part of the Vc library. {{{

    Copyright (C) 2013 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

}}}*/

#define VC_NEWTEST
#include "unittest.h"
#include "../common/simd_array.h"

using namespace Vc;

#define SIMD_ARRAY_LIST                                                                            \
    (SIMD_ARRAYS(32),                                                                              \
     SIMD_ARRAYS(17),                                                                              \
     SIMD_ARRAYS(16),                                                                              \
     SIMD_ARRAYS(8),                                                                               \
     SIMD_ARRAYS(4),                                                                               \
     SIMD_ARRAYS(3),                                                                               \
     SIMD_ARRAYS(2),                                                                               \
     SIMD_ARRAYS(1))

template<typename T, size_t N> constexpr size_t captureN(simd_array<T, N>) { return N; }

TEST_BEGIN(V, createArray, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    typedef typename V::VectorEntryType VT;
    typedef typename V::vector_type Vec;
    V array;

    COMPARE(array.size(), captureN(V()));
    VERIFY(sizeof(array) >= array.size() * sizeof(VT));
    VERIFY(sizeof(array) <= 2 * array.size() * sizeof(VT));
TEST_END

TEST_BEGIN(V, broadcast, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V array = 0;
    array = 1;
    V v0{T(1)};
    V v1 = T(2);
    v0 = 2;
    v1 = 3;
TEST_END

TEST_BEGIN(V, broadcast_equal, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V a = 0;
    V b = 0;
    COMPARE(a, b);
    a = 1;
    b = 1;
    COMPARE(a, b);
TEST_END

TEST_BEGIN(V, broadcast_not_equal, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V a = 0;
    V b = 1;
    VERIFY(all_of(a != b));
    VERIFY(all_of(a < b));
    VERIFY(all_of(a <= b));
    VERIFY(none_of(a > b));
    VERIFY(none_of(a >= b));
    a = 1;
    VERIFY(all_of(a <= b));
    VERIFY(all_of(a >= b));
TEST_END

TEST_BEGIN(V, addition, SIMD_ARRAY_LIST)
{
    V a = 0;
    V b = 1;
    V c = 10;
    COMPARE(a + b, b);
    COMPARE(c + b, V{11});
}
TEST_END

#if 0
TEST_BEGIN(V, load, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    Vc::Memory<V, V::Size + 2> data;
    for (size_t i = 0; i < data.entriesCount(); ++i) {
        data[i] = T(i);
    }

    V a{ &data[0] };
    V b(Vc::IndexesFromZero);
    COMPARE(a, b);

    b.load(&data[0]);
    COMPARE(a, b);

    a.load(&data[1], Vc::Unaligned);
    COMPARE(a, b + 1);

    b = decltype(b)(&data[2], Vc::Unaligned | Vc::Streaming);
    COMPARE(a, b - 1);
TEST_END

TEST(load_converting)
{
    typedef simd_array<float, 32> A;

    Vc::Memory<double_v, 34> data;
    for (size_t i = 0; i < data.entriesCount(); ++i) {
        data[i] = double(i);
    }

    A a{ &data[0] };
    A b(Vc::IndexesFromZero);
    COMPARE(a, b);

    b.load(&data[1], Vc::Unaligned);
    COMPARE(a + 1, b);

    a = A(&data[2], Vc::Unaligned | Vc::Streaming);
    COMPARE(a, b + 1);
}

TEST_ALL_V(V, store)
{
    typedef typename V::EntryType T;
    Vc::Memory<V, 34> data;
    data = V::Zero();

    simd_array<T, 32> a(Vc::IndexesFromZero);
    a.store(&data[0], Vc::Aligned);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i], i);
    a.store(&data[1], Vc::Unaligned);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i + 1], i);
    a.store(&data[0], Vc::Aligned | Vc::Streaming);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i], i);
    a.store(&data[1], Vc::Unaligned | Vc::Streaming);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i + 1], i);
}
#endif
<commit_msg>simd_array: ensure default ctor nulls<commit_after>/*  This file is part of the Vc library. {{{

    Copyright (C) 2013 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc 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 Vc.  If not, see <http://www.gnu.org/licenses/>.

}}}*/

#define VC_NEWTEST
#include "unittest.h"
#include "../common/simd_array.h"

using namespace Vc;

#define SIMD_ARRAY_LIST                                                                            \
    (SIMD_ARRAYS(32),                                                                              \
     SIMD_ARRAYS(17),                                                                              \
     SIMD_ARRAYS(16),                                                                              \
     SIMD_ARRAYS(8),                                                                               \
     SIMD_ARRAYS(4),                                                                               \
     SIMD_ARRAYS(3),                                                                               \
     SIMD_ARRAYS(2),                                                                               \
     SIMD_ARRAYS(1))

template<typename T, size_t N> constexpr size_t captureN(simd_array<T, N>) { return N; }

TEST_BEGIN(V, createArray, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    typedef typename V::VectorEntryType VT;
    typedef typename V::vector_type Vec;
    V array;

    COMPARE(array.size(), captureN(V()));
    VERIFY(sizeof(array) >= array.size() * sizeof(VT));
    VERIFY(sizeof(array) <= 2 * array.size() * sizeof(VT));
TEST_END

TEST_BEGIN(V, broadcast, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V array = 0;
    array = 1;
    V v0{T(1)};
    V v1 = T(2);
    v0 = 2;
    v1 = 3;
    COMPARE(V(), V(0));
TEST_END

TEST_BEGIN(V, broadcast_equal, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V a = 0;
    V b = 0;
    COMPARE(a, b);
    a = 1;
    b = 1;
    COMPARE(a, b);
TEST_END

TEST_BEGIN(V, broadcast_not_equal, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    V a = 0;
    V b = 1;
    VERIFY(all_of(a != b));
    VERIFY(all_of(a < b));
    VERIFY(all_of(a <= b));
    VERIFY(none_of(a > b));
    VERIFY(none_of(a >= b));
    a = 1;
    VERIFY(all_of(a <= b));
    VERIFY(all_of(a >= b));
TEST_END

TEST_BEGIN(V, addition, SIMD_ARRAY_LIST)
{
    V a = 0;
    V b = 1;
    V c = 10;
    COMPARE(a + b, b);
    COMPARE(c + b, V{11});
}
TEST_END

#if 0
TEST_BEGIN(V, load, SIMD_ARRAY_LIST)
    typedef typename V::EntryType T;
    Vc::Memory<V, V::Size + 2> data;
    for (size_t i = 0; i < data.entriesCount(); ++i) {
        data[i] = T(i);
    }

    V a{ &data[0] };
    V b(Vc::IndexesFromZero);
    COMPARE(a, b);

    b.load(&data[0]);
    COMPARE(a, b);

    a.load(&data[1], Vc::Unaligned);
    COMPARE(a, b + 1);

    b = decltype(b)(&data[2], Vc::Unaligned | Vc::Streaming);
    COMPARE(a, b - 1);
TEST_END

TEST(load_converting)
{
    typedef simd_array<float, 32> A;

    Vc::Memory<double_v, 34> data;
    for (size_t i = 0; i < data.entriesCount(); ++i) {
        data[i] = double(i);
    }

    A a{ &data[0] };
    A b(Vc::IndexesFromZero);
    COMPARE(a, b);

    b.load(&data[1], Vc::Unaligned);
    COMPARE(a + 1, b);

    a = A(&data[2], Vc::Unaligned | Vc::Streaming);
    COMPARE(a, b + 1);
}

TEST_ALL_V(V, store)
{
    typedef typename V::EntryType T;
    Vc::Memory<V, 34> data;
    data = V::Zero();

    simd_array<T, 32> a(Vc::IndexesFromZero);
    a.store(&data[0], Vc::Aligned);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i], i);
    a.store(&data[1], Vc::Unaligned);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i + 1], i);
    a.store(&data[0], Vc::Aligned | Vc::Streaming);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i], i);
    a.store(&data[1], Vc::Unaligned | Vc::Streaming);
    for (size_t i = 0; i < 32; ++i) COMPARE(data[i + 1], i);
}
#endif
<|endoftext|>


<commit_before>/*-
 * Copyright 2003,2004 Colin Percival
 * All rights reserved
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted providing that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Changelog:
 * 2005-04-26 - Define the header as a C structure, add a CRC32 checksum to
 *              the header, and make all the types 32-bit.
 *                --Benjamin Smedberg <benjamin@smedbergs.us>
 * 2007-11-14 - Added CalculateCrc() and ApplyBinaryPatch() methods.
 *                --Rahul Kuchhal
 */

#include "mbspatch.h"

#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>

#ifdef _WIN32
# include <io.h>
# include <winsock2.h>
#else
# include <unistd.h>
# include <arpa/inet.h>
#endif

extern "C" {
#include <7zCrc.h>
}

#ifndef SSIZE_MAX
# define SSIZE_MAX LONG_MAX
#endif

int
MBS_ReadHeader(int fd, MBSPatchHeader *header)
{
  int s = read(fd, header, sizeof(MBSPatchHeader));
  if (s != sizeof(MBSPatchHeader))
    return READ_ERROR;

  header->slen      = ntohl(header->slen);
  header->scrc32    = ntohl(header->scrc32);
  header->dlen      = ntohl(header->dlen);
  header->cblen     = ntohl(header->cblen);
  header->difflen   = ntohl(header->difflen);
  header->extralen  = ntohl(header->extralen);

  struct stat hs;
  s = fstat(fd, &hs);
  if (s)
    return READ_ERROR;

  if (memcmp(header->tag, "MBDIFF10", 8) != 0)
    return UNEXPECTED_ERROR;

  if (sizeof(MBSPatchHeader) +
      header->cblen +
      header->difflen +
      header->extralen != int(hs.st_size))
    return UNEXPECTED_ERROR;

  return OK;
}

int
MBS_ApplyPatch(const MBSPatchHeader *header, int patchfd,
               unsigned char *fbuffer, int filefd)
{
  unsigned char *fbufend = fbuffer + header->slen;

  unsigned char *buf = (unsigned char*) malloc(header->cblen +
                                               header->difflen +
                                               header->extralen);
  if (!buf)
    return MEM_ERROR;

  int rv = OK;

  int r = header->cblen + header->difflen + header->extralen;
  unsigned char *wb = buf;
  while (r) {
    int c = read(patchfd, wb, (r > SSIZE_MAX) ? SSIZE_MAX : r);
    if (c < 0) {
      rv = READ_ERROR;
      goto end;
    }

    r -= c;

    if (c == 0 && r) {
      rv = UNEXPECTED_ERROR;
      goto end;
    }
  }

  {
    MBSPatchTriple *ctrlsrc = (MBSPatchTriple*) buf;
    unsigned char *diffsrc = buf + header->cblen;
    unsigned char *extrasrc = diffsrc + header->difflen;

    MBSPatchTriple *ctrlend = (MBSPatchTriple*) diffsrc;
    unsigned char *diffend = extrasrc;
    unsigned char *extraend = extrasrc + header->extralen;

    do {
      ctrlsrc->x = ntohl(ctrlsrc->x);
      ctrlsrc->y = ntohl(ctrlsrc->y);
      ctrlsrc->z = ntohl(ctrlsrc->z);

#ifdef DEBUG_bsmedberg
      printf("Applying block:\n"
             " x: %u\n"
             " y: %u\n"
             " z: %i\n",
             ctrlsrc->x,
             ctrlsrc->y,
             ctrlsrc->z);
#endif

      /* Add x bytes from oldfile to x bytes from the diff block */

      if (fbuffer + ctrlsrc->x > fbufend ||
          diffsrc + ctrlsrc->x > diffend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      for (unsigned int i = 0; i < ctrlsrc->x; ++i) {
        diffsrc[i] += fbuffer[i];
      }
      if ((int) write(filefd, diffsrc, ctrlsrc->x) != ctrlsrc->x) {
        rv = WRITE_ERROR;
        goto end;
      }
      fbuffer += ctrlsrc->x;
      diffsrc += ctrlsrc->x;

      /* Copy y bytes from the extra block */

      if (extrasrc + ctrlsrc->y > extraend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      if ((int) write(filefd, extrasrc, ctrlsrc->y) != ctrlsrc->y) {
        rv = WRITE_ERROR;
        goto end;
      }
      extrasrc += ctrlsrc->y;

      /* "seek" forwards in oldfile by z bytes */

      if (fbuffer + ctrlsrc->z > fbufend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      fbuffer += ctrlsrc->z;

      /* and on to the next control block */

      ++ctrlsrc;
    } while (ctrlsrc < ctrlend);
  }

end:
  free(buf);
  return rv;
}

int CalculateCrc(const unsigned char *buf, int size) {
  CrcGenerateTable();
  unsigned int crc = 0xffffffffL;
  crc = ~CrcCalc(buf, size);
  return crc;
}

int ApplyBinaryPatch(const char *old_file, const char *patch_file,
                     const char *new_file) {
  int ret = 0;
  int pfd = open(patch_file, O_RDONLY | _O_BINARY);
  if (pfd < 0) return READ_ERROR;

  MBSPatchHeader header;
  if (ret = MBS_ReadHeader(pfd, &header)) return ret;

  int ofd = open(old_file, O_RDONLY | _O_BINARY);
  if (ofd < 0) return READ_ERROR;

  struct stat os;
  if (ret = fstat(ofd, &os)) return READ_ERROR;
  if (os.st_size != header.slen) return UNEXPECTED_ERROR;

  unsigned char *buf = (unsigned char*) malloc(header.slen);
  if (!buf) return MEM_ERROR;

  if (read(ofd, buf, header.slen) != header.slen) return READ_ERROR;
  if (CalculateCrc(buf, header.slen) != header.scrc32)
    return CRC_ERROR;

  int nfd = open(new_file, O_WRONLY | O_TRUNC | O_CREAT | _O_BINARY);
  if (nfd < 0) return READ_ERROR;

  MBS_ApplyPatch(&header, pfd, buf, nfd);

  free(buf);
  close(pfd);
  close(ofd);
  close(nfd);
  return OK;
}

<commit_msg>Fix mbspatch.cc to work on non-Windows platforms.<commit_after>/*-
 * Copyright 2003,2004 Colin Percival
 * All rights reserved
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted providing that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Changelog:
 * 2005-04-26 - Define the header as a C structure, add a CRC32 checksum to
 *              the header, and make all the types 32-bit.
 *                --Benjamin Smedberg <benjamin@smedbergs.us>
 * 2007-11-14 - Added CalculateCrc() and ApplyBinaryPatch() methods.
 *                --Rahul Kuchhal
 */

#include "mbspatch.h"

#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>

#ifdef _WIN32
# include <io.h>
# include <winsock2.h>
#else
# include <unistd.h>
# include <arpa/inet.h>
#endif

extern "C" {
#include <7zCrc.h>
}

#ifndef SSIZE_MAX
# define SSIZE_MAX LONG_MAX
#endif

int
MBS_ReadHeader(int fd, MBSPatchHeader *header)
{
  int s = read(fd, header, sizeof(MBSPatchHeader));
  if (s != sizeof(MBSPatchHeader))
    return READ_ERROR;

  header->slen      = ntohl(header->slen);
  header->scrc32    = ntohl(header->scrc32);
  header->dlen      = ntohl(header->dlen);
  header->cblen     = ntohl(header->cblen);
  header->difflen   = ntohl(header->difflen);
  header->extralen  = ntohl(header->extralen);

  struct stat hs;
  s = fstat(fd, &hs);
  if (s)
    return READ_ERROR;

  if (memcmp(header->tag, "MBDIFF10", 8) != 0)
    return UNEXPECTED_ERROR;

  if (sizeof(MBSPatchHeader) +
      header->cblen +
      header->difflen +
      header->extralen != int(hs.st_size))
    return UNEXPECTED_ERROR;

  return OK;
}

int
MBS_ApplyPatch(const MBSPatchHeader *header, int patchfd,
               unsigned char *fbuffer, int filefd)
{
  unsigned char *fbufend = fbuffer + header->slen;

  unsigned char *buf = (unsigned char*) malloc(header->cblen +
                                               header->difflen +
                                               header->extralen);
  if (!buf)
    return MEM_ERROR;

  int rv = OK;

  int r = header->cblen + header->difflen + header->extralen;
  unsigned char *wb = buf;
  while (r) {
    int c = read(patchfd, wb, (r > SSIZE_MAX) ? SSIZE_MAX : r);
    if (c < 0) {
      rv = READ_ERROR;
      goto end;
    }

    r -= c;

    if (c == 0 && r) {
      rv = UNEXPECTED_ERROR;
      goto end;
    }
  }

  {
    MBSPatchTriple *ctrlsrc = (MBSPatchTriple*) buf;
    unsigned char *diffsrc = buf + header->cblen;
    unsigned char *extrasrc = diffsrc + header->difflen;

    MBSPatchTriple *ctrlend = (MBSPatchTriple*) diffsrc;
    unsigned char *diffend = extrasrc;
    unsigned char *extraend = extrasrc + header->extralen;

    do {
      ctrlsrc->x = ntohl(ctrlsrc->x);
      ctrlsrc->y = ntohl(ctrlsrc->y);
      ctrlsrc->z = ntohl(ctrlsrc->z);

#ifdef DEBUG_bsmedberg
      printf("Applying block:\n"
             " x: %u\n"
             " y: %u\n"
             " z: %i\n",
             ctrlsrc->x,
             ctrlsrc->y,
             ctrlsrc->z);
#endif

      /* Add x bytes from oldfile to x bytes from the diff block */

      if (fbuffer + ctrlsrc->x > fbufend ||
          diffsrc + ctrlsrc->x > diffend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      for (unsigned int i = 0; i < ctrlsrc->x; ++i) {
        diffsrc[i] += fbuffer[i];
      }
      if ((int) write(filefd, diffsrc, ctrlsrc->x) != ctrlsrc->x) {
        rv = WRITE_ERROR;
        goto end;
      }
      fbuffer += ctrlsrc->x;
      diffsrc += ctrlsrc->x;

      /* Copy y bytes from the extra block */

      if (extrasrc + ctrlsrc->y > extraend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      if ((int) write(filefd, extrasrc, ctrlsrc->y) != ctrlsrc->y) {
        rv = WRITE_ERROR;
        goto end;
      }
      extrasrc += ctrlsrc->y;

      /* "seek" forwards in oldfile by z bytes */

      if (fbuffer + ctrlsrc->z > fbufend) {
        rv = UNEXPECTED_ERROR;
        goto end;
      }
      fbuffer += ctrlsrc->z;

      /* and on to the next control block */

      ++ctrlsrc;
    } while (ctrlsrc < ctrlend);
  }

end:
  free(buf);
  return rv;
}

int CalculateCrc(const unsigned char *buf, int size) {
  CrcGenerateTable();
  unsigned int crc = 0xffffffffL;
  crc = ~CrcCalc(buf, size);
  return crc;
}

/* _O_BINARY is a MSWindows open() mode flag.  When absent, MSWindows
 * open() translates CR+LF to LF; when present, it passes bytes
 * through faithfully.  Under *nix, we are always in binary mode, so
 * the following #define turns this flag into a no-op w.r.t.  bitwise
 * OR.  Note that this would be DANGEROUS AND UNSOUND if we used
 * _O_BINARY other than as a bitwise OR mask (e.g., as a bitwise AND
 * mask to check for binary mode), but it seems OK in the limited
 * context of the following small function. */
#ifndef _O_BINARY
# define _O_BINARY 0
#endif

int ApplyBinaryPatch(const char *old_file, const char *patch_file,
                     const char *new_file) {
  int ret = 0;
  int pfd = open(patch_file, O_RDONLY | _O_BINARY);
  if (pfd < 0) return READ_ERROR;

  MBSPatchHeader header;
  if (ret = MBS_ReadHeader(pfd, &header)) return ret;

  int ofd = open(old_file, O_RDONLY | _O_BINARY);
  if (ofd < 0) return READ_ERROR;

  struct stat os;
  if (ret = fstat(ofd, &os)) return READ_ERROR;
  if (os.st_size != header.slen) return UNEXPECTED_ERROR;

  unsigned char *buf = (unsigned char*) malloc(header.slen);
  if (!buf) return MEM_ERROR;

  if (read(ofd, buf, header.slen) != header.slen) return READ_ERROR;
  if (CalculateCrc(buf, header.slen) != header.scrc32)
    return CRC_ERROR;

  int nfd = open(new_file, O_WRONLY | O_TRUNC | O_CREAT | _O_BINARY);
  if (nfd < 0) return READ_ERROR;

  MBS_ApplyPatch(&header, pfd, buf, nfd);

  free(buf);
  close(pfd);
  close(ofd);
  close(nfd);
  return OK;
}
<|endoftext|>