<commit_before>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "processcontrol.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtDebug>

#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <signal.h>
#endif

using namespace Akonadi;

ProcessControl::ProcessControl( QObject *parent )
  : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),
  mRestartOnceOnExit( false )
{
  connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ),
           this, SLOT( slotError( QProcess::ProcessError ) ) );
  connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ),
           this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) );
  connect( &mProcess, SIGNAL( readyReadStandardError() ),
           this, SLOT( slotErrorMessages() ) );
  connect( &mProcess, SIGNAL( readyReadStandardOutput() ),
            this, SLOT( slotStdoutMessages() ) );
}

ProcessControl::~ProcessControl()
{
  stop();
}

void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )
{
  mFailedToStart = false;

  mApplication = application;
  mArguments = arguments;
  mPolicy = policy;

  start();
}

void ProcessControl::setCrashPolicy( CrashPolicy policy )
{
  mPolicy = policy;
}

void ProcessControl::stop()
{
  if ( mProcess.state() != QProcess::NotRunning ) {
    mProcess.waitForFinished( 10000 );
    mProcess.terminate();
  }
}

void ProcessControl::slotError( QProcess::ProcessError error )
{
  switch ( error ) {
    case QProcess::Crashed:
      // do nothing, we'll respawn in slotFinished
      break;
    case QProcess::FailedToStart:
    default:
        mFailedToStart = true;
      break;
  }

  qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)",
          qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
}

void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )
{
  if ( exitStatus == QProcess::CrashExit ) {
    if ( mPolicy == RestartOnCrash ) {
      if ( !mFailedToStart ) // don't try to start an unstartable application
        start();
    }
  } else {
    if ( exitCode != 0 ) {
      qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)",
              qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );
      if ( mPolicy == RestartOnCrash ) {
        if ( mCrashCount > 2 ) {
          qWarning() << mApplication << "crashed too often and will not be restarted!";
          mPolicy = StopOnCrash;
          emit unableToStart();
          return;
        }
        ++mCrashCount;
        QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );
        if ( !mFailedToStart ) // don't try to start an unstartable application
          start();
      }
    } else {
      if ( mRestartOnceOnExit ) {
        mRestartOnceOnExit = false;
        qDebug( "Restarting application '%s'.", qPrintable( mApplication ) );
        start();
      } else {
        qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) );
      }
    }
  }
}

void ProcessControl::start()
{
#ifdef Q_OS_UNIX
  QString agentValgrind = QString::fromLocal8Bit( qgetenv("AKONADI_VALGRIND") );
  if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {
    qDebug();
    qDebug() << "============================================================";
    qDebug() << "ProcessControl: Valgrinding process" << mApplication;
    qDebug() << "============================================================";
    qDebug();
    QString valgrindSkin = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) );

    mArguments.prepend( mApplication );
    mApplication = QString::fromLocal8Bit( "valgrind" );
    if ( !valgrindSkin.isEmpty() )
      mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin );
    else
      mArguments.prepend (QLatin1String( "--tool=memcheck") );
  }
#endif

  mProcess.start( mApplication, mArguments );
  if ( !mProcess.waitForStarted( ) ) {
    qDebug( "ProcessControl: Unable to start application '%s' (%s)",
            qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
    return;
  }

#ifdef Q_OS_UNIX
  else {
    QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) );
    pid_t pid = mProcess.pid();
    if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {
      qDebug();
      qDebug() << "============================================================";
      qDebug() << "ProcessControl: Suspending process" << mApplication;
      qDebug() << "'gdb" << pid << "' to debug";
      qDebug() << "'kill -SIGCONT" << pid << "' to continue";
      qDebug() << "============================================================";
      qDebug();
      kill( pid, SIGSTOP );
    }
  }
#endif
}

void Akonadi::ProcessControl::slotStdoutMessages()
{
  mProcess.setReadChannel( QProcess::StandardOutput );
  while ( mProcess.canReadLine() ) {
    QString message = QString::fromUtf8( mProcess.readLine() );
    qDebug() << mApplication << "[out]" << message;
  }
}

void ProcessControl::slotErrorMessages()
{
  mProcess.setReadChannel( QProcess::StandardError );
  while ( mProcess.canReadLine() ) {
    QString message = QString::fromUtf8( mProcess.readLine() );
    emit processErrorMessages( message );
    qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) );
  }
}

void ProcessControl::resetCrashCount()
{
  mCrashCount = 0;
}

