<commit_before>/*************************************************************************
 *
 *  $RCSfile: View.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-31 13:49:24 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_HXX
#define SD_VIEW_HXX

#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVX_FMVIEW_HXX
#include <svx/fmview.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVMARK_HXX //autogen
#include <svx/svdvmark.hxx>
#endif
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

class SdDrawDocument;
class SdrOle2Obj;
class SdrGrafObj;
class SdrMediaObj;
class OutputDevice;
class VirtualDevice;
class ImageMap;
class Point;
class Graphic;
class SdrOutliner;
class TransferableDataHelper;
struct StyleRequestData;

namespace sd {

class DrawDocShell;
struct SdNavigatorDropEvent;
class ViewShell;
class Window;
class ViewClipboard;
class FuPoor;

// -------------------
// - SdViewRedrawRec -
// -------------------

struct SdViewRedrawRec
{
    OutputDevice* pOut;
    Rectangle     aRect;
};

class View : public FmFormView
{
public:
    TYPEINFO();

    View (
        SdDrawDocument* pDrawDoc,
        OutputDevice* pOutDev,
        ViewShell* pViewSh=NULL);
    virtual ~View (void);

    void                    CompleteRedraw( OutputDevice* pOutDev, const Region& rReg, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);

    virtual BOOL            GetAttributes( SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE ) const;
    virtual BOOL            SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll = FALSE);
    virtual void            MarkListHasChanged();
    virtual void            ModelHasChanged();
    virtual void            SelectAll();
    virtual void            DoCut(::Window* pWindow=NULL);
    virtual void            DoCopy(::Window* pWindow=NULL);
    virtual void            DoPaste(::Window* pWindow=NULL);
    virtual void            DoConnect(SdrOle2Obj* pOleObj);
    virtual BOOL            SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr = FALSE);
    virtual void            StartDrag( const Point& rStartPos, Window* pWindow );
    virtual void            DragFinished( sal_Int8 nDropAction );
    virtual sal_Int8 AcceptDrop (
        const AcceptDropEvent& rEvt,
        DropTargetHelper& rTargetHelper,
        ::sd::Window* pTargetWindow = NULL,
        USHORT nPage = SDRPAGE_NOTFOUND,
        USHORT nLayer = SDRPAGE_NOTFOUND);
    virtual sal_Int8 ExecuteDrop (
        const ExecuteDropEvent& rEvt,
        DropTargetHelper& rTargetHelper,
        ::sd::Window* pTargetWindow = NULL,
        USHORT nPage = SDRPAGE_NOTFOUND,
        USHORT nLayer = SDRPAGE_NOTFOUND);

    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateClipboardDataObject (::sd::View*, ::Window& rWindow);
    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateDragDataObject (::sd::View*, ::Window& rWindow,
            const Point& rDragPos);
    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateSelectionDataObject (::sd::View*, ::Window& rWindow);

    void                    UpdateSelectionClipboard( BOOL bForceDeselect );

    inline DrawDocShell* GetDocSh (void) const;
    inline SdDrawDocument* GetDoc (void) const;
    inline ViewShell* GetViewShell (void) const;

    BOOL                    BegTextEdit( SdrObject* pObj, SdrPageView* pPV=NULL, Window* pWin=NULL, BOOL bIsNewObj=FALSE,
                                         SdrOutliner* pGivenOutliner=NULL, OutlinerView* pGivenOutlinerView=NULL,
                                         BOOL bDontDeleteOutliner=FALSE, BOOL bOnlyOneView=FALSE );
    virtual SdrEndTextEditKind EndTextEdit(BOOL bDontDeleteReally=FALSE);

    SdrEndTextEditKind          EndTextEdit(BOOL bDontDeleteReally, FuPoor* pFunc);

    BOOL                    InsertData( const TransferableDataHelper& rDataHelper,
                                        const Point& rPos, sal_Int8& rDnDAction, BOOL bDrag,
                                        ULONG nFormat = 0, USHORT nPage = SDRPAGE_NOTFOUND, USHORT nLayer = SDRLAYER_NOTFOUND );
    SdrGrafObj*             InsertGraphic( const Graphic& rGraphic,
                                           sal_Int8& rAction, const Point& rPos,
                                           SdrObject* pSelectedObj, ImageMap* pImageMap );
    SdrMediaObj*            InsertMediaURL( const rtl::OUString& rMediaURL, sal_Int8& rAction,
                                            const Point& rPos, const Size& rSize );

    BOOL                    IsPresObjSelected(BOOL bOnPage=TRUE, BOOL bOnMasterPage=TRUE, BOOL bCheckPresObjListOnly=FALSE, BOOL bCheckLayoutOnly=FALSE) const;

    void                    SetMarkedOriginalSize();

    VirtualDevice*          CreatePageVDev(USHORT nSdPage, PageKind ePageKind, ULONG nWidthPixel);

    void                    LockRedraw(BOOL bLock);

    BOOL                    IsMorphingAllowed() const;
    BOOL                    IsVectorizeAllowed() const;

    virtual SfxStyleSheet*  GetStyleSheet() const;

    BOOL                    GetExchangeList( List*& rpExchangeList, List* pBookmarkList, USHORT nType );

    virtual void onAccessibilityOptionsChanged();

    virtual SdrModel*   GetMarkedObjModel() const;
    virtual BOOL        Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);

protected:
    SdDrawDocument*         pDoc;
    DrawDocShell*       pDocSh;
    ViewShell* pViewSh;
    SdrMarkList*            pDragSrcMarkList;
    SdrObject*              pDropMarkerObj;
    SdrViewUserMarker*      pDropMarker;
    USHORT                  nDragSrcPgNum;
    Point                   aDropPos;
    ::std::vector< String > aDropFileVector;
    sal_Int8                nAction;
    Timer                   aDropErrorTimer;
    Timer                   aDropInsertFileTimer;
    USHORT                  nLockRedrawSmph;
    List*                   pLockedRedraws;
    bool bIsDropAllowed;

                            DECL_LINK( DropErrorHdl, Timer* );
                            DECL_LINK( DropInsertFileHdl, Timer* );
                            DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent );

private:
    ::std::auto_ptr<ViewClipboard> mpClipboard;
};

DrawDocShell* View::GetDocSh (void) const
{
    return pDocSh;
}
SdDrawDocument* View::GetDoc (void) const
{
    return pDoc;
}

ViewShell* View::GetViewShell (void) const
{
    return pViewSh;
}

} // end of namespace sd

#endif
<commit_msg>INTEGRATION: CWS presentationengine01 (1.6.4); FILE MERGED 2004/10/12 23:11:15 thb 1.6.4.2: RESYNC: (1.6-1.7); FILE MERGED 2004/09/30 20:52:42 cl 1.6.4.1: listen to paragraph changes for effects<commit_after>/*************************************************************************
 *
 *  $RCSfile: View.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 20:15:00 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_VIEW_HXX
#define SD_VIEW_HXX

#ifndef _PRESENTATION_HXX
#include "pres.hxx"
#endif
#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _SVX_FMVIEW_HXX
#include <svx/fmview.hxx>
#endif
#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif
#ifndef _SVDVMARK_HXX //autogen
#include <svx/svdvmark.hxx>
#endif
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif

class SdDrawDocument;
class SdrOle2Obj;
class SdrGrafObj;
class SdrMediaObj;
class OutputDevice;
class VirtualDevice;
class ImageMap;
class Point;
class Graphic;
class SdrOutliner;
class TransferableDataHelper;
struct StyleRequestData;
class Outliner;

namespace sd {

class DrawDocShell;
struct SdNavigatorDropEvent;
class ViewShell;
class Window;
class ViewClipboard;
class FuPoor;

// -------------------
// - SdViewRedrawRec -
// -------------------

struct SdViewRedrawRec
{
    OutputDevice* pOut;
    Rectangle     aRect;
};

class View : public FmFormView
{
public:
    TYPEINFO();

    View (
        SdDrawDocument* pDrawDoc,
        OutputDevice* pOutDev,
        ViewShell* pViewSh=NULL);
    virtual ~View (void);

    void                    CompleteRedraw( OutputDevice* pOutDev, const Region& rReg, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L);

    virtual BOOL            GetAttributes( SfxItemSet& rTargetSet, BOOL bOnlyHardAttr=FALSE ) const;
    virtual BOOL            SetAttributes(const SfxItemSet& rSet, BOOL bReplaceAll = FALSE);
    virtual void            MarkListHasChanged();
    virtual void            ModelHasChanged();
    virtual void            SelectAll();
    virtual void            DoCut(::Window* pWindow=NULL);
    virtual void            DoCopy(::Window* pWindow=NULL);
    virtual void            DoPaste(::Window* pWindow=NULL);
    virtual void            DoConnect(SdrOle2Obj* pOleObj);
    virtual BOOL            SetStyleSheet(SfxStyleSheet* pStyleSheet, BOOL bDontRemoveHardAttr = FALSE);
    virtual void            StartDrag( const Point& rStartPos, Window* pWindow );
    virtual void            DragFinished( sal_Int8 nDropAction );
    virtual sal_Int8 AcceptDrop (
        const AcceptDropEvent& rEvt,
        DropTargetHelper& rTargetHelper,
        ::sd::Window* pTargetWindow = NULL,
        USHORT nPage = SDRPAGE_NOTFOUND,
        USHORT nLayer = SDRPAGE_NOTFOUND);
    virtual sal_Int8 ExecuteDrop (
        const ExecuteDropEvent& rEvt,
        DropTargetHelper& rTargetHelper,
        ::sd::Window* pTargetWindow = NULL,
        USHORT nPage = SDRPAGE_NOTFOUND,
        USHORT nLayer = SDRPAGE_NOTFOUND);

    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateClipboardDataObject (::sd::View*, ::Window& rWindow);
    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateDragDataObject (::sd::View*, ::Window& rWindow,
            const Point& rDragPos);
    ::com::sun::star::uno::Reference<
        ::com::sun::star::datatransfer::XTransferable>
        CreateSelectionDataObject (::sd::View*, ::Window& rWindow);

    void                    UpdateSelectionClipboard( BOOL bForceDeselect );

    inline DrawDocShell* GetDocSh (void) const;
    inline SdDrawDocument* GetDoc (void) const;
    inline ViewShell* GetViewShell (void) const;

    BOOL                    BegTextEdit( SdrObject* pObj, SdrPageView* pPV=NULL, Window* pWin=NULL, BOOL bIsNewObj=FALSE,
                                         SdrOutliner* pGivenOutliner=NULL, OutlinerView* pGivenOutlinerView=NULL,
                                         BOOL bDontDeleteOutliner=FALSE, BOOL bOnlyOneView=FALSE );
    virtual SdrEndTextEditKind EndTextEdit(BOOL bDontDeleteReally=FALSE);

    SdrEndTextEditKind          EndTextEdit(BOOL bDontDeleteReally, FuPoor* pFunc);

    BOOL                    InsertData( const TransferableDataHelper& rDataHelper,
                                        const Point& rPos, sal_Int8& rDnDAction, BOOL bDrag,
                                        ULONG nFormat = 0, USHORT nPage = SDRPAGE_NOTFOUND, USHORT nLayer = SDRLAYER_NOTFOUND );
    SdrGrafObj*             InsertGraphic( const Graphic& rGraphic,
                                           sal_Int8& rAction, const Point& rPos,
                                           SdrObject* pSelectedObj, ImageMap* pImageMap );
    SdrMediaObj*            InsertMediaURL( const rtl::OUString& rMediaURL, sal_Int8& rAction,
                                            const Point& rPos, const Size& rSize );

    BOOL                    IsPresObjSelected(BOOL bOnPage=TRUE, BOOL bOnMasterPage=TRUE, BOOL bCheckPresObjListOnly=FALSE, BOOL bCheckLayoutOnly=FALSE) const;

    void                    SetMarkedOriginalSize();

    VirtualDevice*          CreatePageVDev(USHORT nSdPage, PageKind ePageKind, ULONG nWidthPixel);

    void                    LockRedraw(BOOL bLock);

    BOOL                    IsMorphingAllowed() const;
    BOOL                    IsVectorizeAllowed() const;

    virtual SfxStyleSheet*  GetStyleSheet() const;

    BOOL                    GetExchangeList( List*& rpExchangeList, List* pBookmarkList, USHORT nType );

    virtual void onAccessibilityOptionsChanged();

    virtual SdrModel*   GetMarkedObjModel() const;
    virtual BOOL        Paste(const SdrModel& rMod, const Point& rPos, SdrObjList* pLst=NULL, UINT32 nOptions=0);

protected:
    DECL_LINK( ParagraphInsertedHdl, ::Outliner * );
    DECL_LINK( ParagraphRemovingHdl, ::Outliner * );

    SdDrawDocument*         pDoc;
    DrawDocShell*       pDocSh;
    ViewShell* pViewSh;
    SdrMarkList*            pDragSrcMarkList;
    SdrObject*              pDropMarkerObj;
    SdrViewUserMarker*      pDropMarker;
    USHORT                  nDragSrcPgNum;
    Point                   aDropPos;
    ::std::vector< String > aDropFileVector;
    sal_Int8                nAction;
    Timer                   aDropErrorTimer;
    Timer                   aDropInsertFileTimer;
    USHORT                  nLockRedrawSmph;
    List*                   pLockedRedraws;
    bool bIsDropAllowed;

                            DECL_LINK( DropErrorHdl, Timer* );
                            DECL_LINK( DropInsertFileHdl, Timer* );
                            DECL_LINK( ExecuteNavigatorDrop, SdNavigatorDropEvent* pSdNavigatorDropEvent );

private:
    ::std::auto_ptr<ViewClipboard> mpClipboard;
};

DrawDocShell* View::GetDocSh (void) const
{
    return pDocSh;
}
SdDrawDocument* View::GetDoc (void) const
{
    return pDoc;
}

ViewShell* View::GetViewShell (void) const
{
    return pViewSh;
}

} // end of namespace sd

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: formatclipboard.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2004-12-10 17:22:43 $
 *
 *  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: 2004 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

/*--------------------------------------------------------------------
 --------------------------------------------------------------------*/

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
            return false;
            break;
        case OBJ_CUSTOMSHAPE:
            return true;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.272); FILE MERGED 2005/09/05 13:22:07 rt 1.4.272.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: formatclipboard.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:30:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "formatclipboard.hxx"

