<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optupdt.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2006-11-21 17:07:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "optupdt.hxx"
#include "optupdt.hrc"

#include "dialmgr.hxx"
#include "dialogs.hrc"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#include <osl/file.hxx>
#include <osl/security.hxx>

namespace beans = ::com::sun::star::beans;
namespace container = ::com::sun::star::container;
namespace dialogs = ::com::sun::star::ui::dialogs;
namespace frame = ::com::sun::star::frame;
namespace lang = ::com::sun::star::lang;
namespace uno = ::com::sun::star::uno;
namespace util = ::com::sun::star::util;

// define ----------------------------------------------------------------

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

// class SvxOnlineUpdateTabPage --------------------------------------------------

SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) :

    SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ),
        m_aOptionsLine( this, ResId( FL_OPTIONS ) ),
        m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ),
        m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ),
        m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ),
        m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ),
        m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ),
        m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ),
        m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ),
        m_aDestPath( this, ResId( FT_DESTPATH ) ),
        m_aChangePathButton( this, ResId( PB_CHANGEPATH ) )
{
    FreeResource();

    m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) );
    m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) );
    m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) );
    m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) );

    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    m_xUpdateAccess = uno::Reference < container::XNameReplace >(
        xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ),
        uno::UNO_QUERY_THROW );

    sal_Bool bDownloadSupported = sal_Bool();
    m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported;

    WinBits nStyle = m_aDestPath.GetStyle();
    nStyle |= WB_PATHELLIPSIS;
    m_aDestPath.SetStyle(nStyle);

    m_aAutoDownloadCheckBox.Show(bDownloadSupported);
    m_aDestPathLabel.Show(bDownloadSupported);
    m_aDestPath.Show(bDownloadSupported);
    m_aChangePathButton.Show(bDownloadSupported);
}

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

SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage()
{
}

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

SfxTabPage*
SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxOnlineUpdateTabPage( pParent, rAttrSet );
}

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

BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& )
{
    BOOL bModified = FALSE;

    sal_Bool bValue;
    sal_Int64 nValue;

    if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    nValue = 0;
    if( TRUE == m_aEveryDayButton.IsChecked() )
    {
        if( FALSE == m_aEveryDayButton.GetSavedValue() )
            nValue = 86400;
    }
    else if( TRUE == m_aEveryWeekButton.IsChecked() )
    {
        if( FALSE == m_aEveryWeekButton.GetSavedValue() )
            nValue = 604800;
    }
    else if( TRUE == m_aEveryMonthButton.IsChecked() )
    {
        if( FALSE == m_aEveryMonthButton.GetSavedValue() )
            nValue = 2592000;
    }

    if( nValue > 0 )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) );
        bModified = TRUE;
    }

    if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    rtl::OUString sValue, aURL;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) &&
        ( ! aURL.equals( sValue ) ) )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) );
        bModified = TRUE;
    }

    uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY);
    if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() )
        xChangesBatch->commitChanges();

    return bModified;
}

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

void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& )
{
    sal_Bool bValue = sal_Bool();
    m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue;

    m_aAutoCheckCheckBox.Check(bValue);
    m_aEveryDayButton.Enable(bValue);
    m_aEveryWeekButton.Enable(bValue);
    m_aEveryMonthButton.Enable(bValue);

    sal_Int64 nValue = 0;
    m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue;

    if( nValue == 86400 )
        m_aEveryDayButton.Check();
    else if( nValue == 604800 )
        m_aEveryWeekButton.Check();
    else
        m_aEveryMonthButton.Check();

    m_aAutoCheckCheckBox.SaveValue();
    m_aEveryDayButton.SaveValue();
    m_aEveryWeekButton.SaveValue();
    m_aEveryMonthButton.SaveValue();

    m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue;
    m_aAutoDownloadCheckBox.Check(bValue);
    m_aDestPathLabel.Enable(bValue);
    m_aDestPath.Enable(bValue);
    m_aChangePathButton.Enable(bValue);

    rtl::OUString sValue, aPath;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) )
        m_aDestPath.SetText(aPath);

    m_aAutoDownloadCheckBox.SaveValue();
}

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

void SvxOnlineUpdateTabPage::FillUserData()
{
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aEveryDayButton.Enable(bEnabled);
    m_aEveryWeekButton.Enable(bEnabled);
    m_aEveryMonthButton.Enable(bEnabled);

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aDestPathLabel.Enable(bEnabled);
    m_aDestPath.Enable(bEnabled);
    m_aChangePathButton.Enable(bEnabled);

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    uno::Reference < dialogs::XFolderPicker > xFolderPicker(
        xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ),
        uno::UNO_QUERY );

    rtl::OUString aURL;
    if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) )
        osl::Security().getHomeDir(aURL);

    xFolderPicker->setDisplayDirectory( aURL );
    sal_Int16 nRet = xFolderPicker->execute();

    if ( dialogs::ExecutableDialogResults::OK == nRet )
    {
        rtl::OUString aFolder;
        if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder))
            m_aDestPath.SetText( aFolder );
    }

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    try
    {
        uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
            xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )),
            uno::UNO_QUERY_THROW);

        beans::PropertyValue aProperty;
        aProperty.Name  = UNISTRING( "nodepath" );
        aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") );

        uno::Sequence< uno::Any > aArgumentList( 1 );
        aArgumentList[0] = uno::makeAny( aProperty );

        uno::Reference< container::XNameAccess > xNameAccess(
            xConfigProvider->createInstanceWithArguments(
                UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ),
            uno::UNO_QUERY_THROW );

        util::URL aURL;
        xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete;

        uno::Reference < util::XURLTransformer > xTransformer(
            xFactory->createInstance(  UNISTRING( "com.sun.star.util.URLTransformer" ) ),
            uno::UNO_QUERY_THROW );

        xTransformer->parseStrict(aURL);

        uno::Reference < frame::XDesktop > xDesktop(
            xFactory->createInstance(  UNISTRING( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< frame::XDispatchProvider > xDispatchProvider(
            xDesktop->getCurrentFrame(), uno::UNO_QUERY );

        uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0);

        if( xDispatch.is() )
            xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ());

    }
    catch( const uno::Exception& e )
    {
         OSL_TRACE( "Caught exception: %s\n thread terminated.\n",
            rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
    }

    return 0;
}

<commit_msg>INTEGRATION: CWS fwk61 (1.5.124); FILE MERGED 2007/02/09 11:10:49 pb 1.5.124.1: fix: #i70228# dynamical width of push buttons<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optupdt.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: ihi $ $Date: 2007-03-26 12:07:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif

#include "optupdt.hxx"
#include "optupdt.hrc"

#include "dialmgr.hxx"
#include "dialogs.hrc"

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef  _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_XFOLDERPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFolderPicker.hpp>
#endif

#ifndef  _COM_SUN_STAR_UI_DIALOGS_EXECUTABLEDIALOGRESULTS_HPP_
#include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDESKTOP_HPP_
#include <com/sun/star/frame/XDesktop.hpp>
#endif

#ifndef  _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_
#include <com/sun/star/util/XChangesBatch.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif

#include <osl/file.hxx>
#include <osl/security.hxx>

namespace beans = ::com::sun::star::beans;
namespace container = ::com::sun::star::container;
namespace dialogs = ::com::sun::star::ui::dialogs;
namespace frame = ::com::sun::star::frame;
namespace lang = ::com::sun::star::lang;
namespace uno = ::com::sun::star::uno;
namespace util = ::com::sun::star::util;

// define ----------------------------------------------------------------

#define UNISTRING(s) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(s))

// class SvxOnlineUpdateTabPage --------------------------------------------------