#include "processcontrol.moc"
<commit_msg>add AKONADI_VALGRIND_OPTIONS to specify additional options (besides the skin used) for valgrind<commit_after>/***************************************************************************
 *   Copyright (C) 2006 by Tobias Koenig <tokoe@kde.org>                   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program 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 General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/

#include "processcontrol.h"

#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtDebug>

#ifdef Q_OS_UNIX
#include <sys/types.h>
#include <signal.h>
#endif

using namespace Akonadi;

ProcessControl::ProcessControl( QObject *parent )
  : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),
  mRestartOnceOnExit( false )
{
  connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ),
           this, SLOT( slotError( QProcess::ProcessError ) ) );
  connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ),
           this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) );
  connect( &mProcess, SIGNAL( readyReadStandardError() ),
           this, SLOT( slotErrorMessages() ) );
  connect( &mProcess, SIGNAL( readyReadStandardOutput() ),
            this, SLOT( slotStdoutMessages() ) );
}

ProcessControl::~ProcessControl()
{
  stop();
}

void ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )
{
  mFailedToStart = false;

  mApplication = application;
  mArguments = arguments;
  mPolicy = policy;

  start();
}

void ProcessControl::setCrashPolicy( CrashPolicy policy )
{
  mPolicy = policy;
}

void ProcessControl::stop()
{
  if ( mProcess.state() != QProcess::NotRunning ) {
    mProcess.waitForFinished( 10000 );
    mProcess.terminate();
  }
}

void ProcessControl::slotError( QProcess::ProcessError error )
{
  switch ( error ) {
    case QProcess::Crashed:
      // do nothing, we'll respawn in slotFinished
      break;
    case QProcess::FailedToStart:
    default:
        mFailedToStart = true;
      break;
  }

  qDebug( "ProcessControl: Application '%s' stopped unexpected (%s)",
          qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
}

void ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )
{
  if ( exitStatus == QProcess::CrashExit ) {
    if ( mPolicy == RestartOnCrash ) {
      if ( !mFailedToStart ) // don't try to start an unstartable application
        start();
    }
  } else {
    if ( exitCode != 0 ) {
      qDebug( "ProcessControl: Application '%s' returned with exit code %d (%s)",
              qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );
      if ( mPolicy == RestartOnCrash ) {
        if ( mCrashCount > 2 ) {
          qWarning() << mApplication << "crashed too often and will not be restarted!";
          mPolicy = StopOnCrash;
          emit unableToStart();
          return;
        }
        ++mCrashCount;
        QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );
        if ( !mFailedToStart ) // don't try to start an unstartable application
          start();
      }
    } else {
      if ( mRestartOnceOnExit ) {
        mRestartOnceOnExit = false;
        qDebug( "Restarting application '%s'.", qPrintable( mApplication ) );
        start();
      } else {
        qDebug( "Application '%s' exited normally...", qPrintable( mApplication ) );
      }
    }
  }
}

namespace {
  static QString getEnv( const char* name, const QString& defaultValue=QString() ) {
    const QString v = QString::fromLocal8Bit( qgetenv( "AKONADI_VALGRIND_SKIN" ) );
    return !v.isEmpty() ? v : defaultValue;
  }
}

void ProcessControl::start()
{
#ifdef Q_OS_UNIX
  QString agentValgrind = getEnv( "AKONADI_VALGRIND" );
  if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {

    mArguments.prepend( mApplication );
    mApplication = QString::fromLocal8Bit( "valgrind" );

    const QString valgrindSkin = getEnv( "AKONADI_VALGRIND_SKIN", QString::fromLocal8Bit( "memcheck" ) );
    mArguments.prepend( QLatin1String( "--tool=" ) + valgrindSkin );

    const QString valgrindOptions = getEnv( "AKONADI_VALGRIND_OPTIONS" );
    if ( !valgrindOptions.isEmpty() )
      mArguments.prepend( valgrindOptions );

    qDebug();
    qDebug() << "============================================================";
    qDebug() << "ProcessControl: Valgrinding process" << mApplication;
    if ( !valgrindSkin.isEmpty() )
      qDebug() << "ProcessControl: Valgrind skin:" << valgrindSkin;
    if ( !valgrindOptions.isEmpty() )
      qDebug() << "ProcessControl: Additional Valgrind options:" << valgrindOptions;
    qDebug() << "============================================================";
    qDebug();
  }
#endif

  mProcess.start( mApplication, mArguments );
  if ( !mProcess.waitForStarted( ) ) {
    qDebug( "ProcessControl: Unable to start application '%s' (%s)",
            qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );
    return;
  }

#ifdef Q_OS_UNIX
  else {
    QString agentDebug = QString::fromLocal8Bit( qgetenv( "AKONADI_DEBUG_WAIT" ) );
    pid_t pid = mProcess.pid();
    if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {
      qDebug();
      qDebug() << "============================================================";
      qDebug() << "ProcessControl: Suspending process" << mApplication;
      qDebug() << "'gdb" << pid << "' to debug";
      qDebug() << "'kill -SIGCONT" << pid << "' to continue";
      qDebug() << "============================================================";
      qDebug();
      kill( pid, SIGSTOP );
    }
  }
#endif
}

void Akonadi::ProcessControl::slotStdoutMessages()
{
  mProcess.setReadChannel( QProcess::StandardOutput );
  while ( mProcess.canReadLine() ) {
    QString message = QString::fromUtf8( mProcess.readLine() );
    qDebug() << mApplication << "[out]" << message;
  }
}

void ProcessControl::slotErrorMessages()
{
  mProcess.setReadChannel( QProcess::StandardError );
  while ( mProcess.canReadLine() ) {
    QString message = QString::fromUtf8( mProcess.readLine() );
    emit processErrorMessages( message );
    qDebug( "[%s] %s", qPrintable( mApplication ), qPrintable( message.trimmed() ) );
  }
}

void ProcessControl::resetCrashCount()
{
  mCrashCount = 0;
}

#include "processcontrol.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfiltertabpagexslt.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 07:49:14 $
 *
 *  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_filter.hxx"

#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif

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

#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif

#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfilterhelpids.hrc"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;

XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) :
    TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, &rResMgr ) ),

    maFTDocType( this, ResId( FT_XML_DOCTYPE ) ),
    maEDDocType( this, ResId( ED_XML_DOCTYPE ) ),

    maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA ) ),
    maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA ), INET_PROT_FILE ),
    maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE ) ),

    maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT ) ),
    maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT ), INET_PROT_FILE ),
    maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE ) ),

    maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT ) ),
    maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT ), INET_PROT_FILE ),
    maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE ) ),

    maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE ) ),
    maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE ), INET_PROT_FILE ),
    maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE ) ),

    sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ),
    sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ),
    sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ),
    sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ),
    sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) )
{
    FreeResource();

    try
    {
        Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY );
        if( xCfgMgr.is() )
            sInstPath = xCfgMgr->substituteVariables( sInstPath );
    }
    catch(Exception&)
    {
        DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" );
    }

    maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );

    maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD );
    maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT );
    maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT );
    maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE );
}

XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT()
{
}

bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo )
{
    if( pInfo )
    {
        pInfo->maDocType = maEDDocType.GetText();
        pInfo->maDTD = GetURL( maEDDTDSchema );
        pInfo->maExportXSLT = GetURL( maEDExportXSLT );
        pInfo->maImportXSLT = GetURL( maEDImportXSLT );
        pInfo->maImportTemplate = GetURL( maEDImportTemplate );
    }

    return true;
}

void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo)
{
    if( pInfo )
    {
        maEDDocType.SetText( pInfo->maDocType );

        SetURL( maEDDTDSchema, pInfo->maDTD );
        SetURL( maEDExportXSLT, pInfo->maExportXSLT );
        SetURL( maEDImportXSLT, pInfo->maImportXSLT );
        SetURL( maEDImportTemplate, pInfo->maImportTemplate );
    }
}

void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL )
{
    OUString aPath;

    if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) )
    {
        osl::FileBase::getSystemPathFromFileURL( rURL, aPath );

        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( aPath );
    }
    else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( rURL );
    }
    else if( rURL.getLength() )
    {
        rtl::OUString aURL( rURL );
        aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false );
        osl::FileBase::getSystemPathFromFileURL( aURL, aPath );

        rURLBox.SetBaseURL( aURL );
        rURLBox.SetText( aPath );
    }
    else
    {
        rURLBox.SetBaseURL( sInstPath );
        String aEmpty;
        rURLBox.SetText( aEmpty );
    }
}

OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox )
{
    OUString aURL;
    OUString aStrPath ( rURLBox.GetText() );
    if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        return aStrPath;
    }
    else
    {
        const String aBaseURL ( rURLBox.GetBaseURL() );
        osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL );
    }

    return aURL;
}

IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton )
{
    SvtURLBox* pURLBox;

    if( pButton == &maPBDTDSchemaBrowse )
    {
        pURLBox = &maEDDTDSchema;
    }
    else if( pButton == &maPBExprotXSLT )
    {
        pURLBox = &maEDExportXSLT;
    }
    else if( pButton == &maPBImportXSLT )
    {
        pURLBox = &maEDImportXSLT;
    }
    else
    {
        pURLBox = &maEDImportTemplate;
    }

    // Open Fileopen-Dialog
       ::sfx2::FileDialogHelper aDlg( ::sfx2::FILEOPEN_SIMPLE, 0 );

    aDlg.SetDisplayDirectory( GetURL( *pURLBox ) );

    if ( aDlg.Execute() == ERRCODE_NONE )
    {
        OUString aURL( aDlg.GetPath() );

        SetURL( *pURLBox, aURL );
    }

    return( 0L );
}

<commit_msg>INTEGRATION: CWS sb59 (1.4.192); FILE MERGED 2006/08/22 12:58:29 sb 1.4.192.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfiltertabpagexslt.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 13:45:02 $
 *
 *  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_filter.hxx"

#ifndef _COM_SUN_STAR_FRAME_XCONFIGMANAGER_HPP_
#include <com/sun/star/frame/XConfigManager.hpp>
#endif

#include "com/sun/star/ui/dialogs/TemplateDescription.hpp"

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

#ifndef _UNOTOOLS_LOCALFILEHELPER_HXX
#include <unotools/localfilehelper.hxx>
#endif

#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif

#ifndef SVTOOLS_URIHELPER_HXX
#include <svtools/urihelper.hxx>
#endif

#include "xmlfiltertabpagexslt.hxx"
#include "xmlfiltertabpagexslt.hrc"
#include "xmlfiltersettingsdialog.hxx"
#include "xmlfilterhelpids.hrc"

using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::lang;

XMLFilterTabPageXSLT::XMLFilterTabPageXSLT( Window* pParent, ResMgr& rResMgr, const Reference< XMultiServiceFactory >& rxMSF ) :
    TabPage( pParent, ResId( RID_XML_FILTER_TABPAGE_XSLT, &rResMgr ) ),

    maFTDocType( this, ResId( FT_XML_DOCTYPE ) ),
    maEDDocType( this, ResId( ED_XML_DOCTYPE ) ),

    maFTDTDSchema( this, ResId( FT_XML_DTD_SCHEMA ) ),
    maEDDTDSchema( this, ResId( ED_XML_DTD_SCHEMA ), INET_PROT_FILE ),
    maPBDTDSchemaBrowse( this, ResId( ED_XML_DTD_SCHEMA_BROWSE ) ),

    maFTExportXSLT( this, ResId( FT_XML_EXPORT_XSLT ) ),
    maEDExportXSLT( this, ResId( ED_XML_EXPORT_XSLT ), INET_PROT_FILE ),
    maPBExprotXSLT( this, ResId( PB_XML_EXPORT_XSLT_BROWSE ) ),

    maFTImportXSLT( this, ResId( FT_XML_IMPORT_XSLT ) ),
    maEDImportXSLT( this, ResId( ED_XML_IMPORT_XSLT ), INET_PROT_FILE ),
    maPBImportXSLT( this, ResId( PB_XML_IMPORT_XSLT_BROWSE ) ),

    maFTImportTemplate( this, ResId( FT_XML_IMPORT_TEMPLATE ) ),
    maEDImportTemplate( this, ResId( ED_XML_IMPORT_TEMPLATE ), INET_PROT_FILE ),
    maPBImportTemplate( this, ResId( PB_XML_IMPORT_TEMPLATE_BROWSE ) ),

    sHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ),
    sSHTTPSchema( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ),
    sFILESchema( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ),
    sFTPSchema( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ),
    sInstPath( RTL_CONSTASCII_USTRINGPARAM( "$(prog)/" ) )
{
    FreeResource();

    try
    {
        Reference< XConfigManager > xCfgMgr( rxMSF->createInstance(OUString::createFromAscii("com.sun.star.config.SpecialConfigManager")), UNO_QUERY );
        if( xCfgMgr.is() )
            sInstPath = xCfgMgr->substituteVariables( sInstPath );
    }
    catch(Exception&)
    {
        DBG_ERROR( "XMLFilterTabPageXSLT::XMLFilterTabPageXSLT exception catched!" );
    }

    maPBDTDSchemaBrowse.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBExprotXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportXSLT.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );
    maPBImportTemplate.SetClickHdl( LINK ( this, XMLFilterTabPageXSLT, ClickBrowseHdl_Impl ) );

    maEDDTDSchema.SetHelpId( HID_XML_FILTER_DTD );
    maEDExportXSLT.SetHelpId( HID_XML_FILTER_EXPORT_XSLT );
    maEDImportXSLT.SetHelpId( HID_XML_FILTER_IMPORT_XSLT );
    maEDImportTemplate.SetHelpId( HID_XML_FILTER_IMPORT_TEMPLATE );
}

XMLFilterTabPageXSLT::~XMLFilterTabPageXSLT()
{
}

bool XMLFilterTabPageXSLT::FillInfo( filter_info_impl* pInfo )
{
    if( pInfo )
    {
        pInfo->maDocType = maEDDocType.GetText();
        pInfo->maDTD = GetURL( maEDDTDSchema );
        pInfo->maExportXSLT = GetURL( maEDExportXSLT );
        pInfo->maImportXSLT = GetURL( maEDImportXSLT );
        pInfo->maImportTemplate = GetURL( maEDImportTemplate );
    }

    return true;
}

void XMLFilterTabPageXSLT::SetInfo(const filter_info_impl* pInfo)
{
    if( pInfo )
    {
        maEDDocType.SetText( pInfo->maDocType );

        SetURL( maEDDTDSchema, pInfo->maDTD );
        SetURL( maEDExportXSLT, pInfo->maExportXSLT );
        SetURL( maEDImportXSLT, pInfo->maImportXSLT );
        SetURL( maEDImportTemplate, pInfo->maImportTemplate );
    }
}

void XMLFilterTabPageXSLT::SetURL( SvtURLBox& rURLBox, const OUString& rURL )
{
    OUString aPath;

    if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "file://" ) ) ) )
    {
        osl::FileBase::getSystemPathFromFileURL( rURL, aPath );

        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( aPath );
    }
    else if( rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
             rURL.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        rURLBox.SetBaseURL( rURL );
        rURLBox.SetText( rURL );
    }
    else if( rURL.getLength() )
    {
        rtl::OUString aURL( rURL );
        aURL = URIHelper::SmartRel2Abs( sInstPath, aURL, Link(), false );
        osl::FileBase::getSystemPathFromFileURL( aURL, aPath );

        rURLBox.SetBaseURL( aURL );
        rURLBox.SetText( aPath );
    }
    else
    {
        rURLBox.SetBaseURL( sInstPath );
        String aEmpty;
        rURLBox.SetText( aEmpty );
    }
}

OUString XMLFilterTabPageXSLT::GetURL( SvtURLBox& rURLBox )
{
    OUString aURL;
    OUString aStrPath ( rURLBox.GetText() );
    if( aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "http://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "shttp://" ) ) ) ||
        aStrPath.matchIgnoreAsciiCase( OUString( RTL_CONSTASCII_USTRINGPARAM( "ftp://" ) ) ) )
    {
        return aStrPath;
    }
    else
    {
        const String aBaseURL ( rURLBox.GetBaseURL() );
        osl::FileBase::getFileURLFromSystemPath( aStrPath, aURL );
    }

    return aURL;
}

IMPL_LINK ( XMLFilterTabPageXSLT, ClickBrowseHdl_Impl, PushButton *, pButton )
{
    SvtURLBox* pURLBox;

    if( pButton == &maPBDTDSchemaBrowse )
    {
        pURLBox = &maEDDTDSchema;
    }
    else if( pButton == &maPBExprotXSLT )
    {
        pURLBox = &maEDExportXSLT;
    }
    else if( pButton == &maPBImportXSLT )
    {
        pURLBox = &maEDImportXSLT;
    }
    else
    {
        pURLBox = &maEDImportTemplate;
    }

    // Open Fileopen-Dialog
       ::sfx2::FileDialogHelper aDlg(
        com::sun::star::ui::dialogs::TemplateDescription::FILEOPEN_SIMPLE, 0 );

    aDlg.SetDisplayDirectory( GetURL( *pURLBox ) );

    if ( aDlg.Execute() == ERRCODE_NONE )
    {
        OUString aURL( aDlg.GetPath() );

        SetURL( *pURLBox, aURL );
    }

    return( 0L );
}

<|endoftext|>


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

#ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX
#define _SVTOOLS_STATUSBARCONTROLLER_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

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

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XUPDATABLE_HPP_
#include <com/sun/star/util/XUpdatable.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_
#include <com/sun/star/frame/XFrame.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCH_HPP_
#include <com/sun/star/frame/XDispatch.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSLISTENER_HPP_
#include <com/sun/star/frame/XStatusListener.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XSTATUSBARCONTROLLER_HPP_
#include <com/sun/star/frame/XStatusbarController.hpp>
#endif

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

#ifndef _COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <com/sun/star/frame/XLayoutManager.hpp>
#endif

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif

#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif

#ifndef INCLUDED_HASH_MAP
#include <hash_map>
#define INCLUDED_HASH_MAP
#endif

#include <tools/gen.hxx>

namespace svt
{

class SVT_DLLPUBLIC StatusbarController : public ::com::sun::star::frame::XStatusListener,
                            public ::com::sun::star::frame::XStatusbarController,
                            public ::com::sun::star::lang::XInitialization,
                            public ::com::sun::star::util::XUpdatable,
                            public ::com::sun::star::lang::XComponent,
                            public ::comphelper::OBaseMutex,
                            public ::cppu::OWeakObject
{
    public:
        StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
                             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
                             const rtl::OUString& aCommandURL,
                             unsigned short       nID );
        StatusbarController();
        virtual ~StatusbarController();

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > getLayoutManager() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const;

        void updateStatus( const rtl::OUString aCommandURL );
        void updateStatus();

        ::Rectangle getControlRect() const;

        // XInterface
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL acquire() throw ();
        virtual void SAL_CALL release() throw ();

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUpdatable
        virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        // XEventListener
        virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusListener
        virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusbarController
        virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
                                       ::sal_Int32 nCommand,
                                       ::sal_Bool bMouseEvent,
                                       const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
                                     const ::com::sun::star::awt::Rectangle& rOutputRectangle,
                                     ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);

    protected:
        struct Listener
        {
            Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
                aURL( rURL ), xDispatch( rDispatch ) {}

            ::com::sun::star::util::URL aURL;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
        };

        typedef ::std::hash_map< ::rtl::OUString,
                                 com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >,
                                 ::rtl::OUStringHash,
                                 ::std::equal_to< ::rtl::OUString > > URLToDispatchMap;

        // methods to support status forwarder, known by the old sfx2 toolbox controller implementation
        void addStatusListener( const rtl::OUString& aCommandURL );
        void removeStatusListener( const rtl::OUString& aCommandURL );
        void bindListener();
        void unbindListener();
        sal_Bool isBound() const;

        // execute methods
        // execute bound status bar controller command/execute various commands
        void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
        void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );

        sal_Bool                                                                            m_bInitialized : 1,
                                                                                m_bDisposed : 1;
        unsigned short                                                                      m_nID;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                 m_xFrame;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >                  m_xParentWindow;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xServiceManager;
        rtl::OUString                                                                       m_aCommandURL;
        URLToDispatchMap                                                                    m_aListenerMap;
        ::cppu::OMultiTypeInterfaceContainerHelper                                          m_aListenerContainer;   /// container for ALL Listener
        mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
};

}

#endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.6.26); FILE MERGED 2008/04/01 15:44:24 thb 1.6.26.3: #i85898# Stripping all external header guards 2008/04/01 12:43:09 thb 1.6.26.2: #i85898# Stripping all external header guards 2008/03/31 13:00:56 rt 1.6.26.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: statusbarcontroller.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVTOOLS_STATUSBARCONTROLLER_HXX
#define _SVTOOLS_STATUSBARCONTROLLER_HXX

#include "svtools/svtdllapi.h"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/util/XUpdatable.hpp>
#include <com/sun/star/frame/XFrame.hpp>
#include <com/sun/star/frame/XDispatch.hpp>
#include <com/sun/star/frame/XStatusListener.hpp>
#include <com/sun/star/frame/XStatusbarController.hpp>
#include <com/sun/star/util/XURLTransformer.hpp>
#include <com/sun/star/frame/XLayoutManager.hpp>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <comphelper/broadcasthelper.hxx>

#ifndef INCLUDED_HASH_MAP
#include <hash_map>
#define INCLUDED_HASH_MAP
#endif

#include <tools/gen.hxx>

namespace svt
{

class SVT_DLLPUBLIC StatusbarController : public ::com::sun::star::frame::XStatusListener,
                            public ::com::sun::star::frame::XStatusbarController,
                            public ::com::sun::star::lang::XInitialization,
                            public ::com::sun::star::util::XUpdatable,
                            public ::com::sun::star::lang::XComponent,
                            public ::comphelper::OBaseMutex,
                            public ::cppu::OWeakObject
{
    public:
        StatusbarController( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rServiceManager,
                             const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& xFrame,
                             const rtl::OUString& aCommandURL,
                             unsigned short       nID );
        StatusbarController();
        virtual ~StatusbarController();

        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > getFrameInterface() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > getServiceManager() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager > getLayoutManager() const;
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > getURLTransformer() const;

        void updateStatus( const rtl::OUString aCommandURL );
        void updateStatus();

        ::Rectangle getControlRect() const;

        // XInterface
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL acquire() throw ();
        virtual void SAL_CALL release() throw ();

        // XInitialization
        virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

        // XUpdatable
        virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);

        // XComponent
        virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

        // XEventListener
        virtual void SAL_CALL disposing( const com::sun::star::lang::EventObject& Source ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusListener
        virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );

        // XStatusbarController
        virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
                                       ::sal_Int32 nCommand,
                                       ::sal_Bool bMouseEvent,
                                       const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
                                     const ::com::sun::star::awt::Rectangle& rOutputRectangle,
                                     ::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);

    protected:
        struct Listener
        {
            Listener( const ::com::sun::star::util::URL& rURL, const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >& rDispatch ) :
                aURL( rURL ), xDispatch( rDispatch ) {}

            ::com::sun::star::util::URL aURL;
            ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch > xDispatch;
        };

        typedef ::std::hash_map< ::rtl::OUString,
                                 com::sun::star::uno::Reference< com::sun::star::frame::XDispatch >,
                                 ::rtl::OUStringHash,
                                 ::std::equal_to< ::rtl::OUString > > URLToDispatchMap;

        // methods to support status forwarder, known by the old sfx2 toolbox controller implementation
        void addStatusListener( const rtl::OUString& aCommandURL );
        void removeStatusListener( const rtl::OUString& aCommandURL );
        void bindListener();
        void unbindListener();
        sal_Bool isBound() const;

        // execute methods
        // execute bound status bar controller command/execute various commands
        void execute( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );
        void execute( const rtl::OUString& aCommand, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aArgs );

        sal_Bool                                                                            m_bInitialized : 1,
                                                                                m_bDisposed : 1;
        unsigned short                                                                      m_nID;
        ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >                 m_xFrame;
        ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow >                  m_xParentWindow;
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >    m_xServiceManager;
        rtl::OUString                                                                       m_aCommandURL;
        URLToDispatchMap                                                                    m_aListenerMap;
        ::cppu::OMultiTypeInterfaceContainerHelper                                          m_aListenerContainer;   /// container for ALL Listener
        mutable ::com::sun::star::uno::Reference< ::com::sun::star::util::XURLTransformer > m_xURLTransformer;
};

}

#endif // _SVTOOLS_TOOLBOXCONTROLLER_HXX
<|endoftext|>


<commit_before>// vasi.hxx -- a class to hold some critical vasi data
//
// Written by Curtis Olson, started December 2003.
//
// Copyright (C) 2003  Curtis L. Olson  - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program 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
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

#ifndef _SG_VASI_HXX
#define _SG_VASI_HXX

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>

#include STL_STRING
SG_USING_STD(string);

#include <plib/ssg.h>		// plib include

#include <simgear/math/sg_geodesy.hxx>

class SGVASIUserData : public ssgBase
{

private:

    sgdVec3 abs_pos;
    double alt_m;
    ssgLeaf *leaf;

public:

    SGVASIUserData( sgdVec3 pos_cart, ssgLeaf *l ) {
        sgdCopyVec3( abs_pos, pos_cart );

        double lat, lon;
        sgCartToGeod( abs_pos, &lat, &lon, &alt_m );

        leaf = l;
    }

    ~SGVASIUserData() {}

    double get_alt_m() { return alt_m; }
    double *get_abs_pos() { return abs_pos; }
    int i;

    // color the vasi/papi correctly based on angle
    void set_color( float angle_deg ) {
        int count = leaf->getNumColours();
        double trans = 0.05;
        double color = 1.0;
        double ref;
        float *entry;

        if ( count == 12 ) {
            // PAPI configuration

            // papi D
            ref = 3.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 0; i < 3; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi C
            ref = 3.167;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 3; i < 6; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi B
            ref = 2.833;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 6; i < 9; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi A
            ref = 2.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 9; i < 12; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        } else if ( count == 36 ) {
            // probably vasi, first 18 are downwind bar (2.5 deg)
            ref = 2.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( int i = 0; i < 18; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // last 6 are upwind bar (3.0 deg)
            ref = 3.0;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( int i = 18; i < 36; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        } else {
            // fail safe
            cout << "unknown vasi/papi configuration, count = " << count << endl;
            for ( int i = 0; i < count; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        }
    }
};

#endif // _SG_VASI_HXX
<commit_msg>Oops, I originally had ramped the vasi/papi color transition the wrong way. So as you passed through the target glide slope from low to high it would be colored: red -> white -> small range of transition to red -> white. Now it goes the right way so you get: red -> smooth transition to -> white. You can tell you are getting high if you see the bottom vasi start to turn pink ... etc. etc. hopefully just like in real life.<commit_after>// vasi.hxx -- a class to hold some critical vasi data
//
// Written by Curtis Olson, started December 2003.
//
// Copyright (C) 2003  Curtis L. Olson  - curt@flightgear.org
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program 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
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// $Id$

#ifndef _SG_VASI_HXX
#define _SG_VASI_HXX

#ifndef __cplusplus
# error This library requires C++
#endif

#include <simgear/compiler.h>

#include STL_STRING
SG_USING_STD(string);

#include <plib/ssg.h>		// plib include

#include <simgear/math/sg_geodesy.hxx>

class SGVASIUserData : public ssgBase
{

private:

    sgdVec3 abs_pos;
    double alt_m;
    ssgLeaf *leaf;

public:

    SGVASIUserData( sgdVec3 pos_cart, ssgLeaf *l ) {
        sgdCopyVec3( abs_pos, pos_cart );

        double lat, lon;
        sgCartToGeod( abs_pos, &lat, &lon, &alt_m );

        leaf = l;
    }

    ~SGVASIUserData() {}

    double get_alt_m() { return alt_m; }
    double *get_abs_pos() { return abs_pos; }
    int i;

    // color the vasi/papi correctly based on angle
    void set_color( float angle_deg ) {
        int count = leaf->getNumColours();
        double trans = 0.05;
        double color = 1.0;
        double ref;
        float *entry;

        if ( count == 12 ) {
            // PAPI configuration

            // papi D
            ref = 3.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 0; i < 3; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi C
            ref = 3.167;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 3; i < 6; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi B
            ref = 2.833;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 6; i < 9; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // papi A
            ref = 2.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( i = 9; i < 12; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        } else if ( count == 36 ) {
            // probably vasi, first 18 are downwind bar (2.5 deg)
            ref = 2.5;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( int i = 0; i < 18; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }

            // last 6 are upwind bar (3.0 deg)
            ref = 3.0;
            if ( angle_deg < ref - trans ) {
                color = 0.0;
            } else if ( angle_deg < ref + trans ) {
                color = 1.0 - (ref + trans - angle_deg) * (1 / (2 * trans) );
            } else {
                color = 1.0;
            }
            for ( int i = 18; i < 36; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        } else {
            // fail safe
            cout << "unknown vasi/papi configuration, count = " << count << endl;
            for ( int i = 0; i < count; ++i ) {
                entry = leaf->getColour( i );
                entry[1] = color;
                entry[2] = color;
            }
        }
    }
};

#endif // _SG_VASI_HXX
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>

using namespace std;

int main(){
	int f[20] = {1,1};
	for (int i=2;i<20;i++){
		f[i] = f[i-1] + f[i-2];
	}
	for (int i=0;i<20;i++){
		if(i%4 == 0)cout<<endl;
		cout.width(5);
		cout<<f[i];
	}
	cout<<endl;

	// int a[10], b[10];
 //  	for(int i = 0; i < 10; i++) {
	//     a[i] = i * 2 - 1;
	//     b[10 - i - 1] = a[i];
 //  	}
 //  	for(int i = 0; i < 10; i++) {
	//     cout << "a[" << i << "] = " << a[i] << "  ";
	//     cout << "b[" << i << "] = " << b[i] << endl;
 //  	}

  	return 0;
}<commit_msg>New practice.<commit_after>#include <iostream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
#include <string>

using namespace std;

void rowSum(int a[][4],int nRow){
	for(int i=0;i<nRow;i++){
		for(int j=0;j<4;j++){
			a[i][0] = a[i][j];
		}
	}
}

int main(){
	int table[3][4] = {{1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}};
	for (int i = 0; i < 3; i++)  {
         for (int j = 0; j < 4; j++)
              cout << table[i][j] << "   ";
         cout << endl;
     }
     rowSum(table, 3);
     for(int i=0;i<3;i++){
     	cout << "Sum of row " << i << " is " << table[i][0] << endl;
     }

	// const char key[] = {'a','c','b','a','d'};
	// const int ques_num = 5;
	// char usr_input;
	// int ques = 0, correct_num = 0;

	// cout<<"Enter the "<<ques_num<<" question tests:"<<endl;
	// while(cin.get(usr_input)){
	// 	if(usr_input != '\n'){
	// 		if(usr_input == key[ques]){
	// 			correct_num++;
	// 			cout<<" ";
	// 		}
	// 		else{
	// 			cout<<"*";
	// 		}
	// 		ques++;
	// 	}
	// 	else{
	// 		cout<<"Score: "<<static_cast<float>(correct_num)/ques_num*100<<"%";
	// 		ques = 0; correct_num = 0;cout<<endl;
	// 	}
	// }

	// int f[20] = {1,1};
	// for (int i=2;i<20;i++){
	// 	f[i] = f[i-1] + f[i-2];
	// }
	// for (int i=0;i<20;i++){
	// 	if(i%4 == 0)cout<<endl;
	// 	cout.width(5);
	// 	cout<<f[i];
	// }
	// cout<<endl;

	// int a[10], b[10];
 //  	for(int i = 0; i < 10; i++) {
	//     a[i] = i * 2 - 1;
	//     b[10 - i - 1] = a[i];
 //  	}
 //  	for(int i = 0; i < 10; i++) {
	//     cout << "a[" << i << "] = " << a[i] << "  ";
	//     cout << "b[" << i << "] = " << b[i] << endl;
 //  	}

  	return 0;
}<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _GRFCACHE_HXX
#define _GRFCACHE_HXX

#include <vcl/graph.hxx>
#include <vcl/timer.hxx>
#include <svtools/grfmgr.hxx>

// -----------------------
// - GraphicManagerCache -
// -----------------------

class GraphicCacheEntry;

class GraphicCache
{
private:

    GraphicManager&             mrMgr;
    Timer                       maReleaseTimer;
    List                        maGraphicCache;
    List                        maDisplayCache;
    sal_uLong                       mnReleaseTimeoutSeconds;
    sal_uLong                       mnMaxDisplaySize;
    sal_uLong                       mnMaxObjDisplaySize;
    sal_uLong                       mnUsedDisplaySize;

    sal_Bool                        ImplFreeDisplayCacheSpace( sal_uLong nSizeToFree );
    GraphicCacheEntry*          ImplGetCacheEntry( const GraphicObject& rObj );

                                DECL_LINK( ReleaseTimeoutHdl, Timer* pTimer );

public:

                                GraphicCache( GraphicManager& rMgr,
                                              sal_uLong nDisplayCacheSize = 10000000UL,
                                              sal_uLong nMaxObjDisplayCacheSize = 2400000UL );
                                ~GraphicCache();

public:

    void                        AddGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute,
                                                  const ByteString* pID, const GraphicObject* pCopyObj );
    void                        ReleaseGraphicObject( const GraphicObject& rObj );

    void                        GraphicObjectWasSwappedOut( const GraphicObject& rObj );
    sal_Bool                        FillSwappedGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute );
    void                        GraphicObjectWasSwappedIn( const GraphicObject& rObj );

    ByteString                  GetUniqueID( const GraphicObject& rObj ) const;

public:

    void                        SetMaxDisplayCacheSize( sal_uLong nNewCacheSize );
    sal_uLong                       GetMaxDisplayCacheSize() const { return mnMaxDisplaySize; };

    void                        SetMaxObjDisplayCacheSize( sal_uLong nNewMaxObjSize, sal_Bool bDestroyGreaterCached = sal_False );
    sal_uLong                       GetMaxObjDisplayCacheSize() const { return mnMaxObjDisplaySize; }

    sal_uLong                       GetUsedDisplayCacheSize() const { return mnUsedDisplaySize; }
    sal_uLong                       GetFreeDisplayCacheSize() const { return( mnMaxDisplaySize - mnUsedDisplaySize ); }

    void                        SetCacheTimeout( sal_uLong nTimeoutSeconds );
    sal_uLong                       GetCacheTimeout() const { return mnReleaseTimeoutSeconds; }

    sal_Bool                        IsDisplayCacheable( OutputDevice* pOut, const Point& rPt, const Size& rSz,
                                                    const GraphicObject& rObj, const GraphicAttr& rAttr ) const;
    sal_Bool                        IsInDisplayCache( OutputDevice* pOut, const Point& rPt, const Size& rSz,
                                                  const GraphicObject& rObj, const GraphicAttr& rAttr ) const;
    sal_Bool                        CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz,
                                                       const GraphicObject& rObj, const GraphicAttr& rAttr,
                                                       const BitmapEx& rBmpEx );
    sal_Bool                        CreateDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz,
                                                       const GraphicObject& rObj, const GraphicAttr& rAttr,
                                                       const GDIMetaFile& rMtf );
    sal_Bool                        DrawDisplayCacheObj( OutputDevice* pOut, const Point& rPt, const Size& rSz,
                                                     const GraphicObject& rObj, const GraphicAttr& rAttr );
};

#endif // _GRFCACHE_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Whitespace cleanup<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _GRFCACHE_HXX
#define _GRFCACHE_HXX

#include <vcl/graph.hxx>
#include <vcl/timer.hxx>
#include <svtools/grfmgr.hxx>

// -----------------------
// - GraphicManagerCache -
// -----------------------

class GraphicCacheEntry;

class GraphicCache
{
private:

    GraphicManager&         mrMgr;
    Timer                   maReleaseTimer;
    List                    maGraphicCache;
    List                    maDisplayCache;
    sal_uLong               mnReleaseTimeoutSeconds;
    sal_uLong               mnMaxDisplaySize;
    sal_uLong               mnMaxObjDisplaySize;
    sal_uLong               mnUsedDisplaySize;

    sal_Bool                ImplFreeDisplayCacheSpace( sal_uLong nSizeToFree );
    GraphicCacheEntry*      ImplGetCacheEntry( const GraphicObject& rObj );

                            DECL_LINK( ReleaseTimeoutHdl, Timer* pTimer );

public:

                            GraphicCache(
                                GraphicManager& rMgr,
                                sal_uLong nDisplayCacheSize = 10000000UL,
                                sal_uLong nMaxObjDisplayCacheSize = 2400000UL
                            );

                            ~GraphicCache();

public:

    void                    AddGraphicObject(
                                const GraphicObject& rObj,
                                Graphic& rSubstitute,
                                const ByteString* pID,
                                const GraphicObject* pCopyObj
                            );

    void                    ReleaseGraphicObject( const GraphicObject& rObj );

    void                    GraphicObjectWasSwappedOut( const GraphicObject& rObj );
    sal_Bool                FillSwappedGraphicObject( const GraphicObject& rObj, Graphic& rSubstitute );
    void                    GraphicObjectWasSwappedIn( const GraphicObject& rObj );

    ByteString              GetUniqueID( const GraphicObject& rObj ) const;

public:

    void                    SetMaxDisplayCacheSize( sal_uLong nNewCacheSize );
    sal_uLong               GetMaxDisplayCacheSize() const { return mnMaxDisplaySize; };

    void                    SetMaxObjDisplayCacheSize(
                                sal_uLong nNewMaxObjSize,
                                sal_Bool bDestroyGreaterCached = sal_False
                            );

    sal_uLong               GetMaxObjDisplayCacheSize() const { return mnMaxObjDisplaySize; }

    sal_uLong               GetUsedDisplayCacheSize() const { return mnUsedDisplaySize; }
    sal_uLong               GetFreeDisplayCacheSize() const { return( mnMaxDisplaySize - mnUsedDisplaySize ); }

    void                    SetCacheTimeout( sal_uLong nTimeoutSeconds );
    sal_uLong               GetCacheTimeout() const { return mnReleaseTimeoutSeconds; }

    sal_Bool                IsDisplayCacheable(
                                OutputDevice* pOut,
                                const Point& rPt,
                                const Size& rSz,
                                const GraphicObject& rObj,
                                const GraphicAttr& rAttr
                            ) const;

    sal_Bool                IsInDisplayCache(
                                OutputDevice* pOut,
                                const Point& rPt,
                                const Size& rSz,
                                const GraphicObject& rObj,
                                const GraphicAttr& rAttr
                            ) const;

    sal_Bool                CreateDisplayCacheObj(
                                OutputDevice* pOut,
                                const Point& rPt,
                                const Size& rSz,
                                const GraphicObject& rObj,
                                const GraphicAttr& rAttr,
                                const BitmapEx& rBmpEx
                            );

    sal_Bool                CreateDisplayCacheObj(
                                OutputDevice* pOut,
                                const Point& rPt,
                                const Size& rSz,
                                const GraphicObject& rObj,
                                const GraphicAttr& rAttr,
                                const GDIMetaFile& rMtf
                            );

    sal_Bool                DrawDisplayCacheObj(
                                OutputDevice* pOut,
                                const Point& rPt,
                                const Size& rSz,
                                const GraphicObject& rObj,
                                const GraphicAttr& rAttr
                            );
};

#endif // _GRFCACHE_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <wdt/Throttler.h>
#include <wdt/test/TestCommon.h>

#include <glog/logging.h>
#include <gtest/gtest.h>
#include <chrono>

namespace facebook {
namespace wdt {

void testThrottling(std::shared_ptr<Throttler> throttler, int expectedRate) {
  int64_t numTransferred = 0;
  auto startTime = Clock::now();
  while (durationSeconds(Clock::now() - startTime) < 2) {
    throttler->limit(1000);
    numTransferred += 1000;
  }
  auto endTime = Clock::now();
  double durationSecs = durationSeconds(endTime - startTime);
  double throughputMBps = numTransferred / durationSecs / kMbToB;
  EXPECT_NEAR(throughputMBps, expectedRate, 3);
}

TEST(ThrottlerTest, RATE_CHANGE) {
  WdtOptions options;
  options.avg_mbytes_per_sec = 500;
  std::shared_ptr<Throttler> throttler = Throttler::makeThrottler(options);
  throttler->startTransfer();

  testThrottling(throttler, 500);

  // test rate decrease
  options.avg_mbytes_per_sec = 300;
  throttler->setThrottlerRates(options);
  testThrottling(throttler, 300);

  // test rate increase
  options.avg_mbytes_per_sec = 700;
  throttler->setThrottlerRates(options);
  testThrottling(throttler, 700);

  throttler->endTransfer();
}
}
}
<commit_msg>Reducing throttler rate in test so that it passes with asan<commit_after>#include <wdt/Throttler.h>
#include <wdt/test/TestCommon.h>

#include <glog/logging.h>
#include <gtest/gtest.h>
#include <chrono>

namespace facebook {
namespace wdt {

void testThrottling(std::shared_ptr<Throttler> throttler, int expectedRate) {
  int64_t numTransferred = 0;
  auto startTime = Clock::now();
  while (durationSeconds(Clock::now() - startTime) <= 2) {
    throttler->limit(1000);
    numTransferred += 1000;
  }
  auto endTime = Clock::now();
  double durationSecs = durationSeconds(endTime - startTime);
  double throughputMBps = numTransferred / durationSecs / kMbToB;
  EXPECT_NEAR(throughputMBps, expectedRate, 1);
}

TEST(ThrottlerTest, RATE_CHANGE) {
  WdtOptions options;
  options.avg_mbytes_per_sec = 50;
  std::shared_ptr<Throttler> throttler = Throttler::makeThrottler(options);
  throttler->startTransfer();

  testThrottling(throttler, 50);

  // test rate decrease
  options.avg_mbytes_per_sec = 30;
  throttler->setThrottlerRates(options);
  testThrottling(throttler, 30);

  // test rate increase
  options.avg_mbytes_per_sec = 70;
  throttler->setThrottlerRates(options);
  testThrottling(throttler, 70);

  throttler->endTransfer();
}
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: stylepool.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifdef _MSC_VER
#pragma hdrstop
#endif

#include <vector>
#include <map>

#include "stylepool.hxx"
#include <svtools/itemiter.hxx>
#include <svtools/itempool.hxx>

using namespace boost;

namespace {
    // A "Node" represents a subset of inserted SfxItemSets
    // The root node represents the empty set
    // The other nodes contain a SfxPoolItem and represents an item set which contains their
    // pool item and the pool items of their parents.
    class Node
    {
        std::vector<Node*> mChildren; // child nodes, create by findChildNode(..)
        std::vector< StylePool::SfxItemSet_Pointer_t > aItemSet; // shared pointer an inserted item set or nul
        const SfxPoolItem *pItem;   // my pool item
        Node *pUpper;               // if I'm a child node that's my parent node
    public:
        Node() : pItem( 0 ), pUpper( 0 ) {} // root node Ctor
        Node( const SfxPoolItem& rItem, Node* pParent ) : // child node Ctor
            pItem( rItem.Clone() ), pUpper( pParent ){}
        ~Node();
        const bool hasItemSet() const { return 0 < aItemSet.size(); }
        const StylePool::SfxItemSet_Pointer_t getItemSet() const { return aItemSet[aItemSet.size()-1]; }
        void setItemSet( const SfxItemSet& rSet ){ aItemSet.push_back( StylePool::SfxItemSet_Pointer_t( rSet.Clone() ) ); }
        Node* findChildNode( const SfxPoolItem& rItem );
        Node* nextItemSet( Node* pLast );
        const SfxPoolItem& getPoolItem() const { return *pItem; }
    };

    Node* Node::findChildNode( const SfxPoolItem& rItem )
    {
        Node* pNextNode = this;
        std::vector<Node*>::iterator aIter = mChildren.begin();
        while( aIter != mChildren.end() )
        {
            if( rItem.Which() == (*aIter)->getPoolItem().Which() &&
                rItem == (*aIter)->getPoolItem() )
                return *aIter;
            ++aIter;
        }
        pNextNode = new Node( rItem, pNextNode );
        mChildren.push_back( pNextNode );
        return pNextNode;
    }

    /* Find the next node which has a SfxItemSet.
       The input parameter pLast has a sophisticated meaning:
       downstairs only:
       pLast == 0 => scan your children and their children
                     but neither your parents neither your siblings
       downstairs and upstairs:
       pLast == this => scan your children, their children,
                        the children of your parent behind you, and so on
       partial downstairs and upstairs
       pLast != 0 && pLast != this => scan your children behind the given children,
                        the children of your parent behind you and so on.
    */

    Node* Node::nextItemSet( Node* pLast )
    {
        // Searching downstairs
        std::vector<Node*>::iterator aIter = mChildren.begin();
        // For pLast == 0 and pLast == this all children are of interest
        // for another pLast the search starts behind pLast...
        if( pLast && pLast != this )
        {
            aIter = std::find( mChildren.begin(), mChildren.end(), pLast );
            if( aIter != mChildren.end() )
                ++aIter;
        }
        Node *pNext = 0;
        while( aIter != mChildren.end() )
        {
            pNext = *aIter;
            if( pNext->hasItemSet() ) // any child with item set?
                return pNext;
            pNext = pNext->nextItemSet( 0 ); // 0 => downstairs only
            if( pNext )
                return pNext;
            ++aIter;
        }
        // Searching upstairs
        if( pLast && pUpper )
            pNext = pUpper->nextItemSet( this );
        return pNext;
    }

    Node::~Node()
    {
        std::vector<Node*>::iterator aIter = mChildren.begin();
        while( aIter != mChildren.end() )
        {
            delete *aIter;
            ++aIter;
        }
        delete pItem;
    }

    class Iterator : public IStylePoolIteratorAccess
    {
        std::map< const SfxItemSet*, Node >& rRoot;
        std::map< const SfxItemSet*, Node >::iterator pCurrNode;
        Node* pNode;
    public:
        Iterator( std::map< const SfxItemSet*, Node >& rR )
            : rRoot( rR ), pCurrNode( rR.begin() ), pNode(0) {}
        virtual StylePool::SfxItemSet_Pointer_t getNext();
        virtual ::rtl::OUString getName();
    };

    StylePool::SfxItemSet_Pointer_t Iterator::getNext()
    {
        StylePool::SfxItemSet_Pointer_t pReturn;
        while( pNode || pCurrNode != rRoot.end() )
        {
            if( !pNode )
            {
                pNode = &pCurrNode->second;
                ++pCurrNode;
                if( pNode->hasItemSet() )
                    return pNode->getItemSet();
            }
            pNode = pNode->nextItemSet( pNode );
            if( pNode && pNode->hasItemSet() )
                return pNode->getItemSet();
        }
        return pReturn;
    }

    ::rtl::OUString Iterator::getName()
    {
        ::rtl::OUString aString;
        if( pNode && pNode->hasItemSet() )
            aString = StylePool::nameOf( pNode->getItemSet() );
        return aString;
    }

}