#ifndef _E3D_GLOBL3D_HXX
#include <svx/globl3d.hxx>
#endif

// header for class SfxItemIter
#ifndef _SFXITEMITER_HXX
#include <svtools/itemiter.hxx>
#endif

// header for class SfxStyleSheet
#ifndef _SFXSTYLE_HXX
#include <svtools/style.hxx>
#endif

/*--------------------------------------------------------------------
 --------------------------------------------------------------------*/

SdFormatClipboard::SdFormatClipboard()
        : m_pItemSet(0)
        , m_bPersistentCopy(false)
        , m_nType_Inventor(0)
        , m_nType_Identifier(0)
{
}
SdFormatClipboard::~SdFormatClipboard()
{
    if(m_pItemSet)
        delete m_pItemSet;
}

bool SdFormatClipboard::HasContent() const
{
    return m_pItemSet!=0;
}

bool SdFormatClipboard::CanCopyThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( nObjectInventor != SdrInventor && nObjectInventor != E3dInventor )
        return false;
    switch(nObjectIdentifier)
    {
        case OBJ_NONE:
        case OBJ_GRUP:
            return false;
            break;
        case OBJ_LINE:
        case OBJ_RECT:
        case OBJ_CIRC:
        case OBJ_SECT:
        case OBJ_CARC:
        case OBJ_CCUT:
        case OBJ_POLY:
        case OBJ_PLIN:
        case OBJ_PATHLINE:
        case OBJ_PATHFILL:
        case OBJ_FREELINE:
        case OBJ_FREEFILL:
        case OBJ_SPLNLINE:
        case OBJ_SPLNFILL:
        case OBJ_TEXT:
        case OBJ_TEXTEXT:
        case OBJ_TITLETEXT:
            return true;
            break;
        case OBJ_OUTLINETEXT:
        case OBJ_GRAF:
        case OBJ_OLE2:
        case OBJ_EDGE:
        case OBJ_CAPTION:
            return false;
            break;
        case OBJ_PATHPOLY:
        case OBJ_PATHPLIN:
            return true;
            break;
        case OBJ_PAGE:
        case OBJ_MEASURE:
        case OBJ_DUMMY:
        case OBJ_FRAME:
        case OBJ_UNO:
            return false;
            break;
        case OBJ_CUSTOMSHAPE:
            return true;
            break;
        default:
            return false;
            break;
    }
    return true;
}

bool SdFormatClipboard::HasContentForThisType( UINT32 nObjectInventor, UINT16 nObjectIdentifier ) const
{
    if( !HasContent() )
        return false;
    if( !CanCopyThisType( nObjectInventor, nObjectIdentifier ) )
        return false;
    return true;
}

void SdFormatClipboard::Copy( ::sd::View& rDrawView, bool bPersistentCopy )
{
    this->Erase();
    m_bPersistentCopy = bPersistentCopy;

    const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
    if( rMarkList.GetMarkCount() >= 1 )
    {
        BOOL bOnlyHardAttr = FALSE;
        m_pItemSet = new SfxItemSet( rDrawView.GetAttrFromMarked(bOnlyHardAttr) );

        SdrObject* pObj = rMarkList.GetMark(0)->GetObj();
        m_nType_Inventor = pObj->GetObjInventor();
        m_nType_Identifier = pObj->GetObjIdentifier();
    }
}

void SdFormatClipboard::Paste( ::sd::View& rDrawView
                              , bool bNoCharacterFormats, bool bNoParagraphFormats )
{
    if( !rDrawView.AreObjectsMarked() )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }

    SdrObject* pObj = 0;

    bool bWrongTargetType = false;
    {
        const SdrMarkList& rMarkList = rDrawView.GetMarkedObjectList();
        if( rMarkList.GetMarkCount() != 1 )
            bWrongTargetType = true;
        else
        {
            pObj = rMarkList.GetMark(0)->GetObj();
            if( pObj && pObj->GetStyleSheet() )
                bWrongTargetType = !this->HasContentForThisType( pObj->GetObjInventor(), pObj->GetObjIdentifier() );
        }
    }
    if( bWrongTargetType )
    {
        if(!m_bPersistentCopy)
            this->Erase();
        return;
    }
    if(m_pItemSet)
    {
        //modify source itemset
        {
            BOOL bOnlyHardAttr = FALSE;
            SfxItemSet aTargetSet( pObj->GetStyleSheet()->GetItemSet() );

            USHORT nWhich=0;
            SfxItemState nSourceState;
            SfxItemState nTargetState;
            const SfxPoolItem* pSourceItem=0;
            const SfxPoolItem* pTargetItem=0;
            SfxItemIter aSourceIter(*m_pItemSet);
            pSourceItem = aSourceIter.FirstItem();
            while( pSourceItem!=NULL )
            {
                if (!IsInvalidItem(pSourceItem))
                {
                    nWhich = pSourceItem->Which();
                    if(nWhich)
                    {
                        nSourceState = m_pItemSet->GetItemState( nWhich );
                        nTargetState = aTargetSet.GetItemState( nWhich );
                        pTargetItem = aTargetSet.GetItem( nWhich );
                        ::com::sun::star::uno::Any aSourceValue, aTargetValue;

                        if(!pTargetItem)
                            m_pItemSet->ClearItem(nWhich);
                        else if( (*pSourceItem) == (*pTargetItem) )
                        {
                            //do not set items which have the same content in source and target
                            m_pItemSet->ClearItem(nWhich);
                        }
                    }
                }
                pSourceItem = aSourceIter.NextItem();
            }//end while
        }
        BOOL bReplaceAll = TRUE;
        rDrawView.SetAttrToMarked(*m_pItemSet, bReplaceAll);
    }
    if(!m_bPersistentCopy)
        this->Erase();
}