SvxOnlineUpdateTabPage::SvxOnlineUpdateTabPage( Window* pParent, const SfxItemSet& rSet ) :

    SfxTabPage( pParent, SVX_RES( RID_SVXPAGE_ONLINEUPDATE ), rSet ),
        m_aOptionsLine( this, ResId( FL_OPTIONS ) ),
        m_aAutoCheckCheckBox( this, ResId( CB_AUTOCHECK ) ),
        m_aEveryDayButton( this, ResId( RB_EVERYDAY ) ),
        m_aEveryWeekButton( this, ResId( RB_EVERYWEEK ) ),
        m_aEveryMonthButton( this, ResId( RB_EVERYMONTH ) ),
        m_aCheckNowButton( this, ResId( PB_CHECKNOW ) ),
        m_aAutoDownloadCheckBox( this, ResId( CB_AUTODOWNLOAD ) ),
        m_aDestPathLabel( this, ResId( FT_DESTPATHLABEL ) ),
        m_aDestPath( this, ResId( FT_DESTPATH ) ),
        m_aChangePathButton( this, ResId( PB_CHANGEPATH ) )
{
    FreeResource();

    m_aAutoCheckCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoCheckHdl_Impl ) );
    m_aCheckNowButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, CheckNowHdl_Impl ) );
    m_aAutoDownloadCheckBox.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl ) );
    m_aChangePathButton.SetClickHdl( LINK( this, SvxOnlineUpdateTabPage, FileDialogHdl_Impl ) );

    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    m_xUpdateAccess = uno::Reference < container::XNameReplace >(
        xFactory->createInstance( UNISTRING( "com.sun.star.setup.UpdateCheckConfig" ) ),
        uno::UNO_QUERY_THROW );

    sal_Bool bDownloadSupported = sal_False;
    m_xUpdateAccess->getByName( UNISTRING( "DownloadSupported") ) >>= bDownloadSupported;

    WinBits nStyle = m_aDestPath.GetStyle();
    nStyle |= WB_PATHELLIPSIS;
    m_aDestPath.SetStyle(nStyle);

    m_aAutoDownloadCheckBox.Show(bDownloadSupported);
    m_aDestPathLabel.Show(bDownloadSupported);
    m_aDestPath.Show(bDownloadSupported);
    m_aChangePathButton.Show(bDownloadSupported);

    // dynamical length of the PushButtons
    CalcButtonWidth();
}

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

SvxOnlineUpdateTabPage::~SvxOnlineUpdateTabPage()
{
}

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

SfxTabPage*
SvxOnlineUpdateTabPage::Create( Window* pParent, const SfxItemSet& rAttrSet )
{
    return new SvxOnlineUpdateTabPage( pParent, rAttrSet );
}

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

BOOL SvxOnlineUpdateTabPage::FillItemSet( SfxItemSet& )
{
    BOOL bModified = FALSE;

    sal_Bool bValue;
    sal_Int64 nValue;

    if( m_aAutoCheckCheckBox.GetSavedValue() != m_aAutoCheckCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoCheckCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoCheckEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    nValue = 0;
    if( TRUE == m_aEveryDayButton.IsChecked() )
    {
        if( FALSE == m_aEveryDayButton.GetSavedValue() )
            nValue = 86400;
    }
    else if( TRUE == m_aEveryWeekButton.IsChecked() )
    {
        if( FALSE == m_aEveryWeekButton.GetSavedValue() )
            nValue = 604800;
    }
    else if( TRUE == m_aEveryMonthButton.IsChecked() )
    {
        if( FALSE == m_aEveryMonthButton.GetSavedValue() )
            nValue = 2592000;
    }

    if( nValue > 0 )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("CheckInterval"), uno::makeAny( nValue ) );
        bModified = TRUE;
    }

    if( m_aAutoDownloadCheckBox.GetSavedValue() != m_aAutoDownloadCheckBox.IsChecked() )
    {
        bValue = (TRUE == m_aAutoDownloadCheckBox.IsChecked());
        m_xUpdateAccess->replaceByName( UNISTRING("AutoDownloadEnabled"), uno::makeAny( bValue ) );
        bModified = TRUE;
    }

    rtl::OUString sValue, aURL;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( ( osl::FileBase::E_None == osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) ) &&
        ( ! aURL.equals( sValue ) ) )
    {
        m_xUpdateAccess->replaceByName( UNISTRING("DownloadDestination"), uno::makeAny( aURL ) );
        bModified = TRUE;
    }

    uno::Reference< util::XChangesBatch > xChangesBatch(m_xUpdateAccess, uno::UNO_QUERY);
    if( xChangesBatch.is() && xChangesBatch->hasPendingChanges() )
        xChangesBatch->commitChanges();

    return bModified;
}

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

void SvxOnlineUpdateTabPage::Reset( const SfxItemSet& )
{
    sal_Bool bValue = sal_Bool();
    m_xUpdateAccess->getByName( UNISTRING("AutoCheckEnabled") ) >>= bValue;

    m_aAutoCheckCheckBox.Check(bValue);
    m_aEveryDayButton.Enable(bValue);
    m_aEveryWeekButton.Enable(bValue);
    m_aEveryMonthButton.Enable(bValue);

    sal_Int64 nValue = 0;
    m_xUpdateAccess->getByName( UNISTRING("CheckInterval") ) >>= nValue;

    if( nValue == 86400 )
        m_aEveryDayButton.Check();
    else if( nValue == 604800 )
        m_aEveryWeekButton.Check();
    else
        m_aEveryMonthButton.Check();

    m_aAutoCheckCheckBox.SaveValue();
    m_aEveryDayButton.SaveValue();
    m_aEveryWeekButton.SaveValue();
    m_aEveryMonthButton.SaveValue();

    m_xUpdateAccess->getByName( UNISTRING("AutoDownloadEnabled") ) >>= bValue;
    m_aAutoDownloadCheckBox.Check(bValue);
    m_aDestPathLabel.Enable(bValue);
    m_aDestPath.Enable(bValue);
    m_aChangePathButton.Enable(bValue);

    rtl::OUString sValue, aPath;
    m_xUpdateAccess->getByName( UNISTRING("DownloadDestination") ) >>= sValue;

    if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sValue, aPath) )
        m_aDestPath.SetText(aPath);

    m_aAutoDownloadCheckBox.SaveValue();
}

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

void SvxOnlineUpdateTabPage::FillUserData()
{
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, AutoCheckHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aEveryDayButton.Enable(bEnabled);
    m_aEveryWeekButton.Enable(bEnabled);
    m_aEveryMonthButton.Enable(bEnabled);

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, AutoDownloadHdl_Impl, CheckBox *, pBox )
{
    BOOL bEnabled = pBox->IsChecked();

    m_aDestPathLabel.Enable(bEnabled);
    m_aDestPath.Enable(bEnabled);
    m_aChangePathButton.Enable(bEnabled);

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, FileDialogHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );
    uno::Reference < dialogs::XFolderPicker > xFolderPicker(
        xFactory->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( FOLDER_PICKER_SERVICE_NAME ) ) ),
        uno::UNO_QUERY );

    rtl::OUString aURL;
    if( osl::FileBase::E_None != osl::FileBase::getFileURLFromSystemPath(m_aDestPath.GetText(), aURL) )
        osl::Security().getHomeDir(aURL);

    xFolderPicker->setDisplayDirectory( aURL );
    sal_Int16 nRet = xFolderPicker->execute();

    if ( dialogs::ExecutableDialogResults::OK == nRet )
    {
        rtl::OUString aFolder;
        if( osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(xFolderPicker->getDirectory(), aFolder))
            m_aDestPath.SetText( aFolder );
    }

    return 0;
}

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

IMPL_LINK( SvxOnlineUpdateTabPage, CheckNowHdl_Impl, PushButton *, EMPTYARG )
{
    uno::Reference < lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() );

    try
    {
        uno::Reference< lang::XMultiServiceFactory > xConfigProvider(
            xFactory->createInstance( UNISTRING( "com.sun.star.configuration.ConfigurationProvider" )),
            uno::UNO_QUERY_THROW);

        beans::PropertyValue aProperty;
        aProperty.Name  = UNISTRING( "nodepath" );
        aProperty.Value = uno::makeAny( UNISTRING("org.openoffice.Office.Addons/AddonUI/OfficeHelp/UpdateCheckJob") );

        uno::Sequence< uno::Any > aArgumentList( 1 );
        aArgumentList[0] = uno::makeAny( aProperty );

        uno::Reference< container::XNameAccess > xNameAccess(
            xConfigProvider->createInstanceWithArguments(
                UNISTRING("com.sun.star.configuration.ConfigurationAccess"), aArgumentList ),
            uno::UNO_QUERY_THROW );

        util::URL aURL;
        xNameAccess->getByName(UNISTRING("URL")) >>= aURL.Complete;

        uno::Reference < util::XURLTransformer > xTransformer(
            xFactory->createInstance(  UNISTRING( "com.sun.star.util.URLTransformer" ) ),
            uno::UNO_QUERY_THROW );

        xTransformer->parseStrict(aURL);

        uno::Reference < frame::XDesktop > xDesktop(
            xFactory->createInstance(  UNISTRING( "com.sun.star.frame.Desktop" ) ),
            uno::UNO_QUERY_THROW );

        uno::Reference< frame::XDispatchProvider > xDispatchProvider(
            xDesktop->getCurrentFrame(), uno::UNO_QUERY );

        uno::Reference< frame::XDispatch > xDispatch = xDispatchProvider->queryDispatch(aURL, rtl::OUString(), 0);

        if( xDispatch.is() )
            xDispatch->dispatch(aURL, uno::Sequence< beans::PropertyValue > ());

    }
    catch( const uno::Exception& e )
    {
         OSL_TRACE( "Caught exception: %s\n thread terminated.\n",
            rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_UTF8).getStr());
    }

    return 0;
}

