<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: flyincnt.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-15 11:42:31 $
 *
 *  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 "cntfrm.hxx"
#include "doc.hxx"
#include "flyfrm.hxx"
#include "frmtool.hxx"
#include "frmfmt.hxx"
#include "hints.hxx"

#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#include "txtfrm.hxx"       //fuer IsLocked()
#include "flyfrms.hxx"
// OD 2004-01-19 #110582#
#ifndef _DFLYOBJ_HXX
#include <dflyobj.hxx>
#endif

//aus FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );

/*************************************************************************
|*
|*  SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()
|*
|*  Ersterstellung      MA 01. Dec. 92
|*  Letzte Aenderung    MA 09. Apr. 99
|*
|*************************************************************************/
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :
    SwFlyFrm( pFmt, pAnch )
{
    bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;
    SwTwips nRel = pFmt->GetVertOrient().GetPos();
    // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
    Point aRelPos;
    if( pAnch && pAnch->IsVertical() )
        aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;
    else
        aRelPos.Y() = nRel;
    SetCurrRelPos( aRelPos );
}

SwFlyInCntFrm::~SwFlyInCntFrm()
{
    //und Tschuess.
    if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() )
    {
        SwRect aTmp( GetObjRectWithSpaces() );
        SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
    }
}

// --> OD 2004-06-29 #i28701#
TYPEINIT1(SwFlyInCntFrm,SwFlyFrm);
// <--
/*************************************************************************
|*
|*  SwFlyInCntFrm::SetRefPoint(),
|*
|*  Ersterstellung      MA 01. Dec. 92
|*  Letzte Aenderung    MA 06. Aug. 95
|*
|*************************************************************************/
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint,
                                 const Point& rRelAttr,
                                 const Point& rRelPos )
{
    // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
    ASSERT( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" );
    SwFlyNotify *pNotify = NULL;
    // No notify at a locked fly frame, if a fly frame is locked, there's
    // already a SwFlyNotify object on the stack (MakeAll).
    if( !IsLocked() )
        pNotify = new SwFlyNotify( this );
    aRef = rPoint;
    SetCurrRelPos( rRelAttr );
    SWRECTFN( GetAnchorFrm() )
    (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
    // --> OD 2006-08-25 #i68520#
    InvalidateObjRectWithSpaces();
    // <--
    if( pNotify )
    {
        InvalidatePage();
        bValidPos = FALSE;
        bInvalid  = TRUE;
        Calc();
        delete pNotify;
    }
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::Modify()
|*
|*  Ersterstellung      MA 16. Dec. 92
|*  Letzte Aenderung    MA 02. Sep. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )
{
    BOOL bCallPrepare = FALSE;
    USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
    if( RES_ATTRSET_CHG == nWhich )
    {
        if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
            GetItemState( RES_SURROUND, FALSE ) ||
            SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
            GetItemState( RES_FRMMACRO, FALSE ) )
        {
            SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
            SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );

            aOld.ClearItem( RES_SURROUND );
            aNew.ClearItem( RES_SURROUND );
            aOld.ClearItem( RES_FRMMACRO );
            aNew.ClearItem( RES_FRMMACRO );
            if( aNew.Count() )
            {
                SwFlyFrm::Modify( &aOld, &aNew );
                bCallPrepare = TRUE;
            }
        }
        else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
        {
            SwFlyFrm::Modify( pOld, pNew );
            bCallPrepare = TRUE;
        }
    }
    else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
    {
        SwFlyFrm::Modify( pOld, pNew );
        bCallPrepare = TRUE;
    }

    if ( bCallPrepare && GetAnchorFrm() )
        AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/*************************************************************************
|*
|*  SwFlyInCntFrm::Format()
|*
|*  Beschreibung:       Hier wird der Inhalt initial mit Formatiert.
|*  Ersterstellung      MA 16. Dec. 92
|*  Letzte Aenderung    MA 19. May. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
    if ( !Frm().Height() )
    {
        Lock(); //nicht hintenherum den Anker formatieren.
        SwCntntFrm *pCntnt = ContainsCntnt();
        while ( pCntnt )
        {   pCntnt->Calc();
            pCntnt = pCntnt->GetNextCntntFrm();
        }
        Unlock();
    }
    SwFlyFrm::Format( pAttrs );
}
/*************************************************************************
|*
|*  SwFlyInCntFrm::MakeFlyPos()
|*
|*  Beschreibung        Im Unterschied zu anderen Frms wird hier nur die
|*      die RelPos berechnet. Die absolute Position wird ausschliesslich
|*      per SetAbsPos errechnet.
|*  Ersterstellung      MA 03. Dec. 92
|*  Letzte Aenderung    MA 12. Apr. 96
|*
|*************************************************************************/
// OD 2004-03-23 #i26791#
//void SwFlyInCntFrm::MakeFlyPos()
void SwFlyInCntFrm::MakeObjPos()
{
    if ( !bValidPos )
    {
        // --> OD 2004-08-12 #i32795# - calling methods <::DeepCalc(..)> and
        // <GetAnchorFrm()->GetFormatted()> no longer needed due to the changed
        // formatting of floating screen objects. It also causes layout loops.
//        if ( !GetAnchorFrm()->IsTxtFrm() || !((SwTxtFrm*)GetAnchorFrm())->IsLocked() )
//            ::DeepCalc( GetAnchorFrm() );
//        if( GetAnchorFrm()->IsTxtFrm() )
//            ((SwTxtFrm*)GetAnchorFrm())->GetFormatted();
        // <--
        bValidPos = TRUE;
        SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
        const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
        //Und ggf. noch die aktuellen Werte im Format updaten, dabei darf
        //zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.
        SWRECTFN( GetAnchorFrm() )
        SwTwips nOld = rVert.GetPos();
        SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y();
        if( bRev )
            nAct = -nAct;
        if( nAct != nOld )
        {
            SwFmtVertOrient aVert( rVert );
            aVert.SetPos( nAct );
            pFmt->LockModify();
            pFmt->SetAttr( aVert );
            pFmt->UnlockModify();
        }
    }
}

// --> OD 2004-12-02 #115759#
void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid )
{
    switch ( _nInvalid )
    {
        case INVALID_POS:
        case INVALID_ALL:
        {
            AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() );
        }
        break;
    }
}
// <--
/*************************************************************************
|*
|*  SwFlyInCntFrm::NotifyBackground()
|*
|*  Ersterstellung      MA 03. Dec. 92
|*  Letzte Aenderung    MA 26. Aug. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
                                       PrepareHint eHint)
{
    if ( eHint == PREP_FLY_ATTR_CHG )
        AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG );
    else
        AnchorFrm()->Prepare( eHint, (void*)&rRect );
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::GetRelPos()
|*
|*  Ersterstellung      MA 04. Dec. 92
|*  Letzte Aenderung    MA 04. Dec. 92
|*
|*************************************************************************/
const Point SwFlyInCntFrm::GetRelPos() const
{
    Calc();
    return GetCurrRelPos();
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::RegistFlys()
|*
|*  Ersterstellung      MA 26. Nov. 93
|*  Letzte Aenderung    MA 26. Nov. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::RegistFlys()
{
    // vgl. SwRowFrm::RegistFlys()
    SwPageFrm *pPage = FindPageFrm();
    ASSERT( pPage, "Flys ohne Seite anmelden?" );
    ::RegistFlys( pPage, this );
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::MakeAll()
|*
|*  Ersterstellung      MA 18. Feb. 94
|*  Letzte Aenderung    MA 13. Jun. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeAll()
{
    // OD 2004-01-19 #110582#
    if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )
    {
        return;
    }

    if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() )
        return;

    Lock(); //Der Vorhang faellt

        //uebernimmt im DTor die Benachrichtigung
    const SwFlyNotify aNotify( this );
    SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
    const SwBorderAttrs &rAttrs = *aAccess.Get();

    if ( IsClipped() )
        bValidSize = bHeightClipped = bWidthClipped = FALSE;

    while ( !bValidPos || !bValidSize || !bValidPrtArea )
    {
        //Nur einstellen wenn das Flag gesetzt ist!!
        if ( !bValidSize )
        {
            bValidPrtArea = FALSE;
/*
            // This is also done in the Format function, so I think
            // this code is not necessary anymore:
            long nOldWidth = aFrm.Width();
            const Size aRelSize( CalcRel( rFrmSz ) );
            aFrm.Width( aRelSize.Width() );

            if ( aFrm.Width() > nOldWidth )
                //Damit sich der Inhalt anpasst
                aFrm.Height( aRelSize.Height() );
*/
        }

        if ( !bValidPrtArea )
            MakePrtArea( rAttrs );

        if ( !bValidSize )
            Format( &rAttrs );

        if ( !bValidPos )
        {
            // OD 2004-03-23 #i26791#
            //MakeFlyPos();
            MakeObjPos();
        }

        // --> OD 2006-04-13 #b6402800#
        // re-activate clipping of as-character anchored Writer fly frames
        // depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames>
        if ( bValidPos && bValidSize &&
             GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) )
        {
            SwFrm* pFrm = AnchorFrm();
            if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
                 Frm().Width() > pFrm->Prt().Width() )
            {
                Frm().Width( pFrm->Prt().Width() );
                bValidPrtArea = FALSE;
                bWidthClipped = TRUE;
            }
        }
        // <--
    }
    Unlock();
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.15.2); FILE MERGED 2006/09/01 17:51:48 kaib 1.15.2.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: flyincnt.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 21:18:31 $
 *
 *  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 "cntfrm.hxx"