void SdFormatClipboard::Erase()
{
    if(m_pItemSet)
    {
        delete m_pItemSet;
        m_pItemSet = 0;
    }
    m_nType_Inventor=0;
    m_nType_Identifier=0;
    m_bPersistentCopy = false;
}
<|endoftext|>


<commit_before>/*
Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

https://leetcode.com/problems/regular-expression-matching/
*/
#include <iostream>

using namespace std;

class Solution {
public:
    bool isMatch(string s, string p) {
        return match(s.c_str(), p.c_str());
    }
    bool match(const char* s, const char* p) {
        if (p[0] == '\0') {
            return true;
        }
        if (p[0] == '.') {
            return this->match(&s[1], &p[1]);
        }
        if (p[0] == s[0] && s[0] != '\n') {
            return this->match(&s[1], &p[1]);
        }
        return false;
    }
};

void test(string str, string regular) {
    Solution s;
    cout << "[" << str << "] match [" << regular << "] = [" << (s.isMatch(str, regular) ? "ture]" : "false]") << endl;
}

int main(int argc, char *argv[]) {
    test("abc", "a");
    test("abc", "d");
    test("abc", "a.c");
    test("abc", "ab.");
    return 0;
}
<commit_msg>RegularExpressionMatching accepted<commit_after>/*
Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

https://leetcode.com/problems/regular-expression-matching/
*/
#include <iostream>

using namespace std;

class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        if (p.size() == 1) {
            return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));
        }
        if (p[1] != '*') {
            if (s.empty()) return false;
            return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));
        }
        while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
            if (isMatch(s, p.substr(2))) return true;
            s = s.substr(1);
        }
        return isMatch(s, p.substr(2));
    }
};

void test(string str, string regular, bool expected) {
    Solution s;
    cout << "[" << str << "] match [" << regular << "] = [" << (s.isMatch(str, regular) ? "ture]" : "false]");
    cout << " expected [" << (expected ? "true]" : "false]") << endl;
}

int main(int argc, char *argv[]) {
    test("aaa","aa", false); // false
    test("aa", "a*", true);//true
    test("aa","a", false); //false
    test("aa","aa", true); //true
    test("aaa", "a*", true);//true
    test("aab", "c*a*b", true);//true
    test("aa", ".*", true); // true
    test("ab", ".*", true); // true
    test("aab", "c*a*b", true); // → true
    test("aaa", "ab*ac*a", true);
    /*
    */
    return 0;
}
<|endoftext|>


<commit_before>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

//project
#include "accountsettingspage.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
#include "credentialdialog.h"
#include "service-model.h"
#include "sort-service-model.h"
#include "account-sync-handler.h"

//accounts-qt lib
#include <Accounts/Account>

//Meegotouch
#include <MContainer>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MMessageBox>
#include <MLocale>
#include <MAction>
#include <MLabel>
#include <MGridLayoutPolicy>
#include <MButton>
#include <MContentItem>
#include <MApplicationIfProxy>
#include <MMessageBox>

//Qt
#include <QDebug>
#include <QTimer>
#include <QMultiMap>

//Accounts-Ui
#include "abstract-account-setup-context.h"

#define INFO_BANNER_TIMEOUT 3000

namespace AccountsUI {

class AccountSettingsPagePrivate
{
public:
    AccountSettingsPagePrivate()
            : context(0),
            service(0),
            account(0),
            showAllServices(0),
            usernameAndStatus(0),
            serviceSettingLayout(0),
            layoutServicePolicy(0),
            enableButton(0),
            syncHandler(0),
            changePasswordDialogStarted(false)
    {}

    ~AccountSettingsPagePrivate() {}

    AbstractAccountSetupContext *context;
    const Accounts::Service *service;
    Accounts::Account* account;
    QList<AbstractServiceSetupContext *> contexts;
    MAction *showAllServices;
    MContentItem *usernameAndStatus;
    QString serviceType;
    MLayout *serviceSettingLayout;
    MGridLayoutPolicy *layoutServicePolicy;
    MButton *enableButton;
    Accounts::ServiceList serviceList;
    QList<AbstractSetupContext*> abstractContexts;
    AccountSyncHandler *syncHandler;
    bool changePasswordDialogStarted;
    QMultiMap<QString, ServiceSettingsWidget*> settingsWidgets;
};

void AccountSettingsPage::setServicesToBeShown()
{
    Q_D(AccountSettingsPage);
    /* List the services available on the account and load all the respective
     * plugins. */
    int row = 0;
    //% "%1 Settings"
    setTitle(qtTrId("qtn_acc_ser_prof_set_title").arg(d->context->account()->providerName()));

    ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);
    SortServiceModel *sortModel = new SortServiceModel(this);
    sortModel->setSourceModel(serviceModel);
    sortModel->setEnabledServices(d->context->account()->enabledServices());
    sortModel->sort(ServiceModel::ServiceNameColumn);

    QAbstractProxyModel *proxy = 0;
    // selecting the service type
    if (!d->context->serviceType().isEmpty()) {
        FilterTypeServiceModel *filterServiceModel = new FilterTypeServiceModel(this);
        filterServiceModel->setSourceModel(sortModel);
        filterServiceModel->setFilterFixedString(d->context->serviceType());
        proxy = filterServiceModel;
    } else
        proxy = sortModel;

    for (int i = 0; i < proxy->rowCount(); i++) {
        QModelIndex index = proxy->index(i, 0);
        const QVariant vServiceHelper = index.data(ServiceModel::ServiceHelperColumn);
        ServiceHelper *serviceHelper = vServiceHelper.value<ServiceHelper *>();
        AbstractServiceSetupContext *context =
            serviceHelper->serviceSetupContext(d->context, this);
        d->contexts.append(context);
    }

    /* iterate through the contexts we created for each service, and get the
     * UI widgets to embed */
    QMap<QString, bool> enabledServiceTypes;

    foreach (AbstractServiceSetupContext *context, d->contexts) {
        d->abstractContexts.append(context);
        d->service = context->service();
        const Accounts::Service *service = context->service();
        ServiceSettingsWidget *settingsWidget;

        d->account->selectService(service);

        bool enabled = false;
        if (d->account->enabled() &&
            !enabledServiceTypes.contains(service->serviceType())) {
            enabledServiceTypes.insert(service->serviceType(), true);
            enabled = true;
        }

        if (d->serviceList.count() > 1)
            settingsWidget = new ServiceSettingsWidget(context,
                                                   this,
                                                   ServiceSettingsWidget::EnableButton,
                                                   enabled);
        else
            settingsWidget = new ServiceSettingsWidget(context,
                                                       this,
                                                       ServiceSettingsWidget::MandatorySettings |
                                                       ServiceSettingsWidget::NonMandatorySettings,
                                                       enabled);

        d->settingsWidgets.insertMulti(service->serviceType(), settingsWidget);

        settingsWidget->setHeaderVisible(false);
        d->layoutServicePolicy->addItem(settingsWidget, row++, 0);
    }

    /*
     * no need in extra processing of any signals during content creation
     * */
    foreach (ServiceSettingsWidget *settingsWidget, d->settingsWidgets)
        connect (settingsWidget, SIGNAL(serviceButtonEnabled(const QString&)),
                 this, SLOT(disableSameServiceTypes(const QString&)));
}

AccountSettingsPage::AccountSettingsPage(AbstractAccountSetupContext *context)
        : MApplicationPage(),
          d_ptr(new AccountSettingsPagePrivate())
{
    Q_D(AccountSettingsPage);

    Q_ASSERT (context != NULL);
    d->context = context;
    d->account = d->context->account();
    d->abstractContexts.append(d->context);
    d->serviceType = d->context->serviceType();

    d->syncHandler = new AccountSyncHandler(this);
    connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
            this, SLOT(onSyncStateChanged(const SyncState&)));
    setStyleName("AccountSettingsPage");
}

AccountSettingsPage::~AccountSettingsPage()
{
    delete d_ptr;
}