void SvxOnlineUpdateTabPage::CalcButtonWidth()
{
    // detect the longest button text
    long nTxtWidth = ::std::max( m_aCheckNowButton.GetCtrlTextWidth( m_aCheckNowButton.GetText() ),
                                 m_aCheckNowButton.GetCtrlTextWidth( m_aChangePathButton.GetText() ) );
    // add a little offset
    nTxtWidth = nTxtWidth + 12;
    // compare with the button width
    Size aSize = m_aCheckNowButton.GetSizePixel();
    // and change it if it's necessary
    if ( nTxtWidth > aSize.Width() )
    {
        aSize.Width() = nTxtWidth;
        m_aCheckNowButton.SetSizePixel( aSize );
        m_aChangePathButton.SetSizePixel( aSize );
    }
}

<|endoftext|>


<commit_before>/* $Id$ */
/* Author: Luca Heltai, Wolfgang Bangerth, 2005 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2000, 2004, 2005 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

// Base libraries
#include <base/data_out_base.h>

// C++ libraries
#include <iostream>
#include <fstream>

template <int dim, int spacedim>
void do_convert (const std::vector<std::string> &input_files,
                 const std::string              &output_file,
                 const std::string              &/*parameter_file*/,
                 const std::string              &output_format_extension)
{
  std::ifstream intermediate_stream (input_files[0].c_str());
  AssertThrow (intermediate_stream, ExcIO());

  DataOutReader<dim,spacedim> intermediate_data;
  intermediate_data.read (intermediate_stream);

  std::ofstream output_stream (output_file.c_str());
  AssertThrow (output_stream, ExcIO());

  const typename DataOutInterface<dim,spacedim>::OutputFormat
    output_format
    = intermediate_data.parse_output_format (output_format_extension);

  intermediate_data.write(output_stream, output_format);
}

void convert (const std::vector<std::string> &input_files,
              const std::string              &output_file,
              const std::string              &parameter_file,
              const std::string              &output_format_extension)
{
  std::ifstream input(input_files[0].c_str());
  AssertThrow (input, ExcIO());

  const std::pair<unsigned int, unsigned int>
    dimensions = DataOutBase::determine_intermediate_format_dimensions (input);

  switch (dimensions.first)
    {
      case 1:
            switch (dimensions.second)
              {
                case 1:
                      do_convert <1,1> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;

                case 2:
                      do_convert <1,2> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());

      case 2:
            switch (dimensions.second)
              {
                case 2:
                      do_convert <2,2> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;

                case 3:
                      do_convert <2,3> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());

      case 3:
            switch (dimensions.second)
              {
                case 3:
                      do_convert <3,3> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());
    }

  AssertThrow (false, ExcNotImplemented());
}

int main (int argc, char ** argv)
{
  try
    {
      if (argc == 0)
        {
          std::cout << "Converter from deal.II intermediate format to "
                    << "other graphics formats."
                    << std::endl << std::endl
                    << "Usage: ./step-19 [-p parameter_file] "
                    << "list_of_input_files -x output_format "
                    << "output_file"
                    << std::endl;
          exit (1);
        }

      std::string              parameter_file;
      std::string              output_format_extension;
      std::vector<std::string> file_names;

      for (int i=1; i<argc; ++i)
        {
          if (std::string(argv[i]) == std::string("-p"))
            {
              if (i+1 == argc)
                {
                  std::cerr << "Error: flag '-p' must be followed by the "
                            << "name of a parameter file."
                            << std::endl;
                  exit (1);
                }
              parameter_file = argv[i+1];
              ++i;
            }
          else if (std::string(argv[i]) == std::string("-x"))
            {
              if (i+1 == argc)
                {
                  std::cerr << "Error: flag '-x' must be followed by the "
                            << "name of an output format."
                            << std::endl;
                  exit (1);
                }
              output_format_extension = argv[i+1];
              ++i;
            }
          else
            file_names.push_back (argv[i]);
        }

      if (file_names.size() < 2)
        {
          std::cerr << "Error: No input and/or output files specified."
                    << std::endl;
          exit (1);
        }

      const std::vector<std::string> input_files (file_names.begin(),
                                                  file_names.end()-1);
      const std::string              output_file (file_names.back());

      if (output_format_extension.size() == 0)
        {
          output_format_extension
            = std::string(output_file.begin() + output_file.rfind ('.') + 1,
                          output_file.end());

          if (output_format_extension.size() == 0)
            {
              std::cerr << "Error: could not determine output file format "
                        << "from name of last file name."
                        << std::endl;
              exit (1);
            }
        }

      convert (input_files,
               output_file,
               parameter_file,
               output_format_extension);
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    };

  return 0;
}
<commit_msg>Implement merging files.<commit_after>/* $Id$ */
/* Author: Luca Heltai, Wolfgang Bangerth, 2005 */

/*    $Id$       */
/*    Version: $Name$                                          */
/*                                                                */
/*    Copyright (C) 2005 by the deal.II authors */
/*                                                                */
/*    This file is subject to QPL and may not be  distributed     */
/*    without copyright and license information. Please refer     */
/*    to the file deal.II/doc/license.html for the  text  and     */
/*    further information on this license.                        */

// Base libraries
#include <base/data_out_base.h>

// C++ libraries
#include <iostream>
#include <fstream>

template <int dim, int spacedim>
void do_convert (const std::vector<std::string> &input_files,
                 const std::string              &output_file,
                 const std::string              &/*parameter_file*/,
                 const std::string              &output_format_extension)
{
  std::ifstream intermediate_stream (input_files[0].c_str());
  AssertThrow (intermediate_stream, ExcIO());

  DataOutReader<dim,spacedim> intermediate_data;
  intermediate_data.read (intermediate_stream);

				   // for all following input files
  for (unsigned int i=1; i<input_files.size(); ++i)
    {
      std::ifstream additional_stream (input_files[i].c_str());
      AssertThrow (additional_stream, ExcIO());

      DataOutReader<dim,spacedim> additional_data;
      additional_data.read (additional_stream);
      intermediate_data.merge (additional_data);
    }

  std::ofstream output_stream (output_file.c_str());
  AssertThrow (output_stream, ExcIO());

  const typename DataOutInterface<dim,spacedim>::OutputFormat
    output_format
    = intermediate_data.parse_output_format (output_format_extension);

  intermediate_data.write(output_stream, output_format);
}

void convert (const std::vector<std::string> &input_files,
              const std::string              &output_file,
              const std::string              &parameter_file,
              const std::string              &output_format_extension)
{
  std::ifstream input(input_files[0].c_str());
  AssertThrow (input, ExcIO());

  const std::pair<unsigned int, unsigned int>
    dimensions = DataOutBase::determine_intermediate_format_dimensions (input);

  switch (dimensions.first)
    {
      case 1:
            switch (dimensions.second)
              {
                case 1:
                      do_convert <1,1> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;

                case 2:
                      do_convert <1,2> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());

      case 2:
            switch (dimensions.second)
              {
                case 2:
                      do_convert <2,2> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;

                case 3:
                      do_convert <2,3> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());

      case 3:
            switch (dimensions.second)
              {
                case 3:
                      do_convert <3,3> (input_files,
                                        output_file,
                                        parameter_file,
                                        output_format_extension);
                      return;
              }
            AssertThrow (false, ExcNotImplemented());
    }

  AssertThrow (false, ExcNotImplemented());
}