/* This static method creates a unique name from a shared pointer to a SfxItemSet
   The name is the memory address of the SfxItemSet itself. */

::rtl::OUString StylePool::nameOf( SfxItemSet_Pointer_t pSet )
{
    return ::rtl::OUString::valueOf( reinterpret_cast<sal_IntPtr>( pSet.get() ), 16 );
}

// class StylePoolImpl organized a tree-structure where every node represents a SfxItemSet.
// The insertItemSet method adds a SfxItemSet into the tree if necessary and returns a shared_ptr
// to a copy of the SfxItemSet.
// The aRoot-Node represents an empty SfxItemSet.

class StylePoolImpl
{
private:
    std::map< const SfxItemSet*, Node > aRoot;
    sal_Int32 nCount;
public:
    StylePoolImpl() : nCount(0) {}
    StylePool::SfxItemSet_Pointer_t insertItemSet( const SfxItemSet& rSet );
    IStylePoolIteratorAccess* createIterator();
    sal_Int32 getCount() const { return nCount; }
};

StylePool::SfxItemSet_Pointer_t StylePoolImpl::insertItemSet( const SfxItemSet& rSet )
{
    bool bNonPoolable = false;
    Node* pCurNode = &aRoot[ rSet.GetParent() ];
    SfxItemIter aIter( rSet );
    const SfxPoolItem* pItem = aIter.GetCurItem();
    // Every SfxPoolItem in the SfxItemSet causes a step deeper into the tree,
    // a complete empty SfxItemSet would stay at the root node.
    while( pItem )
    {
        if( !rSet.GetPool()->IsItemFlag(pItem->Which(), SFX_ITEM_POOLABLE ) )
            bNonPoolable = true;
        pCurNode = pCurNode->findChildNode( *pItem );
        pItem = aIter.NextItem();
    }
    // Every leaf node represents an inserted item set, but "non-leaf" nodes represents subsets
    // of inserted itemsets.
    // These nodes could have but does not need to have a shared_ptr to a item set.
    if( !pCurNode->hasItemSet() )
    {
        pCurNode->setItemSet( rSet );
        bNonPoolable = false; // to avoid a double insertion
        ++nCount;
    }
    // If rSet contains at least one non poolable item, a new itemset has to be inserted
    if( bNonPoolable )
        pCurNode->setItemSet( rSet );
#ifdef DEBUG
    {
        sal_Int32 nCheck = -1;
        sal_Int32 nNo = -1;
        IStylePoolIteratorAccess* pIter = createIterator();
        StylePool::SfxItemSet_Pointer_t pTemp;
        do
        {
            ++nCheck;
            pTemp = pIter->getNext();
            if( pCurNode->hasItemSet() && pTemp.get() == pCurNode->getItemSet().get() )
            {
                ::rtl::OUString aStr = pIter->getName();
                nNo = nCheck;
            }
        } while( pTemp.get() );
        DBG_ASSERT( nCount == nCheck, "Wrong counting");
        delete pIter;
    }
#endif
    return pCurNode->getItemSet();
}