void AccountSettingsPage::createContent()
{
    Q_D(AccountSettingsPage);

    //we need a central widget to get the right layout size under the menubar
    MWidget* centralWidget = new MWidget();
    MLayout* layout = new MLayout(centralWidget);
    MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);

    if (d->context) {
        QGraphicsLayoutItem *accountSettingsWidget = d->context->widget();
        if (accountSettingsWidget != 0) {
            layoutPolicy->addItem(accountSettingsWidget);
        } else {
            MWidget *upperWidget = new MWidget(this);
            MLayout *upperLayout = new MLayout(upperWidget);
            MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);

            MLayout *horizontalLayout = new MLayout();
            MLinearLayoutPolicy *horizontalLayoutPolicy = new MLinearLayoutPolicy(horizontalLayout, Qt::Horizontal);
            d->usernameAndStatus = new MContentItem(MContentItem::TwoTextLabels);
            horizontalLayoutPolicy->addItem(d->usernameAndStatus);
            d->serviceList = d->account->services();
            d->enableButton = new MButton();
            d->enableButton->setViewType(MButton::switchType);
            d->enableButton->setCheckable(true);
            d->account->selectService(NULL);
            if ( d->account->enabled())
                d->enableButton->setChecked(true);
            else
                d->enableButton->setChecked(false);
            connect(d->enableButton, SIGNAL(toggled(bool)), this, SLOT(enable(bool)));
            horizontalLayoutPolicy->addItem(d->enableButton);
            if (d->context->account()) {
                d->usernameAndStatus->setTitle(d->context->account()->displayName());
                d->context->account()->selectService(NULL);
                if (!d->context->account()->enabled()) {
                    //% "Disabled"
                    d->usernameAndStatus->setSubtitle(qtTrId("qtn_acc_disabled"));
                } else {
                    d->usernameAndStatus->setSubtitle(QString::null);
                }
            }
            upperLayoutPolicy->addItem(horizontalLayout);

            //% "Change password"
            MButton *changePassword = new MButton(qtTrId("qtn_acc_change_password"));
            upperLayoutPolicy->addItem(changePassword);
            connect(changePassword, SIGNAL(clicked()), this, SLOT(openChangePasswordDialog()));

            layoutPolicy->addItem(upperWidget);
        }
    }

    MWidget *serviceWidget = new MWidget(this);
    d->serviceSettingLayout = new MLayout(serviceWidget);
    d->layoutServicePolicy = new MGridLayoutPolicy(d->serviceSettingLayout);
    layoutPolicy->addItem(serviceWidget);

    /* Sets the service widgets and add it into the layout policy*/
    setServicesToBeShown();

    MContentItem *synchItem = new MContentItem(MContentItem::SingleTextLabel);
    //% "Synchronization"
    synchItem->setTitle(qtTrId("qtn_acc_sync"));
    layoutPolicy->addItem(synchItem);
    connect(synchItem, SIGNAL(clicked()),
            this, SLOT(openSynchUi()));

    layoutPolicy->addStretch();
    setCentralWidget(centralWidget);

    //% "Delete"
    MAction* action = new MAction(qtTrId("qtn_comm_command_delete"), this);
    action->setLocation(MAction::ApplicationMenuLocation);
    addAction(action);

    connect(action, SIGNAL(triggered()),
            this, SLOT(removeAccount()));

    if (d->context && !d->context->serviceType().isEmpty()) {
        QStringList serviceType;
        Accounts::ServiceList services = d->context->account()->services();
        foreach (Accounts::Service *service, services) {
            serviceType.append(service->serviceType());
        }
        serviceType.removeDuplicates();
        if (serviceType.count() > 1) {
            //% "All Services"
            d->showAllServices = new MAction(qtTrId("qtn_acc_settings_all_services"), this);
            d->showAllServices->setLocation(MAction::ApplicationMenuLocation);
            addAction(d->showAllServices);
            connect(d->showAllServices, SIGNAL(triggered()),
                    this, SLOT(showAllServices()));
        }
    }

    //Saving the settings on back button press
    connect(this, SIGNAL(backButtonClicked()),
            this, SLOT(saveSettings()));
}

const AbstractAccountSetupContext *AccountSettingsPage::context()
{
    Q_D(AccountSettingsPage);
    return d->context;
}

void AccountSettingsPage::enable(bool state)
{
    Q_D(AccountSettingsPage);

    if (d->serviceList.count() == 1) {
        d->account->selectService(d->serviceList.at(0));
        d->account->setEnabled(state);
    }

    d->context->account()->selectService(NULL);
    if (state) {
        if (d->usernameAndStatus)
            d->usernameAndStatus->setSubtitle(QString::null);
    } else {
        if (d->usernameAndStatus)
            //% "Disabled"
            d->usernameAndStatus->setSubtitle(qtTrId("qtn_acc_disabled"));
    }

    d->account->setEnabled(state);
}

void AccountSettingsPage::removeAccount()
{
    Q_D(AccountSettingsPage);
    //% "Delete %1 from your device?"
    QString dialogTitle =
        qtTrId("qtn_acc_remove_account").arg(d->context->account()->displayName());
    MMessageBox removeMBox(dialogTitle, M::YesButton | M::NoButton);
    removeMBox.setStyleName("RemoveDialog");

    if (removeMBox.exec() == M::YesButton) {
        d->context->account()->remove();
        d->context->account()->sync();
        ProviderPluginProcess::instance()->quit();
    }
}

void AccountSettingsPage::saveSettings()
{
    Q_D(AccountSettingsPage);
    setProgressIndicatorVisible(true);
    qDebug() << Q_FUNC_INFO;

    //we should call only validate. Storing will be handled
    //in onSyncStateChangted func.
    d->syncHandler->validate(d->abstractContexts);
}

void AccountSettingsPage::onSyncStateChanged(const SyncState &state)
{
    qDebug() << Q_FUNC_INFO;

    Q_D(AccountSettingsPage);
    switch (state) {
        case NotValidated:
            qDebug() << Q_FUNC_INFO << "NotValidated";
            setProgressIndicatorVisible(false);
            break;
        case Validated:
            qDebug() << Q_FUNC_INFO << "Validated";
            d->syncHandler->store(d->abstractContexts);
            break;
        case NotStored:
            qDebug() << Q_FUNC_INFO << "NotStored";
            connect(d->context->account(), SIGNAL(synced()),
                    ProviderPluginProcess::instance(), SLOT(quit()));
            d->context->account()->sync();
            break;
        case Stored:
            qDebug() << Q_FUNC_INFO << "Stored";
            connect(d->context->account(), SIGNAL(synced()),
                    ProviderPluginProcess::instance(), SLOT(quit()));
            d->context->account()->sync();
            break;
        default:
            return;
    }
}

void AccountSettingsPage::openChangePasswordDialog()
{
    Q_D(AccountSettingsPage);
    //ignore multiple clicks
    if (d->changePasswordDialogStarted)
    {
        qDebug() << Q_FUNC_INFO << "Change password dialog is started already";
        return;
    }

    d->changePasswordDialogStarted = true;

    CredentialDialog *credentialDialog = new CredentialDialog(d->account->credentialsId());
    credentialDialog->setParent(this);

    if (!credentialDialog) {
        qCritical() << "Cannot create change password dialog";
        return;
    }
    connect (credentialDialog, SIGNAL(safeToDeleteMe(CredentialDialog*)),
             this, SLOT(deleteCredentialsDialog()));
    //% "Change Password"
    credentialDialog->setTitle(qtTrId("qtn_acc_login_title_change"));
    credentialDialog->exec();
}

void AccountSettingsPage::deleteCredentialsDialog()
{
    Q_D(AccountSettingsPage);
    d->changePasswordDialogStarted = false;
    CredentialDialog *credentialDialog;

    if (sender() != NULL &&
        (credentialDialog = qobject_cast<CredentialDialog *>(sender())) != NULL)
        credentialDialog->deleteLater();
}

void AccountSettingsPage::openSynchUi()
{
    setProgressIndicatorVisible(true);

    //Start Sync-Ui
    MApplicationIfProxy mApplicationIfProxy("com.nokia.syncui", this);

    if (mApplicationIfProxy.connection().isConnected()) {
        mApplicationIfProxy.launch();
    } else {
        MInfoBanner* infoBanner = new MInfoBanner();

        //% "Unable to launch Synchronisation"
        infoBanner->setBodyText(qtTrId("qtn_acc_synchronisation_err_undefined"));
        infoBanner->appear(MSceneWindow::DestroyWhenDone);
        QTimer::singleShot(INFO_BANNER_TIMEOUT, infoBanner, SLOT(disappear()));
    }
    setProgressIndicatorVisible(false);
}

void AccountSettingsPage::showAllServices()
{
    Q_D(AccountSettingsPage);
    d->serviceType = QLatin1String("");
    setServicesToBeShown();
    d->showAllServices->setVisible(false);
}

/*
 * The same serviceTypes cannot be enabled in meantime
 * */