int main (int argc, char ** argv)
{
  try
    {
      if (argc == 0)
        {
          std::cout << "Converter from deal.II intermediate format to "
                    << "other graphics formats."
                    << std::endl << std::endl
                    << "Usage: ./step-19 [-p parameter_file] "
                    << "list_of_input_files -x output_format "
                    << "output_file"
                    << std::endl;
          exit (1);
        }

      std::string              parameter_file;
      std::string              output_format_extension;
      std::vector<std::string> file_names;

      for (int i=1; i<argc; ++i)
        {
          if (std::string(argv[i]) == std::string("-p"))
            {
              if (i+1 == argc)
                {
                  std::cerr << "Error: flag '-p' must be followed by the "
                            << "name of a parameter file."
                            << std::endl;
                  exit (1);
                }
              parameter_file = argv[i+1];
              ++i;
            }
          else if (std::string(argv[i]) == std::string("-x"))
            {
              if (i+1 == argc)
                {
                  std::cerr << "Error: flag '-x' must be followed by the "
                            << "name of an output format."
                            << std::endl;
                  exit (1);
                }
              output_format_extension = argv[i+1];
              ++i;
            }
          else
            file_names.push_back (argv[i]);
        }

      if (file_names.size() < 2)
        {
          std::cerr << "Error: No input and/or output files specified."
                    << std::endl;
          exit (1);
        }

      const std::vector<std::string> input_files (file_names.begin(),
                                                  file_names.end()-1);
      const std::string              output_file (file_names.back());

      if (output_format_extension.size() == 0)
        {
          output_format_extension
            = std::string(output_file.begin() + output_file.rfind ('.') + 1,
                          output_file.end());

          if (output_format_extension.size() == 0)
            {
              std::cerr << "Error: could not determine output file format "
                        << "from name of last file name."
                        << std::endl;
              exit (1);
            }
        }

      convert (input_files,
               output_file,
               parameter_file,
               output_format_extension);
    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    };

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>coverity#705906 Dereference before null check<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <map>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
// -------------------- little helper
#include "generate_cube.hh"
#include "stats.hh"
#include "fill_props.hh"

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

// Set to 1 to use an PolyMesh type.
#define UsePolyMesh 1

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

using namespace OpenMesh;

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

typedef TriMesh_ArrayKernelT<>  TriMesh;
typedef PolyMesh_ArrayKernelT<> PolyMesh;

#if UsePolyMesh
typedef PolyMesh Mesh;
#else
typedef TriMesh Mesh;
#endif

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

#ifndef DOXY_IGNORE_THIS

struct MyData
{
  int             ival;
  double          dval;
  bool            bval;
  OpenMesh::Vec4f vec4fval;

  MyData()
    : ival(0), dval(0.0), bval(false)
  { }

  MyData( const MyData& _cpy )
    : ival(_cpy.ival), dval(_cpy.dval), bval(_cpy.bval),
      vec4fval(_cpy.vec4fval)
  { }

  // ---------- assignment

  MyData& operator = (const MyData& _rhs)
  {
    ival = _rhs.ival;
    dval = _rhs.dval;
    bval = _rhs.bval;
    vec4fval = _rhs.vec4fval;
    return *this;
  }

  MyData& operator = (int    _rhs) { ival = _rhs; return *this; }
  MyData& operator = (double _rhs) { dval = _rhs; return *this; }
  MyData& operator = (bool   _rhs) { bval = _rhs; return *this; }
  MyData& operator = (const OpenMesh::Vec4f& _rhs)
  { vec4fval = _rhs; return *this; }

  // ---------- comparison

  bool operator == (const MyData& _rhs) const
  {
    return ival == _rhs.ival
      &&   dval == _rhs.dval
      &&   bval == _rhs.bval
      &&   vec4fval == _rhs.vec4fval;
  }

  bool operator != (const MyData& _rhs) const { return !(*this == _rhs); }

};

#endif

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

typedef std::map< std::string, unsigned int > MyMap;

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

#ifndef DOXY_IGNORE_THIS

namespace OpenMesh {
  namespace IO {

    // support persistence for struct MyData

    template <> struct binary<MyData>
    {
      typedef MyData value_type;

      static const bool is_streamable = true;

      // return binary size of the value

      static size_t size_of(void)
      {
        return sizeof(int)+sizeof(double)+sizeof(bool)+sizeof(OpenMesh::Vec4f);
      }

      static size_t size_of(const value_type&)
      {
        return size_of();
      }

      static size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
      {
        size_t bytes;
        bytes  = IO::store( _os, _v.ival, _swap );
        bytes += IO::store( _os, _v.dval, _swap );
        bytes += IO::store( _os, _v.bval, _swap );
        bytes += IO::store( _os, _v.vec4fval, _swap );
        return _os.good() ? bytes : 0;
      }

      static size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
      {
        size_t bytes;
        bytes  = IO::restore( _is, _v.ival, _swap );
        bytes += IO::restore( _is, _v.dval, _swap );
        bytes += IO::restore( _is, _v.bval, _swap );
        bytes += IO::restore( _is, _v.vec4fval, _swap );
        return _is.good() ? bytes : 0;
      }
    };

    template <> struct binary< MyMap >
    {
      typedef MyMap value_type;

      static const bool is_streamable = true;

      // return generic binary size of self, if known
      static size_t size_of(void) { return UnknownSize; }

      // return binary size of the value
      static size_t size_of(const value_type& _v)
      {
        if (_v.empty())
          return sizeof(unsigned int);

        value_type::const_iterator it = _v.begin();
        unsigned int   N     = _v.size();
        size_t         bytes = IO::size_of(N);

        for(;it!=_v.end(); ++it)
        {
          bytes += IO::size_of( it->first );
          bytes += IO::size_of( it->second );
        }
        return bytes;
      }

      static
      size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
      {
        size_t   bytes = 0;
        unsigned int N = _v.size();

        value_type::const_iterator it = _v.begin();

        bytes += IO::store( _os, N, _swap );

        for (; it != _v.end() && _os.good(); ++it)
        {
          bytes += IO::store( _os, it->first, _swap );
          bytes += IO::store( _os, it->second, _swap );
        }
        return _os.good() ? bytes : 0;
      }

      static
      size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
      {
        size_t   bytes = 0;
        unsigned int N = 0;

        _v.clear();

        bytes += IO::restore( _is, N, _swap );

        std::string key;
        size_t      val;

        for (size_t i=0; i<N && _is.good(); ++i)
        {
          bytes += IO::restore( _is, key, _swap );
          bytes += IO::restore( _is, val, _swap );
          _v[key] = val;
        }
        return _is.good() ? bytes : 0;
      }
    };

  }
}

#endif

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

int main(void)
{
  //
  Mesh mesh;

  // generate a geometry
  generate_cube<Mesh>(mesh);

  // should display 8 vertices, 18/12 edges, 12/6 faces (Tri/Poly)
  mesh_stats(mesh);

  // print out information about properties
  mesh_property_stats(mesh);

  std::cout << "Define some custom properties..\n";

  OpenMesh::VPropHandleT<float>       vprop_float;
  OpenMesh::EPropHandleT<bool>        eprop_bool;
  OpenMesh::FPropHandleT<std::string> fprop_string;
  OpenMesh::HPropHandleT<MyData>      hprop_mydata;
  OpenMesh::MPropHandleT<MyMap>       mprop_map;

  std::cout << ".. and registrate them at the mesh object.\n";

  mesh.add_property(vprop_float,  "vprop_float");
  mesh.add_property(eprop_bool,   "eprop_bool");
  mesh.add_property(fprop_string, "fprop_string");
  mesh.add_property(hprop_mydata, "hprop_mydata");
  mesh.add_property(mprop_map,    "mprop_map");

  mesh_property_stats(mesh);

  std::cout << "Now let's fill the props..\n";

  fill_props(mesh, vprop_float);
  fill_props(mesh, eprop_bool);
  fill_props(mesh, fprop_string);
  fill_props(mesh, hprop_mydata);
  fill_props(mesh, mprop_map);

  std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
  std::cout << "  " << #PH << " " \
            << (fill_props(mesh, PH, true)?"ok\n":"error\n")

  CHK_PROP(vprop_float);
  CHK_PROP(eprop_bool);
  CHK_PROP(fprop_string);
  CHK_PROP(hprop_mydata);
  CHK_PROP(mprop_map);
#undef CHK_PROP

  std::cout << "Set persistent flag..\n";
#define SET_PERS( PH ) \
    mesh.property(PH).set_persistent(true); \
    std::cout << "  " << #PH << " " \
              << (mesh.property(PH).persistent()?"ok\n":"failed!\n")

  mesh.property(vprop_float).set_persistent(true);
  std::cout << "  vprop_float "
            << (mesh.property(vprop_float).persistent()?"ok\n":"failed!\n");

  SET_PERS( eprop_bool );
  SET_PERS( fprop_string );
  SET_PERS( hprop_mydata );
  mesh.mproperty(mprop_map).set_persistent(true);
  std::cout << "  mprop_map "
            << (mesh.mproperty(mprop_map).persistent()?"ok\n":"failed!\n");

  std::cout << "Write mesh..";
  if (IO::write_mesh( mesh, "persistence-check.om" ))
    std::cout << "  ok\n";
  else
  {
    std::cout << "  failed\n";
    return 1;
  }

  std::cout << "Clear mesh\n";
  mesh.clear();
  mesh_stats(mesh, "  ");

  std::cout << "Read back mesh..";
  try
  {
    if (IO::read_mesh( mesh, "persistence-check.om" ))
      std::cout << "  ok\n";
    else
    {
      std::cout << "  failed!\n";
      return 1;
    }
    mesh_stats(mesh, "  ");
  }
  catch( std::exception &x )
  {
    std::cerr << x.what() << std::endl;
    return 1;
  }

  std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
  std::cout << "  " << #PH << " " \
            << (fill_props(mesh, PH, true)?"ok\n":"error\n")
  CHK_PROP(vprop_float);
  CHK_PROP(eprop_bool);
  CHK_PROP(fprop_string);
  CHK_PROP(hprop_mydata);
  CHK_PROP(mprop_map);
#undef CHK_PROP

  return 0;
}

// end of file
// ============================================================================
<commit_msg>update tutorial<commit_after>#include <iostream>
#include <string>
#include <map>
// -------------------- OpenMesh
#include <OpenMesh/Core/IO/MeshIO.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
// -------------------- little helper
#include "generate_cube.hh"
#include "stats.hh"
#include "fill_props.hh"

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

// Set to 1 to use an PolyMesh type.
#define UsePolyMesh 1

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

using namespace OpenMesh;

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

typedef TriMesh_ArrayKernelT<>  TriMesh;
typedef PolyMesh_ArrayKernelT<> PolyMesh;

#if UsePolyMesh
typedef PolyMesh Mesh;
#else
typedef TriMesh Mesh;
#endif

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

#ifndef DOXY_IGNORE_THIS

struct MyData
{
  int             ival;
  double          dval;
  bool            bval;
  OpenMesh::Vec4f vec4fval;

  MyData()
    : ival(0), dval(0.0), bval(false)
  { }

  MyData( const MyData& _cpy )
    : ival(_cpy.ival), dval(_cpy.dval), bval(_cpy.bval),
      vec4fval(_cpy.vec4fval)
  { }

  // ---------- assignment

  MyData& operator = (const MyData& _rhs)
  {
    ival = _rhs.ival;
    dval = _rhs.dval;
    bval = _rhs.bval;
    vec4fval = _rhs.vec4fval;
    return *this;
  }

  MyData& operator = (int    _rhs) { ival = _rhs; return *this; }
  MyData& operator = (double _rhs) { dval = _rhs; return *this; }
  MyData& operator = (bool   _rhs) { bval = _rhs; return *this; }
  MyData& operator = (const OpenMesh::Vec4f& _rhs)
  { vec4fval = _rhs; return *this; }

  // ---------- comparison

  bool operator == (const MyData& _rhs) const
  {
    return ival == _rhs.ival
      &&   dval == _rhs.dval
      &&   bval == _rhs.bval
      &&   vec4fval == _rhs.vec4fval;
  }

  bool operator != (const MyData& _rhs) const { return !(*this == _rhs); }

};

#endif

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

typedef std::map< std::string, unsigned int > MyMap;

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

#ifndef DOXY_IGNORE_THIS

namespace OpenMesh {
  namespace IO {

    // support persistence for struct MyData

    template <> struct binary<MyData>
    {
      typedef MyData value_type;

      static const bool is_streamable = true;

      // return binary size of the value

      static size_t size_of(void)
      {
        return sizeof(int)+sizeof(double)+sizeof(bool)+sizeof(OpenMesh::Vec4f);
      }

      static size_t size_of(const value_type&)
      {
        return size_of();
      }

      static size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
      {
        size_t bytes;
        bytes  = IO::store( _os, _v.ival, _swap );
        bytes += IO::store( _os, _v.dval, _swap );
        bytes += IO::store( _os, _v.bval, _swap );
        bytes += IO::store( _os, _v.vec4fval, _swap );
        return _os.good() ? bytes : 0;
      }

      static size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
      {
        size_t bytes;
        bytes  = IO::restore( _is, _v.ival, _swap );
        bytes += IO::restore( _is, _v.dval, _swap );
        bytes += IO::restore( _is, _v.bval, _swap );
        bytes += IO::restore( _is, _v.vec4fval, _swap );
        return _is.good() ? bytes : 0;
      }
    };

    template <> struct binary< MyMap >
    {
      typedef MyMap value_type;

      static const bool is_streamable = true;

      // return generic binary size of self, if known
      static size_t size_of(void) { return UnknownSize; }

      // return binary size of the value
      static size_t size_of(const value_type& _v)
      {
        if (_v.empty())
          return sizeof(unsigned int);

        value_type::const_iterator it = _v.begin();
        unsigned int   N     = _v.size();
        size_t         bytes = IO::size_of(N);

        for(;it!=_v.end(); ++it)
        {
          bytes += IO::size_of( it->first );
          bytes += IO::size_of( it->second );
        }
        return bytes;
      }

      static
      size_t store(std::ostream& _os, const value_type& _v, bool _swap=false)
      {
        size_t   bytes = 0;
        unsigned int N = _v.size();

        value_type::const_iterator it = _v.begin();

        bytes += IO::store( _os, N, _swap );

        for (; it != _v.end() && _os.good(); ++it)
        {
          bytes += IO::store( _os, it->first, _swap );
          bytes += IO::store( _os, it->second, _swap );
        }
        return _os.good() ? bytes : 0;
      }

      static
      size_t restore( std::istream& _is, value_type& _v, bool _swap=false)
      {
        size_t   bytes = 0;
        unsigned int N = 0;

        _v.clear();

        bytes += IO::restore( _is, N, _swap );
        value_type::key_type key;
        value_type::mapped_type  val;

        for (size_t i=0; i<N && _is.good(); ++i)
        {
          bytes += IO::restore( _is, key, _swap );
          bytes += IO::restore( _is, val, _swap );
          _v[key] = val;
        }
        return _is.good() ? bytes : 0;
      }
    };

  }
}

#endif

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

int main(void)
{
  //
  Mesh mesh;

  // generate a geometry
  generate_cube<Mesh>(mesh);

  // should display 8 vertices, 18/12 edges, 12/6 faces (Tri/Poly)
  mesh_stats(mesh);

  // print out information about properties
  mesh_property_stats(mesh);

  std::cout << "Define some custom properties..\n";

  OpenMesh::VPropHandleT<float>       vprop_float;
  OpenMesh::EPropHandleT<bool>        eprop_bool;
  OpenMesh::FPropHandleT<std::string> fprop_string;
  OpenMesh::HPropHandleT<MyData>      hprop_mydata;
  OpenMesh::MPropHandleT<MyMap>       mprop_map;

  std::cout << ".. and registrate them at the mesh object.\n";

  mesh.add_property(vprop_float,  "vprop_float");
  mesh.add_property(eprop_bool,   "eprop_bool");
  mesh.add_property(fprop_string, "fprop_string");
  mesh.add_property(hprop_mydata, "hprop_mydata");
  mesh.add_property(mprop_map,    "mprop_map");

  mesh_property_stats(mesh);

  std::cout << "Now let's fill the props..\n";

  fill_props(mesh, vprop_float);
  fill_props(mesh, eprop_bool);
  fill_props(mesh, fprop_string);
  fill_props(mesh, hprop_mydata);
  fill_props(mesh, mprop_map);

  std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
  std::cout << "  " << #PH << " " \
            << (fill_props(mesh, PH, true)?"ok\n":"error\n")

  CHK_PROP(vprop_float);
  CHK_PROP(eprop_bool);
  CHK_PROP(fprop_string);
  CHK_PROP(hprop_mydata);
  CHK_PROP(mprop_map);
#undef CHK_PROP

  std::cout << "Set persistent flag..\n";
#define SET_PERS( PH ) \
    mesh.property(PH).set_persistent(true); \
    std::cout << "  " << #PH << " " \
              << (mesh.property(PH).persistent()?"ok\n":"failed!\n")

  mesh.property(vprop_float).set_persistent(true);
  std::cout << "  vprop_float "
            << (mesh.property(vprop_float).persistent()?"ok\n":"failed!\n");

  SET_PERS( eprop_bool );
  SET_PERS( fprop_string );
  SET_PERS( hprop_mydata );
  mesh.mproperty(mprop_map).set_persistent(true);
  std::cout << "  mprop_map "
            << (mesh.mproperty(mprop_map).persistent()?"ok\n":"failed!\n");

  std::cout << "Write mesh..";
  if (IO::write_mesh( mesh, "persistence-check.om" ))
    std::cout << "  ok\n";
  else
  {
    std::cout << "  failed\n";
    return 1;
  }

  std::cout << "Clear mesh\n";
  mesh.clear();
  mesh_stats(mesh, "  ");

  std::cout << "Read back mesh..";
  try
  {
    if (IO::read_mesh( mesh, "persistence-check.om" ))
      std::cout << "  ok\n";
    else
    {
      std::cout << "  failed!\n";
      return 1;
    }
    mesh_stats(mesh, "  ");
  }
  catch( std::exception &x )
  {
    std::cerr << x.what() << std::endl;
    return 1;
  }

  std::cout << "Check props..\n";
#define CHK_PROP( PH ) \
  std::cout << "  " << #PH << " " \
            << (fill_props(mesh, PH, true)?"ok\n":"error\n")
  CHK_PROP(vprop_float);
  CHK_PROP(eprop_bool);
  CHK_PROP(fprop_string);
  CHK_PROP(hprop_mydata);
  CHK_PROP(mprop_map);
#undef CHK_PROP

  return 0;
}

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


<commit_before>#pragma once

#include <cstdint>
#include <cstddef>

#include <config.h>
#include <util/PageManager.hpp>
#include <util/Scan.hpp>

#include "deltamain/Record.hpp"
#include "deltamain/InsertMap.hpp"

#include <crossbow/allocator.hpp>

namespace tell {
namespace store {

class CuckooTable;
class Modifier;

namespace deltamain {

/**
 * Contains the functionality for garbagabe collection and scan of a memory
 * page in row format (with RowStorePage::Iterator).
 * In case of garbage collection, the page object should only be constructed
 * once for the first page and for all subsequent steps, the reset(.) method
 * should be called. This is important to keep state accross pages.
 */
class RowStorePage {
    PageManager& mPageManager;
    char* mData;
    uint64_t mSize;             //size (used memory) of current page (first 8 bits of data)
    uint64_t mStartOffset;      //offset in current page where gc proceeds
    char* mFillPage;            //page to copy to
    uint64_t mFillOffset;       //offset in fillpage to copy to next

private:

    /**
     * construct new fill page if needed
     */
    void constructFillPage()
    {
        if (!mFillPage)
        {
            mFillPage = reinterpret_cast<char*>(mPageManager.alloc());
            mFillOffset = 8;
        }
    }

    void markCurrentForDeletion() {
        auto oldPage = mData;
        auto& pageManager = mPageManager;
        crossbow::allocator::invoke([oldPage, &pageManager]() { pageManager.free(oldPage); });
    }

public:
    class Iterator {
        friend class RowStorePage;
    private:
        const char* current;
        Iterator(const char* current) : current(current) {}
    public:
        Iterator() {}
        Iterator(const Iterator&) = default;
        Iterator& operator=(const Iterator&) = default;
    public:
        Iterator& operator++();
        Iterator operator++(int);
        bool operator==(const Iterator& other) const;
        bool operator!=(const Iterator& other) const {
            return !(*this == other);
        }
        const char* operator*() const;
    };

    RowStorePage(PageManager& pageManager, char* data, Table *table = nullptr)
        : mPageManager(pageManager)
        , mData(data)
        , mSize(uint64_t(*reinterpret_cast<const uint64_t*>(data)))
        , mStartOffset(8)
        , mFillPage(nullptr)
        , mFillOffset(0) {}

    void reset(char *data)
    {
        mData = data;
        mStartOffset = 8;
        mSize = uint64_t(*reinterpret_cast<const uint64_t*>(data));
    }

    /**
     * Performs a gc step on this page and copies data to a new page.
     * This call either ends when there are
     * (a) no changes to be done (done is set to true and result is set to current page) --> store page in page list, call reset() with address of next page, followed by gc ()
     * (b) no records to copy anymore (done is set to true and result is set to nullptr otherwise) --> call reset() with the address of the next page, followed by gc()
     * (c) new page is full (done is set to false and result is set to new page) --> store new page in page list and call gc() again
     */
    char* gc(uint64_t lowestActiveVersion, InsertMap& insertMap, bool& done, Modifier& hashTable);

    /**
     * fills inserts (from the insertmap) into a new page.
     * Returns the address of that page such that it can be stored.
     */
    char *fillWithInserts(uint64_t lowestActiveVersion, InsertMap& insertMap, Modifier& hashTable);

    Iterator begin() const;
    Iterator end() const;
};

} // namespace deltamain
} // namespace store
} // namespace tell
<commit_msg>Fix Segfault in Garbage Collection<commit_after>#pragma once

#include <cstdint>
#include <cstddef>

#include <config.h>
#include <util/PageManager.hpp>
#include <util/Scan.hpp>

#include "deltamain/Record.hpp"
#include "deltamain/InsertMap.hpp"

#include <crossbow/allocator.hpp>

namespace tell {
namespace store {

class CuckooTable;
class Modifier;

namespace deltamain {

/**
 * Contains the functionality for garbagabe collection and scan of a memory
 * page in row format (with RowStorePage::Iterator).
 * In case of garbage collection, the page object should only be constructed
 * once for the first page and for all subsequent steps, the reset(.) method
 * should be called. This is important to keep state accross pages.
 */
class RowStorePage {
    PageManager& mPageManager;
    char* mData;
    uint64_t mSize;             //size (used memory) of current page (first 8 bits of data)
    uint64_t mStartOffset;      //offset in current page where gc proceeds
    char* mFillPage;            //page to copy to
    uint64_t mFillOffset;       //offset in fillpage to copy to next

private:

    /**
     * construct new fill page if needed
     */
    void constructFillPage()
    {
        if (!mFillPage)
        {
            mFillPage = reinterpret_cast<char*>(mPageManager.alloc());
            mFillOffset = 8;
        }
    }

    void markCurrentForDeletion() {
        auto oldPage = mData;
        auto& pageManager = mPageManager;
        crossbow::allocator::invoke([oldPage, &pageManager]() { pageManager.free(oldPage); });
    }

public:
    class Iterator {
        friend class RowStorePage;
    private:
        const char* current;
        Iterator(const char* current) : current(current) {}
    public:
        Iterator() {}
        Iterator(const Iterator&) = default;
        Iterator& operator=(const Iterator&) = default;
    public:
        Iterator& operator++();
        Iterator operator++(int);
        bool operator==(const Iterator& other) const;
        bool operator!=(const Iterator& other) const {
            return !(*this == other);
        }
        const char* operator*() const;
    };

    RowStorePage(PageManager& pageManager, char* data, Table *table = nullptr)
        : mPageManager(pageManager)
        , mData(data)
        , mSize(data ? *reinterpret_cast<const uint64_t*>(data) : 0u)
        , mStartOffset(8)
        , mFillPage(nullptr)
        , mFillOffset(0) {}

    void reset(char *data)
    {
        mData = data;
        mStartOffset = 8;
        mSize = uint64_t(*reinterpret_cast<const uint64_t*>(data));
    }

    /**
     * Performs a gc step on this page and copies data to a new page.
     * This call either ends when there are
     * (a) no changes to be done (done is set to true and result is set to current page) --> store page in page list, call reset() with address of next page, followed by gc ()
     * (b) no records to copy anymore (done is set to true and result is set to nullptr otherwise) --> call reset() with the address of the next page, followed by gc()
     * (c) new page is full (done is set to false and result is set to new page) --> store new page in page list and call gc() again
     */
    char* gc(uint64_t lowestActiveVersion, InsertMap& insertMap, bool& done, Modifier& hashTable);

    /**
     * fills inserts (from the insertmap) into a new page.
     * Returns the address of that page such that it can be stored.
     */
    char *fillWithInserts(uint64_t lowestActiveVersion, InsertMap& insertMap, Modifier& hashTable);

    Iterator begin() const;
    Iterator end() const;
};

} // namespace deltamain
} // namespace store
} // namespace tell
<|endoftext|>


<commit_before>#include <Timing/TimerManager.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
#include <DoremiEngine/Logging/Include/LoggingModule.hpp>
#include <DoremiEngine/Logging/Include/SubmoduleManager.hpp>
#include <DoremiEngine/Logging/Include/Logger/Logger.hpp>

#include <algorithm>
#include <vector>

namespace Doremi
{
    namespace Core
    {
        using namespace Doremi::Utilities::Chrono;

        TimerManager::TimerManager() {}

        TimerManager::~TimerManager() {}

        TimerManager& TimerManager::GetInstance()
        {
            static TimerManager timerManager;
            return timerManager;
        }

        const TimerData* const TimerManager::StartTimer(const std::string& p_file, const std::string& p_function, const uint32_t& p_lineNumber)
        {
            // See if timer exists
            auto& timer = m_timers.find(TimerKey(p_file, p_function, p_lineNumber));
            if(timer != m_timers.end())
            {
                //// Timer exists
                timer->second.timer.Tick();
                return &timer->second;
            }
            else
            {
                //// Timer does not exist
                // Create new timer
                auto& tTimer = m_timers.emplace(TimerKey(p_file, p_function, p_lineNumber), TimerData(p_lineNumber)).first->second;
                tTimer.timer.Tick();
                return &tTimer;
            }
        }

        void TimerManager::StopTimer(const TimerData* const p_timer)
        {
            TimerData* timer = const_cast<TimerData*>(p_timer);
            timer->data += timer->timer.Tick().GetElapsedTimeInSeconds();
        }

        void TimerManager::StartTimer(const std::string& p_name)
        {
            const auto& timer = m_namedTimers.find(p_name);
            if(timer != m_namedTimers.end())
            {
                //// Already exists
                timer->second.timer.Tick();
            }
            else
            {
                //// Does not already exist
                const auto& tTimer = m_namedTimers.emplace(p_name, TimerData(0));
                tTimer.first->second.timer.Tick();
            }
        }

        void TimerManager::StopTimer(const std::string& p_name)
        {
            const auto& timer = m_namedTimers.find(p_name);
            if(timer != m_namedTimers.end())
            {
                //// Already exists
                timer->second.data += timer->second.timer.Tick().GetElapsedTimeInSeconds();
            }
            else
            {
                const std::string message("Timer with name '" + p_name + "' does not exist.");
                throw std::exception(message.c_str());
            }
        }

        bool sortTimerData(const std::pair<TimerKey, TimerData>& lhs, const std::pair<TimerKey, TimerData>& rhs)
        {
            if(lhs.first.file < rhs.first.file)
            {
                return true;
            }
            else if(rhs.first.file < lhs.first.file)
            {
                return false;
            }
            else
            {
                if(rhs.first.file < lhs.first.file)
                {
                    return true;
                }
                else if(lhs.first.file < rhs.first.file)
                {
                    return false;
                }
                else
                {
                    if(rhs.second.startLine < lhs.second.startLine)
                    {
                        return true;
                    }
                    else if(lhs.second.startLine < rhs.second.startLine)
                    {
                        return false;
                    }
                }
            }
        }

        void TimerManager::DumpData(const DoremiEngine::Core::SharedContext& p_sharedContext)
        {
            std::vector<std::pair<TimerKey, TimerData>> vectorEntries;
            vectorEntries.reserve(m_timers.size());
            for(const auto& entry : m_timers)
            {
                vectorEntries.push_back(std::pair<TimerKey, TimerData>(entry.first, entry.second));
            }

            std::sort(vectorEntries.begin(), vectorEntries.end(), sortTimerData);

            using namespace Doremi::Utilities::Logging;
            auto& logger = p_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger();
            for(const auto& i : vectorEntries)
            {
                logger.LogText(LogTag::TIMER, LogLevel::MASS_DATA_PRINT, "%s:%s:%d, %f ", i.first.file.c_str(), i.first.function.c_str(),
                               i.second.startLine, i.second.data);
            }

            for(const auto& i : m_namedTimers)
            {
                logger.LogText(LogTag::TIMER, LogLevel::MASS_DATA_PRINT, "%s, %f ", i.first.c_str(), i.second.data);
            }
        }
    }
}<commit_msg>Dumping timedata to standard out aswell<commit_after>#include <Timing/TimerManager.hpp>
#include <DoremiEngine/Core/Include/SharedContext.hpp>
#include <DoremiEngine/Logging/Include/LoggingModule.hpp>
#include <DoremiEngine/Logging/Include/SubmoduleManager.hpp>
#include <DoremiEngine/Logging/Include/Logger/Logger.hpp>

#include <algorithm>
#include <vector>

namespace Doremi
{
    namespace Core
    {
        using namespace Doremi::Utilities::Chrono;

        TimerManager::TimerManager() {}

        TimerManager::~TimerManager() {}

        TimerManager& TimerManager::GetInstance()
        {
            static TimerManager timerManager;
            return timerManager;
        }

        const TimerData* const TimerManager::StartTimer(const std::string& p_file, const std::string& p_function, const uint32_t& p_lineNumber)
        {
            // See if timer exists
            auto& timer = m_timers.find(TimerKey(p_file, p_function, p_lineNumber));
            if(timer != m_timers.end())
            {
                //// Timer exists
                timer->second.timer.Tick();
                return &timer->second;
            }
            else
            {
                //// Timer does not exist
                // Create new timer
                auto& tTimer = m_timers.emplace(TimerKey(p_file, p_function, p_lineNumber), TimerData(p_lineNumber)).first->second;
                tTimer.timer.Tick();
                return &tTimer;
            }
        }

        void TimerManager::StopTimer(const TimerData* const p_timer)
        {
            TimerData* timer = const_cast<TimerData*>(p_timer);
            timer->data += timer->timer.Tick().GetElapsedTimeInSeconds();
        }

        void TimerManager::StartTimer(const std::string& p_name)
        {
            const auto& timer = m_namedTimers.find(p_name);
            if(timer != m_namedTimers.end())
            {
                //// Already exists
                timer->second.timer.Tick();
            }
            else
            {
                //// Does not already exist
                const auto& tTimer = m_namedTimers.emplace(p_name, TimerData(0));
                tTimer.first->second.timer.Tick();
            }
        }

        void TimerManager::StopTimer(const std::string& p_name)
        {
            const auto& timer = m_namedTimers.find(p_name);
            if(timer != m_namedTimers.end())
            {
                //// Already exists
                timer->second.data += timer->second.timer.Tick().GetElapsedTimeInSeconds();
            }
            else
            {
                const std::string message("Timer with name '" + p_name + "' does not exist.");
                throw std::exception(message.c_str());
            }
        }

        bool sortTimerData(const std::pair<TimerKey, TimerData>& lhs, const std::pair<TimerKey, TimerData>& rhs)
        {
            if(lhs.first.file < rhs.first.file)
            {
                return true;
            }
            else if(rhs.first.file < lhs.first.file)
            {
                return false;
            }
            else
            {
                if(rhs.first.file < lhs.first.file)
                {
                    return true;
                }
                else if(lhs.first.file < rhs.first.file)
                {
                    return false;
                }
                else
                {
                    if(rhs.second.startLine < lhs.second.startLine)
                    {
                        return true;
                    }
                    else if(lhs.second.startLine < rhs.second.startLine)
                    {
                        return false;
                    }
                }
            }
        }

        void TimerManager::DumpData(const DoremiEngine::Core::SharedContext& p_sharedContext)
        {
            printf("Dumping data.\n");
            std::vector<std::pair<TimerKey, TimerData>> vectorEntries;
            vectorEntries.reserve(m_timers.size());
            for(const auto& entry : m_timers)
            {
                vectorEntries.push_back(std::pair<TimerKey, TimerData>(entry.first, entry.second));
            }

            std::sort(vectorEntries.begin(), vectorEntries.end(), sortTimerData);

            using namespace Doremi::Utilities::Logging;
            auto& logger = p_sharedContext.GetLoggingModule().GetSubModuleManager().GetLogger();
            for(const auto& i : vectorEntries)
            {
                logger.LogText(LogTag::TIMER, LogLevel::MASS_DATA_PRINT, "%s:%s:%d, %f", i.first.file.c_str(), i.first.function.c_str(),
                               i.second.startLine, i.second.data);
                printf("%s:%s:%d, %f\n", i.first.file.c_str(), i.first.function.c_str(), i.second.startLine, i.second.data);
            }

            for(const auto& i : m_namedTimers)
            {
                logger.LogText(LogTag::TIMER, LogLevel::MASS_DATA_PRINT, "%s, %f", i.first.c_str(), i.second.data);
                printf("%s, %f\n", i.first.c_str(), i.second.data);
            }
        }
    }
}<|endoftext|>


<commit_before><commit_msg>coverity#707380 Uncaught exception<commit_after><|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
				std::cout << stderr << " Open shared lib failed " << pLib->GetName() << " " << error << std::endl;
                assert(0);
                return false;
            }
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<commit_msg>add loading DLL error in windows platform<commit_after>// -------------------------------------------------------------------------
//    @FileName      :    NFCPluginManager.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCPluginManager
//
// -------------------------------------------------------------------------