IStylePoolIteratorAccess* StylePoolImpl::createIterator()
{ return new Iterator( aRoot ); }

// Ctor, Dtor and redirected methods of class StylePool, nearly inline ;-)

StylePool::StylePool() : pImpl( new StylePoolImpl() ) {}

StylePool::SfxItemSet_Pointer_t StylePool::insertItemSet( const SfxItemSet& rSet )
{ return pImpl->insertItemSet( rSet ); }

IStylePoolIteratorAccess* StylePool::createIterator()
{ return pImpl->createIterator(); }

sal_Int32 StylePool::getCount() const
{ return pImpl->getCount(); }

StylePool::~StylePool() { delete pImpl; }

// End of class StylePool

<commit_msg>INTEGRATION: CWS sw241bf02_DEV300 (1.6.96.1.22); FILE MERGED 2008/04/30 09:18:44 od 1.6.96.1.22.1: #i87808# if the style access iterator is used to retrieve stored styles, 	 try to provide used styles, if at a certain style pool node 	 are stored more than one style due to non-poolable items<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: stylepool.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifdef _MSC_VER
#pragma hdrstop
#endif

#include <vector>
#include <map>

#include "stylepool.hxx"
#include <svtools/itemiter.hxx>
#include <svtools/itempool.hxx>