void AccountSettingsPage::disableSameServiceTypes(const QString &serviceType)
{
    Q_D(AccountSettingsPage);
    qDebug() << Q_FUNC_INFO << __LINE__;
    if (!sender())
    {
        qCritical() << "disableSameServiceTypes() must be called via signaling";
        return;
    }

    if (d->settingsWidgets.count(serviceType) == 1)
        return;

    foreach (ServiceSettingsWidget *widget, d->settingsWidgets.values(serviceType)) {
        if (widget == sender())
            continue;

        widget->setServiceButtonEnable(false);
    }
}

} // namespace
<commit_msg>Fixing bug 191186 - Services are not shown in account settings<commit_after>/*
 * This file is part of accounts-ui
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Alberto Mardegan <alberto.mardegan@nokia.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

//project
#include "accountsettingspage.h"
#include "provider-plugin-process.h"
#include "service-settings-widget.h"
#include "credentialdialog.h"
#include "service-model.h"
#include "sort-service-model.h"
#include "account-sync-handler.h"

//accounts-qt lib
#include <Accounts/Account>

//Meegotouch
#include <MContainer>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MMessageBox>
#include <MLocale>
#include <MAction>
#include <MLabel>
#include <MGridLayoutPolicy>
#include <MButton>
#include <MContentItem>
#include <MApplicationIfProxy>
#include <MMessageBox>

//Qt
#include <QDebug>
#include <QTimer>
#include <QMultiMap>

//Accounts-Ui
#include "abstract-account-setup-context.h"

#define INFO_BANNER_TIMEOUT 3000

namespace AccountsUI {

class AccountSettingsPagePrivate
{
public:
    AccountSettingsPagePrivate()
            : context(0),
            service(0),
            account(0),
            showAllServices(0),
            usernameAndStatus(0),
            serviceSettingLayout(0),
            layoutServicePolicy(0),
            enableButton(0),
            syncHandler(0),
            changePasswordDialogStarted(false)
    {}

    ~AccountSettingsPagePrivate() {}

    AbstractAccountSetupContext *context;
    const Accounts::Service *service;
    Accounts::Account* account;
    QList<AbstractServiceSetupContext *> contexts;
    MAction *showAllServices;
    MContentItem *usernameAndStatus;
    QString serviceType;
    MLayout *serviceSettingLayout;
    MGridLayoutPolicy *layoutServicePolicy;
    MButton *enableButton;
    Accounts::ServiceList serviceList;
    QList<AbstractSetupContext*> abstractContexts;
    AccountSyncHandler *syncHandler;
    bool changePasswordDialogStarted;
    QMultiMap<QString, ServiceSettingsWidget*> settingsWidgets;
};

void AccountSettingsPage::setServicesToBeShown()
{
    Q_D(AccountSettingsPage);
    /* List the services available on the account and load all the respective
     * plugins. */
    int row = 0;
    //% "%1 Settings"
    setTitle(qtTrId("qtn_acc_ser_prof_set_title").arg(d->context->account()->providerName()));

    ServiceModel *serviceModel = new ServiceModel(d->context->account(), this);
    SortServiceModel *sortModel = new SortServiceModel(this);
    sortModel->setSourceModel(serviceModel);
    sortModel->setEnabledServices(d->context->account()->enabledServices());
    sortModel->sort(ServiceModel::ServiceNameColumn);

    QAbstractProxyModel *proxy = 0;
    // selecting the service type
    if (!d->context->serviceType().isEmpty()) {
        FilterTypeServiceModel *filterServiceModel = new FilterTypeServiceModel(this);
        filterServiceModel->setSourceModel(sortModel);
        filterServiceModel->setFilterFixedString(d->context->serviceType());
        proxy = filterServiceModel;
    } else
        proxy = sortModel;

    for (int i = 0; i < proxy->rowCount(); i++) {
        QModelIndex index = proxy->index(i, 0);
        const QVariant vServiceHelper = index.data(ServiceModel::ServiceHelperColumn);
        ServiceHelper *serviceHelper = vServiceHelper.value<ServiceHelper *>();
        AbstractServiceSetupContext *context =
            serviceHelper->serviceSetupContext(d->context, this);
        d->contexts.append(context);
    }

    /* iterate through the contexts we created for each service, and get the
     * UI widgets to embed */
    QMap<QString, bool> enabledServiceTypes;

    foreach (AbstractServiceSetupContext *context, d->contexts) {
        d->abstractContexts.append(context);
        d->service = context->service();
        const Accounts::Service *service = context->service();
        ServiceSettingsWidget *settingsWidget;

        d->account->selectService(service);

        bool enabled = false;
        if (d->account->enabled() &&
            !enabledServiceTypes.contains(service->serviceType())) {
            enabledServiceTypes.insert(service->serviceType(), true);
            enabled = true;
        }

        if (d->serviceList.count() > 1)
            settingsWidget = new ServiceSettingsWidget(context,
                                                   this,
                                                   ServiceSettingsWidget::EnableButton,
                                                   enabled);
        else
            settingsWidget = new ServiceSettingsWidget(context,
                                                       this,
                                                       ServiceSettingsWidget::MandatorySettings |
                                                       ServiceSettingsWidget::NonMandatorySettings,
                                                       enabled);

        d->settingsWidgets.insertMulti(service->serviceType(), settingsWidget);

        settingsWidget->setHeaderVisible(false);
        d->layoutServicePolicy->addItem(settingsWidget, row++, 0);
    }

    /*
     * no need in extra processing of any signals during content creation
     * */
    foreach (ServiceSettingsWidget *settingsWidget, d->settingsWidgets)
        connect (settingsWidget, SIGNAL(serviceButtonEnabled(const QString&)),
                 this, SLOT(disableSameServiceTypes(const QString&)));
}

AccountSettingsPage::AccountSettingsPage(AbstractAccountSetupContext *context)
        : MApplicationPage(),
          d_ptr(new AccountSettingsPagePrivate())
{
    Q_D(AccountSettingsPage);

    Q_ASSERT (context != NULL);
    d->context = context;
    d->account = d->context->account();
    d->abstractContexts.append(d->context);
    d->serviceType = d->context->serviceType();

    d->syncHandler = new AccountSyncHandler(this);
    connect(d->syncHandler, SIGNAL(syncStateChanged(const SyncState&)),
            this, SLOT(onSyncStateChanged(const SyncState&)));
    setStyleName("AccountSettingsPage");
}

AccountSettingsPage::~AccountSettingsPage()
{
    delete d_ptr;
}

void AccountSettingsPage::createContent()
{
    Q_D(AccountSettingsPage);

    //we need a central widget to get the right layout size under the menubar
    MWidget* centralWidget = new MWidget();
    MLayout* layout = new MLayout(centralWidget);
    MLinearLayoutPolicy *layoutPolicy = new MLinearLayoutPolicy(layout, Qt::Vertical);

    if (d->context) {
        QGraphicsLayoutItem *accountSettingsWidget = d->context->widget();
        d->serviceList = d->account->services();
        if (accountSettingsWidget != 0) {
            layoutPolicy->addItem(accountSettingsWidget);
        } else {
            MWidget *upperWidget = new MWidget(this);
            MLayout *upperLayout = new MLayout(upperWidget);
            MLinearLayoutPolicy *upperLayoutPolicy = new MLinearLayoutPolicy(upperLayout, Qt::Vertical);

            MLayout *horizontalLayout = new MLayout();
            MLinearLayoutPolicy *horizontalLayoutPolicy = new MLinearLayoutPolicy(horizontalLayout, Qt::Horizontal);
            d->usernameAndStatus = new MContentItem(MContentItem::TwoTextLabels);
            horizontalLayoutPolicy->addItem(d->usernameAndStatus);

            d->enableButton = new MButton();
            d->enableButton->setViewType(MButton::switchType);
            d->enableButton->setCheckable(true);
            d->account->selectService(NULL);
            if ( d->account->enabled())
                d->enableButton->setChecked(true);
            else
                d->enableButton->setChecked(false);
            connect(d->enableButton, SIGNAL(toggled(bool)), this, SLOT(enable(bool)));
            horizontalLayoutPolicy->addItem(d->enableButton);
            if (d->context->account()) {
                d->usernameAndStatus->setTitle(d->context->account()->displayName());
                d->context->account()->selectService(NULL);
                if (!d->context->account()->enabled()) {
                    //% "Disabled"
                    d->usernameAndStatus->setSubtitle(qtTrId("qtn_acc_disabled"));
                } else {
                    d->usernameAndStatus->setSubtitle(QString::null);
                }
            }
            upperLayoutPolicy->addItem(horizontalLayout);

            //% "Change password"
            MButton *changePassword = new MButton(qtTrId("qtn_acc_change_password"));
            upperLayoutPolicy->addItem(changePassword);
            connect(changePassword, SIGNAL(clicked()), this, SLOT(openChangePasswordDialog()));

            layoutPolicy->addItem(upperWidget);
        }
    }

    MWidget *serviceWidget = new MWidget(this);
    d->serviceSettingLayout = new MLayout(serviceWidget);
    d->layoutServicePolicy = new MGridLayoutPolicy(d->serviceSettingLayout);
    layoutPolicy->addItem(serviceWidget);

    /* Sets the service widgets and add it into the layout policy*/
    setServicesToBeShown();

    MContentItem *synchItem = new MContentItem(MContentItem::SingleTextLabel);
    //% "Synchronization"
    synchItem->setTitle(qtTrId("qtn_acc_sync"));
    layoutPolicy->addItem(synchItem);
    connect(synchItem, SIGNAL(clicked()),
            this, SLOT(openSynchUi()));

    layoutPolicy->addStretch();
    setCentralWidget(centralWidget);

    //% "Delete"
    MAction* action = new MAction(qtTrId("qtn_comm_command_delete"), this);
    action->setLocation(MAction::ApplicationMenuLocation);
    addAction(action);

    connect(action, SIGNAL(triggered()),
            this, SLOT(removeAccount()));

    if (d->context && !d->context->serviceType().isEmpty()) {
        QStringList serviceType;
        Accounts::ServiceList services = d->context->account()->services();
        foreach (Accounts::Service *service, services) {
            serviceType.append(service->serviceType());
        }
        serviceType.removeDuplicates();
        if (serviceType.count() > 1) {
            //% "All Services"
            d->showAllServices = new MAction(qtTrId("qtn_acc_settings_all_services"), this);
            d->showAllServices->setLocation(MAction::ApplicationMenuLocation);
            addAction(d->showAllServices);
            connect(d->showAllServices, SIGNAL(triggered()),
                    this, SLOT(showAllServices()));
        }
    }

    //Saving the settings on back button press
    connect(this, SIGNAL(backButtonClicked()),
            this, SLOT(saveSettings()));
}

const AbstractAccountSetupContext *AccountSettingsPage::context()
{
    Q_D(AccountSettingsPage);
    return d->context;
}

void AccountSettingsPage::enable(bool state)
{
    Q_D(AccountSettingsPage);

    if (d->serviceList.count() == 1) {
        d->account->selectService(d->serviceList.at(0));
        d->account->setEnabled(state);
    }

    d->context->account()->selectService(NULL);
    if (state) {
        if (d->usernameAndStatus)
            d->usernameAndStatus->setSubtitle(QString::null);
    } else {
        if (d->usernameAndStatus)
            //% "Disabled"
            d->usernameAndStatus->setSubtitle(qtTrId("qtn_acc_disabled"));
    }

    d->account->setEnabled(state);
}

void AccountSettingsPage::removeAccount()
{
    Q_D(AccountSettingsPage);
    //% "Delete %1 from your device?"
    QString dialogTitle =
        qtTrId("qtn_acc_remove_account").arg(d->context->account()->displayName());
    MMessageBox removeMBox(dialogTitle, M::YesButton | M::NoButton);
    removeMBox.setStyleName("RemoveDialog");

    if (removeMBox.exec() == M::YesButton) {
        d->context->account()->remove();
        d->context->account()->sync();
        ProviderPluginProcess::instance()->quit();
    }
}