//#include "stdafx.h"
#include "NFCPluginManager.h"
#include "NFComm/RapidXML/rapidxml.hpp"
#include "NFComm/RapidXML/rapidxml_iterators.hpp"
#include "NFComm/RapidXML/rapidxml_print.hpp"
#include "NFComm/RapidXML/rapidxml_utils.hpp"
#include "NFComm/NFPluginModule/NFIPlugin.h"
#include "NFComm/NFPluginModule/NFIActorDataModule.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#pragma comment( lib, "ws2_32.lib" )

#ifdef NF_DEBUG_MODE

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron_d.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron_d.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron_d.a" )
#endif

#else

#if NF_PLATFORM == NF_PLATFORM_WIN
#pragma comment( lib, "Theron.lib" )
#elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID
#pragma comment( lib, "Theron.a" )
#elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS
#pragma comment( lib, "Theron.a" )
#endif

#endif

bool NFCPluginManager::LoadPlugin()
{
    rapidxml::file<> fdoc( "Plugin.xml" );
    rapidxml::xml_document<>  doc;
    doc.parse<0>( fdoc.data() );

    rapidxml::xml_node<>* pRoot = doc.first_node();
    for ( rapidxml::xml_node<>* pPluginNode = pRoot->first_node("Plugin"); pPluginNode; pPluginNode = pPluginNode->next_sibling("Plugin") )
    {
        const char* strPluginName = pPluginNode->first_attribute( "Name" )->value();
        const char* strMain = pPluginNode->first_attribute( "Main" )->value();

		mPluginNameMap.insert(PluginNameMap::value_type(strPluginName, true));

    }

    rapidxml::xml_node<>* pPluginAppNode = pRoot->first_node("APPID");
    if (!pPluginAppNode)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    const char* strAppID = pPluginAppNode->first_attribute( "Name" )->value();
    if (!strAppID)
    {
        NFASSERT(0, "There are no App ID", __FILE__, __FUNCTION__);
        return false;
    }

    if (!NF_StrTo(strAppID, mnAppID))
    {
        NFASSERT(0, "App ID Convert Error", __FILE__, __FUNCTION__);
        return false;
    }

    return true;
}