using namespace boost;

namespace {
    // A "Node" represents a subset of inserted SfxItemSets
    // The root node represents the empty set
    // The other nodes contain a SfxPoolItem and represents an item set which contains their
    // pool item and the pool items of their parents.
    class Node
    {
        std::vector<Node*> mChildren; // child nodes, create by findChildNode(..)
        std::vector< StylePool::SfxItemSet_Pointer_t > aItemSet; // shared pointer an inserted item set or nul
        const SfxPoolItem *pItem;   // my pool item
        Node *pUpper;               // if I'm a child node that's my parent node
    public:
        Node() : pItem( 0 ), pUpper( 0 ) {} // root node Ctor
        Node( const SfxPoolItem& rItem, Node* pParent ) : // child node Ctor
            pItem( rItem.Clone() ), pUpper( pParent ){}
        ~Node();
        const bool hasItemSet() const { return 0 < aItemSet.size(); }
        // --> OD 2008-04-29 #i87808#
//        const StylePool::SfxItemSet_Pointer_t getItemSet() const { return aItemSet[aItemSet.size()-1]; }
        const StylePool::SfxItemSet_Pointer_t getItemSet() const
        {
            return aItemSet.back();
        }
        const StylePool::SfxItemSet_Pointer_t getUsedOrLastAddedItemSet() const;
        // <--
        void setItemSet( const SfxItemSet& rSet ){ aItemSet.push_back( StylePool::SfxItemSet_Pointer_t( rSet.Clone() ) ); }
        Node* findChildNode( const SfxPoolItem& rItem );
        Node* nextItemSet( Node* pLast );
        const SfxPoolItem& getPoolItem() const { return *pItem; }
    };