void AccountSettingsPage::saveSettings()
{
    Q_D(AccountSettingsPage);
    setProgressIndicatorVisible(true);
    qDebug() << Q_FUNC_INFO;

    //we should call only validate. Storing will be handled
    //in onSyncStateChangted func.
    d->syncHandler->validate(d->abstractContexts);
}

void AccountSettingsPage::onSyncStateChanged(const SyncState &state)
{
    qDebug() << Q_FUNC_INFO;

    Q_D(AccountSettingsPage);
    switch (state) {
        case NotValidated:
            qDebug() << Q_FUNC_INFO << "NotValidated";
            setProgressIndicatorVisible(false);
            break;
        case Validated:
            qDebug() << Q_FUNC_INFO << "Validated";
            d->syncHandler->store(d->abstractContexts);
            break;
        case NotStored:
            qDebug() << Q_FUNC_INFO << "NotStored";
            connect(d->context->account(), SIGNAL(synced()),
                    ProviderPluginProcess::instance(), SLOT(quit()));
            d->context->account()->sync();
            break;
        case Stored:
            qDebug() << Q_FUNC_INFO << "Stored";
            connect(d->context->account(), SIGNAL(synced()),
                    ProviderPluginProcess::instance(), SLOT(quit()));
            d->context->account()->sync();
            break;
        default:
            return;
    }
}

void AccountSettingsPage::openChangePasswordDialog()
{
    Q_D(AccountSettingsPage);
    //ignore multiple clicks
    if (d->changePasswordDialogStarted)
    {
        qDebug() << Q_FUNC_INFO << "Change password dialog is started already";
        return;
    }

    d->changePasswordDialogStarted = true;

    CredentialDialog *credentialDialog = new CredentialDialog(d->account->credentialsId());
    credentialDialog->setParent(this);

    if (!credentialDialog) {
        qCritical() << "Cannot create change password dialog";
        return;
    }
    connect (credentialDialog, SIGNAL(safeToDeleteMe(CredentialDialog*)),
             this, SLOT(deleteCredentialsDialog()));
    //% "Change Password"
    credentialDialog->setTitle(qtTrId("qtn_acc_login_title_change"));
    credentialDialog->exec();
}

void AccountSettingsPage::deleteCredentialsDialog()
{
    Q_D(AccountSettingsPage);
    d->changePasswordDialogStarted = false;
    CredentialDialog *credentialDialog;

    if (sender() != NULL &&
        (credentialDialog = qobject_cast<CredentialDialog *>(sender())) != NULL)
        credentialDialog->deleteLater();
}

void AccountSettingsPage::openSynchUi()
{
    setProgressIndicatorVisible(true);

    //Start Sync-Ui
    MApplicationIfProxy mApplicationIfProxy("com.nokia.syncui", this);

    if (mApplicationIfProxy.connection().isConnected()) {
        mApplicationIfProxy.launch();
    } else {
        MInfoBanner* infoBanner = new MInfoBanner();

        //% "Unable to launch Synchronisation"
        infoBanner->setBodyText(qtTrId("qtn_acc_synchronisation_err_undefined"));
        infoBanner->appear(MSceneWindow::DestroyWhenDone);
        QTimer::singleShot(INFO_BANNER_TIMEOUT, infoBanner, SLOT(disappear()));
    }
    setProgressIndicatorVisible(false);
}

void AccountSettingsPage::showAllServices()
{
    Q_D(AccountSettingsPage);
    d->serviceType = QLatin1String("");
    setServicesToBeShown();
    d->showAllServices->setVisible(false);
}

/*
 * The same serviceTypes cannot be enabled in meantime
 * */
void AccountSettingsPage::disableSameServiceTypes(const QString &serviceType)
{
    Q_D(AccountSettingsPage);
    qDebug() << Q_FUNC_INFO << __LINE__;
    if (!sender())
    {
        qCritical() << "disableSameServiceTypes() must be called via signaling";
        return;
    }

    if (d->settingsWidgets.count(serviceType) == 1)
        return;

    foreach (ServiceSettingsWidget *widget, d->settingsWidgets.values(serviceType)) {
        if (widget == sender())
            continue;

        widget->setServiceButtonEnable(false);
    }
}

} // namespace
<|endoftext|>


<commit_before><commit_msg>Implemented RMSE algorithm.<commit_after><|endoftext|>


<commit_before>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQCompartmentsWidget.cpp,v $
//   $Revision: 1.3 $
//   $Name:  $
//   $Author: aekamal $
//   $Date: 2009/05/15 19:36:28 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include <QHeaderView>

#include "model/CModel.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"

#include "CQCompartmentsWidget.h"
#include "qtUtilities.h"
#include "copasi.h"
#include "CQMessageBox.h"

/*
 *  Constructs a CQCompartmentsWidget which is a child of 'parent', with the
 *  name 'name'.'
 */
CQCompartmentsWidget::CQCompartmentsWidget(QWidget* parent, const char* name)
    : CopasiWidget(parent, name)
{
  setupUi(this);

  //Create Source Data Model.
  mpCompartmentDM = new CQCompartmentDM(this);

  //Create the Proxy Model for sorting/filtering and set its properties.
  mpProxyModel = new CQSortFilterProxyModel();
  mpProxyModel->setDynamicSortFilter(true);
  mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
  mpProxyModel->setFilterKeyColumn(COL_NAME_COMPARTMENTS);

  //Setting values for Types comboBox
  mpTypeDelegate = new CQIndexComboDelegate(&mpCompartmentDM->getTypes(), this);
  mpTblCompartments->setItemDelegateForColumn(COL_TYPE_COMPARTMENTS, mpTypeDelegate);

  mpTblCompartments->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
  mpTblCompartments->verticalHeader()->hide();

  // Connect the table widget
  connect(mpCompartmentDM, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),
          this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&)));
  connect(mpLEFilter, SIGNAL(textChanged(const QString &)),
          this, SLOT(slotFilterChanged()));
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQCompartmentsWidget::~CQCompartmentsWidget()
{
  pdelete(mpTypeDelegate);
  pdelete(mpProxyModel);
  pdelete(mpCompartmentDM);
  // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void CQCompartmentsWidget::languageChange()
{
  retranslateUi(this);
}

void CQCompartmentsWidget::slotBtnDeleteClicked()
{
  if (mpTblCompartments->hasFocus())
    {deleteSelectedCompartment();}
}

void CQCompartmentsWidget::deleteSelectedCompartment()
{
  if (mpTblCompartments->selectionModel()->selectedIndexes().empty())
    {return;}

  QModelIndex &i = mpProxyModel->mapToSource(mpTblCompartments->selectionModel()->selectedIndexes().value(0));
  int delRow = i.row();

  if (mpCompartmentDM->isDefaultRow(i))
    return;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL)
    return;

  CCompartment * pCompartment = pModel->getCompartments()[delRow];

  if (pCompartment == NULL)
    return;

  QMessageBox::StandardButton choice =
    CQMessageBox::confirmDelete(this, pModel, "compartment",
                                FROM_UTF8(pCompartment->getObjectName()),
                                pCompartment->getDeletedObjects());

  if (choice == QMessageBox::Ok)
    {
      if (mpTblCompartments->hasFocus())
        {
          mpCompartmentDM->removeRow(delRow);
          protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, "");
        }
    }
}

void CQCompartmentsWidget::slotBtnClearClicked()
{

  int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Compartments?",
                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::No);

  if (ret == QMessageBox::Yes)
    {
      mpCompartmentDM->clear();
      protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, "");
    }
}

bool CQCompartmentsWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key))
{
  return true;
}

bool CQCompartmentsWidget::leave()
{
  return true;
}

bool CQCompartmentsWidget::enter(const std::string & C_UNUSED(key))
{
  mpProxyModel->setSourceModel(mpCompartmentDM);
  //Set Model for the TableView
  mpTblCompartments->setModel(NULL);
  mpTblCompartments->setModel(mpProxyModel);
  mpTblCompartments->resizeColumnsToContents();

  return true;
}

void CQCompartmentsWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft),
                                       const QModelIndex& C_UNUSED(bottomRight))
{
  mpTblCompartments->resizeColumnsToContents();
  protectedNotify(ListViews::COMPARTMENT, ListViews::CHANGE, "");
  protectedNotify(ListViews::MODEL, ListViews::CHANGE, "");
}

void CQCompartmentsWidget::slotDoubleClicked(const QModelIndex proxyIndex)
{
  QModelIndex index = mpProxyModel->mapToSource(proxyIndex);

  if (mpCompartmentDM->isDefaultRow(index))
    return;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL)
    return;

  std::string key = pModel->getCompartments()[index.row()]->getKey();

  if (CCopasiRootContainer::getKeyFactory()->get(key))
    mpListView->switchToOtherWidget(0, key);
}

void CQCompartmentsWidget::keyPressEvent(QKeyEvent* ev)
{
  if (ev->key() == Qt::Key_Delete)
    slotBtnDeleteClicked();
}

void CQCompartmentsWidget::slotFilterChanged()
{
  QRegExp regExp(mpLEFilter->text() + "|No Name", Qt::CaseInsensitive, QRegExp::RegExp);
  mpProxyModel->setFilterRegExp(regExp);
}
<commit_msg>fix a small problem<commit_after>// Begin CVS Header
//   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQCompartmentsWidget.cpp,v $
//   $Revision: 1.4 $
//   $Name:  $
//   $Author: pwilly $
//   $Date: 2009/05/18 10:51:31 $
// End CVS Header

// Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.

#include <QHeaderView>

#include "model/CModel.h"
#include "CopasiDataModel/CCopasiDataModel.h"
#include "report/CCopasiRootContainer.h"

#include "CQCompartmentsWidget.h"
#include "qtUtilities.h"
#include "copasi.h"
#include "CQMessageBox.h"