void NFCPluginManager::Registered(NFIPlugin* plugin)
{
    std::string strPluginName = plugin->GetPluginName();
    if (!FindPlugin(strPluginName))
    {
        bool bFind = false;
        PluginNameMap::iterator it = mPluginNameMap.begin();
        for (it; it != mPluginNameMap.end(); ++it)
        {
            if (strPluginName == it->first)
            {
                bFind = true;
                break;
            }
        }

        if (bFind)
        {
            mPluginInstanceMap.insert(PluginInstanceMap::value_type(strPluginName, plugin));
            plugin->Install();
        }
    }

}

void NFCPluginManager::UnsRegistered(NFIPlugin* plugin)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(plugin->GetPluginName());
    if (it != mPluginInstanceMap.end())
    {
        it->second->Uninstall();
		delete it->second;
        it->second = NULL;
        mPluginInstanceMap.erase(it);
    }
}

NFIPlugin* NFCPluginManager::FindPlugin(const std::string& strPluginName)
{
    PluginInstanceMap::iterator it = mPluginInstanceMap.find(strPluginName);
    if (it != mPluginInstanceMap.end())
    {
        return it->second;
    }

    return NULL;
}

bool NFCPluginManager::Execute(const float fLasFrametime, const float fStartedTime)
{
    bool bRet = true;

    PluginInstanceMap::iterator it = mPluginInstanceMap.begin();
    for (; it != mPluginInstanceMap.end(); ++it)
    {
        bool tembRet = it->second->Execute(fLasFrametime, fStartedTime);
        bRet = bRet && tembRet;
    }

	ExecuteEvent();

    return bRet;
}