#include "doc.hxx"
#include "flyfrm.hxx"
#include "frmtool.hxx"
#include "frmfmt.hxx"
#include "hints.hxx"

#ifndef _FMTORNT_HXX //autogen
#include <fmtornt.hxx>
#endif
#ifndef _FMTFSIZE_HXX //autogen
#include <fmtfsize.hxx>
#endif
#include "txtfrm.hxx"       //fuer IsLocked()
#include "flyfrms.hxx"
// OD 2004-01-19 #110582#
#ifndef _DFLYOBJ_HXX
#include <dflyobj.hxx>
#endif

//aus FlyCnt.cxx
void DeepCalc( const SwFrm *pFrm );

/*************************************************************************
|*
|*  SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()
|*
|*  Ersterstellung      MA 01. Dec. 92
|*  Letzte Aenderung    MA 09. Apr. 99
|*
|*************************************************************************/
SwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :
    SwFlyFrm( pFmt, pAnch )
{
    bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;
    SwTwips nRel = pFmt->GetVertOrient().GetPos();
    // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
    Point aRelPos;
    if( pAnch && pAnch->IsVertical() )
        aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;
    else
        aRelPos.Y() = nRel;
    SetCurrRelPos( aRelPos );
}

SwFlyInCntFrm::~SwFlyInCntFrm()
{
    //und Tschuess.
    if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() )
    {
        SwRect aTmp( GetObjRectWithSpaces() );
        SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );
    }
}

// --> OD 2004-06-29 #i28701#
TYPEINIT1(SwFlyInCntFrm,SwFlyFrm);
// <--
/*************************************************************************
|*
|*  SwFlyInCntFrm::SetRefPoint(),
|*
|*  Ersterstellung      MA 01. Dec. 92
|*  Letzte Aenderung    MA 06. Aug. 95
|*
|*************************************************************************/
void SwFlyInCntFrm::SetRefPoint( const Point& rPoint,
                                 const Point& rRelAttr,
                                 const Point& rRelPos )
{
    // OD 2004-05-27 #i26791# - member <aRelPos> moved to <SwAnchoredObject>
    ASSERT( rPoint != aRef || rRelAttr != GetCurrRelPos(), "SetRefPoint: no change" );
    SwFlyNotify *pNotify = NULL;
    // No notify at a locked fly frame, if a fly frame is locked, there's
    // already a SwFlyNotify object on the stack (MakeAll).
    if( !IsLocked() )
        pNotify = new SwFlyNotify( this );
    aRef = rPoint;
    SetCurrRelPos( rRelAttr );
    SWRECTFN( GetAnchorFrm() )
    (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );
    // --> OD 2006-08-25 #i68520#
    InvalidateObjRectWithSpaces();
    // <--
    if( pNotify )
    {
        InvalidatePage();
        bValidPos = FALSE;
        bInvalid  = TRUE;
        Calc();
        delete pNotify;
    }
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::Modify()
|*
|*  Ersterstellung      MA 16. Dec. 92
|*  Letzte Aenderung    MA 02. Sep. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )
{
    BOOL bCallPrepare = FALSE;
    USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;
    if( RES_ATTRSET_CHG == nWhich )
    {
        if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
            GetItemState( RES_SURROUND, FALSE ) ||
            SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->
            GetItemState( RES_FRMMACRO, FALSE ) )
        {
            SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );
            SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );

            aOld.ClearItem( RES_SURROUND );
            aNew.ClearItem( RES_SURROUND );
            aOld.ClearItem( RES_FRMMACRO );
            aNew.ClearItem( RES_FRMMACRO );
            if( aNew.Count() )
            {
                SwFlyFrm::Modify( &aOld, &aNew );
                bCallPrepare = TRUE;
            }
        }
        else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())
        {
            SwFlyFrm::Modify( pOld, pNew );
            bCallPrepare = TRUE;
        }
    }
    else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )
    {
        SwFlyFrm::Modify( pOld, pNew );
        bCallPrepare = TRUE;
    }

    if ( bCallPrepare && GetAnchorFrm() )
        AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );
}
/*************************************************************************
|*
|*  SwFlyInCntFrm::Format()
|*
|*  Beschreibung:       Hier wird der Inhalt initial mit Formatiert.
|*  Ersterstellung      MA 16. Dec. 92
|*  Letzte Aenderung    MA 19. May. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )
{
    if ( !Frm().Height() )
    {
        Lock(); //nicht hintenherum den Anker formatieren.
        SwCntntFrm *pCntnt = ContainsCntnt();
        while ( pCntnt )
        {   pCntnt->Calc();
            pCntnt = pCntnt->GetNextCntntFrm();
        }
        Unlock();
    }
    SwFlyFrm::Format( pAttrs );
}
/*************************************************************************
|*
|*  SwFlyInCntFrm::MakeFlyPos()
|*
|*  Beschreibung        Im Unterschied zu anderen Frms wird hier nur die
|*      die RelPos berechnet. Die absolute Position wird ausschliesslich
|*      per SetAbsPos errechnet.
|*  Ersterstellung      MA 03. Dec. 92
|*  Letzte Aenderung    MA 12. Apr. 96
|*
|*************************************************************************/
// OD 2004-03-23 #i26791#
//void SwFlyInCntFrm::MakeFlyPos()
void SwFlyInCntFrm::MakeObjPos()
{
    if ( !bValidPos )
    {
        // --> OD 2004-08-12 #i32795# - calling methods <::DeepCalc(..)> and
        // <GetAnchorFrm()->GetFormatted()> no longer needed due to the changed
        // formatting of floating screen objects. It also causes layout loops.
//        if ( !GetAnchorFrm()->IsTxtFrm() || !((SwTxtFrm*)GetAnchorFrm())->IsLocked() )
//            ::DeepCalc( GetAnchorFrm() );
//        if( GetAnchorFrm()->IsTxtFrm() )
//            ((SwTxtFrm*)GetAnchorFrm())->GetFormatted();
        // <--
        bValidPos = TRUE;
        SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();
        const SwFmtVertOrient &rVert = pFmt->GetVertOrient();
        //Und ggf. noch die aktuellen Werte im Format updaten, dabei darf
        //zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.
        SWRECTFN( GetAnchorFrm() )
        SwTwips nOld = rVert.GetPos();
        SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y();
        if( bRev )
            nAct = -nAct;
        if( nAct != nOld )
        {
            SwFmtVertOrient aVert( rVert );
            aVert.SetPos( nAct );
            pFmt->LockModify();
            pFmt->SetAttr( aVert );
            pFmt->UnlockModify();
        }
    }
}