/*
 *  Constructs a CQCompartmentsWidget which is a child of 'parent', with the
 *  name 'name'.'
 */
CQCompartmentsWidget::CQCompartmentsWidget(QWidget* parent, const char* name)
    : CopasiWidget(parent, name)
{
  setupUi(this);

  //Create Source Data Model.
  mpCompartmentDM = new CQCompartmentDM(this);

  //Create the Proxy Model for sorting/filtering and set its properties.
  mpProxyModel = new CQSortFilterProxyModel();
  mpProxyModel->setDynamicSortFilter(true);
  mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
  mpProxyModel->setFilterKeyColumn(COL_NAME_COMPARTMENTS);

  //Setting values for Types comboBox
  mpTypeDelegate = new CQIndexComboDelegate(&mpCompartmentDM->getTypes(), this);
  mpTblCompartments->setItemDelegateForColumn(COL_TYPE_COMPARTMENTS, mpTypeDelegate);

  mpTblCompartments->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
  mpTblCompartments->verticalHeader()->hide();

  // Connect the table widget
  connect(mpCompartmentDM, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),
          this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&)));
  connect(mpLEFilter, SIGNAL(textChanged(const QString &)),
          this, SLOT(slotFilterChanged()));
}

/*
 *  Destroys the object and frees any allocated resources
 */
CQCompartmentsWidget::~CQCompartmentsWidget()
{
  pdelete(mpTypeDelegate);
  pdelete(mpProxyModel);
  pdelete(mpCompartmentDM);
  // no need to delete child widgets, Qt does it all for us
}

/*
 *  Sets the strings of the subwidgets using the current
 *  language.
 */
void CQCompartmentsWidget::languageChange()
{
  retranslateUi(this);
}

void CQCompartmentsWidget::slotBtnDeleteClicked()
{
  if (mpTblCompartments->hasFocus())
    {deleteSelectedCompartment();}
}

void CQCompartmentsWidget::deleteSelectedCompartment()
{
  if (mpTblCompartments->selectionModel()->selectedIndexes().empty())
    {return;}

//  QModelIndex &i = mpProxyModel->mapToSource(mpTblCompartments->selectionModel()->selectedIndexes().value(0));
  QModelIndex i = mpProxyModel->mapToSource(mpTblCompartments->selectionModel()->selectedIndexes().value(0));
  int delRow = i.row();

  if (mpCompartmentDM->isDefaultRow(i))
    return;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL)
    return;

  CCompartment * pCompartment = pModel->getCompartments()[delRow];

  if (pCompartment == NULL)
    return;

  QMessageBox::StandardButton choice =
    CQMessageBox::confirmDelete(this, pModel, "compartment",
                                FROM_UTF8(pCompartment->getObjectName()),
                                pCompartment->getDeletedObjects());

  if (choice == QMessageBox::Ok)
    {
      if (mpTblCompartments->hasFocus())
        {
          mpCompartmentDM->removeRow(delRow);
          protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, "");
        }
    }
}

void CQCompartmentsWidget::slotBtnClearClicked()
{

  int ret = QMessageBox::question(this, tr("Confirm Delete"), "Delete all Compartments?",
                                  QMessageBox::Yes | QMessageBox::No, QMessageBox::No);

  if (ret == QMessageBox::Yes)
    {
      mpCompartmentDM->clear();
      protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, "");
    }
}

bool CQCompartmentsWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key))
{
  return true;
}

bool CQCompartmentsWidget::leave()
{
  return true;
}

bool CQCompartmentsWidget::enter(const std::string & C_UNUSED(key))
{
  mpProxyModel->setSourceModel(mpCompartmentDM);
  //Set Model for the TableView
  mpTblCompartments->setModel(NULL);
  mpTblCompartments->setModel(mpProxyModel);
  mpTblCompartments->resizeColumnsToContents();

  return true;
}

void CQCompartmentsWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft),
                                       const QModelIndex& C_UNUSED(bottomRight))
{
  mpTblCompartments->resizeColumnsToContents();
  protectedNotify(ListViews::COMPARTMENT, ListViews::CHANGE, "");
  protectedNotify(ListViews::MODEL, ListViews::CHANGE, "");
}

void CQCompartmentsWidget::slotDoubleClicked(const QModelIndex proxyIndex)
{
  QModelIndex index = mpProxyModel->mapToSource(proxyIndex);

  if (mpCompartmentDM->isDefaultRow(index))
    return;

  assert(CCopasiRootContainer::getDatamodelList()->size() > 0);
  CCopasiDataModel* pDataModel = (*CCopasiRootContainer::getDatamodelList())[0];
  assert(pDataModel != NULL);
  CModel * pModel = pDataModel->getModel();

  if (pModel == NULL)
    return;

  std::string key = pModel->getCompartments()[index.row()]->getKey();

  if (CCopasiRootContainer::getKeyFactory()->get(key))
    mpListView->switchToOtherWidget(0, key);
}

void CQCompartmentsWidget::keyPressEvent(QKeyEvent* ev)
{
  if (ev->key() == Qt::Key_Delete)
    slotBtnDeleteClicked();
}

void CQCompartmentsWidget::slotFilterChanged()
{
  QRegExp regExp(mpLEFilter->text() + "|No Name", Qt::CaseInsensitive, QRegExp::RegExp);
  mpProxyModel->setFilterRegExp(regExp);
}
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/report/CCopasiContainer.cpp,v $
   $Revision: 1.28 $
   $Name:  $
   $Author: ssahle $
   $Date: 2005/01/12 15:57:52 $
   End CVS Header */

/**
 * Class CCopasiContainer
 *
 * This class is the is used to group CCopasiObjects logically. It inself is
 * an object. Contained objects are still globally accessible.
 *
 * Copyright Stefan Hoops 2002
 */

#include "copasi.h"
#include "CCopasiObjectName.h"
#include "CCopasiContainer.h"
#include "CCopasiObjectReference.h"
#include "CCopasiStaticString.h"
#include "utilities/CCopasiVector.h"

CCopasiContainer * CCopasiContainer::Root = NULL;

void CCopasiContainer::init() {CCopasiContainer::Root = new CCopasiContainer();}

CCopasiObject * CCopasiContainer::ObjectFromName(const CCopasiObjectName & objName)
{
  std::vector< CCopasiContainer * > dummy;
  return CCopasiContainer::ObjectFromName(dummy, objName);
  //TODO: more effective
}

CCopasiObject * CCopasiContainer::ObjectFromName(const std::vector< CCopasiContainer * > & listOfContainer,
    const CCopasiObjectName & objName)
{
  const CCopasiObject * pObject = NULL;
  CCopasiContainer* pContainer;
  CCopasiObjectName Name;
  unsigned C_INT32 containerIndex;

  //favor to search the list of container first
  for (containerIndex = 0;
       containerIndex < listOfContainer.size() && !pObject;
       containerIndex++)
    {
      pContainer = listOfContainer[containerIndex];

      for (Name = objName, pObject = NULL;
           (Name.getRemainder() != ""
            || Name.getObjectType() == "String") &&
           !pObject;
           Name = Name.getRemainder())
        pObject = pContainer->getObject(Name);
    }

  // if not found search the root
  if (!pObject)
    pObject = CCopasiContainer::Root->getObject(objName);

  return const_cast<CCopasiObject *>(pObject);
}

CCopasiContainer::CCopasiContainer() :
    CCopasiObject("Root", NULL, "CN", CCopasiObject::Container),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::CCopasiContainer(const std::string & name,
                                   const CCopasiContainer * pParent,
                                   const std::string & type,
                                   const unsigned C_INT32 & flag):
    CCopasiObject(name, pParent, type, flag | CCopasiObject::Container),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::CCopasiContainer(const CCopasiContainer & src,
                                   const CCopasiContainer * pParent):
    CCopasiObject(src, pParent),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::~CCopasiContainer()
{
  objectMap::iterator it = mObjects.begin();
  objectMap::iterator end = mObjects.end();

  for (; it != end; it++)
    if (it->second->getObjectParent() == this)
      {
        it->second->setObjectParent(NULL);
        pdelete(it->second);
      }
}

const std::string CCopasiContainer::getObjectUniqueName() const
  {
    // return getObjectName();
    return CCopasiObject::getObjectUniqueName();
  }

const CCopasiObject * CCopasiContainer::getObject(const CCopasiObjectName & cn) const
  {
    if (cn == "")
      return this;

    std::string Name = cn.getObjectName();
    std::string Type = cn.getObjectType();

    if (getObjectName() == Name && getObjectType() == Type)
      return getObject(cn.getRemainder());

    std::pair< objectMap::const_iterator, objectMap::const_iterator > range =
      mObjects.equal_range(Name);

    objectMap::const_iterator it = range.first;

    while (it != range.second && it->second->getObjectType() != Type) ++it;

    //debug
    /*
    std::cout << "Container::getObject(); this->getObjectName(): " << getObjectName() << " CN: " << cn << std::endl;
    objectMap::const_iterator dit, ditEnd=mObjects.end();
    for (dit=mObjects.begin(); dit != ditEnd; ++dit)
      std::cout << "   " << dit->first << " (Name: " << dit->second->getObjectName() << ", Type: " << dit->second->getObjectType() << ")" << std::endl;
    ditEnd=range.second;
    for (dit=range.first; dit != ditEnd; ++dit)
      std::cout << " * " << dit->first << " (Name: " << dit->second->getObjectName() << ", Type: " << dit->second->getObjectType() << ")" << std::endl;
    */

    if (it == range.second)
      {
        if (Type == "String")
          return new CCopasiStaticString(Name, this);
        else
          return NULL;
      }

    const CCopasiObject * pObject = NULL;

    if (it->second->isNameVector() || it->second->isVector())
      {
        pObject = it->second->getObject("[" + cn.getElementName(0, false) + "]");

        if (it->second->getObjectType() == "Reference" || !pObject)
          return pObject;
        else
          return pObject->getObject(cn.getRemainder());
      }

    if (it->second->isContainer())
      return it->second->getObject(cn.getRemainder());

    if (it->second->isMatrix())
      {
        pObject = it->second->getObject("[" + cn.getElementName(0, false) + "]" +     //TODO really?
                                        "[" + cn.getElementName(1, false) + "]");

        if (it->second->getObjectType() == "Reference" || !pObject)
          return pObject;
        else
          return pObject->getObject(cn.getRemainder());
      }

    if (it->second->isReference() || it->second->isStaticString())
      return it->second;

    return it->second->getObject(cn.getRemainder());
  }