    // --> OD 2008-04-29 #i87808#
    const StylePool::SfxItemSet_Pointer_t Node::getUsedOrLastAddedItemSet() const
    {
        std::vector< StylePool::SfxItemSet_Pointer_t >::const_reverse_iterator aIter;

        for ( aIter = aItemSet.rbegin(); aIter != aItemSet.rend(); ++aIter )
        {
            if ( (*aIter).use_count() > 1 )
            {
                return *aIter;
            }
        }

        return aItemSet.back();
    }
    // <--

    Node* Node::findChildNode( const SfxPoolItem& rItem )
    {
        Node* pNextNode = this;
        std::vector<Node*>::iterator aIter = mChildren.begin();
        while( aIter != mChildren.end() )
        {
            if( rItem.Which() == (*aIter)->getPoolItem().Which() &&
                rItem == (*aIter)->getPoolItem() )
                return *aIter;
            ++aIter;
        }
        pNextNode = new Node( rItem, pNextNode );
        mChildren.push_back( pNextNode );
        return pNextNode;
    }

    /* Find the next node which has a SfxItemSet.
       The input parameter pLast has a sophisticated meaning:
       downstairs only:
       pLast == 0 => scan your children and their children
                     but neither your parents neither your siblings
       downstairs and upstairs:
       pLast == this => scan your children, their children,
                        the children of your parent behind you, and so on
       partial downstairs and upstairs
       pLast != 0 && pLast != this => scan your children behind the given children,
                        the children of your parent behind you and so on.
    */