void NFCPluginManager::AddModule(const std::string& strModuleName, NFILogicModule* pModule)
{
    if (!FindModule(strModuleName))
    {
        mModuleInstanceMap.insert(ModuleInstanceMap::value_type(strModuleName, pModule));
    }
}

void NFCPluginManager::RemoveModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        mModuleInstanceMap.erase(it);
    }
}

NFILogicModule* NFCPluginManager::FindModule(const std::string& strModuleName)
{
    ModuleInstanceMap::iterator it = mModuleInstanceMap.find(strModuleName);
    if (it != mModuleInstanceMap.end())
    {
        return it->second;
    }
    return NULL;
}

bool NFCPluginManager::Init()
{
#ifdef NF_DYNAMIC_PLUGIN
    LoadPlugin();

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); ++it)
    {
        LoadPluginLibrary(it->first);
    }

#endif

#else
    //     PluginNameList::iterator it = mPluginNameList.begin();
    //     for (it; it != mPluginNameList.end(); it++)
    //     {
    //         const std::string& strPluginName = *it;
    //         CREATE_PLUGIN( this, strPluginName );
    //     }

    //     CREATE_PLUGIN(this, NFKernelPlugin)
    //     CREATE_PLUGIN(this, NFEventProcessPlugin)
    //     CREATE_PLUGIN(this, NFConfigPlugin)