const CCopasiContainer::objectMap & CCopasiContainer::getObjects() const
{return mObjects;}

void CCopasiContainer::initObjects() {}

bool CCopasiContainer::add(CCopasiObject * pObject,
                           const bool & adopt)
{
  /* We check wheter we are already containing that object. */
  std::pair< objectMap::iterator, objectMap::iterator > range =
    mObjects.equal_range(pObject->getObjectName());
  objectMap::iterator it;

  for (it = range.first; it != range.second; ++it)
    if (it->second == pObject) break;

  if (it != range.second) return false;

  /* This object is not contained, so we can add it. */
  mObjects.insert
  (std::pair<std::string, CCopasiObject * >(pObject->getObjectName(),
      pObject));

  if (adopt) pObject->setObjectParent(this);
  return true;
}

bool CCopasiContainer::remove(CCopasiObject * pObject)
{
  objectMap::iterator it = mObjects.begin();
  objectMap::iterator end = mObjects.end();
  /*
    std::pair< objectMap::iterator, objectMap::iterator > range =
      mObjects.equal_range(pObject->getObjectName());
    objectMap::iterator it;
  */
  for (; it != end; ++it)
    if (it->second == pObject) break;

  if (it == end) return false;

  mObjects.erase(it);

  return true;
}

bool CCopasiContainer::setValueOfNamedReference(std::string name, C_FLOAT64 value)
{
  //const CCopasiObject* tmp = const_cast<CCopasiObject *>(getObject(name));

  std::pair< objectMap::const_iterator, objectMap::const_iterator > range =
    mObjects.equal_range(name);

  const CCopasiObject* tmp = range.first->second;

  if (!tmp) return false;
  if (!tmp->isReference()) return false;
  if (!tmp->isValueDbl()) return false;

  *((C_FLOAT64*)(tmp->getReference())) = value;
  return true;
}
<commit_msg>cleaning up...<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/report/CCopasiContainer.cpp,v $
   $Revision: 1.29 $
   $Name:  $
   $Author: ssahle $
   $Date: 2005/01/12 23:06:40 $
   End CVS Header */

/**
 * Class CCopasiContainer
 *
 * This class is the is used to group CCopasiObjects logically. It inself is
 * an object. Contained objects are still globally accessible.
 *
 * Copyright Stefan Hoops 2002
 */

#include "copasi.h"
#include "CCopasiObjectName.h"
#include "CCopasiContainer.h"
#include "CCopasiObjectReference.h"
#include "CCopasiStaticString.h"
#include "utilities/CCopasiVector.h"

CCopasiContainer * CCopasiContainer::Root = NULL;

void CCopasiContainer::init() {CCopasiContainer::Root = new CCopasiContainer();}

CCopasiObject * CCopasiContainer::ObjectFromName(const CCopasiObjectName & objName)
{
  std::vector< CCopasiContainer * > dummy;
  return CCopasiContainer::ObjectFromName(dummy, objName);
  //TODO: more effective
}

CCopasiObject * CCopasiContainer::ObjectFromName(const std::vector< CCopasiContainer * > & listOfContainer,
    const CCopasiObjectName & objName)
{
  const CCopasiObject * pObject = NULL;
  CCopasiContainer* pContainer;
  CCopasiObjectName Name;
  unsigned C_INT32 containerIndex;

  //favor to search the list of container first
  for (containerIndex = 0;
       containerIndex < listOfContainer.size() && !pObject;
       containerIndex++)
    {
      pContainer = listOfContainer[containerIndex];

      for (Name = objName, pObject = NULL;
           (Name.getRemainder() != ""
            || Name.getObjectType() == "String") &&
           !pObject;
           Name = Name.getRemainder())
        pObject = pContainer->getObject(Name);
    }

  // if not found search the root
  if (!pObject)
    pObject = CCopasiContainer::Root->getObject(objName);

  return const_cast<CCopasiObject *>(pObject);
}

CCopasiContainer::CCopasiContainer() :
    CCopasiObject("Root", NULL, "CN", CCopasiObject::Container),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::CCopasiContainer(const std::string & name,
                                   const CCopasiContainer * pParent,
                                   const std::string & type,
                                   const unsigned C_INT32 & flag):
    CCopasiObject(name, pParent, type, flag | CCopasiObject::Container),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::CCopasiContainer(const CCopasiContainer & src,
                                   const CCopasiContainer * pParent):
    CCopasiObject(src, pParent),
    mObjects()
{addObjectReference("Name", *const_cast<std::string *>(&getObjectName()));}

CCopasiContainer::~CCopasiContainer()
{
  objectMap::iterator it = mObjects.begin();
  objectMap::iterator end = mObjects.end();

  for (; it != end; it++)
    if (it->second->getObjectParent() == this)
      {
        it->second->setObjectParent(NULL);
        pdelete(it->second);
      }
}

const std::string CCopasiContainer::getObjectUniqueName() const
  {
    // return getObjectName();
    return CCopasiObject::getObjectUniqueName();
  }

const CCopasiObject * CCopasiContainer::getObject(const CCopasiObjectName & cn) const
  {
    if (cn == "")
      return this;

    std::string Name = cn.getObjectName();
    std::string Type = cn.getObjectType();

    if (getObjectName() == Name && getObjectType() == Type)
      return getObject(cn.getRemainder());

    std::pair< objectMap::const_iterator, objectMap::const_iterator > range =
      mObjects.equal_range(Name);

    objectMap::const_iterator it = range.first;

    while (it != range.second && it->second->getObjectType() != Type) ++it;

    //debug
    /*
    std::cout << "Container::getObject(); this->getObjectName(): " << getObjectName() << " CN: " << cn << std::endl;
    objectMap::const_iterator dit, ditEnd=mObjects.end();
    for (dit=mObjects.begin(); dit != ditEnd; ++dit)
      std::cout << "   " << dit->first << " (Name: " << dit->second->getObjectName() << ", Type: " << dit->second->getObjectType() << ")" << std::endl;
    ditEnd=range.second;
    for (dit=range.first; dit != ditEnd; ++dit)
      std::cout << " * " << dit->first << " (Name: " << dit->second->getObjectName() << ", Type: " << dit->second->getObjectType() << ")" << std::endl;
    */

    if (it == range.second)
      {
        if (Type == "String")
          return new CCopasiStaticString(Name, this);
        else
          return NULL;
      }

    const CCopasiObject * pObject = NULL;

    if (it->second->isNameVector() || it->second->isVector())
      {
        pObject = it->second->getObject("[" + cn.getElementName(0, false) + "]");

        if (it->second->getObjectType() == "Reference" || !pObject)
          return pObject;
        else
          return pObject->getObject(cn.getRemainder());
      }

    if (it->second->isContainer())
      return it->second->getObject(cn.getRemainder());

    if (it->second->isMatrix())
      {
        pObject = it->second->getObject("[" + cn.getElementName(0, false) + "]" +      //TODO really?
                                        "[" + cn.getElementName(1, false) + "]");

        if (it->second->getObjectType() == "Reference" || !pObject)
          return pObject;
        else
          return pObject->getObject(cn.getRemainder());
      }

    if (it->second->isReference() || it->second->isStaticString())
      return it->second;

    return it->second->getObject(cn.getRemainder());
  }

const CCopasiContainer::objectMap & CCopasiContainer::getObjects() const
{return mObjects;}

void CCopasiContainer::initObjects() {}

bool CCopasiContainer::add(CCopasiObject * pObject,
                           const bool & adopt)
{
  /* We check wheter we are already containing that object. */
  std::pair< objectMap::iterator, objectMap::iterator > range =
    mObjects.equal_range(pObject->getObjectName());
  objectMap::iterator it;

  for (it = range.first; it != range.second; ++it)
    if (it->second == pObject) break;

  if (it != range.second) return false;

  /* This object is not contained, so we can add it. */
  mObjects.insert
  (std::pair<std::string, CCopasiObject * >(pObject->getObjectName(),
      pObject));

  if (adopt) pObject->setObjectParent(this);
  return true;
}

bool CCopasiContainer::remove(CCopasiObject * pObject)
{
  objectMap::iterator it = mObjects.begin();
  objectMap::iterator end = mObjects.end();
  /*
    std::pair< objectMap::iterator, objectMap::iterator > range =
      mObjects.equal_range(pObject->getObjectName());
    objectMap::iterator it;
  */
  for (; it != end; ++it)
    if (it->second == pObject) break;

  if (it == end) return false;

  mObjects.erase(it);

  return true;
}

bool CCopasiContainer::setValueOfNamedReference(std::string name, C_FLOAT64 value)
{
  std::pair< objectMap::const_iterator, objectMap::const_iterator > range =
    mObjects.equal_range(name);

  //assume unique names...
  const CCopasiObject* tmp = range.first->second;

  if (!tmp) return false;
  if (!tmp->isReference()) return false;
  if (!tmp->isValueDbl()) return false;

  *((C_FLOAT64*)(tmp->getReference())) = value;
  return true;
}
<|endoftext|>


<commit_before><commit_msg>[FIXED] Radial Permission<commit_after><|endoftext|>