// --> OD 2004-12-02 #115759#
void SwFlyInCntFrm::_ActionOnInvalidation( const InvalidationType _nInvalid )
{
    switch ( _nInvalid )
    {
        case INVALID_POS:
        case INVALID_ALL:
        {
            AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, &GetFrmFmt() );
        }
        break;
    }
}
// <--
/*************************************************************************
|*
|*  SwFlyInCntFrm::NotifyBackground()
|*
|*  Ersterstellung      MA 03. Dec. 92
|*  Letzte Aenderung    MA 26. Aug. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,
                                       PrepareHint eHint)
{
    if ( eHint == PREP_FLY_ATTR_CHG )
        AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG );
    else
        AnchorFrm()->Prepare( eHint, (void*)&rRect );
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::GetRelPos()
|*
|*  Ersterstellung      MA 04. Dec. 92
|*  Letzte Aenderung    MA 04. Dec. 92
|*
|*************************************************************************/
const Point SwFlyInCntFrm::GetRelPos() const
{
    Calc();
    return GetCurrRelPos();
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::RegistFlys()
|*
|*  Ersterstellung      MA 26. Nov. 93
|*  Letzte Aenderung    MA 26. Nov. 93
|*
|*************************************************************************/
void SwFlyInCntFrm::RegistFlys()
{
    // vgl. SwRowFrm::RegistFlys()
    SwPageFrm *pPage = FindPageFrm();
    ASSERT( pPage, "Flys ohne Seite anmelden?" );
    ::RegistFlys( pPage, this );
}

/*************************************************************************
|*
|*  SwFlyInCntFrm::MakeAll()
|*
|*  Ersterstellung      MA 18. Feb. 94
|*  Letzte Aenderung    MA 13. Jun. 96
|*
|*************************************************************************/
void SwFlyInCntFrm::MakeAll()
{
    // OD 2004-01-19 #110582#
    if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )
    {
        return;
    }

    if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() )
        return;

    Lock(); //Der Vorhang faellt

        //uebernimmt im DTor die Benachrichtigung
    const SwFlyNotify aNotify( this );
    SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );
    const SwBorderAttrs &rAttrs = *aAccess.Get();

    if ( IsClipped() )
        bValidSize = bHeightClipped = bWidthClipped = FALSE;

    while ( !bValidPos || !bValidSize || !bValidPrtArea )
    {
        //Nur einstellen wenn das Flag gesetzt ist!!
        if ( !bValidSize )
        {
            bValidPrtArea = FALSE;
/*
            // This is also done in the Format function, so I think
            // this code is not necessary anymore:
            long nOldWidth = aFrm.Width();
            const Size aRelSize( CalcRel( rFrmSz ) );
            aFrm.Width( aRelSize.Width() );

            if ( aFrm.Width() > nOldWidth )
                //Damit sich der Inhalt anpasst
                aFrm.Height( aRelSize.Height() );
*/
        }

        if ( !bValidPrtArea )
            MakePrtArea( rAttrs );

        if ( !bValidSize )
            Format( &rAttrs );

        if ( !bValidPos )
        {
            // OD 2004-03-23 #i26791#
            //MakeFlyPos();
            MakeObjPos();
        }

        // --> OD 2006-04-13 #b6402800#
        // re-activate clipping of as-character anchored Writer fly frames
        // depending on compatibility option <ClipAsCharacterAnchoredWriterFlyFrames>
        if ( bValidPos && bValidSize &&
             GetFmt()->getIDocumentSettingAccess()->get( IDocumentSettingAccess::CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME ) )
        {
            SwFrm* pFrm = AnchorFrm();
            if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&
                 Frm().Width() > pFrm->Prt().Width() )
            {
                Frm().Width( pFrm->Prt().Width() );
                bValidPrtArea = FALSE;
                bWidthClipped = TRUE;
            }
        }
        // <--
    }
    Unlock();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbVectorDataFileReader.h"
#include "otbImageFileWriter.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include <fstream>
#include <iostream>

#include "itkRGBAPixel.h"
#include "otbImage.h"
#include "otbVectorDataToMapFilter.h"

int otbVectorDataToMapFilterWorld(int argc, char * argv [])
{

  if (argc < 11)
    {
    std::cout << argv[0] << " <input vector filename> <input image filename>"
              << " <output vector filename> "
              << " <sizeX> <sizeY> "
              << " <origin lon> <origin lat> "
              << " <spacing lon> <spacing lat> "
              << " <font filename>"
              << std::endl;
    return EXIT_FAILURE;
    }

  //Read the vector data
  typedef otb::VectorData<>                         VectorDataType;
  typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;

  //Reproject the vector data in the proper projection
  typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;

  VectorDataFileReaderType::Pointer reader0 = VectorDataFileReaderType::New();
  reader0->SetFileName(argv[1]);
  ProjectionFilterType::Pointer projection0 = ProjectionFilterType::New();
  projection0->SetInput(reader0->GetOutput());

  VectorDataFileReaderType::Pointer reader1 = VectorDataFileReaderType::New();
  reader1->SetFileName(argv[2]);
  ProjectionFilterType::Pointer projection1 = ProjectionFilterType::New();
  projection1->SetInput(reader1->GetOutput());

  //Convert the vector data into an image
  typedef itk::RGBAPixel<unsigned char> PixelType;
  typedef otb::Image<PixelType, 2>      ImageType;

  ImageType::SizeType size;
  size[0] = atoi(argv[4]);
  size[1] = atoi(argv[5]);

  ImageType::PointType origin;
  origin[0] = atof(argv[6]);
  origin[1] = atof(argv[7]);

  ImageType::SpacingType spacing;
  spacing[0] = atof(argv[8]);
  spacing[1] = atof(argv[9]);

  typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
  VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
  vectorDataRendering->SetInput(0, projection0->GetOutput());
  vectorDataRendering->SetInput(1, projection1->GetOutput());

  vectorDataRendering->SetSize(size);
  vectorDataRendering->SetOrigin(origin);
  vectorDataRendering->SetSpacing(spacing);
  vectorDataRendering->SetFontFileName(argv[10]);
  vectorDataRendering->AddStyle("world");
  vectorDataRendering->AddStyle("city");
  vectorDataRendering->UseAsOverlayOff();

  //Save the image in a file
  typedef otb::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(vectorDataRendering->GetOutput());
  writer->SetFileName(argv[3]);
  writer->Update();

  return EXIT_SUCCESS;
}
<commit_msg>TEST: explicit definition of the output projRef<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbVectorDataFileReader.h"
#include "otbImageFileWriter.h"
#include "otbVectorData.h"
#include "otbVectorDataProjectionFilter.h"
#include <fstream>
#include <iostream>

#include "itkRGBAPixel.h"
#include "otbImage.h"
#include "otbVectorDataToMapFilter.h"