    Node* Node::nextItemSet( Node* pLast )
    {
        // Searching downstairs
        std::vector<Node*>::iterator aIter = mChildren.begin();
        // For pLast == 0 and pLast == this all children are of interest
        // for another pLast the search starts behind pLast...
        if( pLast && pLast != this )
        {
            aIter = std::find( mChildren.begin(), mChildren.end(), pLast );
            if( aIter != mChildren.end() )
                ++aIter;
        }
        Node *pNext = 0;
        while( aIter != mChildren.end() )
        {
            pNext = *aIter;
            if( pNext->hasItemSet() ) // any child with item set?
                return pNext;
            pNext = pNext->nextItemSet( 0 ); // 0 => downstairs only
            if( pNext )
                return pNext;
            ++aIter;
        }
        // Searching upstairs
        if( pLast && pUpper )
            pNext = pUpper->nextItemSet( this );
        return pNext;
    }

    Node::~Node()
    {
        std::vector<Node*>::iterator aIter = mChildren.begin();
        while( aIter != mChildren.end() )
        {
            delete *aIter;
            ++aIter;
        }
        delete pItem;
    }

    class Iterator : public IStylePoolIteratorAccess
    {
        std::map< const SfxItemSet*, Node >& rRoot;
        std::map< const SfxItemSet*, Node >::iterator pCurrNode;
        Node* pNode;
    public:
        Iterator( std::map< const SfxItemSet*, Node >& rR )
            : rRoot( rR ), pCurrNode( rR.begin() ), pNode(0) {}
        virtual StylePool::SfxItemSet_Pointer_t getNext();
        virtual ::rtl::OUString getName();
    };