#endif

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); itInstance++)
    {
        itInstance->second->Init();
    }

    return true;
}

bool NFCPluginManager::AfterInit()
{
    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for (itAfterInstance; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++)
    {
        itAfterInstance->second->AfterInit();
    }

    return true;
}

bool NFCPluginManager::CheckConfig()
{
    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

bool NFCPluginManager::BeforeShut()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for (itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++)
    {
        itBeforeInstance->second->BeforeShut();
    }

    return true;
}

bool NFCPluginManager::Shut()
{

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for (itInstance; itInstance != mPluginInstanceMap.end(); ++itInstance)
    {
        itInstance->second->Shut();
    }

#ifdef NF_DYNAMIC_PLUGIN

    PluginNameMap::iterator it = mPluginNameMap.begin();
    for (it; it != mPluginNameMap.end(); it++)
    {
        UnLoadPluginLibrary(it->first);
    }

#else

    //     DESTROY_PLUGIN(this, NFConfigPlugin)
    //     DESTROY_PLUGIN(this, NFEventProcessPlugin)
    //     DESTROY_PLUGIN(this, NFKernelPlugin)

#endif
	mPluginInstanceMap.clear();
    mPluginNameMap.clear();
	return true;
}

bool NFCPluginManager::LoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it == mPluginLibMap.end())
    {
        NFCDynLib* pLib = new NFCDynLib(strPluginDLLName);
        bool bLoad = pLib->Load();

        if (bLoad)
        {
            mPluginLibMap.insert(PluginLibMap::value_type(strPluginDLLName, pLib));

            DLL_START_PLUGIN_FUNC pFunc = (DLL_START_PLUGIN_FUNC)pLib->GetSymbol("DllStartPlugin");
            if (!pFunc)
            {
                std::cout << "Find function DllStartPlugin Failed in [" << pLib->GetName() << "]" << std::endl;
                assert(0);
                return false;
            }

            pFunc(this);

            return true;
        }
        else
        {
#if NF_PLATFORM == NF_PLATFORM_LINUX
            char* error = dlerror();
            if (error)
            {
				std::cout << stderr << " Open shared lib failed " << pLib->GetName() << " " << error << std::endl;
                assert(0);
                return false;
            }
#elif NF_PLATFORM == NF_PLATFORM_WIN
            std::cout << stderr << " Open DLL " << pLib->GetName() << " failed, ErrorNo = "<< GetLastError();
#endif // NF_PLATFORM
            std::cout << "Load [" << pLib->GetName() << "] Failed" << std::endl;
            assert(0);
        }
    }

    return false;
}

bool NFCPluginManager::UnLoadPluginLibrary(const std::string& strPluginDLLName)
{
    PluginLibMap::iterator it = mPluginLibMap.find(strPluginDLLName);
    if (it != mPluginLibMap.end())
    {
        NFCDynLib* pLib = it->second;

        DLL_STOP_PLUGIN_FUNC pFunc = (DLL_STOP_PLUGIN_FUNC)pLib->GetSymbol("DllStopPlugin");

        if (pFunc)
        {
            pFunc(this);
        }

        pLib->UnLoad();

        delete pLib;
        pLib = NULL;
        mPluginLibMap.erase(it);

        return true;
    }

    return false;
}

bool NFCPluginManager::ReInitialize()
{
    PluginInstanceMap::iterator itBeforeInstance = mPluginInstanceMap.begin();
    for ( itBeforeInstance; itBeforeInstance != mPluginInstanceMap.end(); itBeforeInstance++ )
    {
        itBeforeInstance->second->BeforeShut();
    }

    PluginInstanceMap::iterator itShutDownInstance = mPluginInstanceMap.begin();
    for ( itShutDownInstance; itShutDownInstance != mPluginInstanceMap.end(); itShutDownInstance++ )
    {
        itShutDownInstance->second->Shut();
    }

    PluginInstanceMap::iterator itInstance = mPluginInstanceMap.begin();
    for ( itInstance; itInstance != mPluginInstanceMap.end(); itInstance++ )
    {
        itInstance->second->Init();
    }

    PluginInstanceMap::iterator itAfterInstance = mPluginInstanceMap.begin();
    for ( ; itAfterInstance != mPluginInstanceMap.end(); itAfterInstance++ )
    {
        itAfterInstance->second->AfterInit();
    }

    PluginInstanceMap::iterator itCheckInstance = mPluginInstanceMap.begin();
    for (itCheckInstance; itCheckInstance != mPluginInstanceMap.end(); itCheckInstance++)
    {
        itCheckInstance->second->CheckConfig();
    }

    return true;
}

void NFCPluginManager::HandlerEx( const NFIActorMessage& message, const Theron::Address from )
{
	//ӵУÿִ֡
	mxQueue.Push(message);
}

bool NFCPluginManager::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.eType == NFIActorMessage::EACTOR_RETURN_EVENT_MSG)
		{
			xMsg.xActorEventFunc->xEndFuncptr->operator()(xMsg.self, xMsg.nSubMsgID, xMsg.data);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}
<|endoftext|>