int otbVectorDataToMapFilterWorld(int argc, char * argv [])
{

  if (argc < 11)
    {
    std::cout << argv[0] << " <input vector filename> <input image filename>"
              << " <output vector filename> "
              << " <sizeX> <sizeY> "
              << " <origin lon> <origin lat> "
              << " <spacing lon> <spacing lat> "
              << " <font filename>"
              << std::endl;
    return EXIT_FAILURE;
    }

  //Read the vector data
  typedef otb::VectorData<>                         VectorDataType;
  typedef otb::VectorDataFileReader<VectorDataType> VectorDataFileReaderType;

  //Reproject the vector data in the proper projection
  typedef otb::VectorDataProjectionFilter<VectorDataType, VectorDataType> ProjectionFilterType;

  std::string outputProjRef("GEOGCS[\"GCS_WGS_1984\", DATUM[\"D_WGS_1984\", "
    "SPHEROID[\"WGS_1984\", 6378137, 298.257223563]], PRIMEM[\"Greenwich\", 0],"
    " UNIT[\"Degree\", 0.017453292519943295]]");

  VectorDataFileReaderType::Pointer reader0 = VectorDataFileReaderType::New();
  reader0->SetFileName(argv[1]);
  ProjectionFilterType::Pointer projection0 = ProjectionFilterType::New();
  projection0->SetInput(reader0->GetOutput());
  projection0->SetOutputProjectionRef(outputProjRef);

  VectorDataFileReaderType::Pointer reader1 = VectorDataFileReaderType::New();
  reader1->SetFileName(argv[2]);
  ProjectionFilterType::Pointer projection1 = ProjectionFilterType::New();
  projection1->SetInput(reader1->GetOutput());
  projection1->SetOutputProjectionRef(outputProjRef);

  //Convert the vector data into an image
  typedef itk::RGBAPixel<unsigned char> PixelType;
  typedef otb::Image<PixelType, 2>      ImageType;

  ImageType::SizeType size;
  size[0] = atoi(argv[4]);
  size[1] = atoi(argv[5]);

  ImageType::PointType origin;
  origin[0] = atof(argv[6]);
  origin[1] = atof(argv[7]);

  ImageType::SpacingType spacing;
  spacing[0] = atof(argv[8]);
  spacing[1] = atof(argv[9]);

  typedef otb::VectorDataToMapFilter<VectorDataType, ImageType> VectorDataToMapFilterType;
  VectorDataToMapFilterType::Pointer vectorDataRendering = VectorDataToMapFilterType::New();
  vectorDataRendering->SetInput(0, projection0->GetOutput());
  vectorDataRendering->SetInput(1, projection1->GetOutput());

  vectorDataRendering->SetSize(size);
  vectorDataRendering->SetOrigin(origin);
  vectorDataRendering->SetSpacing(spacing);
  vectorDataRendering->SetFontFileName(argv[10]);
  vectorDataRendering->AddStyle("world");
  vectorDataRendering->AddStyle("city");
  vectorDataRendering->UseAsOverlayOff();

  //Save the image in a file
  typedef otb::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(vectorDataRendering->GetOutput());
  writer->SetFileName(argv[3]);
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.

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

//==============================================================================
// SampleView plugin
//==============================================================================

#include "sampleviewplugin.h"

//==============================================================================

#include <QIcon>

//==============================================================================

namespace OpenCOR {
namespace SampleView {

//==============================================================================

PLUGININFO_FUNC SampleViewPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("a plugin that provides a test view."));
    descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une vue de test."));

    return new PluginInfo(PluginInfo::Sample, true, false,
                          QStringList() << "Core" << "Sample",
                          descriptions);
}

//==============================================================================
// File handling interface
//==============================================================================

bool SampleViewPlugin::saveFile(const QString &pOldFileName,
                                const QString &pNewFileName)
{
    Q_UNUSED(pOldFileName);
    Q_UNUSED(pNewFileName);

    // We don't handle this interface...

    return false;
}

//==============================================================================

void SampleViewPlugin::fileOpened(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::filePermissionsChanged(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileModified(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileReloaded(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileRenamed(const QString &pOldFileName,
                                   const QString &pNewFileName)
{
    Q_UNUSED(pOldFileName);
    Q_UNUSED(pNewFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileClosed(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================
// I18n interface
//==============================================================================

void SampleViewPlugin::retranslateUi()
{
    // We don't handle this interface...
}

//==============================================================================
// Plugin interface
//==============================================================================

void SampleViewPlugin::initializePlugin(QMainWindow *pMainWindow)
{
    Q_UNUSED(pMainWindow);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::finalizePlugin()
{
    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::pluginInitialized(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::loadSettings(QSettings *pSettings)
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::saveSettings(QSettings *pSettings) const
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::handleAction(const QUrl &pUrl)
{
    Q_UNUSED(pUrl);

    // We don't handle this interface...
}

//==============================================================================
// View interface
//==============================================================================

ViewInterface::Mode SampleViewPlugin::viewMode() const
{
    // Return our mode

    return ViewInterface::Sample;
}

//==============================================================================

QStringList SampleViewPlugin::viewMimeTypes() const
{
    // Return the MIME types we support
    // Note: we allow any kind of file, hence our empty string list...

    return QStringList();
}

//==============================================================================

void SampleViewPlugin::initializeView()
{
    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::finalizeView()
{
    // We don't handle this interface...
}

//==============================================================================

QWidget * SampleViewPlugin::viewWidget(const QString &pFileName,
                                       const bool &pCreate)
{
    // We don't handle this interface...

    return 0;
}

//==============================================================================

void SampleViewPlugin::removeViewWidget(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

QString SampleViewPlugin::viewName() const
{
    // Return our raw view's name

    return tr("Sample");
}

//==============================================================================

QIcon SampleViewPlugin::fileTabIcon(const QString &pFileName) const
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...

    return QIcon();
}

//==============================================================================

}   // namespace SampleView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you 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.

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

//==============================================================================
// SampleView plugin
//==============================================================================

#include "sampleviewplugin.h"

//==============================================================================

#include <QIcon>

//==============================================================================

namespace OpenCOR {
namespace SampleView {

//==============================================================================

PLUGININFO_FUNC SampleViewPluginInfo()
{
    Descriptions descriptions;

    descriptions.insert("en", QString::fromUtf8("a plugin that provides a test view."));
    descriptions.insert("fr", QString::fromUtf8("une extension qui fournit une vue de test."));

    return new PluginInfo(PluginInfo::Sample, true, false,
                          QStringList() << "Core" << "Sample",
                          descriptions);
}

//==============================================================================
// File handling interface
//==============================================================================

bool SampleViewPlugin::saveFile(const QString &pOldFileName,
                                const QString &pNewFileName)
{
    Q_UNUSED(pOldFileName);
    Q_UNUSED(pNewFileName);

    // We don't handle this interface...

    return false;
}

//==============================================================================

void SampleViewPlugin::fileOpened(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::filePermissionsChanged(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileModified(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileReloaded(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileRenamed(const QString &pOldFileName,
                                   const QString &pNewFileName)
{
    Q_UNUSED(pOldFileName);
    Q_UNUSED(pNewFileName);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::fileClosed(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================
// I18n interface
//==============================================================================

void SampleViewPlugin::retranslateUi()
{
    // We don't handle this interface...
}

//==============================================================================
// Plugin interface
//==============================================================================

void SampleViewPlugin::initializePlugin(QMainWindow *pMainWindow)
{
    Q_UNUSED(pMainWindow);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::finalizePlugin()
{
    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::pluginInitialized(const Plugins &pLoadedPlugins)
{
    Q_UNUSED(pLoadedPlugins);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::loadSettings(QSettings *pSettings)
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::saveSettings(QSettings *pSettings) const
{
    Q_UNUSED(pSettings);

    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::handleAction(const QUrl &pUrl)
{
    Q_UNUSED(pUrl);

    // We don't handle this interface...
}

//==============================================================================
// View interface
//==============================================================================

ViewInterface::Mode SampleViewPlugin::viewMode() const
{
    // Return our mode

    return ViewInterface::Sample;
}

//==============================================================================

QStringList SampleViewPlugin::viewMimeTypes() const
{
    // Return the MIME types we support
    // Note: we allow any kind of file, hence our empty string list...

    return QStringList();
}

//==============================================================================

void SampleViewPlugin::initializeView()
{
    // We don't handle this interface...
}

//==============================================================================

void SampleViewPlugin::finalizeView()
{
    // We don't handle this interface...
}

//==============================================================================

QWidget * SampleViewPlugin::viewWidget(const QString &pFileName,
                                       const bool &pCreate)
{
    Q_UNUSED(pFileName);
    Q_UNUSED(pCreate);

    // We don't handle this interface...

    return 0;
}

//==============================================================================

void SampleViewPlugin::removeViewWidget(const QString &pFileName)
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...
}

//==============================================================================

QString SampleViewPlugin::viewName() const
{
    // Return our raw view's name

    return tr("Sample");
}

//==============================================================================

QIcon SampleViewPlugin::fileTabIcon(const QString &pFileName) const
{
    Q_UNUSED(pFileName);

    // We don't handle this interface...

    return QIcon();
}

//==============================================================================

}   // namespace SampleView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before><commit_msg>re-enable histo clearing<commit_after><|endoftext|>


<commit_before>// Conway's Game of Life
//
// Wikipedia
//      https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
// It From Bit: Is The Universe A Cellular Automaton?
//      https://medium.com/starts-with-a-bang/it-from-bit-is-the-universe-a-cellular-automaton-4a5b1426ba6d
//
// build & run
//  cmake -A x64 .. && cmake --build . --config Release && Release\gameoflife.exe

#include "config.h"
#include "olcPixelGameEngine.h"
#include <chrono>
#include <thread>
#include <fstream>
#include <algorithm>

std::vector<std::string> glider = {
    "  o",
    "o o",
    " oo"
};

std::vector<std::string> lwss = { // lightweight spaceship
    " oooo",
    "o   o",
    "    o",
    "o  o"
};

std::vector<std::string> mwss = { // middleweight spaceship
    " ooo",
    "ooooo",
    "ooo oo",
    "   oo"
};

std::vector<std::string> pulsar = { // middleweight spaceship
    "                 ",
    "     o     o     ",
    "     o     o     ",
    "     oo   oo     ",
    "                 ",
    " ooo  oo oo  ooo ",
    "   o o o o o o   ",
    "     oo   oo     ",
    "                 ",
    "     oo   oo     ",
    "   o o o o o o   ",
    " ooo  oo oo  ooo ",
    "                 ",
    "     oo   oo     ",
    "     o     o     ",
    "     o     o     ",
    "                 ",
};

std::vector<std::string> glider_gun = {
    "                                      ",
    "                         o            ",
    "                       o o            ",
    "             oo      oo            oo ",
    "            o   o    oo            oo ",
    " oo        o     o   oo               ",
    " oo        o   o oo    o o            ",
    "           o     o       o            ",
    "            o   o                     ",
    "             oo                       ",
    "                                      ",
};

class GameOfLife : public olc::PixelGameEngine
{
    std::vector<bool> worldA;       ///< state A of the world
    std::vector<bool> worldB;       ///< state B of the world
    std::vector<bool> *world0;      ///< pointer to the old state
    std::vector<bool> *world1;      ///< pointer to the new state

    float timesum = 0.0;            ///< internal variable which stores the accumulted time between 2 updates
    int fps = 5;                    ///< update frequency

    int ox = 20;                ///< x origin of the world
    int oy = 20;                ///< y origin of the world
    int width;             ///< horizontal dimension of the world
    int height;           ///< vertical dimension of the world
    int scale = 3;

    std::vector<std::vector<std::string> > objects;
    int object = 0;

public:
    GameOfLife()
    {
        sAppName = "Game of life";
        objects.push_back(glider);
        objects.push_back(lwss);
        objects.push_back(mwss);
        objects.push_back(pulsar);
        objects.push_back(glider_gun);
        auto object = load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF");

        objects.push_back(object);
    }

public:

    std::vector<std::string> tokenize(std::string const &line)
    {
        std::vector<std::string> tokens;
        std::string token;
        std::stringstream iss(line);
        while (std::getline(iss, token,' '))
            tokens.push_back(token);

        // for(auto &t : tokens)
        //     std::cout << "token: " << t << '\n';
        return tokens;
    }

    std::vector<std::string> load_lif(std::string const &filename)
    {
        std::cout << "loading " << filename << '\n';

        std::ifstream infile(filename);
        if (! infile.is_open())
        {
            std::cerr << "ERROR: "<< filename << " file not found!\n";
            return std::vector<std::string>();
        }

        std::vector<std::string> object;
        int ox = 0;
        int oy = 0;

        std::string line;
        while (std::getline(infile, line))
        {
            // std::cout << "next line...\n";
            if (line[0]=='#')
            {
                auto tokens = tokenize(line);
                if(tokens[0]=="#Life")
                {
                    // std::cout << "file version: " << tokens[1] << '\n';
                }
                else if(tokens[0]=="#P")
                {
                    ox = std::stoi(tokens[1]);
                    oy = std::stoi(tokens[2]);
                    // std::cout << "ox=" << ox << "; ";
                    // std::cout << "oy=" << oy << '\n';
                }
            }
            else
            {
                std::replace( line.begin(), line.end(), '*', 'o');
                std::replace( line.begin(), line.end(), '.', ' ');
                object.push_back(line);
            }
        }
        return object;
    }

    /// convert indices i,j to a 1D array index
    int idx(int i, int j) const
    {
        return i*width+j;
    }

    void set_random(std::vector<bool> &world)
    {
        // random array
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
                world[idx(i,j)] = !static_cast<bool> (rand() % 5);
    }

    void set_empty(std::vector<bool> &world)
    {
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
                world[idx(i,j)] = false;
    }

    bool OnUserCreate() override
    {
        // compute size of the world from margins and scale
        width = (this->ScreenWidth()-2*ox)/scale;
        height = (this->ScreenHeight()-2*oy)/scale;

        // allocate world arrays
        worldA.resize(width*height);
        worldB.resize(width*height);

        set_random(worldA);

        world0 = &worldA;
        world1 = &worldB;

        return true;
    }

    void calculate_new_world()
    {
        // calculate the new world as a function of the old one

        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
            {
                // count neighbours
                int neigh = - static_cast<int>( (*world0)[idx(i,j)] );
                for(int ii=-1; ii<=1; ii++)
                    for(int jj=-1; jj<=1; jj++)
                        if (i+ii>0 && i+ii<height &&
                            j+jj>0 && jj+jj<width )
                            neigh += static_cast<int>( (*world0)[idx(i+ii,j+jj)] );

                if(neigh<2) // underpopulation
                    (*world1)[idx(i,j)] = false;
                else if(neigh>3) // overpopulation
                    (*world1)[idx(i,j)] = false;
                else if(neigh==3) // reproduction
                    (*world1)[idx(i,j)] = true;
                else
                    (*world1)[idx(i,j)] = (*world0)[idx(i,j)];
            }
    }

    void draw_world()
    {
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
            {
                int colour = 0;
                if ((*world0)[idx(i,j)])
                    colour = 255;
                FillRect (ox+(j*scale), oy+(i*scale),
                            scale, scale,
                            olc::Pixel(colour, colour, colour));
            }
    }

    bool OnUserUpdate(float fElapsedTime) override
    {
        // Erase previous frame
        Clear(olc::BLACK);

        if (GetKey(olc::Key::C).bHeld)
            set_empty(*world0);
        if (GetKey(olc::Key::R).bHeld)
            set_random(*world0);
        if (GetKey(olc::Key::LEFT).bPressed || GetMouseWheel() > 0)
        {
            object+=1;
            if (object==objects.size()) object=0;
            std::cout << "setting object to " << object << std::endl;
        }
        if (GetKey(olc::Key::RIGHT).bPressed || GetMouseWheel() < 0)
        {
            object-=1;
            if (object<0) object=objects.size()-1;
            std::cout << "setting object to " << object << std::endl;
        }

        if (GetKey(olc::Key::UP).bPressed)
        {
            fps*=2;
            if (fps>120) fps=120;
            std::cout << "setting fps to " << fps << std::endl;
        }
        if (GetKey(olc::Key::DOWN).bPressed)
        {
            fps/=2;
            if (fps<1) fps=1;
            std::cout << "setting fps to " << fps << std::endl;
        }

        // get mouse pos
        olc::vi2d mpos = {(GetMouseX() - ox)/scale,
                          (GetMouseY() - oy)/scale};

        // accumulate time
        timesum = timesum + fElapsedTime;
        float frametime = 1.0/fps;

        // check that it whether it is time to create a new generation
        if (timesum>frametime)
        {
            while(timesum>frametime)
                timesum -= frametime;

            calculate_new_world();
            // swap world
            auto w = world0;
            world0 = world1;
            world1 = w;
        }

        draw_world();
        // draw borders
        DrawRect(ox-1, oy-1, scale*width+1, scale*height+1, olc::GREEN);

        // draw current object at mouse pos in red
        auto &curobj = objects[object];
        for(int i=0; i<curobj.size(); ++i)
            for(int j=0; j<curobj[i].size(); ++j)
            {
                if(curobj[i][j]!=' ')
                {
                    int posx = mpos.x+j;
                    int posy = mpos.y+i;
                    if (posx>=0 && posx<width && posy>=0 && posy<height)
                        FillRect (ox+(posx*scale), oy+(posy*scale),
                                    scale, scale,
                                    olc::RED);
                }
            }

        if (GetMouse(0).bPressed)
        {
            std::cout << "creating object\n";
            for(int i=0; i<curobj.size(); ++i)
                for(int j=0; j<curobj[i].size(); ++j)
                {
                    bool value = false;
                    if(curobj[i][j]!=' ')
                        value=true;

                    int posx = mpos.x+j;
                    int posy = mpos.y+i;
                    if (posx>=0 && posx<width && posy>=0 && posy<height)
                        (*world0)[idx(posy,posx)] = value;

                }

        }

        // draw title
        this->DrawString({5,5}, "Game of Life");

        return true;
    }
};

int
main()
{

    GameOfLife demo;
    //demo.load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF");

        if (demo.Construct(600, 300, 2, 2))
            demo.Start();

    return 0;
}
<commit_msg>add doc<commit_after>// Conway's Game of Life
//      using "Pixel Game Engine" from Javidx9
//      https://community.onelonecoder.com/
//
//
// Wikipedia
//      https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
// It From Bit: Is The Universe A Cellular Automaton?
//      https://medium.com/starts-with-a-bang/it-from-bit-is-the-universe-a-cellular-automaton-4a5b1426ba6d
// Cellular Automata FAQ
//      http://cafaq.com/lifefaq/index.php
// best 152 patterns from the first quarter-century of Conway's Game of Life (Alan W. Hensel)
//      http://www.ibiblio.org/lifepatterns/lifep.zip
//
// build & run
//  cmake -A x64 .. && cmake --build . --config Release && Release\gameoflife.exe

#include "config.h"
#include "olcPixelGameEngine.h"
#include <chrono>
#include <thread>
#include <fstream>
#include <algorithm>

std::vector<std::string> glider = {
    "  o",
    "o o",
    " oo"
};

std::vector<std::string> lwss = { // lightweight spaceship
    " oooo",
    "o   o",
    "    o",
    "o  o"
};

std::vector<std::string> mwss = { // middleweight spaceship
    " ooo",
    "ooooo",
    "ooo oo",
    "   oo"
};

std::vector<std::string> pulsar = { // middleweight spaceship
    "                 ",
    "     o     o     ",
    "     o     o     ",
    "     oo   oo     ",
    "                 ",
    " ooo  oo oo  ooo ",
    "   o o o o o o   ",
    "     oo   oo     ",
    "                 ",
    "     oo   oo     ",
    "   o o o o o o   ",
    " ooo  oo oo  ooo ",
    "                 ",
    "     oo   oo     ",
    "     o     o     ",
    "     o     o     ",
    "                 ",
};

std::vector<std::string> glider_gun = {
    "                                      ",
    "                         o            ",
    "                       o o            ",
    "             oo      oo            oo ",
    "            o   o    oo            oo ",
    " oo        o     o   oo               ",
    " oo        o   o oo    o o            ",
    "           o     o       o            ",
    "            o   o                     ",
    "             oo                       ",
    "                                      ",
};

class GameOfLife : public olc::PixelGameEngine
{
    std::vector<bool> worldA;       ///< state A of the world
    std::vector<bool> worldB;       ///< state B of the world
    std::vector<bool> *world0;      ///< pointer to the old state
    std::vector<bool> *world1;      ///< pointer to the new state

    float timesum = 0.0;            ///< internal variable which stores the accumulted time between 2 updates
    int fps = 5;                    ///< update frequency

    int ox = 20;                ///< x origin of the world
    int oy = 20;                ///< y origin of the world
    int width;                  ///< horizontal dimension of the world
    int height;                 ///< vertical dimension of the world
    int scale = 3;

    std::vector<std::vector<std::string> > objects;     ///< array storing interesting objects
    int object = 0;             ///< current object

public:
    GameOfLife()
    {
        sAppName = "Game of life";
        // fill "objects" with interesting patterns
        objects.push_back(glider);
        objects.push_back(lwss);
        objects.push_back(mwss);
        objects.push_back(pulsar);
        objects.push_back(glider_gun);
        objects.push_back(load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF"));
    }

private:
    /// split a line of text into an array of tokens (words)
    ///     "a few words" => {"a", "few", "words"}
    std::vector<std::string> tokenize(std::string const &line)
    {
        std::vector<std::string> tokens;
        std::string token;
        std::stringstream iss(line);
        while (std::getline(iss, token,' '))
            tokens.push_back(token);

        // for(auto &t : tokens)
        //     std::cout << "token: " << t << '\n';
        return tokens;
    }

    /// load a .LIF file from Alan W. Hensel's library
    ///     see
    std::vector<std::string> load_lif(std::string const &filename)
    {
        std::cout << "loading " << filename << '\n';

        std::ifstream infile(filename);
        if (! infile.is_open())
        {
            std::cerr << "ERROR: "<< filename << " file not found!\n";
            return std::vector<std::string>();
        }

        std::vector<std::string> object;
        int ox = 0;
        int oy = 0;

        std::string line;
        while (std::getline(infile, line))
        {
            // std::cout << "next line...\n";
            if (line[0]=='#')
            {
                auto tokens = tokenize(line);
                if(tokens[0]=="#Life")
                {
                    // TODO: check version
                    // std::cout << "file version: " << tokens[1] << '\n';
                }
                else if(tokens[0]=="#P")
                {
                    ox = std::stoi(tokens[1]);
                    oy = std::stoi(tokens[2]);
                    // std::cout << "ox=" << ox << "; ";
                    // std::cout << "oy=" << oy << '\n';
                }
            }
            else
            {
                std::replace( line.begin(), line.end(), '*', 'o');
                std::replace( line.begin(), line.end(), '.', ' ');
                object.push_back(line);
            }
        }
        return object;
    }

    /// convert i, j indices to a 1D array index
    int idx(int i, int j) const
    {
        return i*width+j;
    }

    /// fill the world with a random set of dots
    void set_random(std::vector<bool> &world)
    {
        // random array
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
                world[idx(i,j)] = !static_cast<bool> (rand() % 5);
    }

    /// clear the world
    void set_empty(std::vector<bool> &world)
    {
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
                world[idx(i,j)] = false;
    }

    /// PGE function called when aplication starts
    bool OnUserCreate() override
    {
        // compute size of the world from margins and scale
        width = (this->ScreenWidth()-2*ox)/scale;
        height = (this->ScreenHeight()-2*oy)/scale;

        // allocate world arrays
        worldA.resize(width*height);
        worldB.resize(width*height);

        set_random(worldA);

        world0 = &worldA;
        world1 = &worldB;

        return true;
    }

    /// calculate the new world as a function of the old one
    ///     apply the rules of the game of life
    void calculate_new_world()
    {
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
            {
                // count neighbours
                int neigh = - static_cast<int>( (*world0)[idx(i,j)] );
                for(int ii=-1; ii<=1; ii++)
                    for(int jj=-1; jj<=1; jj++)
                        if (i+ii>0 && i+ii<height &&
                            j+jj>0 && jj+jj<width )
                            neigh += static_cast<int>( (*world0)[idx(i+ii,j+jj)] );

                if(neigh<2) // underpopulation
                    (*world1)[idx(i,j)] = false;
                else if(neigh>3) // overpopulation
                    (*world1)[idx(i,j)] = false;
                else if(neigh==3) // reproduction
                    (*world1)[idx(i,j)] = true;
                else
                    (*world1)[idx(i,j)] = (*world0)[idx(i,j)];
            }
    }

    /// draw the current state of the world onto the screen
    void draw_world()
    {
        for (int i = 0; i < height; i++)
            for (int j = 0; j < width; j++)
            {
                int colour = 0;     // black
                if ((*world0)[idx(i,j)])
                    colour = 255;   // white
                FillRect (ox+(j*scale), oy+(i*scale),
                            scale, scale,
                            olc::Pixel(colour, colour, colour));
            }
    }

    /// PGE function called at every new frame
    bool OnUserUpdate(float fElapsedTime) override
    {
        // Erase previous frame
        Clear(olc::BLACK);

        // User interaction management

        if (GetKey(olc::Key::C).bHeld)
            set_empty(*world0);

        if (GetKey(olc::Key::R).bHeld)
            set_random(*world0);

        if (GetKey(olc::Key::LEFT).bPressed || GetMouseWheel() > 0)
        {
            object+=1;
            if (object==objects.size()) object=0;
            std::cout << "setting object to " << object << std::endl;
        }
        if (GetKey(olc::Key::RIGHT).bPressed || GetMouseWheel() < 0)
        {
            object-=1;
            if (object<0) object=objects.size()-1;
            std::cout << "setting object to " << object << std::endl;
        }

        if (GetKey(olc::Key::UP).bPressed)
        {
            fps*=2;
            if (fps>120) fps=120;
            std::cout << "setting fps to " << fps << std::endl;
        }
        if (GetKey(olc::Key::DOWN).bPressed)
        {
            fps/=2;
            if (fps<1) fps=1;
            std::cout << "setting fps to " << fps << std::endl;
        }

        // get mouse pos
        olc::vi2d mpos = {(GetMouseX() - ox)/scale,
                          (GetMouseY() - oy)/scale};

        // accumulate time
        timesum = timesum + fElapsedTime;
        float frametime = 1.0/fps;

        // check that it whether it is time to create a new generation
        if (timesum>frametime)
        {
            while(timesum>frametime)
                timesum -= frametime;

            calculate_new_world();
            // swap world
            auto w = world0;
            world0 = world1;
            world1 = w;
        }

        draw_world();
        // draw borders
        DrawRect(ox-1, oy-1, scale*width+1, scale*height+1, olc::GREEN);

        // draw current object at mouse pos in red
        auto &curobj = objects[object];
        for(int i=0; i<curobj.size(); ++i)
            for(int j=0; j<curobj[i].size(); ++j)
            {
                if(curobj[i][j]!=' ')
                {
                    int posx = mpos.x+j;
                    int posy = mpos.y+i;
                    if (posx>=0 && posx<width && posy>=0 && posy<height)
                        FillRect (ox+(posx*scale), oy+(posy*scale),
                                    scale, scale,
                                    olc::RED);
                }
            }

        if (GetMouse(0).bPressed)
        {
            std::cout << "creating object\n";
            for(int i=0; i<curobj.size(); ++i)
                for(int j=0; j<curobj[i].size(); ++j)
                {
                    bool value = false;
                    if(curobj[i][j]!=' ')
                        value=true;

                    int posx = mpos.x+j;
                    int posy = mpos.y+i;
                    if (posx>=0 && posx<width && posy>=0 && posy<height)
                        (*world0)[idx(posy,posx)] = value;

                }

        }

        // draw title
        this->DrawString({5,5}, "Game of Life");

        return true;
    }
};

int
main()
{

    GameOfLife demo;
    //demo.load_lif(std::string(CMAKE_SOURCE_DIR) + "/life/RABBITS.LIF");

        if (demo.Construct(600, 300, 2, 2))
            demo.Start();

    return 0;
}
<|endoftext|>


<commit_before>/*
    This file is part of libkcal.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

// $Id$

#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>

#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include "event.h"
#include "freebusy.h"
#include "icalformat.h"
#include "calendar.h"

#include "scheduler.h"

using namespace KCal;

ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status)
{
  mIncidence = incidence;
  mMethod = method;
  mStatus = status;
}

QString ScheduleMessage::statusName(ScheduleMessage::Status status)
{
  switch (status) {
    case PublishNew:
      return i18n("Publish");
    case Obsolete:
      return i18n("Obsolete");
    case RequestNew:
      return i18n("New Request");
    case RequestUpdate:
      return i18n("Updated Request");
    default:
      return i18n("Unknown Status: %1").arg(QString::number(status));
  }
}

Scheduler::Scheduler(Calendar *calendar)
{
  mCalendar = calendar;
  mFormat = mCalendar->iCalFormat();
}

Scheduler::~Scheduler()
{
}

bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status)
{
  kdDebug() << "Scheduler::acceptTransaction " << endl;
  switch (method) {
    case Publish:
      return acceptPublish(incidence, status, method);
    case Request:
      return acceptRequest(incidence, status);
    case Add:
      return acceptAdd(incidence, status);
    case Cancel:
      return acceptCancel(incidence, status);
    case Declinecounter:
      return acceptDeclineCounter(incidence, status);
    case Reply:
      return acceptReply(incidence, status, method);
    case Refresh:
      return acceptRefresh(incidence, status);
    case Counter:
      return acceptCounter(incidence, status);
    default:
      deleteTransaction(incidence);
      return false;
  }
  deleteTransaction(incidence);
  return false;
}

QString Scheduler::methodName(Method method)
{
  switch (method) {
    case Publish:
      return i18n("Publish");
    case Request:
      return i18n("Request");
    case Refresh:
      return i18n("Refresh");
    case Cancel:
      return i18n("Cancel");
    case Add:
      return i18n("Add");
    case Reply:
      return i18n("Reply");
    case Counter:
      return i18n("Counter");
    case Declinecounter:
      return i18n("Decline Counter");
    default:
      return i18n("Unknown");
  }
}

bool Scheduler::deleteTransaction(IncidenceBase *)
{
  return true;
}

bool Scheduler::acceptPublish(IncidenceBase *incidence,ScheduleMessage::Status status, Method method)
{
  if(incidence->type()=="FreeBusy") {
    return acceptFreeBusy(incidence, method);
  }
  switch (status) {
    case ScheduleMessage::PublishNew:
      if (!mCalendar->getEvent(incidence->uid())) {
	Incidence *inc = static_cast<Incidence *>(incidence);
        mCalendar->addIncidence(inc);
        deleteTransaction(incidence);
      }
      return true;
    case ScheduleMessage::Obsolete:
      return true;
    default:
      deleteTransaction(incidence);
      return false;
  }
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptRequest(IncidenceBase *incidence,ScheduleMessage::Status status)
{
    Incidence *inc = static_cast<Incidence *>(incidence);
    switch (status) {
    case ScheduleMessage::Obsolete:
      return true;
    case ScheduleMessage::RequestNew:
      mCalendar->addIncidence(inc);
      deleteTransaction(incidence);
      return true;
    case ScheduleMessage::RequestUpdate:
      Event *even;
      even = mCalendar->getEvent(incidence->uid());
      if (even) {
        mCalendar->deleteEvent(even);
      }
      mCalendar->addIncidence(inc);
      deleteTransaction(incidence);
      return true;
    default:
      return false;
    }
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  bool ret = false;
  //get event in calendar
  QPtrList<Event> eventList;
  eventList=mCalendar->getEvents(incidence->dtStart().date(),incidence->dtStart().date(),false);
  Event *ev;
  for ( ev = eventList.first(); ev; ev = eventList.next() ) {
    if (ev->uid()==incidence->uid()) {
      //get matching attendee in calendar
      kdDebug() << "Scheduler::acceptTransaction match found!" << endl;
      mCalendar->deleteEvent(ev);
      ret = true;
    }
  }
  deleteTransaction(incidence);
  return ret;
}

bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

//bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status)
//{
//  deleteTransaction(incidence);
//  return false;
//}

bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status status, Method method)
{
  if(incidence->type()=="FreeBusy") {
    return acceptFreeBusy(incidence, method);
  }
  bool ret = false;
  Event *ev = mCalendar->getEvent(incidence->uid());
  if (ev) {
    //get matching attendee in calendar
    kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl;
    QPtrList<Attendee> attendeesIn = incidence->attendees();
    QPtrList<Attendee> attendeesEv = ev->attendees();
    Attendee *attIn;
    Attendee *attEv;
    for ( attIn = attendeesIn.first(); attIn; attIn = attendeesIn.next() ) {
      for ( attEv = attendeesEv.first(); attEv; attEv = attendeesEv.next() ) {
        if (attIn->email()==attEv->email()) {
          //update attendee-info
          kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl;
          //attEv->setRole(attIn->role());
          attEv->setStatus(attIn->status());
          //attEv->setRSVP(attIn->RSVP());
          ev->setRevision(ev->revision()+1);
          ret = true;
        }
      }
    }
  }
  deleteTransaction(incidence);
  return ret;
}

bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  // handled in korganizer's IncomingDialog
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method)
{
  FreeBusy *freebusy = static_cast<FreeBusy *>(incidence);

  QString freeBusyDirName = locateLocal("appdata","freebusy");
  kdDebug() << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDirName << endl;

  QString from;
  if(method == Scheduler::Publish) {
    from = freebusy->organizer();
  }
  if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) {
    Attendee *attendee = freebusy->attendees().first();
    from = attendee->email();
  }

  QDir freeBusyDir(freeBusyDirName);
  if (!freeBusyDir.exists()) {
    kdDebug() << "Directory " << freeBusyDirName << " does not exist!" << endl;
    kdDebug() << "Creating directory: " << freeBusyDirName << endl;

    if(!freeBusyDir.mkdir(freeBusyDirName, TRUE)) {
      kdDebug() << "Could not create directory: " << freeBusyDirName << endl;
      return false;
    }
  }

  QString filename(freeBusyDirName);
  filename += "/";
  filename += from;
  filename += ".ifb";
  QFile f(filename);

  kdDebug() << "acceptFreeBusy: filename" << filename << endl;

  freebusy->clearAttendees();
  freebusy->setOrganizer(from);

  QString messageText = mFormat->createScheduleMessage(freebusy, Publish);

  if (!f.open(IO_ReadWrite)) {
   kdDebug() << "acceptFreeBusy: Can't open:" << filename << " for writing" << endl;
   return false;
  }
  QTextStream t(&f);
  t << messageText;
  f.close();

  deleteTransaction(incidence);
  return true;
}
<commit_msg>minor fix<commit_after>/*
    This file is part of libkcal.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

// $Id$

#include <qdir.h>
#include <qfile.h>
#include <qtextstream.h>

#include <klocale.h>
#include <kdebug.h>
#include <kstandarddirs.h>

#include "event.h"
#include "freebusy.h"
#include "icalformat.h"
#include "calendar.h"

#include "scheduler.h"

using namespace KCal;

ScheduleMessage::ScheduleMessage(IncidenceBase *incidence,int method,ScheduleMessage::Status status)
{
  mIncidence = incidence;
  mMethod = method;
  mStatus = status;
}

QString ScheduleMessage::statusName(ScheduleMessage::Status status)
{
  switch (status) {
    case PublishNew:
      return i18n("Publish");
    case Obsolete:
      return i18n("Obsolete");
    case RequestNew:
      return i18n("New Request");
    case RequestUpdate:
      return i18n("Updated Request");
    default:
      return i18n("Unknown Status: %1").arg(QString::number(status));
  }
}

Scheduler::Scheduler(Calendar *calendar)
{
  mCalendar = calendar;
  mFormat = mCalendar->iCalFormat();
}

Scheduler::~Scheduler()
{
}

bool Scheduler::acceptTransaction(IncidenceBase *incidence,Method method,ScheduleMessage::Status status)
{
  kdDebug() << "Scheduler::acceptTransaction " << endl;
  switch (method) {
    case Publish:
      return acceptPublish(incidence, status, method);
    case Request:
      return acceptRequest(incidence, status);
    case Add:
      return acceptAdd(incidence, status);
    case Cancel:
      return acceptCancel(incidence, status);
    case Declinecounter:
      return acceptDeclineCounter(incidence, status);
    case Reply:
      return acceptReply(incidence, status, method);
    case Refresh:
      return acceptRefresh(incidence, status);
    case Counter:
      return acceptCounter(incidence, status);
    default:
      deleteTransaction(incidence);
      return false;
  }
  deleteTransaction(incidence);
  return false;
}

QString Scheduler::methodName(Method method)
{
  switch (method) {
    case Publish:
      return i18n("Publish");
    case Request:
      return i18n("Request");
    case Refresh:
      return i18n("Refresh");
    case Cancel:
      return i18n("Cancel");
    case Add:
      return i18n("Add");
    case Reply:
      return i18n("Reply");
    case Counter:
      return i18n("Counter");
    case Declinecounter:
      return i18n("Decline Counter");
    default:
      return i18n("Unknown");
  }
}

bool Scheduler::deleteTransaction(IncidenceBase *)
{
  return true;
}

bool Scheduler::acceptPublish(IncidenceBase *incidence,ScheduleMessage::Status status, Method method)
{
  if(incidence->type()=="FreeBusy") {
    return acceptFreeBusy(incidence, method);
  }
  switch (status) {
    case ScheduleMessage::PublishNew:
      if (!mCalendar->getEvent(incidence->uid())) {
	Incidence *inc = static_cast<Incidence *>(incidence);
        mCalendar->addIncidence(inc);
        deleteTransaction(incidence);
      }
      return true;
    case ScheduleMessage::Obsolete:
      return true;
    default:
      deleteTransaction(incidence);
      return false;
  }
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptRequest(IncidenceBase *incidence,ScheduleMessage::Status status)
{
    Incidence *inc = static_cast<Incidence *>(incidence);
    switch (status) {
    case ScheduleMessage::Obsolete:
      return true;
    case ScheduleMessage::RequestNew:
      mCalendar->addIncidence(inc);
      deleteTransaction(incidence);
      return true;
    case ScheduleMessage::RequestUpdate:
      Event *even;
      even = mCalendar->getEvent(incidence->uid());
      if (even) {
        mCalendar->deleteEvent(even);
      }
      mCalendar->addIncidence(inc);
      deleteTransaction(incidence);
      return true;
    default:
      return false;
    }
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptAdd(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptCancel(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  bool ret = false;
  //get event in calendar
  QPtrList<Event> eventList;
  eventList=mCalendar->getEvents(incidence->dtStart().date(),incidence->dtStart().date(),false);
  Event *ev;
  for ( ev = eventList.first(); ev; ev = eventList.next() ) {
    if (ev->uid()==incidence->uid()) {
      //get matching attendee in calendar
      kdDebug() << "Scheduler::acceptTransaction match found!" << endl;
      mCalendar->deleteEvent(ev);
      ret = true;
    }
  }
  deleteTransaction(incidence);
  return ret;
}

bool Scheduler::acceptDeclineCounter(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

//bool Scheduler::acceptFreeBusy(Incidence *incidence,ScheduleMessage::Status status)
//{
//  deleteTransaction(incidence);
//  return false;
//}

bool Scheduler::acceptReply(IncidenceBase *incidence,ScheduleMessage::Status status, Method method)
{
  if(incidence->type()=="FreeBusy") {
    return acceptFreeBusy(incidence, method);
  }
  bool ret = false;
  Event *ev = mCalendar->getEvent(incidence->uid());
  if (ev) {
    //get matching attendee in calendar
    kdDebug(5800) << "Scheduler::acceptTransaction match found!" << endl;
    QPtrList<Attendee> attendeesIn = incidence->attendees();
    QPtrList<Attendee> attendeesEv = ev->attendees();
    Attendee *attIn;
    Attendee *attEv;
    for ( attIn = attendeesIn.first(); attIn; attIn = attendeesIn.next() ) {
      for ( attEv = attendeesEv.first(); attEv; attEv = attendeesEv.next() ) {
        if (attIn->email()==attEv->email()) {
          //update attendee-info
          kdDebug(5800) << "Scheduler::acceptTransaction update attendee" << endl;
          //attEv->setRole(attIn->role());
          attEv->setStatus(attIn->status());
          //attEv->setRSVP(attIn->RSVP());
          ev->setRevision(ev->revision()+1);
          ret = true;
        }
      }
    }
  }
  if (ret) deleteTransaction(incidence);
  return ret;
}

bool Scheduler::acceptRefresh(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  // handled in korganizer's IncomingDialog
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptCounter(IncidenceBase *incidence,ScheduleMessage::Status status)
{
  deleteTransaction(incidence);
  return false;
}

bool Scheduler::acceptFreeBusy(IncidenceBase *incidence, Method method)
{
  FreeBusy *freebusy = static_cast<FreeBusy *>(incidence);

  QString freeBusyDirName = locateLocal("appdata","freebusy");
  kdDebug() << "acceptFreeBusy:: freeBusyDirName: " << freeBusyDirName << endl;

  QString from;
  if(method == Scheduler::Publish) {
    from = freebusy->organizer();
  }
  if((method == Scheduler::Reply) && (freebusy->attendeeCount() == 1)) {
    Attendee *attendee = freebusy->attendees().first();
    from = attendee->email();
  }

  QDir freeBusyDir(freeBusyDirName);
  if (!freeBusyDir.exists()) {
    kdDebug() << "Directory " << freeBusyDirName << " does not exist!" << endl;
    kdDebug() << "Creating directory: " << freeBusyDirName << endl;

    if(!freeBusyDir.mkdir(freeBusyDirName, TRUE)) {
      kdDebug() << "Could not create directory: " << freeBusyDirName << endl;
      return false;
    }
  }

  QString filename(freeBusyDirName);
  filename += "/";
  filename += from;
  filename += ".ifb";
  QFile f(filename);

  kdDebug() << "acceptFreeBusy: filename" << filename << endl;

  freebusy->clearAttendees();
  freebusy->setOrganizer(from);

  QString messageText = mFormat->createScheduleMessage(freebusy, Publish);

  if (!f.open(IO_ReadWrite)) {
   kdDebug() << "acceptFreeBusy: Can't open:" << filename << " for writing" << endl;
   return false;
  }
  QTextStream t(&f);
  t << messageText;
  f.close();

  deleteTransaction(incidence);
  return true;
}
<|endoftext|>