    StylePool::SfxItemSet_Pointer_t Iterator::getNext()
    {
        StylePool::SfxItemSet_Pointer_t pReturn;
        while( pNode || pCurrNode != rRoot.end() )
        {
            if( !pNode )
            {
                pNode = &pCurrNode->second;
                ++pCurrNode;
                if( pNode->hasItemSet() )
                {
                    // --> OD 2008-04-30 #i87808#
//                    return pNode->getItemSet();
                    return pNode->getUsedOrLastAddedItemSet();
                    // <--
                }
            }
            pNode = pNode->nextItemSet( pNode );
            if( pNode && pNode->hasItemSet() )
            {
                // --> OD 2008-04-30 #i87808#
//                return pNode->getItemSet();
                return pNode->getUsedOrLastAddedItemSet();
                // <--
            }
        }
        return pReturn;
    }

    ::rtl::OUString Iterator::getName()
    {
        ::rtl::OUString aString;
        if( pNode && pNode->hasItemSet() )
        {
            // --> OD 2008-04-30 #i87808#
//            aString = StylePool::nameOf( pNode->getItemSet() );
            aString = StylePool::nameOf( pNode->getUsedOrLastAddedItemSet() );
            // <--
        }
        return aString;
    }

}

/* This static method creates a unique name from a shared pointer to a SfxItemSet
   The name is the memory address of the SfxItemSet itself. */

::rtl::OUString StylePool::nameOf( SfxItemSet_Pointer_t pSet )
{
    return ::rtl::OUString::valueOf( reinterpret_cast<sal_IntPtr>( pSet.get() ), 16 );
}

// class StylePoolImpl organized a tree-structure where every node represents a SfxItemSet.
// The insertItemSet method adds a SfxItemSet into the tree if necessary and returns a shared_ptr
// to a copy of the SfxItemSet.
// The aRoot-Node represents an empty SfxItemSet.

class StylePoolImpl
{
private:
    std::map< const SfxItemSet*, Node > aRoot;
    sal_Int32 nCount;
public:
    StylePoolImpl() : nCount(0) {}
    StylePool::SfxItemSet_Pointer_t insertItemSet( const SfxItemSet& rSet );
    IStylePoolIteratorAccess* createIterator();
    sal_Int32 getCount() const { return nCount; }
};

StylePool::SfxItemSet_Pointer_t StylePoolImpl::insertItemSet( const SfxItemSet& rSet )
{
    bool bNonPoolable = false;
    Node* pCurNode = &aRoot[ rSet.GetParent() ];
    SfxItemIter aIter( rSet );
    const SfxPoolItem* pItem = aIter.GetCurItem();
    // Every SfxPoolItem in the SfxItemSet causes a step deeper into the tree,
    // a complete empty SfxItemSet would stay at the root node.
    while( pItem )
    {
        if( !rSet.GetPool()->IsItemFlag(pItem->Which(), SFX_ITEM_POOLABLE ) )
            bNonPoolable = true;
        pCurNode = pCurNode->findChildNode( *pItem );
        pItem = aIter.NextItem();
    }
    // Every leaf node represents an inserted item set, but "non-leaf" nodes represents subsets
    // of inserted itemsets.
    // These nodes could have but does not need to have a shared_ptr to a item set.
    if( !pCurNode->hasItemSet() )
    {
        pCurNode->setItemSet( rSet );
        bNonPoolable = false; // to avoid a double insertion
        ++nCount;
    }
    // If rSet contains at least one non poolable item, a new itemset has to be inserted
    if( bNonPoolable )
        pCurNode->setItemSet( rSet );
#ifdef DEBUG
    {
        sal_Int32 nCheck = -1;
        sal_Int32 nNo = -1;
        IStylePoolIteratorAccess* pIter = createIterator();
        StylePool::SfxItemSet_Pointer_t pTemp;
        do
        {
            ++nCheck;
            pTemp = pIter->getNext();
            if( pCurNode->hasItemSet() && pTemp.get() == pCurNode->getItemSet().get() )
            {
                ::rtl::OUString aStr = pIter->getName();
                nNo = nCheck;
            }
        } while( pTemp.get() );
        DBG_ASSERT( nCount == nCheck, "Wrong counting");
        delete pIter;
    }
#endif
    return pCurNode->getItemSet();
}

IStylePoolIteratorAccess* StylePoolImpl::createIterator()
{ return new Iterator( aRoot ); }

// Ctor, Dtor and redirected methods of class StylePool, nearly inline ;-)

StylePool::StylePool() : pImpl( new StylePoolImpl() ) {}

StylePool::SfxItemSet_Pointer_t StylePool::insertItemSet( const SfxItemSet& rSet )
{ return pImpl->insertItemSet( rSet ); }

IStylePoolIteratorAccess* StylePool::createIterator()
{ return pImpl->createIterator(); }

sal_Int32 StylePool::getCount() const
{ return pImpl->getCount(); }

StylePool::~StylePool() { delete pImpl; }

// End of class StylePool

<|endoftext|>